-
2
require "vider/version"
-
2
require 'vider/helpers'
-
-
2
module Vider
-
2
module Rails
-
2
class Engine < ::Rails::Engine
-
2
initializer :append_dependent_assets_path, group: :all do |app|
-
2
app.config.assets.precompile += %w( jquery.vide.js vider.js )
-
end
-
end
-
end
-
end
-
2
module ViderVideoTag
-
# A view helper for creating a video background element
-
2
def vider_tag bg, options={}
-
width = options[:width] || '1000px'
-
height = options[:height] || '500px'
-
volume = options[:volume] || 1
-
playback_rate = options[:playback_rate] || 1
-
muted = options[:muted] || true
-
looping = options[:loop] || true
-
autoplay = options[:autoplay] || true
-
position = options[:position] || "50% 50%"
-
poster_type = options[:poster_type] || "detect"
-
-
video_options = "volume: #{volume}, playback_rate: #{playback_rate}, muted: #{muted}, loop: #{looping}, autoplay: #{autoplay}, position: #{position}, poster_type: #{poster_type}" || 'loop: false, muted: false, position: 0% 0%'
-
-
content_tag :div, '', id: 'vider-element', style: "width: #{width}; height: #{height};", data: { vide_bg: bg, vide_options: video_options }
-
end
-
-
# A view helper for adding a video background to an existing element
-
# TODO: Implement this helper
-
2
def vider_for_element_tag bg, options={}
-
end
-
end
-
-
# Add gem's view helpers to ActionView
-
2
ActionView::Base.send :include, ViderVideoTag if defined? ActionView::Base
-
2
module Vider
-
2
VERSION = "0.0.1"
-
end
-
#--
-
# Copyright (c) 2004-2014 David Heinemeier Hansson
-
#
-
# Permission is hereby granted, free of charge, to any person obtaining
-
# a copy of this software and associated documentation files (the
-
# "Software"), to deal in the Software without restriction, including
-
# without limitation the rights to use, copy, modify, merge, publish,
-
# distribute, sublicense, and/or sell copies of the Software, and to
-
# permit persons to whom the Software is furnished to do so, subject to
-
# the following conditions:
-
#
-
# The above copyright notice and this permission notice shall be
-
# included in all copies or substantial portions of the Software.
-
#
-
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
-
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
-
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
-
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-
#++
-
-
2
require 'abstract_controller'
-
2
require 'action_mailer/version'
-
-
# Common Active Support usage in Action Mailer
-
2
require 'active_support/rails'
-
2
require 'active_support/core_ext/class'
-
2
require 'active_support/core_ext/module/attr_internal'
-
2
require 'active_support/core_ext/string/inflections'
-
2
require 'active_support/lazy_load_hooks'
-
-
2
module ActionMailer
-
2
extend ::ActiveSupport::Autoload
-
-
2
eager_autoload do
-
2
autoload :Collector
-
end
-
-
2
autoload :Base
-
2
autoload :DeliveryMethods
-
2
autoload :MailHelper
-
2
autoload :Preview
-
2
autoload :Previews, 'action_mailer/preview'
-
2
autoload :TestCase
-
2
autoload :TestHelper
-
end
-
2
require 'mail'
-
2
require 'action_mailer/collector'
-
2
require 'active_support/core_ext/string/inflections'
-
2
require 'active_support/core_ext/hash/except'
-
2
require 'active_support/core_ext/module/anonymous'
-
-
2
require 'action_mailer/log_subscriber'
-
-
2
module ActionMailer
-
# Action Mailer allows you to send email from your application using a mailer model and views.
-
#
-
# = Mailer Models
-
#
-
# To use Action Mailer, you need to create a mailer model.
-
#
-
# $ rails generate mailer Notifier
-
#
-
# The generated model inherits from <tt>ActionMailer::Base</tt>. A mailer model defines methods
-
# used to generate an email message. In these methods, you can setup variables to be used in
-
# the mailer views, options on the mail itself such as the <tt>:from</tt> address, and attachments.
-
#
-
# class Notifier < ActionMailer::Base
-
# default from: 'no-reply@example.com',
-
# return_path: 'system@example.com'
-
#
-
# def welcome(recipient)
-
# @account = recipient
-
# mail(to: recipient.email_address_with_name,
-
# bcc: ["bcc@example.com", "Order Watcher <watcher@example.com>"])
-
# end
-
# end
-
#
-
# Within the mailer method, you have access to the following methods:
-
#
-
# * <tt>attachments[]=</tt> - Allows you to add attachments to your email in an intuitive
-
# manner; <tt>attachments['filename.png'] = File.read('path/to/filename.png')</tt>
-
#
-
# * <tt>attachments.inline[]=</tt> - Allows you to add an inline attachment to your email
-
# in the same manner as <tt>attachments[]=</tt>
-
#
-
# * <tt>headers[]=</tt> - Allows you to specify any header field in your email such
-
# as <tt>headers['X-No-Spam'] = 'True'</tt>. Note, while most fields like <tt>To:</tt>
-
# <tt>From:</tt> can only appear once in an email header, other fields like <tt>X-Anything</tt>
-
# can appear multiple times. If you want to change a field that can appear multiple times,
-
# you need to set it to nil first so that Mail knows you are replacing it and not adding
-
# another field of the same name.
-
#
-
# * <tt>headers(hash)</tt> - Allows you to specify multiple headers in your email such
-
# as <tt>headers({'X-No-Spam' => 'True', 'In-Reply-To' => '1234@message.id'})</tt>
-
#
-
# * <tt>mail</tt> - Allows you to specify email to be sent.
-
#
-
# The hash passed to the mail method allows you to specify any header that a <tt>Mail::Message</tt>
-
# will accept (any valid email header including optional fields).
-
#
-
# The mail method, if not passed a block, will inspect your views and send all the views with
-
# the same name as the method, so the above action would send the +welcome.text.erb+ view
-
# file as well as the +welcome.text.html.erb+ view file in a +multipart/alternative+ email.
-
#
-
# If you want to explicitly render only certain templates, pass a block:
-
#
-
# mail(to: user.email) do |format|
-
# format.text
-
# format.html
-
# end
-
#
-
# The block syntax is also useful in providing information specific to a part:
-
#
-
# mail(to: user.email) do |format|
-
# format.text(content_transfer_encoding: "base64")
-
# format.html
-
# end
-
#
-
# Or even to render a special view:
-
#
-
# mail(to: user.email) do |format|
-
# format.text
-
# format.html { render "some_other_template" }
-
# end
-
#
-
# = Mailer views
-
#
-
# Like Action Controller, each mailer class has a corresponding view directory in which each
-
# method of the class looks for a template with its name.
-
#
-
# To define a template to be used with a mailing, create an <tt>.erb</tt> file with the same
-
# name as the method in your mailer model. For example, in the mailer defined above, the template at
-
# <tt>app/views/notifier/welcome.text.erb</tt> would be used to generate the email.
-
#
-
# Variables defined in the model are accessible as instance variables in the view.
-
#
-
# Emails by default are sent in plain text, so a sample view for our model example might look like this:
-
#
-
# Hi <%= @account.name %>,
-
# Thanks for joining our service! Please check back often.
-
#
-
# You can even use Action Pack helpers in these views. For example:
-
#
-
# You got a new note!
-
# <%= truncate(@note.body, length: 25) %>
-
#
-
# If you need to access the subject, from or the recipients in the view, you can do that through message object:
-
#
-
# You got a new note from <%= message.from %>!
-
# <%= truncate(@note.body, length: 25) %>
-
#
-
#
-
# = Generating URLs
-
#
-
# URLs can be generated in mailer views using <tt>url_for</tt> or named routes. Unlike controllers from
-
# Action Pack, the mailer instance doesn't have any context about the incoming request, so you'll need
-
# to provide all of the details needed to generate a URL.
-
#
-
# When using <tt>url_for</tt> you'll need to provide the <tt>:host</tt>, <tt>:controller</tt>, and <tt>:action</tt>:
-
#
-
# <%= url_for(host: "example.com", controller: "welcome", action: "greeting") %>
-
#
-
# When using named routes you only need to supply the <tt>:host</tt>:
-
#
-
# <%= users_url(host: "example.com") %>
-
#
-
# You should use the <tt>named_route_url</tt> style (which generates absolute URLs) and avoid using the
-
# <tt>named_route_path</tt> style (which generates relative URLs), since clients reading the mail will
-
# have no concept of a current URL from which to determine a relative path.
-
#
-
# It is also possible to set a default host that will be used in all mailers by setting the <tt>:host</tt>
-
# option as a configuration option in <tt>config/application.rb</tt>:
-
#
-
# config.action_mailer.default_url_options = { host: "example.com" }
-
#
-
# When you decide to set a default <tt>:host</tt> for your mailers, then you need to make sure to use the
-
# <tt>only_path: false</tt> option when using <tt>url_for</tt>. Since the <tt>url_for</tt> view helper
-
# will generate relative URLs by default when a <tt>:host</tt> option isn't explicitly provided, passing
-
# <tt>only_path: false</tt> will ensure that absolute URLs are generated.
-
#
-
# = Sending mail
-
#
-
# Once a mailer action and template are defined, you can deliver your message or create it and save it
-
# for delivery later:
-
#
-
# Notifier.welcome(david).deliver # sends the email
-
# mail = Notifier.welcome(david) # => a Mail::Message object
-
# mail.deliver # sends the email
-
#
-
# You never instantiate your mailer class. Rather, you just call the method you defined on the class itself.
-
#
-
# = Multipart Emails
-
#
-
# Multipart messages can also be used implicitly because Action Mailer will automatically detect and use
-
# multipart templates, where each template is named after the name of the action, followed by the content
-
# type. Each such detected template will be added as a separate part to the message.
-
#
-
# For example, if the following templates exist:
-
# * signup_notification.text.erb
-
# * signup_notification.html.erb
-
# * signup_notification.xml.builder
-
# * signup_notification.yaml.erb
-
#
-
# Each would be rendered and added as a separate part to the message, with the corresponding content
-
# type. The content type for the entire message is automatically set to <tt>multipart/alternative</tt>,
-
# which indicates that the email contains multiple different representations of the same email
-
# body. The same instance variables defined in the action are passed to all email templates.
-
#
-
# Implicit template rendering is not performed if any attachments or parts have been added to the email.
-
# This means that you'll have to manually add each part to the email and set the content type of the email
-
# to <tt>multipart/alternative</tt>.
-
#
-
# = Attachments
-
#
-
# Sending attachment in emails is easy:
-
#
-
# class ApplicationMailer < ActionMailer::Base
-
# def welcome(recipient)
-
# attachments['free_book.pdf'] = File.read('path/to/file.pdf')
-
# mail(to: recipient, subject: "New account information")
-
# end
-
# end
-
#
-
# Which will (if it had both a <tt>welcome.text.erb</tt> and <tt>welcome.html.erb</tt>
-
# template in the view directory), send a complete <tt>multipart/mixed</tt> email with two parts,
-
# the first part being a <tt>multipart/alternative</tt> with the text and HTML email parts inside,
-
# and the second being a <tt>application/pdf</tt> with a Base64 encoded copy of the file.pdf book
-
# with the filename +free_book.pdf+.
-
#
-
# If you need to send attachments with no content, you need to create an empty view for it,
-
# or add an empty body parameter like this:
-
#
-
# class ApplicationMailer < ActionMailer::Base
-
# def welcome(recipient)
-
# attachments['free_book.pdf'] = File.read('path/to/file.pdf')
-
# mail(to: recipient, subject: "New account information", body: "")
-
# end
-
# end
-
#
-
# = Inline Attachments
-
#
-
# You can also specify that a file should be displayed inline with other HTML. This is useful
-
# if you want to display a corporate logo or a photo.
-
#
-
# class ApplicationMailer < ActionMailer::Base
-
# def welcome(recipient)
-
# attachments.inline['photo.png'] = File.read('path/to/photo.png')
-
# mail(to: recipient, subject: "Here is what we look like")
-
# end
-
# end
-
#
-
# And then to reference the image in the view, you create a <tt>welcome.html.erb</tt> file and
-
# make a call to +image_tag+ passing in the attachment you want to display and then call
-
# +url+ on the attachment to get the relative content id path for the image source:
-
#
-
# <h1>Please Don't Cringe</h1>
-
#
-
# <%= image_tag attachments['photo.png'].url -%>
-
#
-
# As we are using Action View's +image_tag+ method, you can pass in any other options you want:
-
#
-
# <h1>Please Don't Cringe</h1>
-
#
-
# <%= image_tag attachments['photo.png'].url, alt: 'Our Photo', class: 'photo' -%>
-
#
-
# = Observing and Intercepting Mails
-
#
-
# Action Mailer provides hooks into the Mail observer and interceptor methods. These allow you to
-
# register classes that are called during the mail delivery life cycle.
-
#
-
# An observer class must implement the <tt>:delivered_email(message)</tt> method which will be
-
# called once for every email sent after the email has been sent.
-
#
-
# An interceptor class must implement the <tt>:delivering_email(message)</tt> method which will be
-
# called before the email is sent, allowing you to make modifications to the email before it hits
-
# the delivery agents. Your class should make any needed modifications directly to the passed
-
# in <tt>Mail::Message</tt> instance.
-
#
-
# = Default Hash
-
#
-
# Action Mailer provides some intelligent defaults for your emails, these are usually specified in a
-
# default method inside the class definition:
-
#
-
# class Notifier < ActionMailer::Base
-
# default sender: 'system@example.com'
-
# end
-
#
-
# You can pass in any header value that a <tt>Mail::Message</tt> accepts. Out of the box,
-
# <tt>ActionMailer::Base</tt> sets the following:
-
#
-
# * <tt>mime_version: "1.0"</tt>
-
# * <tt>charset: "UTF-8",</tt>
-
# * <tt>content_type: "text/plain",</tt>
-
# * <tt>parts_order: [ "text/plain", "text/enriched", "text/html" ]</tt>
-
#
-
# <tt>parts_order</tt> and <tt>charset</tt> are not actually valid <tt>Mail::Message</tt> header fields,
-
# but Action Mailer translates them appropriately and sets the correct values.
-
#
-
# As you can pass in any header, you need to either quote the header as a string, or pass it in as
-
# an underscored symbol, so the following will work:
-
#
-
# class Notifier < ActionMailer::Base
-
# default 'Content-Transfer-Encoding' => '7bit',
-
# content_description: 'This is a description'
-
# end
-
#
-
# Finally, Action Mailer also supports passing <tt>Proc</tt> objects into the default hash, so you
-
# can define methods that evaluate as the message is being generated:
-
#
-
# class Notifier < ActionMailer::Base
-
# default 'X-Special-Header' => Proc.new { my_method }
-
#
-
# private
-
#
-
# def my_method
-
# 'some complex call'
-
# end
-
# end
-
#
-
# Note that the proc is evaluated right at the start of the mail message generation, so if you
-
# set something in the defaults using a proc, and then set the same thing inside of your
-
# mailer method, it will get over written by the mailer method.
-
#
-
# It is also possible to set these default options that will be used in all mailers through
-
# the <tt>default_options=</tt> configuration in <tt>config/application.rb</tt>:
-
#
-
# config.action_mailer.default_options = { from: "no-reply@example.org" }
-
#
-
# = Callbacks
-
#
-
# You can specify callbacks using before_action and after_action for configuring your messages.
-
# This may be useful, for example, when you want to add default inline attachments for all
-
# messages sent out by a certain mailer class:
-
#
-
# class Notifier < ActionMailer::Base
-
# before_action :add_inline_attachment!
-
#
-
# def welcome
-
# mail
-
# end
-
#
-
# private
-
#
-
# def add_inline_attachment!
-
# attachments.inline["footer.jpg"] = File.read('/path/to/filename.jpg')
-
# end
-
# end
-
#
-
# Callbacks in ActionMailer are implemented using AbstractController::Callbacks, so you
-
# can define and configure callbacks in the same manner that you would use callbacks in
-
# classes that inherit from ActionController::Base.
-
#
-
# Note that unless you have a specific reason to do so, you should prefer using before_action
-
# rather than after_action in your ActionMailer classes so that headers are parsed properly.
-
#
-
# = Previewing emails
-
#
-
# You can preview your email templates visually by adding a mailer preview file to the
-
# <tt>ActionMailer::Base.preview_path</tt>. Since most emails do something interesting
-
# with database data, you'll need to write some scenarios to load messages with fake data:
-
#
-
# class NotifierPreview < ActionMailer::Preview
-
# def welcome
-
# Notifier.welcome(User.first)
-
# end
-
# end
-
#
-
# Methods must return a <tt>Mail::Message</tt> object which can be generated by calling the mailer
-
# method without the additional <tt>deliver</tt>. The location of the mailer previews
-
# directory can be configured using the <tt>preview_path</tt> option which has a default
-
# of <tt>test/mailers/previews</tt>:
-
#
-
# config.action_mailer.preview_path = "#{Rails.root}/lib/mailer_previews"
-
#
-
# An overview of all previews is accessible at <tt>http://localhost:3000/rails/mailers</tt>
-
# on a running development server instance.
-
#
-
# Previews can also be intercepted in a similar manner as deliveries can be by registering
-
# a preview interceptor that has a <tt>previewing_email</tt> method:
-
#
-
# class CssInlineStyler
-
# def self.previewing_email(message)
-
# # inline CSS styles
-
# end
-
# end
-
#
-
# config.action_mailer.preview_interceptors :css_inline_styler
-
#
-
# Note that interceptors need to be registered both with <tt>register_interceptor</tt>
-
# and <tt>register_preview_interceptor</tt> if they should operate on both sending and
-
# previewing emails.
-
#
-
# = Configuration options
-
#
-
# These options are specified on the class level, like
-
# <tt>ActionMailer::Base.raise_delivery_errors = true</tt>
-
#
-
# * <tt>default_options</tt> - You can pass this in at a class level as well as within the class itself as
-
# per the above section.
-
#
-
# * <tt>logger</tt> - the logger is used for generating information on the mailing run if available.
-
# Can be set to +nil+ for no logging. Compatible with both Ruby's own +Logger+ and Log4r loggers.
-
#
-
# * <tt>smtp_settings</tt> - Allows detailed configuration for <tt>:smtp</tt> delivery method:
-
# * <tt>:address</tt> - Allows you to use a remote mail server. Just change it from its default
-
# "localhost" setting.
-
# * <tt>:port</tt> - On the off chance that your mail server doesn't run on port 25, you can change it.
-
# * <tt>:domain</tt> - If you need to specify a HELO domain, you can do it here.
-
# * <tt>:user_name</tt> - If your mail server requires authentication, set the username in this setting.
-
# * <tt>:password</tt> - If your mail server requires authentication, set the password in this setting.
-
# * <tt>:authentication</tt> - If your mail server requires authentication, you need to specify the
-
# authentication type here.
-
# This is a symbol and one of <tt>:plain</tt> (will send the password in the clear), <tt>:login</tt> (will
-
# send password Base64 encoded) or <tt>:cram_md5</tt> (combines a Challenge/Response mechanism to exchange
-
# information and a cryptographic Message Digest 5 algorithm to hash important information)
-
# * <tt>:enable_starttls_auto</tt> - When set to true, detects if STARTTLS is enabled in your SMTP server
-
# and starts to use it.
-
# * <tt>:openssl_verify_mode</tt> - When using TLS, you can set how OpenSSL checks the certificate. This is
-
# really useful if you need to validate a self-signed and/or a wildcard certificate. You can use the name
-
# of an OpenSSL verify constant (<tt>'none'</tt>, <tt>'peer'</tt>, <tt>'client_once'</tt>,
-
# <tt>'fail_if_no_peer_cert'</tt>) or directly the constant (<tt>OpenSSL::SSL::VERIFY_NONE</tt>,
-
# <tt>OpenSSL::SSL::VERIFY_PEER</tt>, ...).
-
#
-
# * <tt>sendmail_settings</tt> - Allows you to override options for the <tt>:sendmail</tt> delivery method.
-
# * <tt>:location</tt> - The location of the sendmail executable. Defaults to <tt>/usr/sbin/sendmail</tt>.
-
# * <tt>:arguments</tt> - The command line arguments. Defaults to <tt>-i -t</tt> with <tt>-f sender@address</tt>
-
# added automatically before the message is sent.
-
#
-
# * <tt>file_settings</tt> - Allows you to override options for the <tt>:file</tt> delivery method.
-
# * <tt>:location</tt> - The directory into which emails will be written. Defaults to the application
-
# <tt>tmp/mails</tt>.
-
#
-
# * <tt>raise_delivery_errors</tt> - Whether or not errors should be raised if the email fails to be delivered.
-
#
-
# * <tt>delivery_method</tt> - Defines a delivery method. Possible values are <tt>:smtp</tt> (default),
-
# <tt>:sendmail</tt>, <tt>:test</tt>, and <tt>:file</tt>. Or you may provide a custom delivery method
-
# object e.g. +MyOwnDeliveryMethodClass+. See the Mail gem documentation on the interface you need to
-
# implement for a custom delivery agent.
-
#
-
# * <tt>perform_deliveries</tt> - Determines whether emails are actually sent from Action Mailer when you
-
# call <tt>.deliver</tt> on an mail message or on an Action Mailer method. This is on by default but can
-
# be turned off to aid in functional testing.
-
#
-
# * <tt>deliveries</tt> - Keeps an array of all the emails sent out through the Action Mailer with
-
# <tt>delivery_method :test</tt>. Most useful for unit and functional testing.
-
2
class Base < AbstractController::Base
-
2
include DeliveryMethods
-
2
include Previews
-
-
2
abstract!
-
-
2
include AbstractController::Rendering
-
-
2
include AbstractController::Logger
-
2
include AbstractController::Helpers
-
2
include AbstractController::Translation
-
2
include AbstractController::AssetPaths
-
2
include AbstractController::Callbacks
-
-
2
include ActionView::Layouts
-
-
2
PROTECTED_IVARS = AbstractController::Rendering::DEFAULT_PROTECTED_INSTANCE_VARIABLES + [:@_action_has_layout]
-
-
2
def _protected_ivars # :nodoc:
-
PROTECTED_IVARS
-
end
-
-
2
helper ActionMailer::MailHelper
-
-
2
private_class_method :new #:nodoc:
-
-
2
class_attribute :default_params
-
2
self.default_params = {
-
mime_version: "1.0",
-
charset: "UTF-8",
-
content_type: "text/plain",
-
parts_order: [ "text/plain", "text/enriched", "text/html" ]
-
}.freeze
-
-
2
class << self
-
# Register one or more Observers which will be notified when mail is delivered.
-
2
def register_observers(*observers)
-
2
observers.flatten.compact.each { |observer| register_observer(observer) }
-
end
-
-
# Register one or more Interceptors which will be called before mail is sent.
-
2
def register_interceptors(*interceptors)
-
2
interceptors.flatten.compact.each { |interceptor| register_interceptor(interceptor) }
-
end
-
-
# Register an Observer which will be notified when mail is delivered.
-
# Either a class, string or symbol can be passed in as the Observer.
-
# If a string or symbol is passed in it will be camelized and constantized.
-
2
def register_observer(observer)
-
delivery_observer = case observer
-
when String, Symbol
-
observer.to_s.camelize.constantize
-
else
-
observer
-
end
-
-
Mail.register_observer(delivery_observer)
-
end
-
-
# Register an Interceptor which will be called before mail is sent.
-
# Either a class, string or symbol can be passed in as the Interceptor.
-
# If a string or symbol is passed in it will be camelized and constantized.
-
2
def register_interceptor(interceptor)
-
delivery_interceptor = case interceptor
-
when String, Symbol
-
interceptor.to_s.camelize.constantize
-
else
-
interceptor
-
end
-
-
Mail.register_interceptor(delivery_interceptor)
-
end
-
-
# Returns the name of current mailer. This method is also being used as a path for a view lookup.
-
# If this is an anonymous mailer, this method will return +anonymous+ instead.
-
2
def mailer_name
-
@mailer_name ||= anonymous? ? "anonymous" : name.underscore
-
end
-
# Allows to set the name of current mailer.
-
2
attr_writer :mailer_name
-
2
alias :controller_path :mailer_name
-
-
# Sets the defaults through app configuration:
-
#
-
# config.action_mailer.default { from: "no-reply@example.org" }
-
#
-
# Aliased by ::default_options=
-
2
def default(value = nil)
-
self.default_params = default_params.merge(value).freeze if value
-
default_params
-
end
-
# Allows to set defaults through app configuration:
-
#
-
# config.action_mailer.default_options = { from: "no-reply@example.org" }
-
2
alias :default_options= :default
-
-
# Receives a raw email, parses it into an email object, decodes it,
-
# instantiates a new mailer, and passes the email object to the mailer
-
# object's +receive+ method.
-
#
-
# If you want your mailer to be able to process incoming messages, you'll
-
# need to implement a +receive+ method that accepts the raw email string
-
# as a parameter:
-
#
-
# class MyMailer < ActionMailer::Base
-
# def receive(mail)
-
# # ...
-
# end
-
# end
-
2
def receive(raw_mail)
-
ActiveSupport::Notifications.instrument("receive.action_mailer") do |payload|
-
mail = Mail.new(raw_mail)
-
set_payload_for_mail(payload, mail)
-
new.receive(mail)
-
end
-
end
-
-
# Wraps an email delivery inside of <tt>ActiveSupport::Notifications</tt> instrumentation.
-
#
-
# This method is actually called by the <tt>Mail::Message</tt> object itself
-
# through a callback when you call <tt>:deliver</tt> on the <tt>Mail::Message</tt>,
-
# calling +deliver_mail+ directly and passing a <tt>Mail::Message</tt> will do
-
# nothing except tell the logger you sent the email.
-
2
def deliver_mail(mail) #:nodoc:
-
ActiveSupport::Notifications.instrument("deliver.action_mailer") do |payload|
-
set_payload_for_mail(payload, mail)
-
yield # Let Mail do the delivery actions
-
end
-
end
-
-
2
def respond_to?(method, include_private = false) #:nodoc:
-
6
super || action_methods.include?(method.to_s)
-
end
-
-
2
protected
-
-
2
def set_payload_for_mail(payload, mail) #:nodoc:
-
payload[:mailer] = name
-
payload[:message_id] = mail.message_id
-
payload[:subject] = mail.subject
-
payload[:to] = mail.to
-
payload[:from] = mail.from
-
payload[:bcc] = mail.bcc if mail.bcc.present?
-
payload[:cc] = mail.cc if mail.cc.present?
-
payload[:date] = mail.date
-
payload[:mail] = mail.encoded
-
end
-
-
2
def method_missing(method_name, *args) # :nodoc:
-
if respond_to?(method_name)
-
new(method_name, *args).message
-
else
-
super
-
end
-
end
-
end
-
-
2
attr_internal :message
-
-
# Instantiate a new mailer object. If +method_name+ is not +nil+, the mailer
-
# will be initialized according to the named method. If not, the mailer will
-
# remain uninitialized (useful when you only need to invoke the "receive"
-
# method, for instance).
-
2
def initialize(method_name=nil, *args)
-
super()
-
@_mail_was_called = false
-
@_message = Mail.new
-
process(method_name, *args) if method_name
-
end
-
-
2
def process(method_name, *args) #:nodoc:
-
payload = {
-
mailer: self.class.name,
-
action: method_name
-
}
-
-
ActiveSupport::Notifications.instrument("process.action_mailer", payload) do
-
lookup_context.skip_default_locale!
-
-
super
-
@_message = NullMail.new unless @_mail_was_called
-
end
-
end
-
-
2
class NullMail #:nodoc:
-
2
def body; '' end
-
-
2
def method_missing(*args)
-
nil
-
end
-
end
-
-
# Returns the name of the mailer object.
-
2
def mailer_name
-
self.class.mailer_name
-
end
-
-
# Allows you to pass random and unusual headers to the new <tt>Mail::Message</tt>
-
# object which will add them to itself.
-
#
-
# headers['X-Special-Domain-Specific-Header'] = "SecretValue"
-
#
-
# You can also pass a hash into headers of header field names and values,
-
# which will then be set on the <tt>Mail::Message</tt> object:
-
#
-
# headers 'X-Special-Domain-Specific-Header' => "SecretValue",
-
# 'In-Reply-To' => incoming.message_id
-
#
-
# The resulting <tt>Mail::Message</tt> will have the following in its header:
-
#
-
# X-Special-Domain-Specific-Header: SecretValue
-
2
def headers(args = nil)
-
if args
-
@_message.headers(args)
-
else
-
@_message
-
end
-
end
-
-
# Allows you to add attachments to an email, like so:
-
#
-
# mail.attachments['filename.jpg'] = File.read('/path/to/filename.jpg')
-
#
-
# If you do this, then Mail will take the file name and work out the mime type
-
# set the Content-Type, Content-Disposition, Content-Transfer-Encoding and
-
# base64 encode the contents of the attachment all for you.
-
#
-
# You can also specify overrides if you want by passing a hash instead of a string:
-
#
-
# mail.attachments['filename.jpg'] = {mime_type: 'application/x-gzip',
-
# content: File.read('/path/to/filename.jpg')}
-
#
-
# If you want to use a different encoding than Base64, you can pass an encoding in,
-
# but then it is up to you to pass in the content pre-encoded, and don't expect
-
# Mail to know how to decode this data:
-
#
-
# file_content = SpecialEncode(File.read('/path/to/filename.jpg'))
-
# mail.attachments['filename.jpg'] = {mime_type: 'application/x-gzip',
-
# encoding: 'SpecialEncoding',
-
# content: file_content }
-
#
-
# You can also search for specific attachments:
-
#
-
# # By Filename
-
# mail.attachments['filename.jpg'] # => Mail::Part object or nil
-
#
-
# # or by index
-
# mail.attachments[0] # => Mail::Part (first attachment)
-
#
-
2
def attachments
-
if @_mail_was_called
-
LateAttachmentsProxy.new(@_message.attachments)
-
else
-
@_message.attachments
-
end
-
end
-
-
2
class LateAttachmentsProxy < SimpleDelegator
-
2
def inline; _raise_error end
-
2
def []=(_name, _content); _raise_error end
-
-
2
private
-
2
def _raise_error
-
raise RuntimeError, "Can't add attachments after `mail` was called.\n" \
-
"Make sure to use `attachments[]=` before calling `mail`."
-
end
-
end
-
-
# The main method that creates the message and renders the email templates. There are
-
# two ways to call this method, with a block, or without a block.
-
#
-
# Both methods accept a headers hash. This hash allows you to specify the most used headers
-
# in an email message, these are:
-
#
-
# * +:subject+ - The subject of the message, if this is omitted, Action Mailer will
-
# ask the Rails I18n class for a translated +:subject+ in the scope of
-
# <tt>[mailer_scope, action_name]</tt> or if this is missing, will translate the
-
# humanized version of the +action_name+
-
# * +:to+ - Who the message is destined for, can be a string of addresses, or an array
-
# of addresses.
-
# * +:from+ - Who the message is from
-
# * +:cc+ - Who you would like to Carbon-Copy on this email, can be a string of addresses,
-
# or an array of addresses.
-
# * +:bcc+ - Who you would like to Blind-Carbon-Copy on this email, can be a string of
-
# addresses, or an array of addresses.
-
# * +:reply_to+ - Who to set the Reply-To header of the email to.
-
# * +:date+ - The date to say the email was sent on.
-
#
-
# You can set default values for any of the above headers (except +:date+)
-
# by using the ::default class method:
-
#
-
# class Notifier < ActionMailer::Base
-
# default from: 'no-reply@test.lindsaar.net',
-
# bcc: 'email_logger@test.lindsaar.net',
-
# reply_to: 'bounces@test.lindsaar.net'
-
# end
-
#
-
# If you need other headers not listed above, you can either pass them in
-
# as part of the headers hash or use the <tt>headers['name'] = value</tt>
-
# method.
-
#
-
# When a +:return_path+ is specified as header, that value will be used as
-
# the 'envelope from' address for the Mail message. Setting this is useful
-
# when you want delivery notifications sent to a different address than the
-
# one in +:from+. Mail will actually use the +:return_path+ in preference
-
# to the +:sender+ in preference to the +:from+ field for the 'envelope
-
# from' value.
-
#
-
# If you do not pass a block to the +mail+ method, it will find all
-
# templates in the view paths using by default the mailer name and the
-
# method name that it is being called from, it will then create parts for
-
# each of these templates intelligently, making educated guesses on correct
-
# content type and sequence, and return a fully prepared <tt>Mail::Message</tt>
-
# ready to call <tt>:deliver</tt> on to send.
-
#
-
# For example:
-
#
-
# class Notifier < ActionMailer::Base
-
# default from: 'no-reply@test.lindsaar.net'
-
#
-
# def welcome
-
# mail(to: 'mikel@test.lindsaar.net')
-
# end
-
# end
-
#
-
# Will look for all templates at "app/views/notifier" with name "welcome".
-
# If no welcome template exists, it will raise an ActionView::MissingTemplate error.
-
#
-
# However, those can be customized:
-
#
-
# mail(template_path: 'notifications', template_name: 'another')
-
#
-
# And now it will look for all templates at "app/views/notifications" with name "another".
-
#
-
# If you do pass a block, you can render specific templates of your choice:
-
#
-
# mail(to: 'mikel@test.lindsaar.net') do |format|
-
# format.text
-
# format.html
-
# end
-
#
-
# You can even render plain text directly without using a template:
-
#
-
# mail(to: 'mikel@test.lindsaar.net') do |format|
-
# format.text { render plain: "Hello Mikel!" }
-
# format.html { render html: "<h1>Hello Mikel!</h1>".html_safe }
-
# end
-
#
-
# Which will render a +multipart/alternative+ email with +text/plain+ and
-
# +text/html+ parts.
-
#
-
# The block syntax also allows you to customize the part headers if desired:
-
#
-
# mail(to: 'mikel@test.lindsaar.net') do |format|
-
# format.text(content_transfer_encoding: "base64")
-
# format.html
-
# end
-
#
-
2
def mail(headers = {}, &block)
-
return @_message if @_mail_was_called && headers.blank? && !block
-
-
m = @_message
-
-
# At the beginning, do not consider class default for content_type
-
content_type = headers[:content_type]
-
-
# Call all the procs (if any)
-
default_values = {}
-
self.class.default.each do |k,v|
-
default_values[k] = v.is_a?(Proc) ? instance_eval(&v) : v
-
end
-
-
# Handle defaults
-
headers = headers.reverse_merge(default_values)
-
headers[:subject] ||= default_i18n_subject
-
-
# Apply charset at the beginning so all fields are properly quoted
-
m.charset = charset = headers[:charset]
-
-
# Set configure delivery behavior
-
wrap_delivery_behavior!(headers.delete(:delivery_method), headers.delete(:delivery_method_options))
-
-
# Assign all headers except parts_order, content_type and body
-
assignable = headers.except(:parts_order, :content_type, :body, :template_name, :template_path)
-
assignable.each { |k, v| m[k] = v }
-
-
# Render the templates and blocks
-
responses = collect_responses(headers, &block)
-
@_mail_was_called = true
-
-
create_parts_from_responses(m, responses)
-
-
# Setup content type, reapply charset and handle parts order
-
m.content_type = set_content_type(m, content_type, headers[:content_type])
-
m.charset = charset
-
-
if m.multipart?
-
m.body.set_sort_order(headers[:parts_order])
-
m.body.sort_parts!
-
end
-
-
m
-
end
-
-
2
protected
-
-
# Used by #mail to set the content type of the message.
-
#
-
# It will use the given +user_content_type+, or multipart if the mail
-
# message has any attachments. If the attachments are inline, the content
-
# type will be "multipart/related", otherwise "multipart/mixed".
-
#
-
# If there is no content type passed in via headers, and there are no
-
# attachments, or the message is multipart, then the default content type is
-
# used.
-
2
def set_content_type(m, user_content_type, class_default)
-
params = m.content_type_parameters || {}
-
case
-
when user_content_type.present?
-
user_content_type
-
when m.has_attachments?
-
if m.attachments.detect { |a| a.inline? }
-
["multipart", "related", params]
-
else
-
["multipart", "mixed", params]
-
end
-
when m.multipart?
-
["multipart", "alternative", params]
-
else
-
m.content_type || class_default
-
end
-
end
-
-
# Translates the +subject+ using Rails I18n class under <tt>[mailer_scope, action_name]</tt> scope.
-
# If it does not find a translation for the +subject+ under the specified scope it will default to a
-
# humanized version of the <tt>action_name</tt>.
-
# If the subject has interpolations, you can pass them through the +interpolations+ parameter.
-
2
def default_i18n_subject(interpolations = {})
-
mailer_scope = self.class.mailer_name.tr('/', '.')
-
I18n.t(:subject, interpolations.merge(scope: [mailer_scope, action_name], default: action_name.humanize))
-
end
-
-
2
def collect_responses(headers) #:nodoc:
-
responses = []
-
-
if block_given?
-
collector = ActionMailer::Collector.new(lookup_context) { render(action_name) }
-
yield(collector)
-
responses = collector.responses
-
elsif headers[:body]
-
responses << {
-
body: headers.delete(:body),
-
content_type: self.class.default[:content_type] || "text/plain"
-
}
-
else
-
templates_path = headers.delete(:template_path) || self.class.mailer_name
-
templates_name = headers.delete(:template_name) || action_name
-
-
each_template(Array(templates_path), templates_name) do |template|
-
self.formats = template.formats
-
-
responses << {
-
body: render(template: template),
-
content_type: template.type.to_s
-
}
-
end
-
end
-
-
responses
-
end
-
-
2
def each_template(paths, name, &block) #:nodoc:
-
templates = lookup_context.find_all(name, paths)
-
if templates.empty?
-
raise ActionView::MissingTemplate.new(paths, name, paths, false, 'mailer')
-
else
-
templates.uniq { |t| t.formats }.each(&block)
-
end
-
end
-
-
2
def create_parts_from_responses(m, responses) #:nodoc:
-
if responses.size == 1 && !m.has_attachments?
-
responses[0].each { |k,v| m[k] = v }
-
elsif responses.size > 1 && m.has_attachments?
-
container = Mail::Part.new
-
container.content_type = "multipart/alternative"
-
responses.each { |r| insert_part(container, r, m.charset) }
-
m.add_part(container)
-
else
-
responses.each { |r| insert_part(m, r, m.charset) }
-
end
-
end
-
-
2
def insert_part(container, response, charset) #:nodoc:
-
response[:charset] ||= charset
-
part = Mail::Part.new(response)
-
container.add_part(part)
-
end
-
-
2
ActiveSupport.run_load_hooks(:action_mailer, self)
-
end
-
end
-
2
require 'abstract_controller/collector'
-
2
require 'active_support/core_ext/hash/reverse_merge'
-
2
require 'active_support/core_ext/array/extract_options'
-
-
2
module ActionMailer
-
2
class Collector
-
2
include AbstractController::Collector
-
2
attr_reader :responses
-
-
2
def initialize(context, &block)
-
@context = context
-
@responses = []
-
@default_render = block
-
end
-
-
2
def any(*args, &block)
-
options = args.extract_options!
-
raise ArgumentError, "You have to supply at least one format" if args.empty?
-
args.each { |type| send(type, options.dup, &block) }
-
end
-
2
alias :all :any
-
-
2
def custom(mime, options = {})
-
options.reverse_merge!(content_type: mime.to_s)
-
@context.formats = [mime.to_sym]
-
options[:body] = block_given? ? yield : @default_render.call
-
@responses << options
-
end
-
end
-
end
-
2
require 'tmpdir'
-
-
2
module ActionMailer
-
# This module handles everything related to mail delivery, from registering
-
# new delivery methods to configuring the mail object to be sent.
-
2
module DeliveryMethods
-
2
extend ActiveSupport::Concern
-
-
2
included do
-
2
class_attribute :delivery_methods, :delivery_method
-
-
# Do not make this inheritable, because we always want it to propagate
-
2
cattr_accessor :raise_delivery_errors
-
2
self.raise_delivery_errors = true
-
-
2
cattr_accessor :perform_deliveries
-
2
self.perform_deliveries = true
-
-
2
self.delivery_methods = {}.freeze
-
2
self.delivery_method = :smtp
-
-
2
add_delivery_method :smtp, Mail::SMTP,
-
address: "localhost",
-
port: 25,
-
domain: 'localhost.localdomain',
-
user_name: nil,
-
password: nil,
-
authentication: nil,
-
enable_starttls_auto: true
-
-
2
add_delivery_method :file, Mail::FileDelivery,
-
location: defined?(Rails.root) ? "#{Rails.root}/tmp/mails" : "#{Dir.tmpdir}/mails"
-
-
2
add_delivery_method :sendmail, Mail::Sendmail,
-
location: '/usr/sbin/sendmail',
-
arguments: '-i -t'
-
-
2
add_delivery_method :test, Mail::TestMailer
-
end
-
-
# Helpers for creating and wrapping delivery behavior, used by DeliveryMethods.
-
2
module ClassMethods
-
# Provides a list of emails that have been delivered by Mail::TestMailer
-
2
delegate :deliveries, :deliveries=, to: Mail::TestMailer
-
-
# Adds a new delivery method through the given class using the given
-
# symbol as alias and the default options supplied.
-
#
-
# add_delivery_method :sendmail, Mail::Sendmail,
-
# location: '/usr/sbin/sendmail',
-
# arguments: '-i -t'
-
2
def add_delivery_method(symbol, klass, default_options={})
-
8
class_attribute(:"#{symbol}_settings") unless respond_to?(:"#{symbol}_settings")
-
8
send(:"#{symbol}_settings=", default_options)
-
8
self.delivery_methods = delivery_methods.merge(symbol.to_sym => klass).freeze
-
end
-
-
2
def wrap_delivery_behavior(mail, method=nil, options=nil) # :nodoc:
-
method ||= self.delivery_method
-
mail.delivery_handler = self
-
-
case method
-
when NilClass
-
raise "Delivery method cannot be nil"
-
when Symbol
-
if klass = delivery_methods[method]
-
mail.delivery_method(klass, (send(:"#{method}_settings") || {}).merge(options || {}))
-
else
-
raise "Invalid delivery method #{method.inspect}"
-
end
-
else
-
mail.delivery_method(method)
-
end
-
-
mail.perform_deliveries = perform_deliveries
-
mail.raise_delivery_errors = raise_delivery_errors
-
end
-
end
-
-
2
def wrap_delivery_behavior!(*args) # :nodoc:
-
self.class.wrap_delivery_behavior(message, *args)
-
end
-
end
-
end
-
2
module ActionMailer
-
# Returns the version of the currently loaded ActionMailer as a <tt>Gem::Version</tt>
-
2
def self.gem_version
-
Gem::Version.new VERSION::STRING
-
end
-
-
2
module VERSION
-
2
MAJOR = 4
-
2
MINOR = 1
-
2
TINY = 8
-
2
PRE = nil
-
-
2
STRING = [MAJOR, MINOR, TINY, PRE].compact.join(".")
-
end
-
end
-
2
require 'active_support/log_subscriber'
-
-
2
module ActionMailer
-
# Implements the ActiveSupport::LogSubscriber for logging notifications when
-
# email is delivered and received.
-
2
class LogSubscriber < ActiveSupport::LogSubscriber
-
# An email was delivered.
-
2
def deliver(event)
-
return unless logger.info?
-
recipients = Array(event.payload[:to]).join(', ')
-
info("\nSent mail to #{recipients} (#{event.duration.round(1)}ms)")
-
debug(event.payload[:mail])
-
end
-
-
# An email was received.
-
2
def receive(event)
-
return unless logger.info?
-
info("\nReceived mail (#{event.duration.round(1)}ms)")
-
debug(event.payload[:mail])
-
end
-
-
# An email was generated.
-
2
def process(event)
-
mailer = event.payload[:mailer]
-
action = event.payload[:action]
-
debug("\n#{mailer}##{action}: processed outbound mail in #{event.duration.round(1)}ms")
-
end
-
-
# Use the logger configured for ActionMailer::Base
-
2
def logger
-
ActionMailer::Base.logger
-
end
-
end
-
end
-
-
2
ActionMailer::LogSubscriber.attach_to :action_mailer
-
2
module ActionMailer
-
# Provides helper methods for ActionMailer::Base that can be used for easily
-
# formatting messages, accessing mailer or message instances, and the
-
# attachments list.
-
2
module MailHelper
-
# Take the text and format it, indented two spaces for each line, and
-
# wrapped at 72 columns.
-
2
def block_format(text)
-
formatted = text.split(/\n\r?\n/).collect { |paragraph|
-
format_paragraph(paragraph)
-
}.join("\n\n")
-
-
# Make list points stand on their own line
-
formatted.gsub!(/[ ]*([*]+) ([^*]*)/) { |s| " #{$1} #{$2.strip}\n" }
-
formatted.gsub!(/[ ]*([#]+) ([^#]*)/) { |s| " #{$1} #{$2.strip}\n" }
-
-
formatted
-
end
-
-
# Access the mailer instance.
-
2
def mailer
-
@_controller
-
end
-
-
# Access the message instance.
-
2
def message
-
@_message
-
end
-
-
# Access the message attachments list.
-
2
def attachments
-
mailer.attachments
-
end
-
-
# Returns +text+ wrapped at +len+ columns and indented +indent+ spaces.
-
#
-
# my_text = 'Here is a sample text with more than 40 characters'
-
#
-
# format_paragraph(my_text, 25, 4)
-
# # => " Here is a sample text with\n more than 40 characters"
-
2
def format_paragraph(text, len = 72, indent = 2)
-
sentences = [[]]
-
-
text.split.each do |word|
-
if sentences.first.present? && (sentences.last + [word]).join(' ').length > len
-
sentences << [word]
-
else
-
sentences.last << word
-
end
-
end
-
-
indentation = " " * indent
-
sentences.map! { |sentence|
-
"#{indentation}#{sentence.join(' ')}"
-
}.join "\n"
-
end
-
end
-
end
-
2
require "action_mailer"
-
2
require "rails"
-
2
require "abstract_controller/railties/routes_helpers"
-
-
2
module ActionMailer
-
2
class Railtie < Rails::Railtie # :nodoc:
-
2
config.action_mailer = ActiveSupport::OrderedOptions.new
-
2
config.eager_load_namespaces << ActionMailer
-
-
2
initializer "action_mailer.logger" do
-
4
ActiveSupport.on_load(:action_mailer) { self.logger ||= Rails.logger }
-
end
-
-
2
initializer "action_mailer.set_configs" do |app|
-
2
paths = app.config.paths
-
2
options = app.config.action_mailer
-
-
2
options.assets_dir ||= paths["public"].first
-
2
options.javascripts_dir ||= paths["public/javascripts"].first
-
2
options.stylesheets_dir ||= paths["public/stylesheets"].first
-
-
2
if Rails.env.development?
-
options.preview_path ||= defined?(Rails.root) ? "#{Rails.root}/test/mailers/previews" : nil
-
end
-
-
# make sure readers methods get compiled
-
2
options.asset_host ||= app.config.asset_host
-
2
options.relative_url_root ||= app.config.relative_url_root
-
-
2
ActiveSupport.on_load(:action_mailer) do
-
2
include AbstractController::UrlFor
-
2
extend ::AbstractController::Railties::RoutesHelpers.with(app.routes)
-
2
include app.routes.mounted_helpers
-
-
2
register_interceptors(options.delete(:interceptors))
-
2
register_preview_interceptors(options.delete(:preview_interceptors))
-
2
register_observers(options.delete(:observers))
-
-
14
options.each { |k,v| send("#{k}=", v) }
-
end
-
end
-
-
2
initializer "action_mailer.compile_config_methods" do
-
2
ActiveSupport.on_load(:action_mailer) do
-
2
config.compile_methods! if config.respond_to?(:compile_methods!)
-
end
-
end
-
-
2
config.after_initialize do
-
2
if ActionMailer::Base.preview_path
-
ActiveSupport::Dependencies.autoload_paths << ActionMailer::Base.preview_path
-
end
-
end
-
end
-
end
-
1
require 'active_support/test_case'
-
-
1
module ActionMailer
-
1
class NonInferrableMailerError < ::StandardError
-
1
def initialize(name)
-
super "Unable to determine the mailer to test from #{name}. " +
-
"You'll need to specify it using tests YourMailer in your " +
-
"test case definition"
-
end
-
end
-
-
1
class TestCase < ActiveSupport::TestCase
-
1
module Behavior
-
1
extend ActiveSupport::Concern
-
-
1
include ActiveSupport::Testing::ConstantLookup
-
1
include TestHelper
-
-
1
included do
-
1
class_attribute :_mailer_class
-
1
setup :initialize_test_deliveries
-
1
setup :set_expected_mail
-
end
-
-
1
module ClassMethods
-
1
def tests(mailer)
-
case mailer
-
when String, Symbol
-
self._mailer_class = mailer.to_s.camelize.constantize
-
when Module
-
self._mailer_class = mailer
-
else
-
raise NonInferrableMailerError.new(mailer)
-
end
-
end
-
-
1
def mailer_class
-
if mailer = self._mailer_class
-
mailer
-
else
-
tests determine_default_mailer(name)
-
end
-
end
-
-
1
def determine_default_mailer(name)
-
mailer = determine_constant_from_test_name(name) do |constant|
-
Class === constant && constant < ActionMailer::Base
-
end
-
raise NonInferrableMailerError.new(name) if mailer.nil?
-
mailer
-
end
-
end
-
-
1
protected
-
-
1
def initialize_test_deliveries
-
ActionMailer::Base.delivery_method = :test
-
ActionMailer::Base.perform_deliveries = true
-
ActionMailer::Base.deliveries.clear
-
end
-
-
1
def set_expected_mail
-
@expected = Mail.new
-
@expected.content_type ["text", "plain", { "charset" => charset }]
-
@expected.mime_version = '1.0'
-
end
-
-
1
private
-
-
1
def charset
-
"UTF-8"
-
end
-
-
1
def encode(subject)
-
Mail::Encodings.q_value_encode(subject, charset)
-
end
-
-
1
def read_fixture(action)
-
IO.readlines(File.join(Rails.root, 'test', 'fixtures', self.class.mailer_class.name.underscore, action))
-
end
-
end
-
-
1
include Behavior
-
end
-
end
-
1
module ActionMailer
-
1
module TestHelper
-
# Asserts that the number of emails sent matches the given number.
-
#
-
# def test_emails
-
# assert_emails 0
-
# ContactMailer.welcome.deliver
-
# assert_emails 1
-
# ContactMailer.welcome.deliver
-
# assert_emails 2
-
# end
-
#
-
# If a block is passed, that block should cause the specified number of
-
# emails to be sent.
-
#
-
# def test_emails_again
-
# assert_emails 1 do
-
# ContactMailer.welcome.deliver
-
# end
-
#
-
# assert_emails 2 do
-
# ContactMailer.welcome.deliver
-
# ContactMailer.welcome.deliver
-
# end
-
# end
-
1
def assert_emails(number)
-
if block_given?
-
original_count = ActionMailer::Base.deliveries.size
-
yield
-
new_count = ActionMailer::Base.deliveries.size
-
assert_equal original_count + number, new_count, "#{number} emails expected, but #{new_count - original_count} were sent"
-
else
-
assert_equal number, ActionMailer::Base.deliveries.size
-
end
-
end
-
-
# Assert that no emails have been sent.
-
#
-
# def test_emails
-
# assert_no_emails
-
# ContactMailer.welcome.deliver
-
# assert_emails 1
-
# end
-
#
-
# If a block is passed, that block should not cause any emails to be sent.
-
#
-
# def test_emails_again
-
# assert_no_emails do
-
# # No emails should be sent from this block
-
# end
-
# end
-
#
-
# Note: This assertion is simply a shortcut for:
-
#
-
# assert_emails 0
-
1
def assert_no_emails(&block)
-
assert_emails 0, &block
-
end
-
end
-
end
-
2
require_relative 'gem_version'
-
-
2
module ActionMailer
-
# Returns the version of the currently loaded ActionMailer as a <tt>Gem::Version</tt>
-
2
def self.version
-
gem_version
-
end
-
end
-
2
require 'action_pack'
-
2
require 'active_support/rails'
-
2
require 'active_support/core_ext/module/attr_internal'
-
2
require 'active_support/core_ext/module/anonymous'
-
2
require 'active_support/i18n'
-
-
2
module AbstractController
-
2
extend ActiveSupport::Autoload
-
-
2
autoload :Base
-
2
autoload :Callbacks
-
2
autoload :Collector
-
2
autoload :DoubleRenderError, "abstract_controller/rendering"
-
2
autoload :Helpers
-
2
autoload :Logger
-
2
autoload :Rendering
-
2
autoload :Translation
-
2
autoload :AssetPaths
-
2
autoload :UrlFor
-
end
-
2
module AbstractController
-
2
module AssetPaths #:nodoc:
-
2
extend ActiveSupport::Concern
-
-
2
included do
-
4
config_accessor :asset_host, :assets_dir, :javascripts_dir,
-
:stylesheets_dir, :default_asset_host_protocol, :relative_url_root
-
end
-
end
-
end
-
2
require 'erubis'
-
2
require 'set'
-
2
require 'active_support/configurable'
-
2
require 'active_support/descendants_tracker'
-
2
require 'active_support/core_ext/module/anonymous'
-
-
2
module AbstractController
-
2
class Error < StandardError #:nodoc:
-
end
-
-
2
class ActionNotFound < StandardError #:nodoc:
-
end
-
-
# <tt>AbstractController::Base</tt> is a low-level API. Nobody should be
-
# using it directly, and subclasses (like ActionController::Base) are
-
# expected to provide their own +render+ method, since rendering means
-
# different things depending on the context.
-
2
class Base
-
2
attr_internal :response_body
-
2
attr_internal :action_name
-
2
attr_internal :formats
-
-
2
include ActiveSupport::Configurable
-
2
extend ActiveSupport::DescendantsTracker
-
-
2
undef_method :not_implemented
-
2
class << self
-
2
attr_reader :abstract
-
2
alias_method :abstract?, :abstract
-
-
# Define a controller as abstract. See internal_methods for more
-
# details.
-
2
def abstract!
-
8
@abstract = true
-
end
-
-
2
def inherited(klass) # :nodoc:
-
# Define the abstract ivar on subclasses so that we don't get
-
# uninitialized ivar warnings
-
19
unless klass.instance_variable_defined?(:@abstract)
-
19
klass.instance_variable_set(:@abstract, false)
-
end
-
19
super
-
end
-
-
# A list of all internal methods for a controller. This finds the first
-
# abstract superclass of a controller, and gets a list of all public
-
# instance methods on that abstract class. Public instance methods of
-
# a controller would normally be considered action methods, so methods
-
# declared on abstract classes are being removed.
-
# (ActionController::Metal and ActionController::Base are defined as abstract)
-
2
def internal_methods
-
10
controller = self
-
-
10
controller = controller.superclass until controller.abstract?
-
10
controller.public_instance_methods(true)
-
end
-
-
# The list of hidden actions. Defaults to an empty array.
-
# This can be modified by other modules or subclasses
-
# to specify particular actions as hidden.
-
#
-
# ==== Returns
-
# * <tt>Array</tt> - An array of method names that should not be considered actions.
-
2
def hidden_actions
-
2
[]
-
end
-
-
# A list of method names that should be considered actions. This
-
# includes all public instance methods on a controller, less
-
# any internal methods (see #internal_methods), adding back in
-
# any methods that are internal, but still exist on the class
-
# itself. Finally, #hidden_actions are removed.
-
#
-
# ==== Returns
-
# * <tt>Set</tt> - A set of all methods that should be considered actions.
-
2
def action_methods
-
@action_methods ||= begin
-
# All public instance methods of this class, including ancestors
-
10
methods = (public_instance_methods(true) -
-
# Except for public instance methods of Base and its ancestors
-
internal_methods +
-
# Be sure to include shadowed public instance methods of this class
-
1434
public_instance_methods(false)).uniq.map { |x| x.to_s } -
-
# And always exclude explicitly hidden actions
-
hidden_actions.to_a
-
-
# Clear out AS callback method pollution
-
1426
Set.new(methods.reject { |method| method =~ /_one_time_conditions/ })
-
10
end
-
end
-
-
# action_methods are cached and there is sometimes need to refresh
-
# them. clear_action_methods! allows you to do that, so next time
-
# you run action_methods, they will be recalculated
-
2
def clear_action_methods!
-
490
@action_methods = nil
-
end
-
-
# Returns the full controller name, underscored, without the ending Controller.
-
# For instance, MyApp::MyPostsController would return "my_app/my_posts" for
-
# controller_path.
-
#
-
# ==== Returns
-
# * <tt>String</tt>
-
2
def controller_path
-
77
@controller_path ||= name.sub(/Controller$/, '').underscore unless anonymous?
-
end
-
-
# Refresh the cached action_methods when a new action_method is added.
-
2
def method_added(name)
-
490
super
-
490
clear_action_methods!
-
end
-
end
-
-
2
abstract!
-
-
# Calls the action going through the entire action dispatch stack.
-
#
-
# The actual method that is called is determined by calling
-
# #method_for_action. If no method can handle the action, then an
-
# ActionNotFound error is raised.
-
#
-
# ==== Returns
-
# * <tt>self</tt>
-
2
def process(action, *args)
-
24
@_action_name = action_name = action.to_s
-
-
24
unless action_name = _find_action_name(action_name)
-
raise ActionNotFound, "The action '#{action}' could not be found for #{self.class.name}"
-
end
-
-
24
@_response_body = nil
-
-
24
process_action(action_name, *args)
-
end
-
-
# Delegates to the class' #controller_path
-
2
def controller_path
-
24
self.class.controller_path
-
end
-
-
# Delegates to the class' #action_methods
-
2
def action_methods
-
self.class.action_methods
-
end
-
-
# Returns true if a method for the action is available and
-
# can be dispatched, false otherwise.
-
#
-
# Notice that <tt>action_methods.include?("foo")</tt> may return
-
# false and <tt>available_action?("foo")</tt> returns true because
-
# this method considers actions that are also available
-
# through other means, for example, implicit render ones.
-
#
-
# ==== Parameters
-
# * <tt>action_name</tt> - The name of an action to be tested
-
#
-
# ==== Returns
-
# * <tt>TrueClass</tt>, <tt>FalseClass</tt>
-
2
def available_action?(action_name)
-
_find_action_name(action_name).present?
-
end
-
-
2
private
-
-
# Returns true if the name can be considered an action because
-
# it has a method defined in the controller.
-
#
-
# ==== Parameters
-
# * <tt>name</tt> - The name of an action to be tested
-
#
-
# ==== Returns
-
# * <tt>TrueClass</tt>, <tt>FalseClass</tt>
-
#
-
# :api: private
-
2
def action_method?(name)
-
24
self.class.action_methods.include?(name)
-
end
-
-
# Call the action. Override this in a subclass to modify the
-
# behavior around processing an action. This, and not #process,
-
# is the intended way to override action dispatching.
-
#
-
# Notice that the first argument is the method to be dispatched
-
# which is *not* necessarily the same as the action name.
-
2
def process_action(method_name, *args)
-
24
send_action(method_name, *args)
-
end
-
-
# Actually call the method associated with the action. Override
-
# this method if you wish to change how action methods are called,
-
# not to add additional behavior around it. For example, you would
-
# override #send_action if you want to inject arguments into the
-
# method.
-
2
alias send_action send
-
-
# If the action name was not found, but a method called "action_missing"
-
# was found, #method_for_action will return "_handle_action_missing".
-
# This method calls #action_missing with the current action name.
-
2
def _handle_action_missing(*args)
-
action_missing(@_action_name, *args)
-
end
-
-
# Takes an action name and returns the name of the method that will
-
# handle the action.
-
#
-
# It checks if the action name is valid and returns false otherwise.
-
#
-
# See method_for_action for more information.
-
#
-
# ==== Parameters
-
# * <tt>action_name</tt> - An action name to find a method name for
-
#
-
# ==== Returns
-
# * <tt>string</tt> - The name of the method that handles the action
-
# * false - No valid method name could be found. Raise ActionNotFound.
-
2
def _find_action_name(action_name)
-
24
_valid_action_name?(action_name) && method_for_action(action_name)
-
end
-
-
# Takes an action name and returns the name of the method that will
-
# handle the action. In normal cases, this method returns the same
-
# name as it receives. By default, if #method_for_action receives
-
# a name that is not an action, it will look for an #action_missing
-
# method and return "_handle_action_missing" if one is found.
-
#
-
# Subclasses may override this method to add additional conditions
-
# that should be considered an action. For instance, an HTTP controller
-
# with a template matching the action name is considered to exist.
-
#
-
# If you override this method to handle additional cases, you may
-
# also provide a method (like _handle_method_missing) to handle
-
# the case.
-
#
-
# If none of these conditions are true, and method_for_action
-
# returns nil, an ActionNotFound exception will be raised.
-
#
-
# ==== Parameters
-
# * <tt>action_name</tt> - An action name to find a method name for
-
#
-
# ==== Returns
-
# * <tt>string</tt> - The name of the method that handles the action
-
# * <tt>nil</tt> - No method name could be found.
-
2
def method_for_action(action_name)
-
24
if action_method?(action_name)
-
24
action_name
-
elsif respond_to?(:action_missing, true)
-
"_handle_action_missing"
-
end
-
end
-
-
# Checks if the action name is valid and returns false otherwise.
-
2
def _valid_action_name?(action_name)
-
24
!action_name.to_s.include? File::SEPARATOR
-
end
-
end
-
end
-
2
module AbstractController
-
2
module Callbacks
-
2
extend ActiveSupport::Concern
-
-
# Uses ActiveSupport::Callbacks as the base functionality. For
-
# more details on the whole callback system, read the documentation
-
# for ActiveSupport::Callbacks.
-
2
include ActiveSupport::Callbacks
-
-
2
included do
-
4
define_callbacks :process_action,
-
72
terminator: ->(controller,_) { controller.response_body },
-
skip_after_callbacks_if_terminated: true
-
end
-
-
# Override AbstractController::Base's process_action to run the
-
# process_action callbacks around the normal behavior.
-
2
def process_action(*args)
-
24
run_callbacks(:process_action) do
-
24
super
-
end
-
end
-
-
2
module ClassMethods
-
# If :only or :except are used, convert the options into the
-
# :unless and :if options of ActiveSupport::Callbacks.
-
# The basic idea is that :only => :index gets converted to
-
# :if => proc {|c| c.action_name == "index" }.
-
#
-
# ==== Options
-
# * <tt>only</tt> - The callback should be run only for this action
-
# * <tt>except</tt> - The callback should be run for all actions except this action
-
2
def _normalize_callback_options(options)
-
10
_normalize_callback_option(options, :only, :if)
-
10
_normalize_callback_option(options, :except, :unless)
-
end
-
-
2
def _normalize_callback_option(options, from, to) # :nodoc:
-
20
if from = options[from]
-
from = Array(from).map {|o| "action_name == '#{o}'"}.join(" || ")
-
options[to] = Array(options[to]).unshift(from)
-
end
-
end
-
-
# Skip before, after, and around action callbacks matching any of the names
-
# Aliased as skip_filter.
-
#
-
# ==== Parameters
-
# * <tt>names</tt> - A list of valid names that could be used for
-
# callbacks. Note that skipping uses Ruby equality, so it's
-
# impossible to skip a callback defined using an anonymous proc
-
# using #skip_filter
-
2
def skip_action_callback(*names)
-
skip_before_action(*names)
-
skip_after_action(*names)
-
skip_around_action(*names)
-
end
-
-
2
alias_method :skip_filter, :skip_action_callback
-
-
# Take callback names and an optional callback proc, normalize them,
-
# then call the block with each callback. This allows us to abstract
-
# the normalization across several methods that use it.
-
#
-
# ==== Parameters
-
# * <tt>callbacks</tt> - An array of callbacks, with an optional
-
# options hash as the last parameter.
-
# * <tt>block</tt> - A proc that should be added to the callbacks.
-
#
-
# ==== Block Parameters
-
# * <tt>name</tt> - The callback to be added
-
# * <tt>options</tt> - A hash of options to be used when adding the callback
-
2
def _insert_callbacks(callbacks, block = nil)
-
10
options = callbacks.extract_options!
-
10
_normalize_callback_options(options)
-
10
callbacks.push(block) if block
-
10
callbacks.each do |callback|
-
12
yield callback, options
-
end
-
end
-
-
##
-
# :method: before_action
-
#
-
# :call-seq: before_action(names, block)
-
#
-
# Append a callback before actions. See _insert_callbacks for parameter details.
-
# Aliased as before_filter.
-
-
##
-
# :method: prepend_before_action
-
#
-
# :call-seq: prepend_before_action(names, block)
-
#
-
# Prepend a callback before actions. See _insert_callbacks for parameter details.
-
# Aliased as prepend_before_filter.
-
-
##
-
# :method: skip_before_action
-
#
-
# :call-seq: skip_before_action(names)
-
#
-
# Skip a callback before actions. See _insert_callbacks for parameter details.
-
# Aliased as skip_before_filter.
-
-
##
-
# :method: append_before_action
-
#
-
# :call-seq: append_before_action(names, block)
-
#
-
# Append a callback before actions. See _insert_callbacks for parameter details.
-
# Aliased as append_before_filter.
-
-
##
-
# :method: after_action
-
#
-
# :call-seq: after_action(names, block)
-
#
-
# Append a callback after actions. See _insert_callbacks for parameter details.
-
# Aliased as after_filter.
-
-
##
-
# :method: prepend_after_action
-
#
-
# :call-seq: prepend_after_action(names, block)
-
#
-
# Prepend a callback after actions. See _insert_callbacks for parameter details.
-
# Aliased as prepend_after_filter.
-
-
##
-
# :method: skip_after_action
-
#
-
# :call-seq: skip_after_action(names)
-
#
-
# Skip a callback after actions. See _insert_callbacks for parameter details.
-
# Aliased as skip_after_filter.
-
-
##
-
# :method: append_after_action
-
#
-
# :call-seq: append_after_action(names, block)
-
#
-
# Append a callback after actions. See _insert_callbacks for parameter details.
-
# Aliased as append_after_filter.
-
-
##
-
# :method: around_action
-
#
-
# :call-seq: around_action(names, block)
-
#
-
# Append a callback around actions. See _insert_callbacks for parameter details.
-
# Aliased as around_filter.
-
-
##
-
# :method: prepend_around_action
-
#
-
# :call-seq: prepend_around_action(names, block)
-
#
-
# Prepend a callback around actions. See _insert_callbacks for parameter details.
-
# Aliased as prepend_around_filter.
-
-
##
-
# :method: skip_around_action
-
#
-
# :call-seq: skip_around_action(names)
-
#
-
# Skip a callback around actions. See _insert_callbacks for parameter details.
-
# Aliased as skip_around_filter.
-
-
##
-
# :method: append_around_action
-
#
-
# :call-seq: append_around_action(names, block)
-
#
-
# Append a callback around actions. See _insert_callbacks for parameter details.
-
# Aliased as append_around_filter.
-
-
# set up before_action, prepend_before_action, skip_before_action, etc.
-
# for each of before, after, and around.
-
2
[:before, :after, :around].each do |callback|
-
6
class_eval <<-RUBY_EVAL, __FILE__, __LINE__ + 1
-
# Append a before, after or around callback. See _insert_callbacks
-
# for details on the allowed parameters.
-
def #{callback}_action(*names, &blk) # def before_action(*names, &blk)
-
_insert_callbacks(names, blk) do |name, options| # _insert_callbacks(names, blk) do |name, options|
-
set_callback(:process_action, :#{callback}, name, options) # set_callback(:process_action, :before, name, options)
-
end # end
-
end # end
-
-
alias_method :#{callback}_filter, :#{callback}_action
-
-
# Prepend a before, after or around callback. See _insert_callbacks
-
# for details on the allowed parameters.
-
def prepend_#{callback}_action(*names, &blk) # def prepend_before_action(*names, &blk)
-
_insert_callbacks(names, blk) do |name, options| # _insert_callbacks(names, blk) do |name, options|
-
set_callback(:process_action, :#{callback}, name, options.merge(:prepend => true)) # set_callback(:process_action, :before, name, options.merge(:prepend => true))
-
end # end
-
end # end
-
-
alias_method :prepend_#{callback}_filter, :prepend_#{callback}_action
-
-
# Skip a before, after or around callback. See _insert_callbacks
-
# for details on the allowed parameters.
-
def skip_#{callback}_action(*names) # def skip_before_action(*names)
-
_insert_callbacks(names) do |name, options| # _insert_callbacks(names) do |name, options|
-
skip_callback(:process_action, :#{callback}, name, options) # skip_callback(:process_action, :before, name, options)
-
end # end
-
end # end
-
-
alias_method :skip_#{callback}_filter, :skip_#{callback}_action
-
-
# *_action is the same as append_*_action
-
alias_method :append_#{callback}_action, :#{callback}_action # alias_method :append_before_action, :before_action
-
alias_method :append_#{callback}_filter, :#{callback}_action # alias_method :append_before_filter, :before_action
-
RUBY_EVAL
-
end
-
end
-
end
-
end
-
2
require "action_dispatch/http/mime_type"
-
-
2
module AbstractController
-
2
module Collector
-
2
def self.generate_method_for_mime(mime)
-
44
sym = mime.is_a?(Symbol) ? mime : mime.to_sym
-
44
const = sym.upcase
-
44
class_eval <<-RUBY, __FILE__, __LINE__ + 1
-
def #{sym}(*args, &block) # def html(*args, &block)
-
custom(Mime::#{const}, *args, &block) # custom(Mime::HTML, *args, &block)
-
end # end
-
RUBY
-
end
-
-
2
Mime::SET.each do |mime|
-
44
generate_method_for_mime(mime)
-
end
-
-
2
Mime::Type.register_callback do |mime|
-
generate_method_for_mime(mime) unless self.instance_methods.include?(mime.to_sym)
-
end
-
-
2
protected
-
-
2
def method_missing(symbol, &block)
-
const_name = symbol.upcase
-
-
unless Mime.const_defined?(const_name)
-
raise NoMethodError, "To respond to a custom format, register it as a MIME type first: " \
-
"http://guides.rubyonrails.org/action_controller_overview.html#restful-downloads. " \
-
"If you meant to respond to a variant like :tablet or :phone, not a custom format, " \
-
"be sure to nest your variant response within a format response: " \
-
"format.html { |html| html.tablet { ... } }"
-
end
-
-
mime_constant = Mime.const_get(const_name)
-
-
if Mime::SET.include?(mime_constant)
-
AbstractController::Collector.generate_method_for_mime(mime_constant)
-
send(symbol, &block)
-
else
-
super
-
end
-
end
-
end
-
end
-
2
require 'active_support/dependencies'
-
-
2
module AbstractController
-
2
module Helpers
-
2
extend ActiveSupport::Concern
-
-
2
included do
-
5
class_attribute :_helpers
-
5
self._helpers = Module.new
-
-
5
class_attribute :_helper_methods
-
5
self._helper_methods = Array.new
-
end
-
-
2
class MissingHelperError < LoadError
-
2
def initialize(error, path)
-
1
@error = error
-
1
@path = "helpers/#{path}.rb"
-
1
set_backtrace error.backtrace
-
-
1
if error.path =~ /^#{path}(\.rb)?$/
-
1
super("Missing helper file helpers/%s.rb" % path)
-
else
-
raise error
-
end
-
end
-
end
-
-
2
module ClassMethods
-
2
MissingHelperError = ActiveSupport::Deprecation::DeprecatedConstantProxy.new('AbstractController::Helpers::ClassMethods::MissingHelperError',
-
'AbstractController::Helpers::MissingHelperError')
-
-
# When a class is inherited, wrap its helper module in a new module.
-
# This ensures that the parent class's module can be changed
-
# independently of the child class's.
-
2
def inherited(klass)
-
13
helpers = _helpers
-
26
klass._helpers = Module.new { include helpers }
-
26
klass.class_eval { default_helper_module! } unless klass.anonymous?
-
13
super
-
end
-
-
# Declare a controller method as a helper. For example, the following
-
# makes the +current_user+ controller method available to the view:
-
# class ApplicationController < ActionController::Base
-
# helper_method :current_user, :logged_in?
-
#
-
# def current_user
-
# @current_user ||= User.find_by(id: session[:user])
-
# end
-
#
-
# def logged_in?
-
# current_user != nil
-
# end
-
# end
-
#
-
# In a view:
-
# <% if logged_in? -%>Welcome, <%= current_user.name %><% end -%>
-
#
-
# ==== Parameters
-
# * <tt>method[, method]</tt> - A name or names of a method on the controller
-
# to be made available on the view.
-
2
def helper_method(*meths)
-
16
meths.flatten!
-
16
self._helper_methods += meths
-
-
16
meths.each do |meth|
-
20
_helpers.class_eval <<-ruby_eval, __FILE__, __LINE__ + 1
-
def #{meth}(*args, &blk) # def current_user(*args, &blk)
-
controller.send(%(#{meth}), *args, &blk) # controller.send(:current_user, *args, &blk)
-
end # end
-
ruby_eval
-
end
-
end
-
-
# The +helper+ class method can take a series of helper module names, a block, or both.
-
#
-
# ==== Options
-
# * <tt>*args</tt> - Module, Symbol, String
-
# * <tt>block</tt> - A block defining helper methods
-
#
-
# When the argument is a module it will be included directly in the template class.
-
# helper FooHelper # => includes FooHelper
-
#
-
# When the argument is a string or symbol, the method will provide the "_helper" suffix, require the file
-
# and include the module in the template class. The second form illustrates how to include custom helpers
-
# when working with namespaced controllers, or other cases where the file containing the helper definition is not
-
# in one of Rails' standard load paths:
-
# helper :foo # => requires 'foo_helper' and includes FooHelper
-
# helper 'resources/foo' # => requires 'resources/foo_helper' and includes Resources::FooHelper
-
#
-
# Additionally, the +helper+ class method can receive and evaluate a block, making the methods defined available
-
# to the template.
-
#
-
# # One line
-
# helper { def hello() "Hello, world!" end }
-
#
-
# # Multi-line
-
# helper do
-
# def foo(bar)
-
# "#{bar} is the very best"
-
# end
-
# end
-
#
-
# Finally, all the above styles can be mixed together, and the +helper+ method can be invoked with a mix of
-
# +symbols+, +strings+, +modules+ and blocks.
-
#
-
# helper(:three, BlindHelper) { def mice() 'mice' end }
-
#
-
2
def helper(*args, &block)
-
28
modules_for_helpers(args).each do |mod|
-
108
add_template_helper(mod)
-
end
-
-
27
_helpers.module_eval(&block) if block_given?
-
end
-
-
# Clears up all existing helpers in this class, only keeping the helper
-
# with the same name as this class.
-
2
def clear_helpers
-
inherited_helper_methods = _helper_methods
-
self._helpers = Module.new
-
self._helper_methods = Array.new
-
-
inherited_helper_methods.each { |meth| helper_method meth }
-
default_helper_module! unless anonymous?
-
end
-
-
# Returns a list of modules, normalized from the acceptable kinds of
-
# helpers with the following behavior:
-
#
-
# String or Symbol:: :FooBar or "FooBar" becomes "foo_bar_helper",
-
# and "foo_bar_helper.rb" is loaded using require_dependency.
-
#
-
# Module:: No further processing
-
#
-
# After loading the appropriate files, the corresponding modules
-
# are returned.
-
#
-
# ==== Parameters
-
# * <tt>args</tt> - An array of helpers
-
#
-
# ==== Returns
-
# * <tt>Array</tt> - A normalized list of modules for the list of
-
# helpers provided.
-
2
def modules_for_helpers(args)
-
28
args.flatten.map! do |arg|
-
109
case arg
-
when String, Symbol
-
97
file_name = "#{arg.to_s.underscore}_helper"
-
97
begin
-
97
require_dependency(file_name)
-
rescue LoadError => e
-
1
raise AbstractController::Helpers::MissingHelperError.new(e, file_name)
-
end
-
96
file_name.camelize.constantize
-
when Module
-
12
arg
-
else
-
raise ArgumentError, "helper must be a String, Symbol, or Module"
-
end
-
end
-
end
-
-
2
private
-
# Makes all the (instance) methods in the helper module available to templates
-
# rendered through this controller.
-
#
-
# ==== Parameters
-
# * <tt>module</tt> - The module to include into the current helper module
-
# for the class
-
2
def add_template_helper(mod)
-
216
_helpers.module_eval { include mod }
-
end
-
-
2
def default_helper_module!
-
13
module_name = name.sub(/Controller$/, '')
-
13
module_path = module_name.underscore
-
13
helper module_path
-
rescue MissingSourceFile => e
-
1
raise e unless e.is_missing? "helpers/#{module_path}_helper"
-
rescue NameError => e
-
raise e unless e.missing_name? "#{module_name}Helper"
-
end
-
end
-
end
-
end
-
2
require "active_support/benchmarkable"
-
-
2
module AbstractController
-
2
module Logger #:nodoc:
-
2
extend ActiveSupport::Concern
-
-
2
included do
-
4
config_accessor :logger
-
4
include ActiveSupport::Benchmarkable
-
end
-
end
-
end
-
2
module AbstractController
-
2
module Railties
-
2
module RoutesHelpers
-
2
def self.with(routes)
-
4
Module.new do
-
4
define_method(:inherited) do |klass|
-
13
super(klass)
-
28
if namespace = klass.parents.detect { |m| m.respond_to?(:railtie_routes_url_helpers) }
-
klass.send(:include, namespace.railtie_routes_url_helpers)
-
else
-
13
klass.send(:include, routes.url_helpers)
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
2
require 'active_support/concern'
-
2
require 'active_support/core_ext/class/attribute'
-
2
require 'action_view'
-
2
require 'action_view/view_paths'
-
2
require 'set'
-
-
2
module AbstractController
-
2
class DoubleRenderError < Error
-
2
DEFAULT_MESSAGE = "Render and/or redirect were called multiple times in this action. Please note that you may only call render OR redirect, and at most once per action. Also note that neither redirect nor render terminate execution of the action, so if you want to exit an action after redirecting, you need to do something like \"redirect_to(...) and return\"."
-
-
2
def initialize(message = nil)
-
super(message || DEFAULT_MESSAGE)
-
end
-
end
-
-
2
module Rendering
-
2
extend ActiveSupport::Concern
-
2
include ActionView::ViewPaths
-
-
# Normalize arguments, options and then delegates render_to_body and
-
# sticks the result in self.response_body.
-
# :api: public
-
2
def render(*args, &block)
-
24
options = _normalize_render(*args, &block)
-
24
self.response_body = render_to_body(options)
-
24
_process_format(rendered_format, options) if rendered_format
-
24
self.response_body
-
end
-
-
# Raw rendering of a template to a string.
-
#
-
# It is similar to render, except that it does not
-
# set the response_body and it should be guaranteed
-
# to always return a string.
-
#
-
# If a component extends the semantics of response_body
-
# (as Action Controller extends it to be anything that
-
# responds to the method each), this method needs to be
-
# overridden in order to still return a string.
-
# :api: plugin
-
2
def render_to_string(*args, &block)
-
options = _normalize_render(*args, &block)
-
render_to_body(options)
-
end
-
-
# Performs the actual template rendering.
-
# :api: public
-
2
def render_to_body(options = {})
-
end
-
-
# Returns Content-Type of rendered content
-
# :api: public
-
2
def rendered_format
-
Mime::TEXT
-
end
-
-
2
DEFAULT_PROTECTED_INSTANCE_VARIABLES = Set.new %w(
-
@_action_name @_response_body @_formats @_prefixes @_config
-
@_view_context_class @_view_renderer @_lookup_context
-
@_routes @_db_runtime
-
).map(&:to_sym)
-
-
# This method should return a hash with assigns.
-
# You can overwrite this configuration per controller.
-
# :api: public
-
2
def view_assigns
-
35
protected_vars = _protected_ivars
-
35
variables = instance_variables
-
-
662
variables.reject! { |s| protected_vars.include? s }
-
35
variables.each_with_object({}) { |name, hash|
-
43
hash[name.slice(1, name.length)] = instance_variable_get(name)
-
}
-
end
-
-
# Normalize args by converting render "foo" to render :action => "foo" and
-
# render "foo/bar" to render :file => "foo/bar".
-
# :api: plugin
-
2
def _normalize_args(action=nil, options={})
-
24
if action.is_a? Hash
-
action
-
else
-
24
options
-
end
-
end
-
-
# Normalize options.
-
# :api: plugin
-
2
def _normalize_options(options)
-
24
options
-
end
-
-
# Process extra options.
-
# :api: plugin
-
2
def _process_options(options)
-
24
options
-
end
-
-
# Process the rendered format.
-
# :api: private
-
2
def _process_format(format, options = {})
-
end
-
-
# Normalize args and options.
-
# :api: private
-
2
def _normalize_render(*args, &block)
-
24
options = _normalize_args(*args, &block)
-
#TODO: remove defined? when we restore AP <=> AV dependency
-
24
if defined?(request) && request && request.variant.present?
-
options[:variant] = request.variant
-
end
-
24
_normalize_options(options)
-
24
options
-
end
-
-
2
def _protected_ivars # :nodoc:
-
DEFAULT_PROTECTED_INSTANCE_VARIABLES
-
end
-
end
-
end
-
2
module AbstractController
-
2
module Translation
-
# Delegates to <tt>I18n.translate</tt>. Also aliased as <tt>t</tt>.
-
#
-
# When the given key starts with a period, it will be scoped by the current
-
# controller and action. So if you call <tt>translate(".foo")</tt> from
-
# <tt>PeopleController#index</tt>, it will convert the call to
-
# <tt>I18n.translate("people.index.foo")</tt>. This makes it less repetitive
-
# to translate many keys within the same controller / action and gives you a
-
# simple framework for scoping them consistently.
-
2
def translate(*args)
-
key = args.first
-
if key.is_a?(String) && (key[0] == '.')
-
key = "#{ controller_path.tr('/', '.') }.#{ action_name }#{ key }"
-
args[0] = key
-
end
-
-
I18n.translate(*args)
-
end
-
2
alias :t :translate
-
-
# Delegates to <tt>I18n.localize</tt>. Also aliased as <tt>l</tt>.
-
2
def localize(*args)
-
I18n.localize(*args)
-
end
-
2
alias :l :localize
-
end
-
end
-
2
module AbstractController
-
# Includes +url_for+ into the host class (e.g. an abstract controller or mailer). The class
-
# has to provide a +RouteSet+ by implementing the <tt>_routes</tt> methods. Otherwise, an
-
# exception will be raised.
-
#
-
# Note that this module is completely decoupled from HTTP - the only requirement is a valid
-
# <tt>_routes</tt> implementation.
-
2
module UrlFor
-
2
extend ActiveSupport::Concern
-
2
include ActionDispatch::Routing::UrlFor
-
-
2
def _routes
-
raise "In order to use #url_for, you must include routing helpers explicitly. " \
-
"For instance, `include Rails.application.routes.url_helpers"
-
end
-
-
2
module ClassMethods
-
2
def _routes
-
nil
-
end
-
-
2
def action_methods
-
@action_methods ||= begin
-
8
if _routes
-
8
super - _routes.named_routes.helper_names
-
else
-
super
-
end
-
24
end
-
end
-
end
-
end
-
end
-
2
require 'active_support/rails'
-
2
require 'abstract_controller'
-
2
require 'action_dispatch'
-
2
require 'action_controller/metal/live'
-
2
require 'action_controller/metal/strong_parameters'
-
-
2
module ActionController
-
2
extend ActiveSupport::Autoload
-
-
2
autoload :Base
-
2
autoload :Caching
-
2
autoload :Metal
-
2
autoload :Middleware
-
-
2
autoload_under "metal" do
-
2
autoload :Compatibility
-
2
autoload :ConditionalGet
-
2
autoload :Cookies
-
2
autoload :DataStreaming
-
2
autoload :Flash
-
2
autoload :ForceSSL
-
2
autoload :Head
-
2
autoload :Helpers
-
2
autoload :HideActions
-
2
autoload :HttpAuthentication
-
2
autoload :ImplicitRender
-
2
autoload :Instrumentation
-
2
autoload :MimeResponds
-
2
autoload :ParamsWrapper
-
2
autoload :RackDelegation
-
2
autoload :Redirecting
-
2
autoload :Renderers
-
2
autoload :Rendering
-
2
autoload :RequestForgeryProtection
-
2
autoload :Rescue
-
2
autoload :Responder
-
2
autoload :Streaming
-
2
autoload :StrongParameters
-
2
autoload :Testing
-
2
autoload :UrlFor
-
end
-
-
2
autoload :TestCase, 'action_controller/test_case'
-
2
autoload :TemplateAssertions, 'action_controller/test_case'
-
-
2
def self.eager_load!
-
super
-
ActionController::Caching.eager_load!
-
end
-
end
-
-
# Common Active Support usage in Action Controller
-
2
require 'active_support/core_ext/module/attribute_accessors'
-
2
require 'active_support/core_ext/load_error'
-
2
require 'active_support/core_ext/module/attr_internal'
-
2
require 'active_support/core_ext/name_error'
-
2
require 'active_support/core_ext/uri'
-
2
require 'active_support/inflector'
-
2
require 'action_view'
-
2
require "action_controller/log_subscriber"
-
2
require "action_controller/metal/params_wrapper"
-
-
2
module ActionController
-
# Action Controllers are the core of a web request in \Rails. They are made up of one or more actions that are executed
-
# on request and then either it renders a template or redirects to another action. An action is defined as a public method
-
# on the controller, which will automatically be made accessible to the web-server through \Rails Routes.
-
#
-
# By default, only the ApplicationController in a \Rails application inherits from <tt>ActionController::Base</tt>. All other
-
# controllers in turn inherit from ApplicationController. This gives you one class to configure things such as
-
# request forgery protection and filtering of sensitive request parameters.
-
#
-
# A sample controller could look like this:
-
#
-
# class PostsController < ApplicationController
-
# def index
-
# @posts = Post.all
-
# end
-
#
-
# def create
-
# @post = Post.create params[:post]
-
# redirect_to posts_path
-
# end
-
# end
-
#
-
# Actions, by default, render a template in the <tt>app/views</tt> directory corresponding to the name of the controller and action
-
# after executing code in the action. For example, the +index+ action of the PostsController would render the
-
# template <tt>app/views/posts/index.html.erb</tt> by default after populating the <tt>@posts</tt> instance variable.
-
#
-
# Unlike index, the create action will not render a template. After performing its main purpose (creating a
-
# new post), it initiates a redirect instead. This redirect works by returning an external
-
# "302 Moved" HTTP response that takes the user to the index action.
-
#
-
# These two methods represent the two basic action archetypes used in Action Controllers. Get-and-show and do-and-redirect.
-
# Most actions are variations on these themes.
-
#
-
# == Requests
-
#
-
# For every request, the router determines the value of the +controller+ and +action+ keys. These determine which controller
-
# and action are called. The remaining request parameters, the session (if one is available), and the full request with
-
# all the HTTP headers are made available to the action through accessor methods. Then the action is performed.
-
#
-
# The full request object is available via the request accessor and is primarily used to query for HTTP headers:
-
#
-
# def server_ip
-
# location = request.env["SERVER_ADDR"]
-
# render plain: "This server hosted at #{location}"
-
# end
-
#
-
# == Parameters
-
#
-
# All request parameters, whether they come from a GET or POST request, or from the URL, are available through the params method
-
# which returns a hash. For example, an action that was performed through <tt>/posts?category=All&limit=5</tt> will include
-
# <tt>{ "category" => "All", "limit" => "5" }</tt> in params.
-
#
-
# It's also possible to construct multi-dimensional parameter hashes by specifying keys using brackets, such as:
-
#
-
# <input type="text" name="post[name]" value="david">
-
# <input type="text" name="post[address]" value="hyacintvej">
-
#
-
# A request stemming from a form holding these inputs will include <tt>{ "post" => { "name" => "david", "address" => "hyacintvej" } }</tt>.
-
# If the address input had been named <tt>post[address][street]</tt>, the params would have included
-
# <tt>{ "post" => { "address" => { "street" => "hyacintvej" } } }</tt>. There's no limit to the depth of the nesting.
-
#
-
# == Sessions
-
#
-
# Sessions allow you to store objects in between requests. This is useful for objects that are not yet ready to be persisted,
-
# such as a Signup object constructed in a multi-paged process, or objects that don't change much and are needed all the time, such
-
# as a User object for a system that requires login. The session should not be used, however, as a cache for objects where it's likely
-
# they could be changed unknowingly. It's usually too much work to keep it all synchronized -- something databases already excel at.
-
#
-
# You can place objects in the session by using the <tt>session</tt> method, which accesses a hash:
-
#
-
# session[:person] = Person.authenticate(user_name, password)
-
#
-
# And retrieved again through the same hash:
-
#
-
# Hello #{session[:person]}
-
#
-
# For removing objects from the session, you can either assign a single key to +nil+:
-
#
-
# # removes :person from session
-
# session[:person] = nil
-
#
-
# or you can remove the entire session with +reset_session+.
-
#
-
# Sessions are stored by default in a browser cookie that's cryptographically signed, but unencrypted.
-
# This prevents the user from tampering with the session but also allows them to see its contents.
-
#
-
# Do not put secret information in cookie-based sessions!
-
#
-
# == Responses
-
#
-
# Each action results in a response, which holds the headers and document to be sent to the user's browser. The actual response
-
# object is generated automatically through the use of renders and redirects and requires no user intervention.
-
#
-
# == Renders
-
#
-
# Action Controller sends content to the user by using one of five rendering methods. The most versatile and common is the rendering
-
# of a template. Included in the Action Pack is the Action View, which enables rendering of ERB templates. It's automatically configured.
-
# The controller passes objects to the view by assigning instance variables:
-
#
-
# def show
-
# @post = Post.find(params[:id])
-
# end
-
#
-
# Which are then automatically available to the view:
-
#
-
# Title: <%= @post.title %>
-
#
-
# You don't have to rely on the automated rendering. For example, actions that could result in the rendering of different templates
-
# will use the manual rendering methods:
-
#
-
# def search
-
# @results = Search.find(params[:query])
-
# case @results.count
-
# when 0 then render action: "no_results"
-
# when 1 then render action: "show"
-
# when 2..10 then render action: "show_many"
-
# end
-
# end
-
#
-
# Read more about writing ERB and Builder templates in ActionView::Base.
-
#
-
# == Redirects
-
#
-
# Redirects are used to move from one action to another. For example, after a <tt>create</tt> action, which stores a blog entry to the
-
# database, we might like to show the user the new entry. Because we're following good DRY principles (Don't Repeat Yourself), we're
-
# going to reuse (and redirect to) a <tt>show</tt> action that we'll assume has already been created. The code might look like this:
-
#
-
# def create
-
# @entry = Entry.new(params[:entry])
-
# if @entry.save
-
# # The entry was saved correctly, redirect to show
-
# redirect_to action: 'show', id: @entry.id
-
# else
-
# # things didn't go so well, do something else
-
# end
-
# end
-
#
-
# In this case, after saving our new entry to the database, the user is redirected to the <tt>show</tt> method, which is then executed.
-
# Note that this is an external HTTP-level redirection which will cause the browser to make a second request (a GET to the show action),
-
# and not some internal re-routing which calls both "create" and then "show" within one request.
-
#
-
# Learn more about <tt>redirect_to</tt> and what options you have in ActionController::Redirecting.
-
#
-
# == Calling multiple redirects or renders
-
#
-
# An action may contain only a single render or a single redirect. Attempting to try to do either again will result in a DoubleRenderError:
-
#
-
# def do_something
-
# redirect_to action: "elsewhere"
-
# render action: "overthere" # raises DoubleRenderError
-
# end
-
#
-
# If you need to redirect on the condition of something, then be sure to add "and return" to halt execution.
-
#
-
# def do_something
-
# redirect_to(action: "elsewhere") and return if monkeys.nil?
-
# render action: "overthere" # won't be called if monkeys is nil
-
# end
-
#
-
2
class Base < Metal
-
2
abstract!
-
-
# We document the request and response methods here because albeit they are
-
# implemented in ActionController::Metal, the type of the returned objects
-
# is unknown at that level.
-
-
##
-
# :method: request
-
#
-
# Returns an ActionDispatch::Request instance that represents the
-
# current request.
-
-
##
-
# :method: response
-
#
-
# Returns an ActionDispatch::Response that represents the current
-
# response.
-
-
# Shortcut helper that returns all the modules included in
-
# ActionController::Base except the ones passed as arguments:
-
#
-
# class MetalController
-
# ActionController::Base.without_modules(:ParamsWrapper, :Streaming).each do |left|
-
# include left
-
# end
-
# end
-
#
-
# This gives better control over what you want to exclude and makes it
-
# easier to create a bare controller class, instead of listing the modules
-
# required manually.
-
2
def self.without_modules(*modules)
-
modules = modules.map do |m|
-
m.is_a?(Symbol) ? ActionController.const_get(m) : m
-
end
-
-
MODULES - modules
-
end
-
-
2
MODULES = [
-
AbstractController::Rendering,
-
AbstractController::Translation,
-
AbstractController::AssetPaths,
-
-
Helpers,
-
HideActions,
-
UrlFor,
-
Redirecting,
-
ActionView::Layouts,
-
Rendering,
-
Renderers::All,
-
ConditionalGet,
-
RackDelegation,
-
Caching,
-
MimeResponds,
-
ImplicitRender,
-
StrongParameters,
-
-
Cookies,
-
Flash,
-
RequestForgeryProtection,
-
ForceSSL,
-
Streaming,
-
DataStreaming,
-
HttpAuthentication::Basic::ControllerMethods,
-
HttpAuthentication::Digest::ControllerMethods,
-
HttpAuthentication::Token::ControllerMethods,
-
-
# Before callbacks should also be executed the earliest as possible, so
-
# also include them at the bottom.
-
AbstractController::Callbacks,
-
-
# Append rescue at the bottom to wrap as much as possible.
-
Rescue,
-
-
# Add instrumentations hooks at the bottom, to ensure they instrument
-
# all the methods properly.
-
Instrumentation,
-
-
# Params wrapper should come before instrumentation so they are
-
# properly showed in logs
-
ParamsWrapper
-
]
-
-
2
MODULES.each do |mod|
-
58
include mod
-
end
-
-
# Define some internal variables that should not be propagated to the view.
-
2
PROTECTED_IVARS = AbstractController::Rendering::DEFAULT_PROTECTED_INSTANCE_VARIABLES + [
-
:@_status, :@_headers, :@_params, :@_env, :@_response, :@_request,
-
:@_view_runtime, :@_stream, :@_url_options, :@_action_has_layout ]
-
-
2
def _protected_ivars # :nodoc:
-
35
PROTECTED_IVARS
-
end
-
-
2
def self.protected_instance_variables
-
PROTECTED_IVARS
-
end
-
-
2
ActiveSupport.run_load_hooks(:action_controller, self)
-
end
-
end
-
2
require 'fileutils'
-
2
require 'uri'
-
2
require 'set'
-
-
2
module ActionController
-
# \Caching is a cheap way of speeding up slow applications by keeping the result of
-
# calculations, renderings, and database calls around for subsequent requests.
-
#
-
# You can read more about each approach by clicking the modules below.
-
#
-
# Note: To turn off all caching, set
-
# config.action_controller.perform_caching = false
-
#
-
# == \Caching stores
-
#
-
# All the caching stores from ActiveSupport::Cache are available to be used as backends
-
# for Action Controller caching.
-
#
-
# Configuration examples (MemoryStore is the default):
-
#
-
# config.action_controller.cache_store = :memory_store
-
# config.action_controller.cache_store = :file_store, '/path/to/cache/directory'
-
# config.action_controller.cache_store = :mem_cache_store, 'localhost'
-
# config.action_controller.cache_store = :mem_cache_store, Memcached::Rails.new('localhost:11211')
-
# config.action_controller.cache_store = MyOwnStore.new('parameter')
-
2
module Caching
-
2
extend ActiveSupport::Concern
-
2
extend ActiveSupport::Autoload
-
-
2
eager_autoload do
-
2
autoload :Fragments
-
end
-
-
2
module ConfigMethods
-
2
def cache_store
-
config.cache_store
-
end
-
-
2
def cache_store=(store)
-
2
config.cache_store = ActiveSupport::Cache.lookup_store(store)
-
end
-
-
2
private
-
2
def cache_configured?
-
perform_caching && cache_store
-
end
-
end
-
-
2
include RackDelegation
-
2
include AbstractController::Callbacks
-
-
2
include ConfigMethods
-
2
include Fragments
-
-
2
included do
-
2
extend ConfigMethods
-
-
2
config_accessor :default_static_extension
-
2
self.default_static_extension ||= '.html'
-
-
2
config_accessor :perform_caching
-
2
self.perform_caching = true if perform_caching.nil?
-
-
2
class_attribute :_view_cache_dependencies
-
2
self._view_cache_dependencies = []
-
2
helper_method :view_cache_dependencies if respond_to?(:helper_method)
-
end
-
-
2
module ClassMethods
-
2
def view_cache_dependency(&dependency)
-
self._view_cache_dependencies += [dependency]
-
end
-
end
-
-
2
def view_cache_dependencies
-
self.class._view_cache_dependencies.map { |dep| instance_exec(&dep) }.compact
-
end
-
-
2
protected
-
# Convenience accessor.
-
2
def cache(key, options = {}, &block)
-
if cache_configured?
-
cache_store.fetch(ActiveSupport::Cache.expand_cache_key(key, :controller), options, &block)
-
else
-
yield
-
end
-
end
-
end
-
end
-
2
module ActionController
-
2
module Caching
-
# Fragment caching is used for caching various blocks within
-
# views without caching the entire action as a whole. This is
-
# useful when certain elements of an action change frequently or
-
# depend on complicated state while other parts rarely change or
-
# can be shared amongst multiple parties. The caching is done using
-
# the +cache+ helper available in the Action View. See
-
# ActionView::Helpers::CacheHelper for more information.
-
#
-
# While it's strongly recommended that you use key-based cache
-
# expiration (see links in CacheHelper for more information),
-
# it is also possible to manually expire caches. For example:
-
#
-
# expire_fragment('name_of_cache')
-
2
module Fragments
-
# Given a key (as described in +expire_fragment+), returns
-
# a key suitable for use in reading, writing, or expiring a
-
# cached fragment. All keys are prefixed with <tt>views/</tt> and uses
-
# ActiveSupport::Cache.expand_cache_key for the expansion.
-
2
def fragment_cache_key(key)
-
ActiveSupport::Cache.expand_cache_key(key.is_a?(Hash) ? url_for(key).split("://").last : key, :views)
-
end
-
-
# Writes +content+ to the location signified by
-
# +key+ (see +expire_fragment+ for acceptable formats).
-
2
def write_fragment(key, content, options = nil)
-
return content unless cache_configured?
-
-
key = fragment_cache_key(key)
-
instrument_fragment_cache :write_fragment, key do
-
content = content.to_str
-
cache_store.write(key, content, options)
-
end
-
content
-
end
-
-
# Reads a cached fragment from the location signified by +key+
-
# (see +expire_fragment+ for acceptable formats).
-
2
def read_fragment(key, options = nil)
-
return unless cache_configured?
-
-
key = fragment_cache_key(key)
-
instrument_fragment_cache :read_fragment, key do
-
result = cache_store.read(key, options)
-
result.respond_to?(:html_safe) ? result.html_safe : result
-
end
-
end
-
-
# Check if a cached fragment from the location signified by
-
# +key+ exists (see +expire_fragment+ for acceptable formats).
-
2
def fragment_exist?(key, options = nil)
-
return unless cache_configured?
-
key = fragment_cache_key(key)
-
-
instrument_fragment_cache :exist_fragment?, key do
-
cache_store.exist?(key, options)
-
end
-
end
-
-
# Removes fragments from the cache.
-
#
-
# +key+ can take one of three forms:
-
#
-
# * String - This would normally take the form of a path, like
-
# <tt>pages/45/notes</tt>.
-
# * Hash - Treated as an implicit call to +url_for+, like
-
# <tt>{ controller: 'pages', action: 'notes', id: 45}</tt>
-
# * Regexp - Will remove any fragment that matches, so
-
# <tt>%r{pages/\d*/notes}</tt> might remove all notes. Make sure you
-
# don't use anchors in the regex (<tt>^</tt> or <tt>$</tt>) because
-
# the actual filename matched looks like
-
# <tt>./cache/filename/path.cache</tt>. Note: Regexp expiration is
-
# only supported on caches that can iterate over all keys (unlike
-
# memcached).
-
#
-
# +options+ is passed through to the cache store's +delete+
-
# method (or <tt>delete_matched</tt>, for Regexp keys).
-
2
def expire_fragment(key, options = nil)
-
return unless cache_configured?
-
key = fragment_cache_key(key) unless key.is_a?(Regexp)
-
-
instrument_fragment_cache :expire_fragment, key do
-
if key.is_a?(Regexp)
-
cache_store.delete_matched(key, options)
-
else
-
cache_store.delete(key, options)
-
end
-
end
-
end
-
-
2
def instrument_fragment_cache(name, key) # :nodoc:
-
ActiveSupport::Notifications.instrument("#{name}.action_controller", :key => key){ yield }
-
end
-
end
-
end
-
end
-
-
2
module ActionController
-
2
class LogSubscriber < ActiveSupport::LogSubscriber
-
2
INTERNAL_PARAMS = %w(controller action format _method only_path)
-
-
2
def start_processing(event)
-
24
return unless logger.info?
-
-
24
payload = event.payload
-
24
params = payload[:params].except(*INTERNAL_PARAMS)
-
24
format = payload[:format]
-
24
format = format.to_s.upcase if format.is_a?(Symbol)
-
-
24
info "Processing by #{payload[:controller]}##{payload[:action]} as #{format}"
-
24
info " Parameters: #{params.inspect}" unless params.empty?
-
end
-
-
2
def process_action(event)
-
24
return unless logger.info?
-
-
24
payload = event.payload
-
24
additions = ActionController::Base.log_process_action(payload)
-
-
24
status = payload[:status]
-
24
if status.nil? && payload[:exception].present?
-
exception_class_name = payload[:exception].first
-
status = ActionDispatch::ExceptionWrapper.status_code_for_exception(exception_class_name)
-
end
-
24
message = "Completed #{status} #{Rack::Utils::HTTP_STATUS_CODES[status]} in #{event.duration.round}ms"
-
24
message << " (#{additions.join(" | ")})" unless additions.blank?
-
-
24
info(message)
-
end
-
-
2
def halted_callback(event)
-
info("Filter chain halted as #{event.payload[:filter].inspect} rendered or redirected")
-
end
-
-
2
def send_file(event)
-
info("Sent file #{event.payload[:path]} (#{event.duration.round(1)}ms)")
-
end
-
-
2
def redirect_to(event)
-
info("Redirected to #{event.payload[:location]}")
-
end
-
-
2
def send_data(event)
-
info("Sent data #{event.payload[:filename]} (#{event.duration.round(1)}ms)")
-
end
-
-
2
def unpermitted_parameters(event)
-
unpermitted_keys = event.payload[:keys]
-
debug("Unpermitted parameters: #{unpermitted_keys.join(", ")}")
-
end
-
-
2
def deep_munge(event)
-
message = "Value for params[:#{event.payload[:keys].join('][:')}] was set "\
-
"to nil, because it was one of [], [null] or [null, null, ...]. "\
-
"Go to http://guides.rubyonrails.org/security.html#unsafe-query-generation "\
-
"for more information."\
-
-
debug(message)
-
end
-
-
%w(write_fragment read_fragment exist_fragment?
-
2
expire_fragment expire_page write_page).each do |method|
-
12
class_eval <<-METHOD, __FILE__, __LINE__ + 1
-
def #{method}(event)
-
return unless logger.info?
-
key_or_path = event.payload[:key] || event.payload[:path]
-
human_name = #{method.to_s.humanize.inspect}
-
info("\#{human_name} \#{key_or_path} (\#{event.duration.round(1)}ms)")
-
end
-
METHOD
-
end
-
-
2
def logger
-
248
ActionController::Base.logger
-
end
-
end
-
end
-
-
2
ActionController::LogSubscriber.attach_to :action_controller
-
2
require 'active_support/core_ext/array/extract_options'
-
2
require 'action_dispatch/middleware/stack'
-
-
2
module ActionController
-
# Extend ActionDispatch middleware stack to make it aware of options
-
# allowing the following syntax in controllers:
-
#
-
# class PostsController < ApplicationController
-
# use AuthenticationMiddleware, except: [:index, :show]
-
# end
-
#
-
2
class MiddlewareStack < ActionDispatch::MiddlewareStack #:nodoc:
-
2
class Middleware < ActionDispatch::MiddlewareStack::Middleware #:nodoc:
-
2
def initialize(klass, *args, &block)
-
options = args.extract_options!
-
@only = Array(options.delete(:only)).map(&:to_s)
-
@except = Array(options.delete(:except)).map(&:to_s)
-
args << options unless options.empty?
-
super
-
end
-
-
2
def valid?(action)
-
if @only.present?
-
@only.include?(action)
-
elsif @except.present?
-
!@except.include?(action)
-
else
-
true
-
end
-
end
-
end
-
-
2
def build(action, app=nil, &block)
-
13
app ||= block
-
13
action = action.to_s
-
13
raise "MiddlewareStack#build requires an app" unless app
-
-
13
middlewares.reverse.inject(app) do |a, middleware|
-
middleware.valid?(action) ? middleware.build(a) : a
-
end
-
end
-
end
-
-
# <tt>ActionController::Metal</tt> is the simplest possible controller, providing a
-
# valid Rack interface without the additional niceties provided by
-
# <tt>ActionController::Base</tt>.
-
#
-
# A sample metal controller might look like this:
-
#
-
# class HelloController < ActionController::Metal
-
# def index
-
# self.response_body = "Hello World!"
-
# end
-
# end
-
#
-
# And then to route requests to your metal controller, you would add
-
# something like this to <tt>config/routes.rb</tt>:
-
#
-
# get 'hello', to: HelloController.action(:index)
-
#
-
# The +action+ method returns a valid Rack application for the \Rails
-
# router to dispatch to.
-
#
-
# == Rendering Helpers
-
#
-
# <tt>ActionController::Metal</tt> by default provides no utilities for rendering
-
# views, partials, or other responses aside from explicitly calling of
-
# <tt>response_body=</tt>, <tt>content_type=</tt>, and <tt>status=</tt>. To
-
# add the render helpers you're used to having in a normal controller, you
-
# can do the following:
-
#
-
# class HelloController < ActionController::Metal
-
# include AbstractController::Rendering
-
# include ActionView::Layouts
-
# append_view_path "#{Rails.root}/app/views"
-
#
-
# def index
-
# render "hello/index"
-
# end
-
# end
-
#
-
# == Redirection Helpers
-
#
-
# To add redirection helpers to your metal controller, do the following:
-
#
-
# class HelloController < ActionController::Metal
-
# include ActionController::Redirecting
-
# include Rails.application.routes.url_helpers
-
#
-
# def index
-
# redirect_to root_url
-
# end
-
# end
-
#
-
# == Other Helpers
-
#
-
# You can refer to the modules included in <tt>ActionController::Base</tt> to see
-
# other features you can bring into your metal controller.
-
#
-
2
class Metal < AbstractController::Base
-
2
abstract!
-
-
2
attr_internal_writer :env
-
-
2
def env
-
94
@_env ||= {}
-
end
-
-
# Returns the last part of the controller's name, underscored, without the ending
-
# <tt>Controller</tt>. For instance, PostsController returns <tt>posts</tt>.
-
# Namespaces are left out, so Admin::PostsController returns <tt>posts</tt> as well.
-
#
-
# ==== Returns
-
# * <tt>string</tt>
-
2
def self.controller_name
-
@controller_name ||= name.demodulize.sub(/Controller$/, '').underscore
-
end
-
-
# Delegates to the class' <tt>controller_name</tt>
-
2
def controller_name
-
self.class.controller_name
-
end
-
-
# The details below can be overridden to support a specific
-
# Request and Response object. The default ActionController::Base
-
# implementation includes RackDelegation, which makes a request
-
# and response object available. You might wish to control the
-
# environment and response manually for performance reasons.
-
-
2
attr_internal :headers, :response, :request
-
2
delegate :session, :to => "@_request"
-
-
2
def initialize
-
28
@_headers = {"Content-Type" => "text/html"}
-
28
@_status = 200
-
28
@_request = nil
-
28
@_response = nil
-
28
@_routes = nil
-
28
super
-
end
-
-
2
def params
-
@_params ||= request.parameters
-
end
-
-
2
def params=(val)
-
@_params = val
-
end
-
-
# Basic implementations for content_type=, location=, and headers are
-
# provided to reduce the dependency on the RackDelegation module
-
# in Renderer and Redirector.
-
-
2
def content_type=(type)
-
headers["Content-Type"] = type.to_s
-
end
-
-
2
def content_type
-
headers["Content-Type"]
-
end
-
-
2
def location
-
headers["Location"]
-
end
-
-
2
def location=(url)
-
headers["Location"] = url
-
end
-
-
# basic url_for that can be overridden for more robust functionality
-
2
def url_for(string)
-
string
-
end
-
-
2
def status
-
@_status
-
end
-
-
2
def status=(status)
-
@_status = Rack::Utils.status_code(status)
-
end
-
-
2
def response_body=(body)
-
24
body = [body] unless body.nil? || body.respond_to?(:each)
-
24
super
-
end
-
-
2
def performed?
-
24
response_body || (response && response.committed?)
-
end
-
-
2
def dispatch(name, request) #:nodoc:
-
13
@_request = request
-
13
@_env = request.env
-
13
@_env['action_controller.instance'] = self
-
13
process(name)
-
13
to_a
-
end
-
-
2
def to_a #:nodoc:
-
13
response ? response.to_a : [status, headers, response_body]
-
end
-
-
2
class_attribute :middleware_stack
-
2
self.middleware_stack = ActionController::MiddlewareStack.new
-
-
2
def self.inherited(base) # :nodoc:
-
15
base.middleware_stack = middleware_stack.dup
-
15
super
-
end
-
-
# Pushes the given Rack middleware and its arguments to the bottom of the
-
# middleware stack.
-
2
def self.use(*args, &block)
-
middleware_stack.use(*args, &block)
-
end
-
-
# Alias for +middleware_stack+.
-
2
def self.middleware
-
middleware_stack
-
end
-
-
# Makes the controller a Rack endpoint that runs the action in the given
-
# +env+'s +action_dispatch.request.path_parameters+ key.
-
2
def self.call(env)
-
action(env['action_dispatch.request.path_parameters'][:action]).call(env)
-
end
-
-
# Returns a Rack endpoint for the given action name.
-
2
def self.action(name, klass = ActionDispatch::Request)
-
13
middleware_stack.build(name.to_s) do |env|
-
13
new.dispatch(name, klass.new(env))
-
end
-
end
-
-
2
def _status_code
-
@_status
-
end
-
end
-
end
-
2
require 'active_support/core_ext/hash/keys'
-
-
2
module ActionController
-
2
module ConditionalGet
-
2
extend ActiveSupport::Concern
-
-
2
include RackDelegation
-
2
include Head
-
-
2
included do
-
2
class_attribute :etaggers
-
2
self.etaggers = []
-
end
-
-
2
module ClassMethods
-
# Allows you to consider additional controller-wide information when generating an etag.
-
# For example, if you serve pages tailored depending on who's logged in at the moment, you
-
# may want to add the current user id to be part of the etag to prevent authorized displaying
-
# of cached pages.
-
#
-
# class InvoicesController < ApplicationController
-
# etag { current_user.try :id }
-
#
-
# def show
-
# # Etag will differ even for the same invoice when it's viewed by a different current_user
-
# @invoice = Invoice.find(params[:id])
-
# fresh_when(@invoice)
-
# end
-
# end
-
2
def etag(&etagger)
-
self.etaggers += [etagger]
-
end
-
end
-
-
# Sets the etag, +last_modified+, or both on the response and renders a
-
# <tt>304 Not Modified</tt> response if the request is already fresh.
-
#
-
# === Parameters:
-
#
-
# * <tt>:etag</tt>.
-
# * <tt>:last_modified</tt>.
-
# * <tt>:public</tt> By default the Cache-Control header is private, set this to
-
# +true+ if you want your application to be cachable by other devices (proxy caches).
-
#
-
# === Example:
-
#
-
# def show
-
# @article = Article.find(params[:id])
-
# fresh_when(etag: @article, last_modified: @article.created_at, public: true)
-
# end
-
#
-
# This will render the show template if the request isn't sending a matching etag or
-
# If-Modified-Since header and just a <tt>304 Not Modified</tt> response if there's a match.
-
#
-
# You can also just pass a record where +last_modified+ will be set by calling
-
# +updated_at+ and the etag by passing the object itself.
-
#
-
# def show
-
# @article = Article.find(params[:id])
-
# fresh_when(@article)
-
# end
-
#
-
# When passing a record, you can still set whether the public header:
-
#
-
# def show
-
# @article = Article.find(params[:id])
-
# fresh_when(@article, public: true)
-
# end
-
2
def fresh_when(record_or_options, additional_options = {})
-
if record_or_options.is_a? Hash
-
options = record_or_options
-
options.assert_valid_keys(:etag, :last_modified, :public)
-
else
-
record = record_or_options
-
options = { etag: record, last_modified: record.try(:updated_at) }.merge!(additional_options)
-
end
-
-
response.etag = combine_etags(options[:etag]) if options[:etag]
-
response.last_modified = options[:last_modified] if options[:last_modified]
-
response.cache_control[:public] = true if options[:public]
-
-
head :not_modified if request.fresh?(response)
-
end
-
-
# Sets the +etag+ and/or +last_modified+ on the response and checks it against
-
# the client request. If the request doesn't match the options provided, the
-
# request is considered stale and should be generated from scratch. Otherwise,
-
# it's fresh and we don't need to generate anything and a reply of <tt>304 Not Modified</tt> is sent.
-
#
-
# === Parameters:
-
#
-
# * <tt>:etag</tt>.
-
# * <tt>:last_modified</tt>.
-
# * <tt>:public</tt> By default the Cache-Control header is private, set this to
-
# +true+ if you want your application to be cachable by other devices (proxy caches).
-
#
-
# === Example:
-
#
-
# def show
-
# @article = Article.find(params[:id])
-
#
-
# if stale?(etag: @article, last_modified: @article.created_at)
-
# @statistics = @article.really_expensive_call
-
# respond_to do |format|
-
# # all the supported formats
-
# end
-
# end
-
# end
-
#
-
# You can also just pass a record where +last_modified+ will be set by calling
-
# updated_at and the etag by passing the object itself.
-
#
-
# def show
-
# @article = Article.find(params[:id])
-
#
-
# if stale?(@article)
-
# @statistics = @article.really_expensive_call
-
# respond_to do |format|
-
# # all the supported formats
-
# end
-
# end
-
# end
-
#
-
# When passing a record, you can still set whether the public header:
-
#
-
# def show
-
# @article = Article.find(params[:id])
-
#
-
# if stale?(@article, public: true)
-
# @statistics = @article.really_expensive_call
-
# respond_to do |format|
-
# # all the supported formats
-
# end
-
# end
-
# end
-
2
def stale?(record_or_options, additional_options = {})
-
fresh_when(record_or_options, additional_options)
-
!request.fresh?(response)
-
end
-
-
# Sets a HTTP 1.1 Cache-Control header. Defaults to issuing a +private+
-
# instruction, so that intermediate caches must not cache the response.
-
#
-
# expires_in 20.minutes
-
# expires_in 3.hours, public: true
-
# expires_in 3.hours, public: true, must_revalidate: true
-
#
-
# This method will overwrite an existing Cache-Control header.
-
# See http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html for more possibilities.
-
#
-
# The method will also ensure a HTTP Date header for client compatibility.
-
2
def expires_in(seconds, options = {})
-
response.cache_control.merge!(
-
:max_age => seconds,
-
:public => options.delete(:public),
-
:must_revalidate => options.delete(:must_revalidate)
-
)
-
options.delete(:private)
-
-
response.cache_control[:extras] = options.map {|k,v| "#{k}=#{v}"}
-
response.date = Time.now unless response.date?
-
end
-
-
# Sets a HTTP 1.1 Cache-Control header of <tt>no-cache</tt> so no caching should
-
# occur by the browser or intermediate caches (like caching proxy servers).
-
2
def expires_now
-
response.cache_control.replace(:no_cache => true)
-
end
-
-
2
private
-
2
def combine_etags(etag)
-
[ etag, *etaggers.map { |etagger| instance_exec(&etagger) }.compact ]
-
end
-
end
-
end
-
2
module ActionController #:nodoc:
-
2
module Cookies
-
2
extend ActiveSupport::Concern
-
-
2
include RackDelegation
-
-
2
included do
-
2
helper_method :cookies
-
end
-
-
2
private
-
2
def cookies
-
24
request.cookie_jar
-
end
-
end
-
end
-
2
require 'action_controller/metal/exceptions'
-
-
2
module ActionController #:nodoc:
-
# Methods for sending arbitrary data and for streaming files to the browser,
-
# instead of rendering.
-
2
module DataStreaming
-
2
extend ActiveSupport::Concern
-
-
2
include ActionController::Rendering
-
-
2
DEFAULT_SEND_FILE_TYPE = 'application/octet-stream'.freeze #:nodoc:
-
2
DEFAULT_SEND_FILE_DISPOSITION = 'attachment'.freeze #:nodoc:
-
-
2
protected
-
# Sends the file. This uses a server-appropriate method (such as X-Sendfile)
-
# via the Rack::Sendfile middleware. The header to use is set via
-
# +config.action_dispatch.x_sendfile_header+.
-
# Your server can also configure this for you by setting the X-Sendfile-Type header.
-
#
-
# Be careful to sanitize the path parameter if it is coming from a web
-
# page. <tt>send_file(params[:path])</tt> allows a malicious user to
-
# download any file on your server.
-
#
-
# Options:
-
# * <tt>:filename</tt> - suggests a filename for the browser to use.
-
# Defaults to <tt>File.basename(path)</tt>.
-
# * <tt>:type</tt> - specifies an HTTP content type.
-
# You can specify either a string or a symbol for a registered type register with
-
# <tt>Mime::Type.register</tt>, for example :json
-
# If omitted, type will be guessed from the file extension specified in <tt>:filename</tt>.
-
# If no content type is registered for the extension, default type 'application/octet-stream' will be used.
-
# * <tt>:disposition</tt> - specifies whether the file will be shown inline or downloaded.
-
# Valid values are 'inline' and 'attachment' (default).
-
# * <tt>:status</tt> - specifies the status code to send with the response. Defaults to 200.
-
# * <tt>:url_based_filename</tt> - set to +true+ if you want the browser guess the filename from
-
# the URL, which is necessary for i18n filenames on certain browsers
-
# (setting <tt>:filename</tt> overrides this option).
-
#
-
# The default Content-Type and Content-Disposition headers are
-
# set to download arbitrary binary files in as many browsers as
-
# possible. IE versions 4, 5, 5.5, and 6 are all known to have
-
# a variety of quirks (especially when downloading over SSL).
-
#
-
# Simple download:
-
#
-
# send_file '/path/to.zip'
-
#
-
# Show a JPEG in the browser:
-
#
-
# send_file '/path/to.jpeg', type: 'image/jpeg', disposition: 'inline'
-
#
-
# Show a 404 page in the browser:
-
#
-
# send_file '/path/to/404.html', type: 'text/html; charset=utf-8', status: 404
-
#
-
# Read about the other Content-* HTTP headers if you'd like to
-
# provide the user with more information (such as Content-Description) in
-
# http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.11.
-
#
-
# Also be aware that the document may be cached by proxies and browsers.
-
# The Pragma and Cache-Control headers declare how the file may be cached
-
# by intermediaries. They default to require clients to validate with
-
# the server before releasing cached responses. See
-
# http://www.mnot.net/cache_docs/ for an overview of web caching and
-
# http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.9
-
# for the Cache-Control header spec.
-
2
def send_file(path, options = {}) #:doc:
-
raise MissingFile, "Cannot read file #{path}" unless File.file?(path) and File.readable?(path)
-
-
options[:filename] ||= File.basename(path) unless options[:url_based_filename]
-
send_file_headers! options
-
-
self.status = options[:status] || 200
-
self.content_type = options[:content_type] if options.key?(:content_type)
-
self.response_body = FileBody.new(path)
-
end
-
-
# Avoid having to pass an open file handle as the response body.
-
# Rack::Sendfile will usually intercept the response and uses
-
# the path directly, so there is no reason to open the file.
-
2
class FileBody #:nodoc:
-
2
attr_reader :to_path
-
-
2
def initialize(path)
-
@to_path = path
-
end
-
-
# Stream the file's contents if Rack::Sendfile isn't present.
-
2
def each
-
File.open(to_path, 'rb') do |file|
-
while chunk = file.read(16384)
-
yield chunk
-
end
-
end
-
end
-
end
-
-
# Sends the given binary data to the browser. This method is similar to
-
# <tt>render plain: data</tt>, but also allows you to specify whether
-
# the browser should display the response as a file attachment (i.e. in a
-
# download dialog) or as inline data. You may also set the content type,
-
# the apparent file name, and other things.
-
#
-
# Options:
-
# * <tt>:filename</tt> - suggests a filename for the browser to use.
-
# * <tt>:type</tt> - specifies an HTTP content type. Defaults to 'application/octet-stream'. You can specify
-
# either a string or a symbol for a registered type register with <tt>Mime::Type.register</tt>, for example :json
-
# If omitted, type will be guessed from the file extension specified in <tt>:filename</tt>.
-
# If no content type is registered for the extension, default type 'application/octet-stream' will be used.
-
# * <tt>:disposition</tt> - specifies whether the file will be shown inline or downloaded.
-
# Valid values are 'inline' and 'attachment' (default).
-
# * <tt>:status</tt> - specifies the status code to send with the response. Defaults to 200.
-
#
-
# Generic data download:
-
#
-
# send_data buffer
-
#
-
# Download a dynamically-generated tarball:
-
#
-
# send_data generate_tgz('dir'), filename: 'dir.tgz'
-
#
-
# Display an image Active Record in the browser:
-
#
-
# send_data image.data, type: image.content_type, disposition: 'inline'
-
#
-
# See +send_file+ for more information on HTTP Content-* headers and caching.
-
2
def send_data(data, options = {}) #:doc:
-
send_file_headers! options
-
render options.slice(:status, :content_type).merge(:text => data)
-
end
-
-
2
private
-
2
def send_file_headers!(options)
-
type_provided = options.has_key?(:type)
-
-
content_type = options.fetch(:type, DEFAULT_SEND_FILE_TYPE)
-
raise ArgumentError, ":type option required" if content_type.nil?
-
-
if content_type.is_a?(Symbol)
-
extension = Mime[content_type]
-
raise ArgumentError, "Unknown MIME type #{options[:type]}" unless extension
-
self.content_type = extension
-
else
-
if !type_provided && options[:filename]
-
# If type wasn't provided, try guessing from file extension.
-
content_type = Mime::Type.lookup_by_extension(File.extname(options[:filename]).downcase.delete('.')) || content_type
-
end
-
self.content_type = content_type
-
end
-
-
disposition = options.fetch(:disposition, DEFAULT_SEND_FILE_DISPOSITION)
-
unless disposition.nil?
-
disposition = disposition.to_s
-
disposition += %(; filename="#{options[:filename]}") if options[:filename]
-
headers['Content-Disposition'] = disposition
-
end
-
-
headers['Content-Transfer-Encoding'] = 'binary'
-
-
response.sending_file = true
-
-
# Fix a problem with IE 6.0 on opening downloaded files:
-
# If Cache-Control: no-cache is set (which Rails does by default),
-
# IE removes the file it just downloaded from its cache immediately
-
# after it displays the "open/save" dialog, which means that if you
-
# hit "open" the file isn't there anymore when the application that
-
# is called for handling the download is run, so let's workaround that
-
response.cache_control[:public] ||= false
-
end
-
end
-
end
-
2
module ActionController
-
2
class ActionControllerError < StandardError #:nodoc:
-
end
-
-
2
class BadRequest < ActionControllerError #:nodoc:
-
2
attr_reader :original_exception
-
-
2
def initialize(type = nil, e = nil)
-
return super() unless type && e
-
-
super("Invalid #{type} parameters: #{e.message}")
-
@original_exception = e
-
set_backtrace e.backtrace
-
end
-
end
-
-
2
class RenderError < ActionControllerError #:nodoc:
-
end
-
-
2
class RoutingError < ActionControllerError #:nodoc:
-
2
attr_reader :failures
-
2
def initialize(message, failures=[])
-
super(message)
-
@failures = failures
-
end
-
end
-
-
2
class ActionController::UrlGenerationError < RoutingError #:nodoc:
-
end
-
-
2
class MethodNotAllowed < ActionControllerError #:nodoc:
-
2
def initialize(*allowed_methods)
-
super("Only #{allowed_methods.to_sentence(:locale => :en)} requests are allowed.")
-
end
-
end
-
-
2
class NotImplemented < MethodNotAllowed #:nodoc:
-
end
-
-
2
class UnknownController < ActionControllerError #:nodoc:
-
end
-
-
2
class MissingFile < ActionControllerError #:nodoc:
-
end
-
-
2
class SessionOverflowError < ActionControllerError #:nodoc:
-
2
DEFAULT_MESSAGE = 'Your session data is larger than the data column in which it is to be stored. You must increase the size of your data column if you intend to store large data.'
-
-
2
def initialize(message = nil)
-
super(message || DEFAULT_MESSAGE)
-
end
-
end
-
-
2
class UnknownHttpMethod < ActionControllerError #:nodoc:
-
end
-
-
2
class UnknownFormat < ActionControllerError #:nodoc:
-
end
-
end
-
2
module ActionController #:nodoc:
-
2
module Flash
-
2
extend ActiveSupport::Concern
-
-
2
included do
-
2
class_attribute :_flash_types, instance_accessor: false
-
2
self._flash_types = []
-
-
2
delegate :flash, to: :request
-
2
add_flash_types(:alert, :notice)
-
end
-
-
2
module ClassMethods
-
# Creates new flash types. You can pass as many types as you want to create
-
# flash types other than the default <tt>alert</tt> and <tt>notice</tt> in
-
# your controllers and views. For instance:
-
#
-
# # in application_controller.rb
-
# class ApplicationController < ActionController::Base
-
# add_flash_types :warning
-
# end
-
#
-
# # in your controller
-
# redirect_to user_path(@user), warning: "Incomplete profile"
-
#
-
# # in your view
-
# <%= warning %>
-
#
-
# This method will automatically define a new method for each of the given
-
# names, and it will be available in your views.
-
2
def add_flash_types(*types)
-
2
types.each do |type|
-
4
next if _flash_types.include?(type)
-
-
4
define_method(type) do
-
request.flash[type]
-
end
-
4
helper_method type
-
-
4
self._flash_types += [type]
-
end
-
end
-
end
-
-
2
protected
-
2
def redirect_to(options = {}, response_status_and_flash = {}) #:doc:
-
self.class._flash_types.each do |flash_type|
-
if type = response_status_and_flash.delete(flash_type)
-
flash[flash_type] = type
-
end
-
end
-
-
if other_flashes = response_status_and_flash.delete(:flash)
-
flash.update(other_flashes)
-
end
-
-
super(options, response_status_and_flash)
-
end
-
end
-
end
-
2
require 'active_support/core_ext/hash/except'
-
2
require 'active_support/core_ext/hash/slice'
-
-
2
module ActionController
-
# This module provides a method which will redirect browser to use HTTPS
-
# protocol. This will ensure that user's sensitive information will be
-
# transferred safely over the internet. You _should_ always force browser
-
# to use HTTPS when you're transferring sensitive information such as
-
# user authentication, account information, or credit card information.
-
#
-
# Note that if you are really concerned about your application security,
-
# you might consider using +config.force_ssl+ in your config file instead.
-
# That will ensure all the data transferred via HTTPS protocol and prevent
-
# user from getting session hijacked when accessing the site under unsecured
-
# HTTP protocol.
-
2
module ForceSSL
-
2
extend ActiveSupport::Concern
-
2
include AbstractController::Callbacks
-
-
2
ACTION_OPTIONS = [:only, :except, :if, :unless]
-
2
URL_OPTIONS = [:protocol, :host, :domain, :subdomain, :port, :path]
-
2
REDIRECT_OPTIONS = [:status, :flash, :alert, :notice]
-
-
2
module ClassMethods
-
# Force the request to this particular controller or specified actions to be
-
# under HTTPS protocol.
-
#
-
# If you need to disable this for any reason (e.g. development) then you can use
-
# an +:if+ or +:unless+ condition.
-
#
-
# class AccountsController < ApplicationController
-
# force_ssl if: :ssl_configured?
-
#
-
# def ssl_configured?
-
# !Rails.env.development?
-
# end
-
# end
-
#
-
# ==== URL Options
-
# You can pass any of the following options to affect the redirect url
-
# * <tt>host</tt> - Redirect to a different host name
-
# * <tt>subdomain</tt> - Redirect to a different subdomain
-
# * <tt>domain</tt> - Redirect to a different domain
-
# * <tt>port</tt> - Redirect to a non-standard port
-
# * <tt>path</tt> - Redirect to a different path
-
#
-
# ==== Redirect Options
-
# You can pass any of the following options to affect the redirect status and response
-
# * <tt>status</tt> - Redirect with a custom status (default is 301 Moved Permanently)
-
# * <tt>flash</tt> - Set a flash message when redirecting
-
# * <tt>alert</tt> - Set an alert message when redirecting
-
# * <tt>notice</tt> - Set a notice message when redirecting
-
#
-
# ==== Action Options
-
# You can pass any of the following options to affect the before_action callback
-
# * <tt>only</tt> - The callback should be run only for this action
-
# * <tt>except</tt> - The callback should be run for all actions except this action
-
# * <tt>if</tt> - A symbol naming an instance method or a proc; the callback
-
# will be called only when it returns a true value.
-
# * <tt>unless</tt> - A symbol naming an instance method or a proc; the callback
-
# will be called only when it returns a false value.
-
2
def force_ssl(options = {})
-
action_options = options.slice(*ACTION_OPTIONS)
-
redirect_options = options.except(*ACTION_OPTIONS)
-
before_action(action_options) do
-
force_ssl_redirect(redirect_options)
-
end
-
end
-
end
-
-
# Redirect the existing request to use the HTTPS protocol.
-
#
-
# ==== Parameters
-
# * <tt>host_or_options</tt> - Either a host name or any of the url & redirect options
-
# available to the <tt>force_ssl</tt> method.
-
2
def force_ssl_redirect(host_or_options = nil)
-
unless request.ssl?
-
options = {
-
:protocol => 'https://',
-
:host => request.host,
-
:path => request.fullpath,
-
:status => :moved_permanently
-
}
-
-
if host_or_options.is_a?(Hash)
-
options.merge!(host_or_options)
-
elsif host_or_options
-
options.merge!(:host => host_or_options)
-
end
-
-
secure_url = ActionDispatch::Http::URL.url_for(options.slice(*URL_OPTIONS))
-
flash.keep if respond_to?(:flash)
-
redirect_to secure_url, options.slice(*REDIRECT_OPTIONS)
-
end
-
end
-
end
-
end
-
2
module ActionController
-
2
module Head
-
# Returns a response that has no content (merely headers). The options
-
# argument is interpreted to be a hash of header names and values.
-
# This allows you to easily return a response that consists only of
-
# significant headers:
-
#
-
# head :created, location: person_path(@person)
-
#
-
# head :created, location: @person
-
#
-
# It can also be used to return exceptional conditions:
-
#
-
# return head(:method_not_allowed) unless request.post?
-
# return head(:bad_request) unless valid_request?
-
# render
-
2
def head(status, options = {})
-
options, status = status, nil if status.is_a?(Hash)
-
status ||= options.delete(:status) || :ok
-
location = options.delete(:location)
-
content_type = options.delete(:content_type)
-
-
options.each do |key, value|
-
headers[key.to_s.dasherize.split('-').each { |v| v[0] = v[0].chr.upcase }.join('-')] = value.to_s
-
end
-
-
self.status = status
-
self.location = url_for(location) if location
-
-
if include_content?(self._status_code)
-
self.content_type = content_type || (Mime[formats.first] if formats)
-
self.response.charset = false if self.response
-
self.response_body = " "
-
else
-
headers.delete('Content-Type')
-
headers.delete('Content-Length')
-
self.response_body = ""
-
end
-
end
-
-
2
private
-
# :nodoc:
-
2
def include_content?(status)
-
case status
-
when 100..199
-
false
-
when 204, 205, 304
-
false
-
else
-
true
-
end
-
end
-
end
-
end
-
2
module ActionController
-
# The \Rails framework provides a large number of helpers for working with assets, dates, forms,
-
# numbers and model objects, to name a few. These helpers are available to all templates
-
# by default.
-
#
-
# In addition to using the standard template helpers provided, creating custom helpers to
-
# extract complicated logic or reusable functionality is strongly encouraged. By default, each controller
-
# will include all helpers. These helpers are only accessible on the controller through <tt>.helpers</tt>
-
#
-
# In previous versions of \Rails the controller will include a helper whose
-
# name matches that of the controller, e.g., <tt>MyController</tt> will automatically
-
# include <tt>MyHelper</tt>. To return old behavior set +config.action_controller.include_all_helpers+ to +false+.
-
#
-
# Additional helpers can be specified using the +helper+ class method in ActionController::Base or any
-
# controller which inherits from it.
-
#
-
# The +to_s+ method from the \Time class can be wrapped in a helper method to display a custom message if
-
# a \Time object is blank:
-
#
-
# module FormattedTimeHelper
-
# def format_time(time, format=:long, blank_message=" ")
-
# time.blank? ? blank_message : time.to_s(format)
-
# end
-
# end
-
#
-
# FormattedTimeHelper can now be included in a controller, using the +helper+ class method:
-
#
-
# class EventsController < ActionController::Base
-
# helper FormattedTimeHelper
-
# def index
-
# @events = Event.all
-
# end
-
# end
-
#
-
# Then, in any view rendered by <tt>EventController</tt>, the <tt>format_time</tt> method can be called:
-
#
-
# <% @events.each do |event| -%>
-
# <p>
-
# <%= format_time(event.time, :short, "N/A") %> | <%= event.name %>
-
# </p>
-
# <% end -%>
-
#
-
# Finally, assuming we have two event instances, one which has a time and one which does not,
-
# the output might look like this:
-
#
-
# 23 Aug 11:30 | Carolina Railhawks Soccer Match
-
# N/A | Carolina Railhaws Training Workshop
-
#
-
2
module Helpers
-
2
extend ActiveSupport::Concern
-
-
4
class << self; attr_accessor :helpers_path; end
-
2
include AbstractController::Helpers
-
-
2
included do
-
2
class_attribute :helpers_path, :include_all_helpers
-
2
self.helpers_path ||= []
-
2
self.include_all_helpers = true
-
end
-
-
2
module ClassMethods
-
# Declares helper accessors for controller attributes. For example, the
-
# following adds new +name+ and <tt>name=</tt> instance methods to a
-
# controller and makes them available to the view:
-
# attr_accessor :name
-
# helper_attr :name
-
#
-
# ==== Parameters
-
# * <tt>attrs</tt> - Names of attributes to be converted into helpers.
-
2
def helper_attr(*attrs)
-
attrs.flatten.each { |attr| helper_method(attr, "#{attr}=") }
-
end
-
-
# Provides a proxy to access helpers methods from outside the view.
-
2
def helpers
-
@helper_proxy ||= begin
-
proxy = ActionView::Base.new
-
proxy.config = config.inheritable_copy
-
proxy.extend(_helpers)
-
end
-
end
-
-
# Overwrite modules_for_helpers to accept :all as argument, which loads
-
# all helpers in helpers_path.
-
#
-
# ==== Parameters
-
# * <tt>args</tt> - A list of helpers
-
#
-
# ==== Returns
-
# * <tt>array</tt> - A normalized list of modules for the list of helpers provided.
-
2
def modules_for_helpers(args)
-
26
args += all_application_helpers if args.delete(:all)
-
26
super(args)
-
end
-
-
2
def all_helpers_from_path(path)
-
3
helpers = Array(path).flat_map do |_path|
-
9
extract = /^#{Regexp.quote(_path.to_s)}\/?(.*)_helper.rb$/
-
93
names = Dir["#{_path}/**/*_helper.rb"].map { |file| file.sub(extract, '\1') }
-
9
names.sort!
-
end
-
3
helpers.uniq!
-
3
helpers
-
end
-
-
2
private
-
# Extract helper names from files in <tt>app/helpers/**/*_helper.rb</tt>
-
2
def all_application_helpers
-
3
all_helpers_from_path(helpers_path)
-
end
-
end
-
end
-
end
-
-
2
module ActionController
-
# Adds the ability to prevent public methods on a controller to be called as actions.
-
2
module HideActions
-
2
extend ActiveSupport::Concern
-
-
2
included do
-
2
class_attribute :hidden_actions
-
2
self.hidden_actions = Set.new.freeze
-
end
-
-
2
private
-
-
# Overrides AbstractController::Base#action_method? to return false if the
-
# action name is in the list of hidden actions.
-
2
def method_for_action(action_name)
-
24
self.class.visible_action?(action_name) && super
-
end
-
-
2
module ClassMethods
-
# Sets all of the actions passed in as hidden actions.
-
#
-
# ==== Parameters
-
# * <tt>args</tt> - A list of actions
-
2
def hide_action(*args)
-
2
self.hidden_actions = hidden_actions.dup.merge(args.map(&:to_s)).freeze
-
end
-
-
2
def visible_action?(action_name)
-
24
not hidden_actions.include?(action_name)
-
end
-
-
# Overrides AbstractController::Base#action_methods to remove any methods
-
# that are listed as hidden methods.
-
2
def action_methods
-
1296
@action_methods ||= Set.new(super.reject { |name| hidden_actions.include?(name) }).freeze
-
end
-
end
-
end
-
end
-
2
require 'base64'
-
-
2
module ActionController
-
# Makes it dead easy to do HTTP Basic, Digest and Token authentication.
-
2
module HttpAuthentication
-
# Makes it dead easy to do HTTP \Basic authentication.
-
#
-
# === Simple \Basic example
-
#
-
# class PostsController < ApplicationController
-
# http_basic_authenticate_with name: "dhh", password: "secret", except: :index
-
#
-
# def index
-
# render plain: "Everyone can see me!"
-
# end
-
#
-
# def edit
-
# render plain: "I'm only accessible if you know the password"
-
# end
-
# end
-
#
-
# === Advanced \Basic example
-
#
-
# Here is a more advanced \Basic example where only Atom feeds and the XML API is protected by HTTP authentication,
-
# the regular HTML interface is protected by a session approach:
-
#
-
# class ApplicationController < ActionController::Base
-
# before_action :set_account, :authenticate
-
#
-
# protected
-
# def set_account
-
# @account = Account.find_by(url_name: request.subdomains.first)
-
# end
-
#
-
# def authenticate
-
# case request.format
-
# when Mime::XML, Mime::ATOM
-
# if user = authenticate_with_http_basic { |u, p| @account.users.authenticate(u, p) }
-
# @current_user = user
-
# else
-
# request_http_basic_authentication
-
# end
-
# else
-
# if session_authenticated?
-
# @current_user = @account.users.find(session[:authenticated][:user_id])
-
# else
-
# redirect_to(login_url) and return false
-
# end
-
# end
-
# end
-
# end
-
#
-
# In your integration tests, you can do something like this:
-
#
-
# def test_access_granted_from_xml
-
# get(
-
# "/notes/1.xml", nil,
-
# 'HTTP_AUTHORIZATION' => ActionController::HttpAuthentication::Basic.encode_credentials(users(:dhh).name, users(:dhh).password)
-
# )
-
#
-
# assert_equal 200, status
-
# end
-
2
module Basic
-
2
extend self
-
-
2
module ControllerMethods
-
2
extend ActiveSupport::Concern
-
-
2
module ClassMethods
-
2
def http_basic_authenticate_with(options = {})
-
before_action(options.except(:name, :password, :realm)) do
-
authenticate_or_request_with_http_basic(options[:realm] || "Application") do |name, password|
-
name == options[:name] && password == options[:password]
-
end
-
end
-
end
-
end
-
-
2
def authenticate_or_request_with_http_basic(realm = "Application", &login_procedure)
-
authenticate_with_http_basic(&login_procedure) || request_http_basic_authentication(realm)
-
end
-
-
2
def authenticate_with_http_basic(&login_procedure)
-
HttpAuthentication::Basic.authenticate(request, &login_procedure)
-
end
-
-
2
def request_http_basic_authentication(realm = "Application")
-
HttpAuthentication::Basic.authentication_request(self, realm)
-
end
-
end
-
-
2
def authenticate(request, &login_procedure)
-
if has_basic_credentials?(request)
-
login_procedure.call(*user_name_and_password(request))
-
end
-
end
-
-
2
def has_basic_credentials?(request)
-
request.authorization.present? && (auth_scheme(request) == 'Basic')
-
end
-
-
2
def user_name_and_password(request)
-
decode_credentials(request).split(':', 2)
-
end
-
-
2
def decode_credentials(request)
-
::Base64.decode64(auth_param(request) || '')
-
end
-
-
2
def auth_scheme(request)
-
request.authorization.split(' ', 2).first
-
end
-
-
2
def auth_param(request)
-
request.authorization.split(' ', 2).second
-
end
-
-
2
def encode_credentials(user_name, password)
-
"Basic #{::Base64.strict_encode64("#{user_name}:#{password}")}"
-
end
-
-
2
def authentication_request(controller, realm)
-
controller.headers["WWW-Authenticate"] = %(Basic realm="#{realm.gsub(/"/, "")}")
-
controller.status = 401
-
controller.response_body = "HTTP Basic: Access denied.\n"
-
end
-
end
-
-
# Makes it dead easy to do HTTP \Digest authentication.
-
#
-
# === Simple \Digest example
-
#
-
# require 'digest/md5'
-
# class PostsController < ApplicationController
-
# REALM = "SuperSecret"
-
# USERS = {"dhh" => "secret", #plain text password
-
# "dap" => Digest::MD5.hexdigest(["dap",REALM,"secret"].join(":"))} #ha1 digest password
-
#
-
# before_action :authenticate, except: [:index]
-
#
-
# def index
-
# render plain: "Everyone can see me!"
-
# end
-
#
-
# def edit
-
# render plain: "I'm only accessible if you know the password"
-
# end
-
#
-
# private
-
# def authenticate
-
# authenticate_or_request_with_http_digest(REALM) do |username|
-
# USERS[username]
-
# end
-
# end
-
# end
-
#
-
# === Notes
-
#
-
# The +authenticate_or_request_with_http_digest+ block must return the user's password
-
# or the ha1 digest hash so the framework can appropriately hash to check the user's
-
# credentials. Returning +nil+ will cause authentication to fail.
-
#
-
# Storing the ha1 hash: MD5(username:realm:password), is better than storing a plain password. If
-
# the password file or database is compromised, the attacker would be able to use the ha1 hash to
-
# authenticate as the user at this +realm+, but would not have the user's password to try using at
-
# other sites.
-
#
-
# In rare instances, web servers or front proxies strip authorization headers before
-
# they reach your application. You can debug this situation by logging all environment
-
# variables, and check for HTTP_AUTHORIZATION, amongst others.
-
2
module Digest
-
2
extend self
-
-
2
module ControllerMethods
-
2
def authenticate_or_request_with_http_digest(realm = "Application", &password_procedure)
-
authenticate_with_http_digest(realm, &password_procedure) || request_http_digest_authentication(realm)
-
end
-
-
# Authenticate with HTTP Digest, returns true or false
-
2
def authenticate_with_http_digest(realm = "Application", &password_procedure)
-
HttpAuthentication::Digest.authenticate(request, realm, &password_procedure)
-
end
-
-
# Render output including the HTTP Digest authentication header
-
2
def request_http_digest_authentication(realm = "Application", message = nil)
-
HttpAuthentication::Digest.authentication_request(self, realm, message)
-
end
-
end
-
-
# Returns false on a valid response, true otherwise
-
2
def authenticate(request, realm, &password_procedure)
-
request.authorization && validate_digest_response(request, realm, &password_procedure)
-
end
-
-
# Returns false unless the request credentials response value matches the expected value.
-
# First try the password as a ha1 digest password. If this fails, then try it as a plain
-
# text password.
-
2
def validate_digest_response(request, realm, &password_procedure)
-
secret_key = secret_token(request)
-
credentials = decode_credentials_header(request)
-
valid_nonce = validate_nonce(secret_key, request, credentials[:nonce])
-
-
if valid_nonce && realm == credentials[:realm] && opaque(secret_key) == credentials[:opaque]
-
password = password_procedure.call(credentials[:username])
-
return false unless password
-
-
method = request.env['rack.methodoverride.original_method'] || request.env['REQUEST_METHOD']
-
uri = credentials[:uri]
-
-
[true, false].any? do |trailing_question_mark|
-
[true, false].any? do |password_is_ha1|
-
_uri = trailing_question_mark ? uri + "?" : uri
-
expected = expected_response(method, _uri, credentials, password, password_is_ha1)
-
expected == credentials[:response]
-
end
-
end
-
end
-
end
-
-
# Returns the expected response for a request of +http_method+ to +uri+ with the decoded +credentials+ and the expected +password+
-
# Optional parameter +password_is_ha1+ is set to +true+ by default, since best practice is to store ha1 digest instead
-
# of a plain-text password.
-
2
def expected_response(http_method, uri, credentials, password, password_is_ha1=true)
-
ha1 = password_is_ha1 ? password : ha1(credentials, password)
-
ha2 = ::Digest::MD5.hexdigest([http_method.to_s.upcase, uri].join(':'))
-
::Digest::MD5.hexdigest([ha1, credentials[:nonce], credentials[:nc], credentials[:cnonce], credentials[:qop], ha2].join(':'))
-
end
-
-
2
def ha1(credentials, password)
-
::Digest::MD5.hexdigest([credentials[:username], credentials[:realm], password].join(':'))
-
end
-
-
2
def encode_credentials(http_method, credentials, password, password_is_ha1)
-
credentials[:response] = expected_response(http_method, credentials[:uri], credentials, password, password_is_ha1)
-
"Digest " + credentials.sort_by {|x| x[0].to_s }.map {|v| "#{v[0]}='#{v[1]}'" }.join(', ')
-
end
-
-
2
def decode_credentials_header(request)
-
decode_credentials(request.authorization)
-
end
-
-
2
def decode_credentials(header)
-
ActiveSupport::HashWithIndifferentAccess[header.to_s.gsub(/^Digest\s+/, '').split(',').map do |pair|
-
key, value = pair.split('=', 2)
-
[key.strip, value.to_s.gsub(/^"|"$/,'').delete('\'')]
-
end]
-
end
-
-
2
def authentication_header(controller, realm)
-
secret_key = secret_token(controller.request)
-
nonce = self.nonce(secret_key)
-
opaque = opaque(secret_key)
-
controller.headers["WWW-Authenticate"] = %(Digest realm="#{realm}", qop="auth", algorithm=MD5, nonce="#{nonce}", opaque="#{opaque}")
-
end
-
-
2
def authentication_request(controller, realm, message = nil)
-
message ||= "HTTP Digest: Access denied.\n"
-
authentication_header(controller, realm)
-
controller.status = 401
-
controller.response_body = message
-
end
-
-
2
def secret_token(request)
-
key_generator = request.env["action_dispatch.key_generator"]
-
http_auth_salt = request.env["action_dispatch.http_auth_salt"]
-
key_generator.generate_key(http_auth_salt)
-
end
-
-
# Uses an MD5 digest based on time to generate a value to be used only once.
-
#
-
# A server-specified data string which should be uniquely generated each time a 401 response is made.
-
# It is recommended that this string be base64 or hexadecimal data.
-
# Specifically, since the string is passed in the header lines as a quoted string, the double-quote character is not allowed.
-
#
-
# The contents of the nonce are implementation dependent.
-
# The quality of the implementation depends on a good choice.
-
# A nonce might, for example, be constructed as the base 64 encoding of
-
#
-
# time-stamp H(time-stamp ":" ETag ":" private-key)
-
#
-
# where time-stamp is a server-generated time or other non-repeating value,
-
# ETag is the value of the HTTP ETag header associated with the requested entity,
-
# and private-key is data known only to the server.
-
# With a nonce of this form a server would recalculate the hash portion after receiving the client authentication header and
-
# reject the request if it did not match the nonce from that header or
-
# if the time-stamp value is not recent enough. In this way the server can limit the time of the nonce's validity.
-
# The inclusion of the ETag prevents a replay request for an updated version of the resource.
-
# (Note: including the IP address of the client in the nonce would appear to offer the server the ability
-
# to limit the reuse of the nonce to the same client that originally got it.
-
# However, that would break proxy farms, where requests from a single user often go through different proxies in the farm.
-
# Also, IP address spoofing is not that hard.)
-
#
-
# An implementation might choose not to accept a previously used nonce or a previously used digest, in order to
-
# protect against a replay attack. Or, an implementation might choose to use one-time nonces or digests for
-
# POST, PUT, or PATCH requests and a time-stamp for GET requests. For more details on the issues involved see Section 4
-
# of this document.
-
#
-
# The nonce is opaque to the client. Composed of Time, and hash of Time with secret
-
# key from the Rails session secret generated upon creation of project. Ensures
-
# the time cannot be modified by client.
-
2
def nonce(secret_key, time = Time.now)
-
t = time.to_i
-
hashed = [t, secret_key]
-
digest = ::Digest::MD5.hexdigest(hashed.join(":"))
-
::Base64.strict_encode64("#{t}:#{digest}")
-
end
-
-
# Might want a shorter timeout depending on whether the request
-
# is a PATCH, PUT, or POST, and if client is browser or web service.
-
# Can be much shorter if the Stale directive is implemented. This would
-
# allow a user to use new nonce without prompting user again for their
-
# username and password.
-
2
def validate_nonce(secret_key, request, value, seconds_to_timeout=5*60)
-
return false if value.nil?
-
t = ::Base64.decode64(value).split(":").first.to_i
-
nonce(secret_key, t) == value && (t - Time.now.to_i).abs <= seconds_to_timeout
-
end
-
-
# Opaque based on random generation - but changing each request?
-
2
def opaque(secret_key)
-
::Digest::MD5.hexdigest(secret_key)
-
end
-
-
end
-
-
# Makes it dead easy to do HTTP Token authentication.
-
#
-
# Simple Token example:
-
#
-
# class PostsController < ApplicationController
-
# TOKEN = "secret"
-
#
-
# before_action :authenticate, except: [ :index ]
-
#
-
# def index
-
# render plain: "Everyone can see me!"
-
# end
-
#
-
# def edit
-
# render plain: "I'm only accessible if you know the password"
-
# end
-
#
-
# private
-
# def authenticate
-
# authenticate_or_request_with_http_token do |token, options|
-
# token == TOKEN
-
# end
-
# end
-
# end
-
#
-
#
-
# Here is a more advanced Token example where only Atom feeds and the XML API is protected by HTTP token authentication,
-
# the regular HTML interface is protected by a session approach:
-
#
-
# class ApplicationController < ActionController::Base
-
# before_action :set_account, :authenticate
-
#
-
# protected
-
# def set_account
-
# @account = Account.find_by(url_name: request.subdomains.first)
-
# end
-
#
-
# def authenticate
-
# case request.format
-
# when Mime::XML, Mime::ATOM
-
# if user = authenticate_with_http_token { |t, o| @account.users.authenticate(t, o) }
-
# @current_user = user
-
# else
-
# request_http_token_authentication
-
# end
-
# else
-
# if session_authenticated?
-
# @current_user = @account.users.find(session[:authenticated][:user_id])
-
# else
-
# redirect_to(login_url) and return false
-
# end
-
# end
-
# end
-
# end
-
#
-
#
-
# In your integration tests, you can do something like this:
-
#
-
# def test_access_granted_from_xml
-
# get(
-
# "/notes/1.xml", nil,
-
# 'HTTP_AUTHORIZATION' => ActionController::HttpAuthentication::Token.encode_credentials(users(:dhh).token)
-
# )
-
#
-
# assert_equal 200, status
-
# end
-
#
-
#
-
# On shared hosts, Apache sometimes doesn't pass authentication headers to
-
# FCGI instances. If your environment matches this description and you cannot
-
# authenticate, try this rule in your Apache setup:
-
#
-
# RewriteRule ^(.*)$ dispatch.fcgi [E=X-HTTP_AUTHORIZATION:%{HTTP:Authorization},QSA,L]
-
2
module Token
-
2
TOKEN_REGEX = /^Token /
-
2
AUTHN_PAIR_DELIMITERS = /(?:,|;|\t+)/
-
2
extend self
-
-
2
module ControllerMethods
-
2
def authenticate_or_request_with_http_token(realm = "Application", &login_procedure)
-
authenticate_with_http_token(&login_procedure) || request_http_token_authentication(realm)
-
end
-
-
2
def authenticate_with_http_token(&login_procedure)
-
Token.authenticate(self, &login_procedure)
-
end
-
-
2
def request_http_token_authentication(realm = "Application")
-
Token.authentication_request(self, realm)
-
end
-
end
-
-
# If token Authorization header is present, call the login
-
# procedure with the present token and options.
-
#
-
# [controller]
-
# ActionController::Base instance for the current request.
-
#
-
# [login_procedure]
-
# Proc to call if a token is present. The Proc should take two arguments:
-
#
-
# authenticate(controller) { |token, options| ... }
-
#
-
# Returns the return value of <tt>login_procedure</tt> if a
-
# token is found. Returns <tt>nil</tt> if no token is found.
-
-
2
def authenticate(controller, &login_procedure)
-
token, options = token_and_options(controller.request)
-
unless token.blank?
-
login_procedure.call(token, options)
-
end
-
end
-
-
# Parses the token and options out of the token authorization header. If
-
# the header looks like this:
-
# Authorization: Token token="abc", nonce="def"
-
# Then the returned token is "abc", and the options is {nonce: "def"}
-
#
-
# request - ActionDispatch::Request instance with the current headers.
-
#
-
# Returns an Array of [String, Hash] if a token is present.
-
# Returns nil if no token is found.
-
2
def token_and_options(request)
-
authorization_request = request.authorization.to_s
-
if authorization_request[TOKEN_REGEX]
-
params = token_params_from authorization_request
-
[params.shift[1], Hash[params].with_indifferent_access]
-
end
-
end
-
-
2
def token_params_from(auth)
-
rewrite_param_values params_array_from raw_params auth
-
end
-
-
# Takes raw_params and turns it into an array of parameters
-
2
def params_array_from(raw_params)
-
raw_params.map { |param| param.split %r/=(.+)?/ }
-
end
-
-
# This removes the `"` characters wrapping the value.
-
2
def rewrite_param_values(array_params)
-
array_params.each { |param| (param[1] || "").gsub! %r/^"|"$/, '' }
-
end
-
-
# This method takes an authorization body and splits up the key-value
-
# pairs by the standardized `:`, `;`, or `\t` delimiters defined in
-
# `AUTHN_PAIR_DELIMITERS`.
-
2
def raw_params(auth)
-
auth.sub(TOKEN_REGEX, '').split(/"\s*#{AUTHN_PAIR_DELIMITERS}\s*/)
-
end
-
-
# Encodes the given token and options into an Authorization header value.
-
#
-
# token - String token.
-
# options - optional Hash of the options.
-
#
-
# Returns String.
-
2
def encode_credentials(token, options = {})
-
values = ["token=#{token.to_s.inspect}"] + options.map do |key, value|
-
"#{key}=#{value.to_s.inspect}"
-
end
-
"Token #{values * ", "}"
-
end
-
-
# Sets a WWW-Authenticate to let the client know a token is desired.
-
#
-
# controller - ActionController::Base instance for the outgoing response.
-
# realm - String realm to use in the header.
-
#
-
# Returns nothing.
-
2
def authentication_request(controller, realm)
-
controller.headers["WWW-Authenticate"] = %(Token realm="#{realm.gsub(/"/, "")}")
-
controller.__send__ :render, :text => "HTTP Token: Access denied.\n", :status => :unauthorized
-
end
-
end
-
end
-
end
-
2
module ActionController
-
2
module ImplicitRender
-
2
def send_action(method, *args)
-
24
ret = super
-
24
default_render unless performed?
-
24
ret
-
end
-
-
2
def default_render(*args)
-
20
render(*args)
-
end
-
-
2
def method_for_action(action_name)
-
super || if template_exists?(action_name.to_s, _prefixes)
-
"default_render"
-
24
end
-
end
-
end
-
end
-
2
require 'benchmark'
-
2
require 'abstract_controller/logger'
-
-
2
module ActionController
-
# Adds instrumentation to several ends in ActionController::Base. It also provides
-
# some hooks related with process_action, this allows an ORM like Active Record
-
# and/or DataMapper to plug in ActionController and show related information.
-
#
-
# Check ActiveRecord::Railties::ControllerRuntime for an example.
-
2
module Instrumentation
-
2
extend ActiveSupport::Concern
-
-
2
include AbstractController::Logger
-
2
include ActionController::RackDelegation
-
-
2
attr_internal :view_runtime
-
-
2
def process_action(*args)
-
24
raw_payload = {
-
:controller => self.class.name,
-
:action => self.action_name,
-
:params => request.filtered_parameters,
-
:format => request.format.try(:ref),
-
:method => request.method,
-
24
:path => (request.fullpath rescue "unknown")
-
}
-
-
24
ActiveSupport::Notifications.instrument("start_processing.action_controller", raw_payload.dup)
-
-
24
ActiveSupport::Notifications.instrument("process_action.action_controller", raw_payload) do |payload|
-
24
result = super
-
24
payload[:status] = response.status
-
24
append_info_to_payload(payload)
-
24
result
-
end
-
end
-
-
2
def render(*args)
-
24
render_output = nil
-
24
self.view_runtime = cleanup_view_runtime do
-
48
Benchmark.ms { render_output = super }
-
end
-
24
render_output
-
end
-
-
2
def send_file(path, options={})
-
ActiveSupport::Notifications.instrument("send_file.action_controller",
-
options.merge(:path => path)) do
-
super
-
end
-
end
-
-
2
def send_data(data, options = {})
-
ActiveSupport::Notifications.instrument("send_data.action_controller", options) do
-
super
-
end
-
end
-
-
2
def redirect_to(*args)
-
ActiveSupport::Notifications.instrument("redirect_to.action_controller") do |payload|
-
result = super
-
payload[:status] = response.status
-
payload[:location] = response.filtered_location
-
result
-
end
-
end
-
-
2
private
-
-
# A hook invoked every time a before callback is halted.
-
2
def halted_callback_hook(filter)
-
ActiveSupport::Notifications.instrument("halted_callback.action_controller", :filter => filter)
-
end
-
-
# A hook which allows you to clean up any time taken into account in
-
# views wrongly, like database querying time.
-
#
-
# def cleanup_view_runtime
-
# super - time_taken_in_something_expensive
-
# end
-
#
-
# :api: plugin
-
2
def cleanup_view_runtime #:nodoc:
-
24
yield
-
end
-
-
# Every time after an action is processed, this method is invoked
-
# with the payload, so you can add more information.
-
# :api: plugin
-
2
def append_info_to_payload(payload) #:nodoc:
-
24
payload[:view_runtime] = view_runtime
-
end
-
-
2
module ClassMethods
-
# A hook which allows other frameworks to log what happened during
-
# controller process action. This method should return an array
-
# with the messages to be added.
-
# :api: plugin
-
2
def log_process_action(payload) #:nodoc:
-
24
messages, view_runtime = [], payload[:view_runtime]
-
24
messages << ("Views: %.1fms" % view_runtime.to_f) if view_runtime
-
24
messages
-
end
-
end
-
end
-
end
-
2
require 'action_dispatch/http/response'
-
2
require 'delegate'
-
2
require 'active_support/json'
-
-
2
module ActionController
-
# Mix this module in to your controller, and all actions in that controller
-
# will be able to stream data to the client as it's written.
-
#
-
# class MyController < ActionController::Base
-
# include ActionController::Live
-
#
-
# def stream
-
# response.headers['Content-Type'] = 'text/event-stream'
-
# 100.times {
-
# response.stream.write "hello world\n"
-
# sleep 1
-
# }
-
# ensure
-
# response.stream.close
-
# end
-
# end
-
#
-
# There are a few caveats with this use. You *cannot* write headers after the
-
# response has been committed (Response#committed? will return truthy).
-
# Calling +write+ or +close+ on the response stream will cause the response
-
# object to be committed. Make sure all headers are set before calling write
-
# or close on your stream.
-
#
-
# You *must* call close on your stream when you're finished, otherwise the
-
# socket may be left open forever.
-
#
-
# The final caveat is that your actions are executed in a separate thread than
-
# the main thread. Make sure your actions are thread safe, and this shouldn't
-
# be a problem (don't share state across threads, etc).
-
2
module Live
-
# This class provides the ability to write an SSE (Server Sent Event)
-
# to an IO stream. The class is initialized with a stream and can be used
-
# to either write a JSON string or an object which can be converted to JSON.
-
#
-
# Writing an object will convert it into standard SSE format with whatever
-
# options you have configured. You may choose to set the following options:
-
#
-
# 1) Event. If specified, an event with this name will be dispatched on
-
# the browser.
-
# 2) Retry. The reconnection time in milliseconds used when attempting
-
# to send the event.
-
# 3) Id. If the connection dies while sending an SSE to the browser, then
-
# the server will receive a +Last-Event-ID+ header with value equal to +id+.
-
#
-
# After setting an option in the constructor of the SSE object, all future
-
# SSEs sent across the stream will use those options unless overridden.
-
#
-
# Example Usage:
-
#
-
# class MyController < ActionController::Base
-
# include ActionController::Live
-
#
-
# def index
-
# response.headers['Content-Type'] = 'text/event-stream'
-
# sse = SSE.new(response.stream, retry: 300, event: "event-name")
-
# sse.write({ name: 'John'})
-
# sse.write({ name: 'John'}, id: 10)
-
# sse.write({ name: 'John'}, id: 10, event: "other-event")
-
# sse.write({ name: 'John'}, id: 10, event: "other-event", retry: 500)
-
# ensure
-
# sse.close
-
# end
-
# end
-
#
-
# Note: SSEs are not currently supported by IE. However, they are supported
-
# by Chrome, Firefox, Opera, and Safari.
-
2
class SSE
-
-
2
WHITELISTED_OPTIONS = %w( retry event id )
-
-
2
def initialize(stream, options = {})
-
@stream = stream
-
@options = options
-
end
-
-
2
def close
-
@stream.close
-
end
-
-
2
def write(object, options = {})
-
case object
-
when String
-
perform_write(object, options)
-
else
-
perform_write(ActiveSupport::JSON.encode(object), options)
-
end
-
end
-
-
2
private
-
-
2
def perform_write(json, options)
-
current_options = @options.merge(options).stringify_keys
-
-
WHITELISTED_OPTIONS.each do |option_name|
-
if (option_value = current_options[option_name])
-
@stream.write "#{option_name}: #{option_value}\n"
-
end
-
end
-
-
@stream.write "data: #{json}\n\n"
-
end
-
end
-
-
2
class Buffer < ActionDispatch::Response::Buffer #:nodoc:
-
2
include MonitorMixin
-
-
2
def initialize(response)
-
@error_callback = lambda { true }
-
@cv = new_cond
-
super(response, SizedQueue.new(10))
-
end
-
-
2
def write(string)
-
unless @response.committed?
-
@response.headers["Cache-Control"] = "no-cache"
-
@response.headers.delete "Content-Length"
-
end
-
-
super
-
end
-
-
2
def each
-
@response.sending!
-
while str = @buf.pop
-
yield str
-
end
-
@response.sent!
-
end
-
-
2
def close
-
synchronize do
-
super
-
@buf.push nil
-
@cv.broadcast
-
end
-
end
-
-
2
def await_close
-
synchronize do
-
@cv.wait_until { @closed }
-
end
-
end
-
-
2
def on_error(&block)
-
@error_callback = block
-
end
-
-
2
def call_on_error
-
@error_callback.call
-
end
-
end
-
-
2
class Response < ActionDispatch::Response #:nodoc: all
-
2
class Header < DelegateClass(Hash)
-
2
def initialize(response, header)
-
@response = response
-
super(header)
-
end
-
-
2
def []=(k,v)
-
if @response.committed?
-
raise ActionDispatch::IllegalStateError, 'header already sent'
-
end
-
-
super
-
end
-
-
2
def merge(other)
-
self.class.new @response, __getobj__.merge(other)
-
end
-
-
2
def to_hash
-
__getobj__.dup
-
end
-
end
-
-
2
private
-
-
2
def before_committed
-
super
-
jar = request.cookie_jar
-
# The response can be committed multiple times
-
jar.write self unless committed?
-
end
-
-
2
def before_sending
-
super
-
request.cookie_jar.commit!
-
headers.freeze
-
end
-
-
2
def build_buffer(response, body)
-
buf = Live::Buffer.new response
-
body.each { |part| buf.write part }
-
buf
-
end
-
-
2
def merge_default_headers(original, default)
-
Header.new self, super
-
end
-
-
2
def handle_conditional_get!
-
super unless committed?
-
end
-
end
-
-
2
def process(name)
-
t1 = Thread.current
-
locals = t1.keys.map { |key| [key, t1[key]] }
-
-
error = nil
-
# This processes the action in a child thread. It lets us return the
-
# response code and headers back up the rack stack, and still process
-
# the body in parallel with sending data to the client
-
Thread.new {
-
t2 = Thread.current
-
t2.abort_on_exception = true
-
-
# Since we're processing the view in a different thread, copy the
-
# thread locals from the main thread to the child thread. :'(
-
locals.each { |k,v| t2[k] = v }
-
-
begin
-
super(name)
-
rescue => e
-
if @_response.committed?
-
begin
-
@_response.stream.write(ActionView::Base.streaming_completion_on_exception) if request.format == :html
-
@_response.stream.call_on_error
-
rescue => exception
-
log_error(exception)
-
ensure
-
log_error(e)
-
@_response.stream.close
-
end
-
else
-
error = e
-
end
-
ensure
-
@_response.commit!
-
end
-
}
-
-
@_response.await_commit
-
raise error if error
-
end
-
-
2
def log_error(exception)
-
logger = ActionController::Base.logger
-
return unless logger
-
-
message = "\n#{exception.class} (#{exception.message}):\n"
-
message << exception.annoted_source_code.to_s if exception.respond_to?(:annoted_source_code)
-
message << " " << exception.backtrace.join("\n ")
-
logger.fatal("#{message}\n\n")
-
end
-
-
2
def response_body=(body)
-
super
-
response.close if response
-
end
-
-
2
def set_response!(request)
-
if request.env["HTTP_VERSION"] == "HTTP/1.0"
-
super
-
else
-
@_response = Live::Response.new
-
@_response.request = request
-
end
-
end
-
end
-
end
-
2
require 'active_support/core_ext/array/extract_options'
-
2
require 'abstract_controller/collector'
-
-
2
module ActionController #:nodoc:
-
2
module MimeResponds
-
2
extend ActiveSupport::Concern
-
-
2
included do
-
2
class_attribute :responder, :mimes_for_respond_to
-
2
self.responder = ActionController::Responder
-
2
clear_respond_to
-
end
-
-
2
module ClassMethods
-
# Defines mime types that are rendered by default when invoking
-
# <tt>respond_with</tt>.
-
#
-
# respond_to :html, :xml, :json
-
#
-
# Specifies that all actions in the controller respond to requests
-
# for <tt>:html</tt>, <tt>:xml</tt> and <tt>:json</tt>.
-
#
-
# To specify on per-action basis, use <tt>:only</tt> and
-
# <tt>:except</tt> with an array of actions or a single action:
-
#
-
# respond_to :html
-
# respond_to :xml, :json, except: [ :edit ]
-
#
-
# This specifies that all actions respond to <tt>:html</tt>
-
# and all actions except <tt>:edit</tt> respond to <tt>:xml</tt> and
-
# <tt>:json</tt>.
-
#
-
# respond_to :json, only: :create
-
#
-
# This specifies that the <tt>:create</tt> action and no other responds
-
# to <tt>:json</tt>.
-
2
def respond_to(*mimes)
-
options = mimes.extract_options!
-
-
only_actions = Array(options.delete(:only)).map(&:to_s)
-
except_actions = Array(options.delete(:except)).map(&:to_s)
-
-
new = mimes_for_respond_to.dup
-
mimes.each do |mime|
-
mime = mime.to_sym
-
new[mime] = {}
-
new[mime][:only] = only_actions unless only_actions.empty?
-
new[mime][:except] = except_actions unless except_actions.empty?
-
end
-
self.mimes_for_respond_to = new.freeze
-
end
-
-
# Clear all mime types in <tt>respond_to</tt>.
-
#
-
2
def clear_respond_to
-
2
self.mimes_for_respond_to = Hash.new.freeze
-
end
-
end
-
-
# Without web-service support, an action which collects the data for displaying a list of people
-
# might look something like this:
-
#
-
# def index
-
# @people = Person.all
-
# end
-
#
-
# Here's the same action, with web-service support baked in:
-
#
-
# def index
-
# @people = Person.all
-
#
-
# respond_to do |format|
-
# format.html
-
# format.xml { render xml: @people }
-
# end
-
# end
-
#
-
# What that says is, "if the client wants HTML in response to this action, just respond as we
-
# would have before, but if the client wants XML, return them the list of people in XML format."
-
# (Rails determines the desired response format from the HTTP Accept header submitted by the client.)
-
#
-
# Supposing you have an action that adds a new person, optionally creating their company
-
# (by name) if it does not already exist, without web-services, it might look like this:
-
#
-
# def create
-
# @company = Company.find_or_create_by(name: params[:company][:name])
-
# @person = @company.people.create(params[:person])
-
#
-
# redirect_to(person_list_url)
-
# end
-
#
-
# Here's the same action, with web-service support baked in:
-
#
-
# def create
-
# company = params[:person].delete(:company)
-
# @company = Company.find_or_create_by(name: company[:name])
-
# @person = @company.people.create(params[:person])
-
#
-
# respond_to do |format|
-
# format.html { redirect_to(person_list_url) }
-
# format.js
-
# format.xml { render xml: @person.to_xml(include: @company) }
-
# end
-
# end
-
#
-
# If the client wants HTML, we just redirect them back to the person list. If they want JavaScript,
-
# then it is an Ajax request and we render the JavaScript template associated with this action.
-
# Lastly, if the client wants XML, we render the created person as XML, but with a twist: we also
-
# include the person's company in the rendered XML, so you get something like this:
-
#
-
# <person>
-
# <id>...</id>
-
# ...
-
# <company>
-
# <id>...</id>
-
# <name>...</name>
-
# ...
-
# </company>
-
# </person>
-
#
-
# Note, however, the extra bit at the top of that action:
-
#
-
# company = params[:person].delete(:company)
-
# @company = Company.find_or_create_by(name: company[:name])
-
#
-
# This is because the incoming XML document (if a web-service request is in process) can only contain a
-
# single root-node. So, we have to rearrange things so that the request looks like this (url-encoded):
-
#
-
# person[name]=...&person[company][name]=...&...
-
#
-
# And, like this (xml-encoded):
-
#
-
# <person>
-
# <name>...</name>
-
# <company>
-
# <name>...</name>
-
# </company>
-
# </person>
-
#
-
# In other words, we make the request so that it operates on a single entity's person. Then, in the action,
-
# we extract the company data from the request, find or create the company, and then create the new person
-
# with the remaining data.
-
#
-
# Note that you can define your own XML parameter parser which would allow you to describe multiple entities
-
# in a single request (i.e., by wrapping them all in a single root node), but if you just go with the flow
-
# and accept Rails' defaults, life will be much easier.
-
#
-
# If you need to use a MIME type which isn't supported by default, you can register your own handlers in
-
# config/initializers/mime_types.rb as follows.
-
#
-
# Mime::Type.register "image/jpg", :jpg
-
#
-
# Respond to also allows you to specify a common block for different formats by using any:
-
#
-
# def index
-
# @people = Person.all
-
#
-
# respond_to do |format|
-
# format.html
-
# format.any(:xml, :json) { render request.format.to_sym => @people }
-
# end
-
# end
-
#
-
# In the example above, if the format is xml, it will render:
-
#
-
# render xml: @people
-
#
-
# Or if the format is json:
-
#
-
# render json: @people
-
#
-
# Since this is a common pattern, you can use the class method respond_to
-
# with the respond_with method to have the same results:
-
#
-
# class PeopleController < ApplicationController
-
# respond_to :html, :xml, :json
-
#
-
# def index
-
# @people = Person.all
-
# respond_with(@people)
-
# end
-
# end
-
#
-
# Formats can have different variants.
-
#
-
# The request variant is a specialization of the request format, like <tt>:tablet</tt>,
-
# <tt>:phone</tt>, or <tt>:desktop</tt>.
-
#
-
# We often want to render different html/json/xml templates for phones,
-
# tablets, and desktop browsers. Variants make it easy.
-
#
-
# You can set the variant in a +before_action+:
-
#
-
# request.variant = :tablet if request.user_agent =~ /iPad/
-
#
-
# Respond to variants in the action just like you respond to formats:
-
#
-
# respond_to do |format|
-
# format.html do |variant|
-
# variant.tablet # renders app/views/projects/show.html+tablet.erb
-
# variant.phone { extra_setup; render ... }
-
# variant.none { special_setup } # executed only if there is no variant set
-
# end
-
# end
-
#
-
# Provide separate templates for each format and variant:
-
#
-
# app/views/projects/show.html.erb
-
# app/views/projects/show.html+tablet.erb
-
# app/views/projects/show.html+phone.erb
-
#
-
# When you're not sharing any code within the format, you can simplify defining variants
-
# using the inline syntax:
-
#
-
# respond_to do |format|
-
# format.js { render "trash" }
-
# format.html.phone { redirect_to progress_path }
-
# format.html.none { render "trash" }
-
# end
-
#
-
# Variants also support common `any`/`all` block that formats have.
-
#
-
# It works for both inline:
-
#
-
# respond_to do |format|
-
# format.html.any { render text: "any" }
-
# format.html.phone { render text: "phone" }
-
# end
-
#
-
# and block syntax:
-
#
-
# respond_to do |format|
-
# format.html do |variant|
-
# variant.any(:tablet, :phablet){ render text: "any" }
-
# variant.phone { render text: "phone" }
-
# end
-
# end
-
#
-
# You can also set an array of variants:
-
#
-
# request.variant = [:tablet, :phone]
-
#
-
# which will work similarly to formats and MIME types negotiation. If there will be no
-
# :tablet variant declared, :phone variant will be picked:
-
#
-
# respond_to do |format|
-
# format.html.none
-
# format.html.phone # this gets rendered
-
# end
-
#
-
# Be sure to check the documentation of +respond_with+ and
-
# <tt>ActionController::MimeResponds.respond_to</tt> for more examples.
-
2
def respond_to(*mimes, &block)
-
raise ArgumentError, "respond_to takes either types or a block, never both" if mimes.any? && block_given?
-
-
if collector = retrieve_collector_from_mimes(mimes, &block)
-
response = collector.response
-
response ? response.call : render({})
-
end
-
end
-
-
# For a given controller action, respond_with generates an appropriate
-
# response based on the mime-type requested by the client.
-
#
-
# If the method is called with just a resource, as in this example -
-
#
-
# class PeopleController < ApplicationController
-
# respond_to :html, :xml, :json
-
#
-
# def index
-
# @people = Person.all
-
# respond_with @people
-
# end
-
# end
-
#
-
# then the mime-type of the response is typically selected based on the
-
# request's Accept header and the set of available formats declared
-
# by previous calls to the controller's class method +respond_to+. Alternatively
-
# the mime-type can be selected by explicitly setting <tt>request.format</tt> in
-
# the controller.
-
#
-
# If an acceptable format is not identified, the application returns a
-
# '406 - not acceptable' status. Otherwise, the default response is to render
-
# a template named after the current action and the selected format,
-
# e.g. <tt>index.html.erb</tt>. If no template is available, the behavior
-
# depends on the selected format:
-
#
-
# * for an html response - if the request method is +get+, an exception
-
# is raised but for other requests such as +post+ the response
-
# depends on whether the resource has any validation errors (i.e.
-
# assuming that an attempt has been made to save the resource,
-
# e.g. by a +create+ action) -
-
# 1. If there are no errors, i.e. the resource
-
# was saved successfully, the response +redirect+'s to the resource
-
# i.e. its +show+ action.
-
# 2. If there are validation errors, the response
-
# renders a default action, which is <tt>:new</tt> for a
-
# +post+ request or <tt>:edit</tt> for +patch+ or +put+.
-
# Thus an example like this -
-
#
-
# respond_to :html, :xml
-
#
-
# def create
-
# @user = User.new(params[:user])
-
# flash[:notice] = 'User was successfully created.' if @user.save
-
# respond_with(@user)
-
# end
-
#
-
# is equivalent, in the absence of <tt>create.html.erb</tt>, to -
-
#
-
# def create
-
# @user = User.new(params[:user])
-
# respond_to do |format|
-
# if @user.save
-
# flash[:notice] = 'User was successfully created.'
-
# format.html { redirect_to(@user) }
-
# format.xml { render xml: @user }
-
# else
-
# format.html { render action: "new" }
-
# format.xml { render xml: @user }
-
# end
-
# end
-
# end
-
#
-
# * for a javascript request - if the template isn't found, an exception is
-
# raised.
-
# * for other requests - i.e. data formats such as xml, json, csv etc, if
-
# the resource passed to +respond_with+ responds to <code>to_<format></code>,
-
# the method attempts to render the resource in the requested format
-
# directly, e.g. for an xml request, the response is equivalent to calling
-
# <code>render xml: resource</code>.
-
#
-
# === Nested resources
-
#
-
# As outlined above, the +resources+ argument passed to +respond_with+
-
# can play two roles. It can be used to generate the redirect url
-
# for successful html requests (e.g. for +create+ actions when
-
# no template exists), while for formats other than html and javascript
-
# it is the object that gets rendered, by being converted directly to the
-
# required format (again assuming no template exists).
-
#
-
# For redirecting successful html requests, +respond_with+ also supports
-
# the use of nested resources, which are supplied in the same way as
-
# in <code>form_for</code> and <code>polymorphic_url</code>. For example -
-
#
-
# def create
-
# @project = Project.find(params[:project_id])
-
# @task = @project.comments.build(params[:task])
-
# flash[:notice] = 'Task was successfully created.' if @task.save
-
# respond_with(@project, @task)
-
# end
-
#
-
# This would cause +respond_with+ to redirect to <code>project_task_url</code>
-
# instead of <code>task_url</code>. For request formats other than html or
-
# javascript, if multiple resources are passed in this way, it is the last
-
# one specified that is rendered.
-
#
-
# === Customizing response behavior
-
#
-
# Like +respond_to+, +respond_with+ may also be called with a block that
-
# can be used to overwrite any of the default responses, e.g. -
-
#
-
# def create
-
# @user = User.new(params[:user])
-
# flash[:notice] = "User was successfully created." if @user.save
-
#
-
# respond_with(@user) do |format|
-
# format.html { render }
-
# end
-
# end
-
#
-
# The argument passed to the block is an ActionController::MimeResponds::Collector
-
# object which stores the responses for the formats defined within the
-
# block. Note that formats with responses defined explicitly in this way
-
# do not have to first be declared using the class method +respond_to+.
-
#
-
# Also, a hash passed to +respond_with+ immediately after the specified
-
# resource(s) is interpreted as a set of options relevant to all
-
# formats. Any option accepted by +render+ can be used, e.g.
-
# respond_with @people, status: 200
-
# However, note that these options are ignored after an unsuccessful attempt
-
# to save a resource, e.g. when automatically rendering <tt>:new</tt>
-
# after a post request.
-
#
-
# Two additional options are relevant specifically to +respond_with+ -
-
# 1. <tt>:location</tt> - overwrites the default redirect location used after
-
# a successful html +post+ request.
-
# 2. <tt>:action</tt> - overwrites the default render action used after an
-
# unsuccessful html +post+ request.
-
2
def respond_with(*resources, &block)
-
if self.class.mimes_for_respond_to.empty?
-
raise "In order to use respond_with, first you need to declare the " \
-
"formats your controller responds to in the class level."
-
end
-
-
if collector = retrieve_collector_from_mimes(&block)
-
options = resources.size == 1 ? {} : resources.extract_options!
-
options = options.clone
-
options[:default_response] = collector.response
-
(options.delete(:responder) || self.class.responder).call(self, resources, options)
-
end
-
end
-
-
2
protected
-
-
# Collect mimes declared in the class method respond_to valid for the
-
# current action.
-
2
def collect_mimes_from_class_level #:nodoc:
-
action = action_name.to_s
-
-
self.class.mimes_for_respond_to.keys.select do |mime|
-
config = self.class.mimes_for_respond_to[mime]
-
-
if config[:except]
-
!config[:except].include?(action)
-
elsif config[:only]
-
config[:only].include?(action)
-
else
-
true
-
end
-
end
-
end
-
-
# Returns a Collector object containing the appropriate mime-type response
-
# for the current request, based on the available responses defined by a block.
-
# In typical usage this is the block passed to +respond_with+ or +respond_to+.
-
#
-
# Sends :not_acceptable to the client and returns nil if no suitable format
-
# is available.
-
2
def retrieve_collector_from_mimes(mimes=nil, &block) #:nodoc:
-
mimes ||= collect_mimes_from_class_level
-
collector = Collector.new(mimes, request.variant)
-
block.call(collector) if block_given?
-
format = collector.negotiate_format(request)
-
-
if format
-
_process_format(format)
-
collector
-
else
-
raise ActionController::UnknownFormat
-
end
-
end
-
-
# A container for responses available from the current controller for
-
# requests for different mime-types sent to a particular action.
-
#
-
# The public controller methods +respond_with+ and +respond_to+ may be called
-
# with a block that is used to define responses to different mime-types, e.g.
-
# for +respond_to+ :
-
#
-
# respond_to do |format|
-
# format.html
-
# format.xml { render xml: @people }
-
# end
-
#
-
# In this usage, the argument passed to the block (+format+ above) is an
-
# instance of the ActionController::MimeResponds::Collector class. This
-
# object serves as a container in which available responses can be stored by
-
# calling any of the dynamically generated, mime-type-specific methods such
-
# as +html+, +xml+ etc on the Collector. Each response is represented by a
-
# corresponding block if present.
-
#
-
# A subsequent call to #negotiate_format(request) will enable the Collector
-
# to determine which specific mime-type it should respond with for the current
-
# request, with this response then being accessible by calling #response.
-
2
class Collector
-
2
include AbstractController::Collector
-
2
attr_accessor :format
-
-
2
def initialize(mimes, variant = nil)
-
@responses = {}
-
@variant = variant
-
-
mimes.each { |mime| @responses["Mime::#{mime.upcase}".constantize] = nil }
-
end
-
-
2
def any(*args, &block)
-
if args.any?
-
args.each { |type| send(type, &block) }
-
else
-
custom(Mime::ALL, &block)
-
end
-
end
-
2
alias :all :any
-
-
2
def custom(mime_type, &block)
-
mime_type = Mime::Type.lookup(mime_type.to_s) unless mime_type.is_a?(Mime::Type)
-
@responses[mime_type] ||= if block_given?
-
block
-
else
-
VariantCollector.new(@variant)
-
end
-
end
-
-
2
def response
-
response = @responses.fetch(format, @responses[Mime::ALL])
-
if response.is_a?(VariantCollector) # `format.html.phone` - variant inline syntax
-
response.variant
-
elsif response.nil? || response.arity == 0 # `format.html` - just a format, call its block
-
response
-
else # `format.html{ |variant| variant.phone }` - variant block syntax
-
variant_collector = VariantCollector.new(@variant)
-
response.call(variant_collector) # call format block with variants collector
-
variant_collector.variant
-
end
-
end
-
-
2
def negotiate_format(request)
-
@format = request.negotiate_mime(@responses.keys)
-
end
-
-
2
class VariantCollector #:nodoc:
-
2
def initialize(variant = nil)
-
@variant = variant
-
@variants = {}
-
end
-
-
2
def any(*args, &block)
-
if block_given?
-
if args.any? && args.none?{ |a| a == @variant }
-
args.each{ |v| @variants[v] = block }
-
else
-
@variants[:any] = block
-
end
-
end
-
end
-
2
alias :all :any
-
-
2
def method_missing(name, *args, &block)
-
@variants[name] = block if block_given?
-
end
-
-
2
def variant
-
if @variant.nil?
-
@variants[:none] || @variants[:any]
-
elsif (@variants.keys & @variant).any?
-
@variant.each do |v|
-
return @variants[v] if @variants.key?(v)
-
end
-
else
-
@variants[:any]
-
end
-
end
-
end
-
end
-
end
-
end
-
2
require 'active_support/core_ext/hash/slice'
-
2
require 'active_support/core_ext/hash/except'
-
2
require 'active_support/core_ext/module/anonymous'
-
2
require 'active_support/core_ext/struct'
-
2
require 'action_dispatch/http/mime_type'
-
-
2
module ActionController
-
# Wraps the parameters hash into a nested hash. This will allow clients to submit
-
# POST requests without having to specify any root elements.
-
#
-
# This functionality is enabled in +config/initializers/wrap_parameters.rb+
-
# and can be customized. If you are upgrading to \Rails 3.1, this file will
-
# need to be created for the functionality to be enabled.
-
#
-
# You could also turn it on per controller by setting the format array to
-
# a non-empty array:
-
#
-
# class UsersController < ApplicationController
-
# wrap_parameters format: [:json, :xml]
-
# end
-
#
-
# If you enable +ParamsWrapper+ for +:json+ format, instead of having to
-
# send JSON parameters like this:
-
#
-
# {"user": {"name": "Konata"}}
-
#
-
# You can send parameters like this:
-
#
-
# {"name": "Konata"}
-
#
-
# And it will be wrapped into a nested hash with the key name matching the
-
# controller's name. For example, if you're posting to +UsersController+,
-
# your new +params+ hash will look like this:
-
#
-
# {"name" => "Konata", "user" => {"name" => "Konata"}}
-
#
-
# You can also specify the key in which the parameters should be wrapped to,
-
# and also the list of attributes it should wrap by using either +:include+ or
-
# +:exclude+ options like this:
-
#
-
# class UsersController < ApplicationController
-
# wrap_parameters :person, include: [:username, :password]
-
# end
-
#
-
# On ActiveRecord models with no +:include+ or +:exclude+ option set,
-
# it will only wrap the parameters returned by the class method
-
# <tt>attribute_names</tt>.
-
#
-
# If you're going to pass the parameters to an +ActiveModel+ object (such as
-
# <tt>User.new(params[:user])</tt>), you might consider passing the model class to
-
# the method instead. The +ParamsWrapper+ will actually try to determine the
-
# list of attribute names from the model and only wrap those attributes:
-
#
-
# class UsersController < ApplicationController
-
# wrap_parameters Person
-
# end
-
#
-
# You still could pass +:include+ and +:exclude+ to set the list of attributes
-
# you want to wrap.
-
#
-
# By default, if you don't specify the key in which the parameters would be
-
# wrapped to, +ParamsWrapper+ will actually try to determine if there's
-
# a model related to it or not. This controller, for example:
-
#
-
# class Admin::UsersController < ApplicationController
-
# end
-
#
-
# will try to check if <tt>Admin::User</tt> or +User+ model exists, and use it to
-
# determine the wrapper key respectively. If both models don't exist,
-
# it will then fallback to use +user+ as the key.
-
2
module ParamsWrapper
-
2
extend ActiveSupport::Concern
-
-
2
EXCLUDE_PARAMETERS = %w(authenticity_token _method utf8)
-
-
2
require 'mutex_m'
-
-
2
class Options < Struct.new(:name, :format, :include, :exclude, :klass, :model) # :nodoc:
-
2
include Mutex_m
-
-
2
def self.from_hash(hash)
-
4
name = hash[:name]
-
4
format = Array(hash[:format])
-
4
include = hash[:include] && Array(hash[:include]).collect(&:to_s)
-
4
exclude = hash[:exclude] && Array(hash[:exclude]).collect(&:to_s)
-
4
new name, format, include, exclude, nil, nil
-
end
-
-
2
def initialize(name, format, include, exclude, klass, model) # nodoc
-
4
super
-
4
@include_set = include
-
4
@name_set = name
-
end
-
-
2
def model
-
super || synchronize { super || self.model = _default_wrap_model }
-
end
-
-
2
def include
-
return super if @include_set
-
-
m = model
-
synchronize do
-
return super if @include_set
-
-
@include_set = true
-
-
unless super || exclude
-
if m.respond_to?(:attribute_names) && m.attribute_names.any?
-
self.include = m.attribute_names
-
end
-
end
-
end
-
end
-
-
2
def name
-
return super if @name_set
-
-
m = model
-
synchronize do
-
return super if @name_set
-
-
@name_set = true
-
-
unless super || klass.anonymous?
-
self.name = m ? m.to_s.demodulize.underscore :
-
klass.controller_name.singularize
-
end
-
end
-
end
-
-
2
private
-
# Determine the wrapper model from the controller's name. By convention,
-
# this could be done by trying to find the defined model that has the
-
# same singularize name as the controller. For example, +UsersController+
-
# will try to find if the +User+ model exists.
-
#
-
# This method also does namespace lookup. Foo::Bar::UsersController will
-
# try to find Foo::Bar::User, Foo::User and finally User.
-
2
def _default_wrap_model #:nodoc:
-
return nil if klass.anonymous?
-
model_name = klass.name.sub(/Controller$/, '').classify
-
-
begin
-
if model_klass = model_name.safe_constantize
-
model_klass
-
else
-
namespaces = model_name.split("::")
-
namespaces.delete_at(-2)
-
break if namespaces.last == model_name
-
model_name = namespaces.join("::")
-
end
-
end until model_klass
-
-
model_klass
-
end
-
end
-
-
2
included do
-
2
class_attribute :_wrapper_options
-
2
self._wrapper_options = Options.from_hash(format: [])
-
end
-
-
2
module ClassMethods
-
2
def _set_wrapper_options(options)
-
self._wrapper_options = Options.from_hash(options)
-
end
-
-
# Sets the name of the wrapper key, or the model which +ParamsWrapper+
-
# would use to determine the attribute names from.
-
#
-
# ==== Examples
-
# wrap_parameters format: :xml
-
# # enables the parameter wrapper for XML format
-
#
-
# wrap_parameters :person
-
# # wraps parameters into +params[:person]+ hash
-
#
-
# wrap_parameters Person
-
# # wraps parameters by determining the wrapper key from Person class
-
# (+person+, in this case) and the list of attribute names
-
#
-
# wrap_parameters include: [:username, :title]
-
# # wraps only +:username+ and +:title+ attributes from parameters.
-
#
-
# wrap_parameters false
-
# # disables parameters wrapping for this controller altogether.
-
#
-
# ==== Options
-
# * <tt>:format</tt> - The list of formats in which the parameters wrapper
-
# will be enabled.
-
# * <tt>:include</tt> - The list of attribute names which parameters wrapper
-
# will wrap into a nested hash.
-
# * <tt>:exclude</tt> - The list of attribute names which parameters wrapper
-
# will exclude from a nested hash.
-
2
def wrap_parameters(name_or_model_or_options, options = {})
-
2
model = nil
-
-
2
case name_or_model_or_options
-
when Hash
-
2
options = name_or_model_or_options
-
when false
-
options = options.merge(:format => [])
-
when Symbol, String
-
options = options.merge(:name => name_or_model_or_options)
-
else
-
model = name_or_model_or_options
-
end
-
-
2
opts = Options.from_hash _wrapper_options.to_h.slice(:format).merge(options)
-
2
opts.model = model
-
2
opts.klass = self
-
-
2
self._wrapper_options = opts
-
end
-
-
# Sets the default wrapper key or model which will be used to determine
-
# wrapper key and attribute names. Will be called automatically when the
-
# module is inherited.
-
2
def inherited(klass)
-
13
if klass._wrapper_options.format.any?
-
13
params = klass._wrapper_options.dup
-
13
params.klass = klass
-
13
klass._wrapper_options = params
-
end
-
13
super
-
end
-
end
-
-
# Performs parameters wrapping upon the request. Will be called automatically
-
# by the metal call stack.
-
2
def process_action(*args)
-
24
if _wrapper_enabled?
-
if request.parameters[_wrapper_key].present?
-
wrapped_hash = _extract_parameters(request.parameters)
-
else
-
wrapped_hash = _wrap_parameters request.request_parameters
-
end
-
-
wrapped_keys = request.request_parameters.keys
-
wrapped_filtered_hash = _wrap_parameters request.filtered_parameters.slice(*wrapped_keys)
-
-
# This will make the wrapped hash accessible from controller and view
-
request.parameters.merge! wrapped_hash
-
request.request_parameters.merge! wrapped_hash
-
-
# This will make the wrapped hash displayed in the log file
-
request.filtered_parameters.merge! wrapped_filtered_hash
-
end
-
24
super
-
end
-
-
2
private
-
-
# Returns the wrapper key which will use to stored wrapped parameters.
-
2
def _wrapper_key
-
_wrapper_options.name
-
end
-
-
# Returns the list of enabled formats.
-
2
def _wrapper_formats
-
24
_wrapper_options.format
-
end
-
-
# Returns the list of parameters which will be selected for wrapped.
-
2
def _wrap_parameters(parameters)
-
{ _wrapper_key => _extract_parameters(parameters) }
-
end
-
-
2
def _extract_parameters(parameters)
-
if include_only = _wrapper_options.include
-
parameters.slice(*include_only)
-
else
-
exclude = _wrapper_options.exclude || []
-
parameters.except(*(exclude + EXCLUDE_PARAMETERS))
-
end
-
end
-
-
# Checks if we should perform parameters wrapping.
-
2
def _wrapper_enabled?
-
24
ref = request.content_mime_type.try(:ref)
-
24
_wrapper_formats.include?(ref) && _wrapper_key && !request.request_parameters[_wrapper_key]
-
end
-
end
-
end
-
2
require 'action_dispatch/http/request'
-
2
require 'action_dispatch/http/response'
-
-
2
module ActionController
-
2
module RackDelegation
-
2
extend ActiveSupport::Concern
-
-
2
delegate :headers, :status=, :location=, :content_type=,
-
:status, :location, :content_type, :_status_code, :to => "@_response"
-
-
2
def dispatch(action, request)
-
13
set_response!(request)
-
13
super(action, request)
-
end
-
-
2
def response_body=(body)
-
24
response.body = body if response
-
24
super
-
end
-
-
2
def reset_session
-
@_request.reset_session
-
end
-
-
2
private
-
-
2
def set_response!(request)
-
13
@_response = ActionDispatch::Response.new
-
13
@_response.request = request
-
end
-
end
-
end
-
2
module ActionController
-
2
class RedirectBackError < AbstractController::Error #:nodoc:
-
2
DEFAULT_MESSAGE = 'No HTTP_REFERER was set in the request to this action, so redirect_to :back could not be called successfully. If this is a test, make sure to specify request.env["HTTP_REFERER"].'
-
-
2
def initialize(message = nil)
-
super(message || DEFAULT_MESSAGE)
-
end
-
end
-
-
2
module Redirecting
-
2
extend ActiveSupport::Concern
-
-
2
include AbstractController::Logger
-
2
include ActionController::RackDelegation
-
2
include ActionController::UrlFor
-
-
# Redirects the browser to the target specified in +options+. This parameter can take one of three forms:
-
#
-
# * <tt>Hash</tt> - The URL will be generated by calling url_for with the +options+.
-
# * <tt>Record</tt> - The URL will be generated by calling url_for with the +options+, which will reference a named URL for that record.
-
# * <tt>String</tt> starting with <tt>protocol://</tt> (like <tt>http://</tt>) or a protocol relative reference (like <tt>//</tt>) - Is passed straight through as the target for redirection.
-
# * <tt>String</tt> not containing a protocol - The current protocol and host is prepended to the string.
-
# * <tt>Proc</tt> - A block that will be executed in the controller's context. Should return any option accepted by +redirect_to+.
-
# * <tt>:back</tt> - Back to the page that issued the request. Useful for forms that are triggered from multiple places.
-
# Short-hand for <tt>redirect_to(request.env["HTTP_REFERER"])</tt>
-
#
-
# redirect_to action: "show", id: 5
-
# redirect_to post
-
# redirect_to "http://www.rubyonrails.org"
-
# redirect_to "/images/screenshot.jpg"
-
# redirect_to articles_url
-
# redirect_to :back
-
# redirect_to proc { edit_post_url(@post) }
-
#
-
# The redirection happens as a "302 Found" header unless otherwise specified.
-
#
-
# redirect_to post_url(@post), status: :found
-
# redirect_to action: 'atom', status: :moved_permanently
-
# redirect_to post_url(@post), status: 301
-
# redirect_to action: 'atom', status: 302
-
#
-
# The status code can either be a standard {HTTP Status code}[http://www.iana.org/assignments/http-status-codes] as an
-
# integer, or a symbol representing the downcased, underscored and symbolized description.
-
# Note that the status code must be a 3xx HTTP code, or redirection will not occur.
-
#
-
# If you are using XHR requests other than GET or POST and redirecting after the
-
# request then some browsers will follow the redirect using the original request
-
# method. This may lead to undesirable behavior such as a double DELETE. To work
-
# around this you can return a <tt>303 See Other</tt> status code which will be
-
# followed using a GET request.
-
#
-
# redirect_to posts_url, status: :see_other
-
# redirect_to action: 'index', status: 303
-
#
-
# It is also possible to assign a flash message as part of the redirection. There are two special accessors for the commonly used flash names
-
# +alert+ and +notice+ as well as a general purpose +flash+ bucket.
-
#
-
# redirect_to post_url(@post), alert: "Watch it, mister!"
-
# redirect_to post_url(@post), status: :found, notice: "Pay attention to the road"
-
# redirect_to post_url(@post), status: 301, flash: { updated_post_id: @post.id }
-
# redirect_to({ action: 'atom' }, alert: "Something serious happened")
-
#
-
# When using <tt>redirect_to :back</tt>, if there is no referrer, ActionController::RedirectBackError will be raised. You may specify some fallback
-
# behavior for this case by rescuing ActionController::RedirectBackError.
-
2
def redirect_to(options = {}, response_status = {}) #:doc:
-
raise ActionControllerError.new("Cannot redirect to nil!") unless options
-
raise ActionControllerError.new("Cannot redirect to a parameter hash!") if options.is_a?(ActionController::Parameters)
-
raise AbstractController::DoubleRenderError if response_body
-
-
self.status = _extract_redirect_to_status(options, response_status)
-
self.location = _compute_redirect_to_location(options)
-
self.response_body = "<html><body>You are being <a href=\"#{ERB::Util.h(location)}\">redirected</a>.</body></html>"
-
end
-
-
2
def _compute_redirect_to_location(options) #:nodoc:
-
case options
-
# The scheme name consist of a letter followed by any combination of
-
# letters, digits, and the plus ("+"), period ("."), or hyphen ("-")
-
# characters; and is terminated by a colon (":").
-
# See http://tools.ietf.org/html/rfc3986#section-3.1
-
# The protocol relative scheme starts with a double slash "//".
-
when /\A([a-z][a-z\d\-+\.]*:|\/\/).*/i
-
options
-
when String
-
request.protocol + request.host_with_port + options
-
when :back
-
request.headers["Referer"] or raise RedirectBackError
-
when Proc
-
_compute_redirect_to_location options.call
-
else
-
url_for(options)
-
end.delete("\0\r\n")
-
end
-
-
2
private
-
2
def _extract_redirect_to_status(options, response_status)
-
if options.is_a?(Hash) && options.key?(:status)
-
Rack::Utils.status_code(options.delete(:status))
-
elsif response_status.key?(:status)
-
Rack::Utils.status_code(response_status[:status])
-
else
-
302
-
end
-
end
-
end
-
end
-
2
require 'set'
-
-
2
module ActionController
-
# See <tt>Renderers.add</tt>
-
2
def self.add_renderer(key, &block)
-
Renderers.add(key, &block)
-
end
-
-
2
class MissingRenderer < LoadError
-
2
def initialize(format)
-
super "No renderer defined for format: #{format}"
-
end
-
end
-
-
2
module Renderers
-
2
extend ActiveSupport::Concern
-
-
2
included do
-
2
class_attribute :_renderers
-
2
self._renderers = Set.new.freeze
-
end
-
-
2
module ClassMethods
-
2
def use_renderers(*args)
-
renderers = _renderers + args
-
self._renderers = renderers.freeze
-
end
-
2
alias use_renderer use_renderers
-
end
-
-
2
def render_to_body(options)
-
24
_handle_render_options(options) || super
-
end
-
-
2
def _handle_render_options(options)
-
24
_renderers.each do |name|
-
72
if options.key?(name)
-
_process_options(options)
-
return send("_render_option_#{name}", options.delete(name), options)
-
end
-
end
-
nil
-
end
-
-
# Hash of available renderers, mapping a renderer name to its proc.
-
# Default keys are <tt>:json</tt>, <tt>:js</tt>, <tt>:xml</tt>.
-
2
RENDERERS = Set.new
-
-
# Adds a new renderer to call within controller actions.
-
# A renderer is invoked by passing its name as an option to
-
# <tt>AbstractController::Rendering#render</tt>. To create a renderer
-
# pass it a name and a block. The block takes two arguments, the first
-
# is the value paired with its key and the second is the remaining
-
# hash of options passed to +render+.
-
#
-
# Create a csv renderer:
-
#
-
# ActionController::Renderers.add :csv do |obj, options|
-
# filename = options[:filename] || 'data'
-
# str = obj.respond_to?(:to_csv) ? obj.to_csv : obj.to_s
-
# send_data str, type: Mime::CSV,
-
# disposition: "attachment; filename=#{filename}.csv"
-
# end
-
#
-
# Note that we used Mime::CSV for the csv mime type as it comes with Rails.
-
# For a custom renderer, you'll need to register a mime type with
-
# <tt>Mime::Type.register</tt>.
-
#
-
# To use the csv renderer in a controller action:
-
#
-
# def show
-
# @csvable = Csvable.find(params[:id])
-
# respond_to do |format|
-
# format.html
-
# format.csv { render csv: @csvable, filename: @csvable.name }
-
# }
-
# end
-
# To use renderers and their mime types in more concise ways, see
-
# <tt>ActionController::MimeResponds::ClassMethods.respond_to</tt> and
-
# <tt>ActionController::MimeResponds#respond_with</tt>
-
2
def self.add(key, &block)
-
6
define_method("_render_option_#{key}", &block)
-
6
RENDERERS << key.to_sym
-
end
-
-
2
module All
-
2
extend ActiveSupport::Concern
-
2
include Renderers
-
-
2
included do
-
2
self._renderers = RENDERERS
-
end
-
end
-
-
2
add :json do |json, options|
-
json = json.to_json(options) unless json.kind_of?(String)
-
-
if options[:callback].present?
-
if self.content_type.nil? || self.content_type == Mime::JSON
-
self.content_type = Mime::JS
-
end
-
-
"/**/#{options[:callback]}(#{json})"
-
else
-
self.content_type ||= Mime::JSON
-
json
-
end
-
end
-
-
2
add :js do |js, options|
-
self.content_type ||= Mime::JS
-
js.respond_to?(:to_js) ? js.to_js(options) : js
-
end
-
-
2
add :xml do |xml, options|
-
self.content_type ||= Mime::XML
-
xml.respond_to?(:to_xml) ? xml.to_xml(options) : xml
-
end
-
end
-
end
-
2
module ActionController
-
2
module Rendering
-
2
extend ActiveSupport::Concern
-
-
2
RENDER_FORMATS_IN_PRIORITY = [:body, :text, :plain, :html]
-
-
# Before processing, set the request formats in current controller formats.
-
2
def process_action(*) #:nodoc:
-
24
self.formats = request.formats.map(&:ref).compact
-
24
super
-
end
-
-
# Check for double render errors and set the content_type after rendering.
-
2
def render(*args) #:nodoc:
-
24
raise ::AbstractController::DoubleRenderError if self.response_body
-
24
super
-
end
-
-
# Overwrite render_to_string because body can now be set to a rack body.
-
2
def render_to_string(*)
-
result = super
-
if result.respond_to?(:each)
-
string = ""
-
result.each { |r| string << r }
-
string
-
else
-
result
-
end
-
end
-
-
2
def render_to_body(options = {})
-
24
super || _render_in_priorities(options) || ' '
-
end
-
-
2
private
-
-
2
def _render_in_priorities(options)
-
RENDER_FORMATS_IN_PRIORITY.each do |format|
-
return options[format] if options.key?(format)
-
end
-
-
nil
-
end
-
-
2
def _process_format(format, options = {})
-
24
super
-
-
24
if options[:plain]
-
self.content_type = Mime::TEXT
-
else
-
24
self.content_type ||= format.to_s
-
end
-
end
-
-
# Normalize arguments by catching blocks and setting them on :update.
-
2
def _normalize_args(action=nil, options={}, &blk) #:nodoc:
-
24
options = super
-
24
options[:update] = blk if block_given?
-
24
options
-
end
-
-
# Normalize both text and status options.
-
2
def _normalize_options(options) #:nodoc:
-
24
_normalize_text(options)
-
-
24
if options[:html]
-
options[:html] = ERB::Util.html_escape(options[:html])
-
end
-
-
24
if options.delete(:nothing) || _any_render_format_is_nil?(options)
-
options[:body] = " "
-
end
-
-
24
if options[:status]
-
options[:status] = Rack::Utils.status_code(options[:status])
-
end
-
-
24
super
-
end
-
-
2
def _normalize_text(options)
-
24
RENDER_FORMATS_IN_PRIORITY.each do |format|
-
96
if options.key?(format) && options[format].respond_to?(:to_text)
-
options[format] = options[format].to_text
-
end
-
end
-
end
-
-
2
def _any_render_format_is_nil?(options)
-
120
RENDER_FORMATS_IN_PRIORITY.any? { |format| options.key?(format) && options[format].nil? }
-
end
-
-
# Process controller specific options, as status, content-type and location.
-
2
def _process_options(options) #:nodoc:
-
24
status, content_type, location = options.values_at(:status, :content_type, :location)
-
-
24
self.status = status if status
-
24
self.content_type = content_type if content_type
-
24
self.headers["Location"] = url_for(location) if location
-
-
24
super
-
end
-
end
-
end
-
2
require 'rack/session/abstract/id'
-
2
require 'action_controller/metal/exceptions'
-
-
2
module ActionController #:nodoc:
-
2
class InvalidAuthenticityToken < ActionControllerError #:nodoc:
-
end
-
-
2
class InvalidCrossOriginRequest < ActionControllerError #:nodoc:
-
end
-
-
# Controller actions are protected from Cross-Site Request Forgery (CSRF) attacks
-
# by including a token in the rendered html for your application. This token is
-
# stored as a random string in the session, to which an attacker does not have
-
# access. When a request reaches your application, \Rails verifies the received
-
# token with the token in the session. Only HTML and JavaScript requests are checked,
-
# so this will not protect your XML API (presumably you'll have a different
-
# authentication scheme there anyway).
-
#
-
# GET requests are not protected since they don't have side effects like writing
-
# to the database and don't leak sensitive information. JavaScript requests are
-
# an exception: a third-party site can use a <script> tag to reference a JavaScript
-
# URL on your site. When your JavaScript response loads on their site, it executes.
-
# With carefully crafted JavaScript on their end, sensitive data in your JavaScript
-
# response may be extracted. To prevent this, only XmlHttpRequest (known as XHR or
-
# Ajax) requests are allowed to make GET requests for JavaScript responses.
-
#
-
# It's important to remember that XML or JSON requests are also affected and if
-
# you're building an API you'll need something like:
-
#
-
# class ApplicationController < ActionController::Base
-
# protect_from_forgery
-
# skip_before_action :verify_authenticity_token, if: :json_request?
-
#
-
# protected
-
#
-
# def json_request?
-
# request.format.json?
-
# end
-
# end
-
#
-
# CSRF protection is turned on with the <tt>protect_from_forgery</tt> method,
-
# which checks the token and resets the session if it doesn't match what was expected.
-
# A call to this method is generated for new \Rails applications by default.
-
#
-
# The token parameter is named <tt>authenticity_token</tt> by default. The name and
-
# value of this token must be added to every layout that renders forms by including
-
# <tt>csrf_meta_tags</tt> in the html +head+.
-
#
-
# Learn more about CSRF attacks and securing your application in the
-
# {Ruby on Rails Security Guide}[http://guides.rubyonrails.org/security.html].
-
2
module RequestForgeryProtection
-
2
extend ActiveSupport::Concern
-
-
2
include AbstractController::Helpers
-
2
include AbstractController::Callbacks
-
-
2
included do
-
# Sets the token parameter name for RequestForgery. Calling +protect_from_forgery+
-
# sets it to <tt>:authenticity_token</tt> by default.
-
2
config_accessor :request_forgery_protection_token
-
2
self.request_forgery_protection_token ||= :authenticity_token
-
-
# Holds the class which implements the request forgery protection.
-
2
config_accessor :forgery_protection_strategy
-
2
self.forgery_protection_strategy = nil
-
-
# Controls whether request forgery protection is turned on or not. Turned off by default only in test mode.
-
2
config_accessor :allow_forgery_protection
-
2
self.allow_forgery_protection = true if allow_forgery_protection.nil?
-
-
2
helper_method :form_authenticity_token
-
2
helper_method :protect_against_forgery?
-
end
-
-
2
module ClassMethods
-
# Turn on request forgery protection. Bear in mind that only non-GET, HTML/JavaScript requests are checked.
-
#
-
# class ApplicationController < ActionController::Base
-
# protect_from_forgery
-
# end
-
#
-
# class FooController < ApplicationController
-
# protect_from_forgery except: :index
-
#
-
# You can disable CSRF protection on controller by skipping the verification before_action:
-
# skip_before_action :verify_authenticity_token
-
#
-
# Valid Options:
-
#
-
# * <tt>:only/:except</tt> - Passed to the <tt>before_action</tt> call. Set which actions are verified.
-
# * <tt>:with</tt> - Set the method to handle unverified request.
-
#
-
# Valid unverified request handling methods are:
-
# * <tt>:exception</tt> - Raises ActionController::InvalidAuthenticityToken exception.
-
# * <tt>:reset_session</tt> - Resets the session.
-
# * <tt>:null_session</tt> - Provides an empty session during request but doesn't reset it completely. Used as default if <tt>:with</tt> option is not specified.
-
2
def protect_from_forgery(options = {})
-
2
self.forgery_protection_strategy = protection_method_class(options[:with] || :null_session)
-
2
self.request_forgery_protection_token ||= :authenticity_token
-
2
prepend_before_action :verify_authenticity_token, options
-
2
append_after_action :verify_same_origin_request
-
end
-
-
2
private
-
-
2
def protection_method_class(name)
-
2
ActionController::RequestForgeryProtection::ProtectionMethods.const_get(name.to_s.classify)
-
rescue NameError
-
raise ArgumentError, 'Invalid request forgery protection method, use :null_session, :exception, or :reset_session'
-
end
-
end
-
-
2
module ProtectionMethods
-
2
class NullSession
-
2
def initialize(controller)
-
@controller = controller
-
end
-
-
# This is the method that defines the application behavior when a request is found to be unverified.
-
2
def handle_unverified_request
-
request = @controller.request
-
request.session = NullSessionHash.new(request.env)
-
request.env['action_dispatch.request.flash_hash'] = nil
-
request.env['rack.session.options'] = { skip: true }
-
request.env['action_dispatch.cookies'] = NullCookieJar.build(request)
-
end
-
-
2
protected
-
-
2
class NullSessionHash < Rack::Session::Abstract::SessionHash #:nodoc:
-
2
def initialize(env)
-
super(nil, env)
-
@data = {}
-
@loaded = true
-
end
-
-
# no-op
-
2
def destroy; end
-
-
2
def exists?
-
true
-
end
-
end
-
-
2
class NullCookieJar < ActionDispatch::Cookies::CookieJar #:nodoc:
-
2
def self.build(request)
-
key_generator = request.env[ActionDispatch::Cookies::GENERATOR_KEY]
-
host = request.host
-
secure = request.ssl?
-
-
new(key_generator, host, secure, options_for_env({}))
-
end
-
-
2
def write(*)
-
# nothing
-
end
-
end
-
end
-
-
2
class ResetSession
-
2
def initialize(controller)
-
@controller = controller
-
end
-
-
2
def handle_unverified_request
-
@controller.reset_session
-
end
-
end
-
-
2
class Exception
-
2
def initialize(controller)
-
@controller = controller
-
end
-
-
2
def handle_unverified_request
-
raise ActionController::InvalidAuthenticityToken
-
end
-
end
-
end
-
-
2
protected
-
# The actual before_action that is used to verify the CSRF token.
-
# Don't override this directly. Provide your own forgery protection
-
# strategy instead. If you override, you'll disable same-origin
-
# `<script>` verification.
-
#
-
# Lean on the protect_from_forgery declaration to mark which actions are
-
# due for same-origin request verification. If protect_from_forgery is
-
# enabled on an action, this before_action flags its after_action to
-
# verify that JavaScript responses are for XHR requests, ensuring they
-
# follow the browser's same-origin policy.
-
2
def verify_authenticity_token
-
24
mark_for_same_origin_verification!
-
-
24
if !verified_request?
-
logger.warn "Can't verify CSRF token authenticity" if logger
-
handle_unverified_request
-
end
-
end
-
-
2
def handle_unverified_request
-
forgery_protection_strategy.new(self).handle_unverified_request
-
end
-
-
2
CROSS_ORIGIN_JAVASCRIPT_WARNING = "Security warning: an embedded " \
-
"<script> tag on another site requested protected JavaScript. " \
-
"If you know what you're doing, go ahead and disable forgery " \
-
"protection on this action to permit cross-origin JavaScript embedding."
-
2
private_constant :CROSS_ORIGIN_JAVASCRIPT_WARNING
-
-
# If `verify_authenticity_token` was run (indicating that we have
-
# forgery protection enabled for this request) then also verify that
-
# we aren't serving an unauthorized cross-origin response.
-
2
def verify_same_origin_request
-
24
if marked_for_same_origin_verification? && non_xhr_javascript_response?
-
logger.warn CROSS_ORIGIN_JAVASCRIPT_WARNING if logger
-
raise ActionController::InvalidCrossOriginRequest, CROSS_ORIGIN_JAVASCRIPT_WARNING
-
end
-
end
-
-
# GET requests are checked for cross-origin JavaScript after rendering.
-
2
def mark_for_same_origin_verification!
-
24
@marked_for_same_origin_verification = request.get?
-
end
-
-
# If the `verify_authenticity_token` before_action ran, verify that
-
# JavaScript responses are only served to same-origin GET requests.
-
2
def marked_for_same_origin_verification?
-
24
@marked_for_same_origin_verification ||= false
-
end
-
-
# Check for cross-origin JavaScript responses.
-
2
def non_xhr_javascript_response?
-
20
content_type =~ %r(\Atext/javascript) && !request.xhr?
-
end
-
-
# Returns true or false if a request is verified. Checks:
-
#
-
# * is it a GET or HEAD request? Gets should be safe and idempotent
-
# * Does the form_authenticity_token match the given token value from the params?
-
# * Does the X-CSRF-Token header match the form_authenticity_token
-
2
def verified_request?
-
24
!protect_against_forgery? || request.get? || request.head? ||
-
form_authenticity_token == params[request_forgery_protection_token] ||
-
form_authenticity_token == request.headers['X-CSRF-Token']
-
end
-
-
# Sets the token value for the current session.
-
2
def form_authenticity_token
-
session[:_csrf_token] ||= SecureRandom.base64(32)
-
end
-
-
# The form's authenticity parameter. Override to provide your own.
-
2
def form_authenticity_param
-
params[request_forgery_protection_token]
-
end
-
-
# Checks if the controller allows forgery protection.
-
2
def protect_against_forgery?
-
59
allow_forgery_protection
-
end
-
end
-
end
-
2
module ActionController #:nodoc:
-
# This module is responsible to provide `rescue_from` helpers
-
# to controllers and configure when detailed exceptions must be
-
# shown.
-
2
module Rescue
-
2
extend ActiveSupport::Concern
-
2
include ActiveSupport::Rescuable
-
-
2
def rescue_with_handler(exception)
-
if (exception.respond_to?(:original_exception) &&
-
(orig_exception = exception.original_exception) &&
-
handler_for_rescue(orig_exception))
-
exception = orig_exception
-
end
-
super(exception)
-
end
-
-
# Override this method if you want to customize when detailed
-
# exceptions must be shown. This method is only called when
-
# consider_all_requests_local is false. By default, it returns
-
# false, but someone may set it to `request.local?` so local
-
# requests in production still shows the detailed exception pages.
-
2
def show_detailed_exceptions?
-
false
-
end
-
-
2
private
-
2
def process_action(*args)
-
24
super
-
rescue Exception => exception
-
request.env['action_dispatch.show_detailed_exceptions'] ||= show_detailed_exceptions?
-
rescue_with_handler(exception) || raise(exception)
-
end
-
end
-
end
-
2
require 'active_support/json'
-
-
2
module ActionController #:nodoc:
-
# Responsible for exposing a resource to different mime requests,
-
# usually depending on the HTTP verb. The responder is triggered when
-
# <code>respond_with</code> is called. The simplest case to study is a GET request:
-
#
-
# class PeopleController < ApplicationController
-
# respond_to :html, :xml, :json
-
#
-
# def index
-
# @people = Person.all
-
# respond_with(@people)
-
# end
-
# end
-
#
-
# When a request comes in, for example for an XML response, three steps happen:
-
#
-
# 1) the responder searches for a template at people/index.xml;
-
#
-
# 2) if the template is not available, it will invoke <code>#to_xml</code> on the given resource;
-
#
-
# 3) if the responder does not <code>respond_to :to_xml</code>, call <code>#to_format</code> on it.
-
#
-
# === Builtin HTTP verb semantics
-
#
-
# The default \Rails responder holds semantics for each HTTP verb. Depending on the
-
# content type, verb and the resource status, it will behave differently.
-
#
-
# Using \Rails default responder, a POST request for creating an object could
-
# be written as:
-
#
-
# def create
-
# @user = User.new(params[:user])
-
# flash[:notice] = 'User was successfully created.' if @user.save
-
# respond_with(@user)
-
# end
-
#
-
# Which is exactly the same as:
-
#
-
# def create
-
# @user = User.new(params[:user])
-
#
-
# respond_to do |format|
-
# if @user.save
-
# flash[:notice] = 'User was successfully created.'
-
# format.html { redirect_to(@user) }
-
# format.xml { render xml: @user, status: :created, location: @user }
-
# else
-
# format.html { render action: "new" }
-
# format.xml { render xml: @user.errors, status: :unprocessable_entity }
-
# end
-
# end
-
# end
-
#
-
# The same happens for PATCH/PUT and DELETE requests.
-
#
-
# === Nested resources
-
#
-
# You can supply nested resources as you do in <code>form_for</code> and <code>polymorphic_url</code>.
-
# Consider the project has many tasks example. The create action for
-
# TasksController would be like:
-
#
-
# def create
-
# @project = Project.find(params[:project_id])
-
# @task = @project.tasks.build(params[:task])
-
# flash[:notice] = 'Task was successfully created.' if @task.save
-
# respond_with(@project, @task)
-
# end
-
#
-
# Giving several resources ensures that the responder will redirect to
-
# <code>project_task_url</code> instead of <code>task_url</code>.
-
#
-
# Namespaced and singleton resources require a symbol to be given, as in
-
# polymorphic urls. If a project has one manager which has many tasks, it
-
# should be invoked as:
-
#
-
# respond_with(@project, :manager, @task)
-
#
-
# Note that if you give an array, it will be treated as a collection,
-
# so the following is not equivalent:
-
#
-
# respond_with [@project, :manager, @task]
-
#
-
# === Custom options
-
#
-
# <code>respond_with</code> also allows you to pass options that are forwarded
-
# to the underlying render call. Those options are only applied for success
-
# scenarios. For instance, you can do the following in the create method above:
-
#
-
# def create
-
# @project = Project.find(params[:project_id])
-
# @task = @project.tasks.build(params[:task])
-
# flash[:notice] = 'Task was successfully created.' if @task.save
-
# respond_with(@project, @task, status: 201)
-
# end
-
#
-
# This will return status 201 if the task was saved successfully. If not,
-
# it will simply ignore the given options and return status 422 and the
-
# resource errors. You can also override the location to redirect to:
-
#
-
# respond_with(@project, location: root_path)
-
#
-
# To customize the failure scenario, you can pass a block to
-
# <code>respond_with</code>:
-
#
-
# def create
-
# @project = Project.find(params[:project_id])
-
# @task = @project.tasks.build(params[:task])
-
# respond_with(@project, @task, status: 201) do |format|
-
# if @task.save
-
# flash[:notice] = 'Task was successfully created.'
-
# else
-
# format.html { render "some_special_template" }
-
# end
-
# end
-
# end
-
#
-
# Using <code>respond_with</code> with a block follows the same syntax as <code>respond_to</code>.
-
2
class Responder
-
2
attr_reader :controller, :request, :format, :resource, :resources, :options
-
-
2
DEFAULT_ACTIONS_FOR_VERBS = {
-
:post => :new,
-
:patch => :edit,
-
:put => :edit
-
}
-
-
2
def initialize(controller, resources, options={})
-
@controller = controller
-
@request = @controller.request
-
@format = @controller.formats.first
-
@resource = resources.last
-
@resources = resources
-
@options = options
-
@action = options.delete(:action)
-
@default_response = options.delete(:default_response)
-
end
-
-
2
delegate :head, :render, :redirect_to, :to => :controller
-
2
delegate :get?, :post?, :patch?, :put?, :delete?, :to => :request
-
-
# Undefine :to_json and :to_yaml since it's defined on Object
-
2
undef_method(:to_json) if method_defined?(:to_json)
-
2
undef_method(:to_yaml) if method_defined?(:to_yaml)
-
-
# Initializes a new responder and invokes the proper format. If the format is
-
# not defined, call to_format.
-
#
-
2
def self.call(*args)
-
new(*args).respond
-
end
-
-
# Main entry point for responder responsible to dispatch to the proper format.
-
#
-
2
def respond
-
method = "to_#{format}"
-
respond_to?(method) ? send(method) : to_format
-
end
-
-
# HTML format does not render the resource, it always attempt to render a
-
# template.
-
#
-
2
def to_html
-
default_render
-
rescue ActionView::MissingTemplate => e
-
navigation_behavior(e)
-
end
-
-
# to_js simply tries to render a template. If no template is found, raises the error.
-
2
def to_js
-
default_render
-
end
-
-
# All other formats follow the procedure below. First we try to render a
-
# template, if the template is not available, we verify if the resource
-
# responds to :to_format and display it.
-
#
-
2
def to_format
-
if get? || !has_errors? || response_overridden?
-
default_render
-
else
-
display_errors
-
end
-
rescue ActionView::MissingTemplate => e
-
api_behavior(e)
-
end
-
-
2
protected
-
-
# This is the common behavior for formats associated with browsing, like :html, :iphone and so forth.
-
2
def navigation_behavior(error)
-
if get?
-
raise error
-
elsif has_errors? && default_action
-
render :action => default_action
-
else
-
redirect_to navigation_location
-
end
-
end
-
-
# This is the common behavior for formats associated with APIs, such as :xml and :json.
-
2
def api_behavior(error)
-
raise error unless resourceful?
-
raise MissingRenderer.new(format) unless has_renderer?
-
-
if get?
-
display resource
-
elsif post?
-
display resource, :status => :created, :location => api_location
-
else
-
head :no_content
-
end
-
end
-
-
# Checks whether the resource responds to the current format or not.
-
#
-
2
def resourceful?
-
resource.respond_to?("to_#{format}")
-
end
-
-
# Returns the resource location by retrieving it from the options or
-
# returning the resources array.
-
#
-
2
def resource_location
-
options[:location] || resources
-
end
-
2
alias :navigation_location :resource_location
-
2
alias :api_location :resource_location
-
-
# If a response block was given, use it, otherwise call render on
-
# controller.
-
#
-
2
def default_render
-
if @default_response
-
@default_response.call(options)
-
else
-
controller.default_render(options)
-
end
-
end
-
-
# Display is just a shortcut to render a resource with the current format.
-
#
-
# display @user, status: :ok
-
#
-
# For XML requests it's equivalent to:
-
#
-
# render xml: @user, status: :ok
-
#
-
# Options sent by the user are also used:
-
#
-
# respond_with(@user, status: :created)
-
# display(@user, status: :ok)
-
#
-
# Results in:
-
#
-
# render xml: @user, status: :created
-
#
-
2
def display(resource, given_options={})
-
controller.render given_options.merge!(options).merge!(format => resource)
-
end
-
-
2
def display_errors
-
controller.render format => resource_errors, :status => :unprocessable_entity
-
end
-
-
# Check whether the resource has errors.
-
#
-
2
def has_errors?
-
resource.respond_to?(:errors) && !resource.errors.empty?
-
end
-
-
# Check whether the necessary Renderer is available
-
2
def has_renderer?
-
Renderers::RENDERERS.include?(format)
-
end
-
-
# By default, render the <code>:edit</code> action for HTML requests with errors, unless
-
# the verb was POST.
-
#
-
2
def default_action
-
@action ||= DEFAULT_ACTIONS_FOR_VERBS[request.request_method_symbol]
-
end
-
-
2
def resource_errors
-
respond_to?("#{format}_resource_errors", true) ? send("#{format}_resource_errors") : resource.errors
-
end
-
-
2
def json_resource_errors
-
{:errors => resource.errors}
-
end
-
-
2
def response_overridden?
-
@default_response.present?
-
end
-
end
-
end
-
2
require 'rack/chunked'
-
-
2
module ActionController #:nodoc:
-
# Allows views to be streamed back to the client as they are rendered.
-
#
-
# The default way Rails renders views is by first rendering the template
-
# and then the layout. The response is sent to the client after the whole
-
# template is rendered, all queries are made, and the layout is processed.
-
#
-
# Streaming inverts the rendering flow by rendering the layout first and
-
# streaming each part of the layout as they are processed. This allows the
-
# header of the HTML (which is usually in the layout) to be streamed back
-
# to client very quickly, allowing JavaScripts and stylesheets to be loaded
-
# earlier than usual.
-
#
-
# This approach was introduced in Rails 3.1 and is still improving. Several
-
# Rack middlewares may not work and you need to be careful when streaming.
-
# Those points are going to be addressed soon.
-
#
-
# In order to use streaming, you will need to use a Ruby version that
-
# supports fibers (fibers are supported since version 1.9.2 of the main
-
# Ruby implementation).
-
#
-
# Streaming can be added to a given template easily, all you need to do is
-
# to pass the :stream option.
-
#
-
# class PostsController
-
# def index
-
# @posts = Post.all
-
# render stream: true
-
# end
-
# end
-
#
-
# == When to use streaming
-
#
-
# Streaming may be considered to be overkill for lightweight actions like
-
# +new+ or +edit+. The real benefit of streaming is on expensive actions
-
# that, for example, do a lot of queries on the database.
-
#
-
# In such actions, you want to delay queries execution as much as you can.
-
# For example, imagine the following +dashboard+ action:
-
#
-
# def dashboard
-
# @posts = Post.all
-
# @pages = Page.all
-
# @articles = Article.all
-
# end
-
#
-
# Most of the queries here are happening in the controller. In order to benefit
-
# from streaming you would want to rewrite it as:
-
#
-
# def dashboard
-
# # Allow lazy execution of the queries
-
# @posts = Post.all
-
# @pages = Page.all
-
# @articles = Article.all
-
# render stream: true
-
# end
-
#
-
# Notice that :stream only works with templates. Rendering :json
-
# or :xml with :stream won't work.
-
#
-
# == Communication between layout and template
-
#
-
# When streaming, rendering happens top-down instead of inside-out.
-
# Rails starts with the layout, and the template is rendered later,
-
# when its +yield+ is reached.
-
#
-
# This means that, if your application currently relies on instance
-
# variables set in the template to be used in the layout, they won't
-
# work once you move to streaming. The proper way to communicate
-
# between layout and template, regardless of whether you use streaming
-
# or not, is by using +content_for+, +provide+ and +yield+.
-
#
-
# Take a simple example where the layout expects the template to tell
-
# which title to use:
-
#
-
# <html>
-
# <head><title><%= yield :title %></title></head>
-
# <body><%= yield %></body>
-
# </html>
-
#
-
# You would use +content_for+ in your template to specify the title:
-
#
-
# <%= content_for :title, "Main" %>
-
# Hello
-
#
-
# And the final result would be:
-
#
-
# <html>
-
# <head><title>Main</title></head>
-
# <body>Hello</body>
-
# </html>
-
#
-
# However, if +content_for+ is called several times, the final result
-
# would have all calls concatenated. For instance, if we have the following
-
# template:
-
#
-
# <%= content_for :title, "Main" %>
-
# Hello
-
# <%= content_for :title, " page" %>
-
#
-
# The final result would be:
-
#
-
# <html>
-
# <head><title>Main page</title></head>
-
# <body>Hello</body>
-
# </html>
-
#
-
# This means that, if you have <code>yield :title</code> in your layout
-
# and you want to use streaming, you would have to render the whole template
-
# (and eventually trigger all queries) before streaming the title and all
-
# assets, which kills the purpose of streaming. For this reason Rails 3.1
-
# introduces a new helper called +provide+ that does the same as +content_for+
-
# but tells the layout to stop searching for other entries and continue rendering.
-
#
-
# For instance, the template above using +provide+ would be:
-
#
-
# <%= provide :title, "Main" %>
-
# Hello
-
# <%= content_for :title, " page" %>
-
#
-
# Giving:
-
#
-
# <html>
-
# <head><title>Main</title></head>
-
# <body>Hello</body>
-
# </html>
-
#
-
# That said, when streaming, you need to properly check your templates
-
# and choose when to use +provide+ and +content_for+.
-
#
-
# == Headers, cookies, session and flash
-
#
-
# When streaming, the HTTP headers are sent to the client right before
-
# it renders the first line. This means that, modifying headers, cookies,
-
# session or flash after the template starts rendering will not propagate
-
# to the client.
-
#
-
# == Middlewares
-
#
-
# Middlewares that need to manipulate the body won't work with streaming.
-
# You should disable those middlewares whenever streaming in development
-
# or production. For instance, <tt>Rack::Bug</tt> won't work when streaming as it
-
# needs to inject contents in the HTML body.
-
#
-
# Also <tt>Rack::Cache</tt> won't work with streaming as it does not support
-
# streaming bodies yet. Whenever streaming Cache-Control is automatically
-
# set to "no-cache".
-
#
-
# == Errors
-
#
-
# When it comes to streaming, exceptions get a bit more complicated. This
-
# happens because part of the template was already rendered and streamed to
-
# the client, making it impossible to render a whole exception page.
-
#
-
# Currently, when an exception happens in development or production, Rails
-
# will automatically stream to the client:
-
#
-
# "><script>window.location = "/500.html"</script></html>
-
#
-
# The first two characters (">) are required in case the exception happens
-
# while rendering attributes for a given tag. You can check the real cause
-
# for the exception in your logger.
-
#
-
# == Web server support
-
#
-
# Not all web servers support streaming out-of-the-box. You need to check
-
# the instructions for each of them.
-
#
-
# ==== Unicorn
-
#
-
# Unicorn supports streaming but it needs to be configured. For this, you
-
# need to create a config file as follow:
-
#
-
# # unicorn.config.rb
-
# listen 3000, tcp_nopush: false
-
#
-
# And use it on initialization:
-
#
-
# unicorn_rails --config-file unicorn.config.rb
-
#
-
# You may also want to configure other parameters like <tt>:tcp_nodelay</tt>.
-
# Please check its documentation for more information: http://unicorn.bogomips.org/Unicorn/Configurator.html#method-i-listen
-
#
-
# If you are using Unicorn with Nginx, you may need to tweak Nginx.
-
# Streaming should work out of the box on Rainbows.
-
#
-
# ==== Passenger
-
#
-
# To be described.
-
#
-
2
module Streaming
-
2
extend ActiveSupport::Concern
-
-
2
protected
-
-
# Set proper cache control and transfer encoding when streaming
-
2
def _process_options(options) #:nodoc:
-
24
super
-
24
if options[:stream]
-
if env["HTTP_VERSION"] == "HTTP/1.0"
-
options.delete(:stream)
-
else
-
headers["Cache-Control"] ||= "no-cache"
-
headers["Transfer-Encoding"] = "chunked"
-
headers.delete("Content-Length")
-
end
-
end
-
end
-
-
# Call render_body if we are streaming instead of usual +render+.
-
2
def _render_template(options) #:nodoc:
-
24
if options.delete(:stream)
-
Rack::Chunked::Body.new view_renderer.render_body(view_context, options)
-
else
-
24
super
-
end
-
end
-
end
-
end
-
2
require 'active_support/core_ext/hash/indifferent_access'
-
2
require 'active_support/core_ext/array/wrap'
-
2
require 'active_support/rescuable'
-
2
require 'action_dispatch/http/upload'
-
2
require 'stringio'
-
2
require 'set'
-
-
2
module ActionController
-
# Raised when a required parameter is missing.
-
#
-
# params = ActionController::Parameters.new(a: {})
-
# params.fetch(:b)
-
# # => ActionController::ParameterMissing: param not found: b
-
# params.require(:a)
-
# # => ActionController::ParameterMissing: param not found: a
-
2
class ParameterMissing < KeyError
-
2
attr_reader :param # :nodoc:
-
-
2
def initialize(param) # :nodoc:
-
@param = param
-
super("param is missing or the value is empty: #{param}")
-
end
-
end
-
-
# Raised when a supplied parameter is not expected.
-
#
-
# params = ActionController::Parameters.new(a: "123", b: "456")
-
# params.permit(:c)
-
# # => ActionController::UnpermittedParameters: found unexpected keys: a, b
-
2
class UnpermittedParameters < IndexError
-
2
attr_reader :params # :nodoc:
-
-
2
def initialize(params) # :nodoc:
-
@params = params
-
super("found unpermitted parameters: #{params.join(", ")}")
-
end
-
end
-
-
# == Action Controller \Parameters
-
#
-
# Allows to choose which attributes should be whitelisted for mass updating
-
# and thus prevent accidentally exposing that which shouldn’t be exposed.
-
# Provides two methods for this purpose: #require and #permit. The former is
-
# used to mark parameters as required. The latter is used to set the parameter
-
# as permitted and limit which attributes should be allowed for mass updating.
-
#
-
# params = ActionController::Parameters.new({
-
# person: {
-
# name: 'Francesco',
-
# age: 22,
-
# role: 'admin'
-
# }
-
# })
-
#
-
# permitted = params.require(:person).permit(:name, :age)
-
# permitted # => {"name"=>"Francesco", "age"=>22}
-
# permitted.class # => ActionController::Parameters
-
# permitted.permitted? # => true
-
#
-
# Person.first.update!(permitted)
-
# # => #<Person id: 1, name: "Francesco", age: 22, role: "user">
-
#
-
# It provides two options that controls the top-level behavior of new instances:
-
#
-
# * +permit_all_parameters+ - If it's +true+, all the parameters will be
-
# permitted by default. The default is +false+.
-
# * +action_on_unpermitted_parameters+ - Allow to control the behavior when parameters
-
# that are not explicitly permitted are found. The values can be <tt>:log</tt> to
-
# write a message on the logger or <tt>:raise</tt> to raise
-
# ActionController::UnpermittedParameters exception. The default value is <tt>:log</tt>
-
# in test and development environments, +false+ otherwise.
-
#
-
# Examples:
-
#
-
# params = ActionController::Parameters.new
-
# params.permitted? # => false
-
#
-
# ActionController::Parameters.permit_all_parameters = true
-
#
-
# params = ActionController::Parameters.new
-
# params.permitted? # => true
-
#
-
# params = ActionController::Parameters.new(a: "123", b: "456")
-
# params.permit(:c)
-
# # => {}
-
#
-
# ActionController::Parameters.action_on_unpermitted_parameters = :raise
-
#
-
# params = ActionController::Parameters.new(a: "123", b: "456")
-
# params.permit(:c)
-
# # => ActionController::UnpermittedParameters: found unpermitted keys: a, b
-
#
-
# <tt>ActionController::Parameters</tt> is inherited from
-
# <tt>ActiveSupport::HashWithIndifferentAccess</tt>, this means
-
# that you can fetch values using either <tt>:key</tt> or <tt>"key"</tt>.
-
#
-
# params = ActionController::Parameters.new(key: 'value')
-
# params[:key] # => "value"
-
# params["key"] # => "value"
-
2
class Parameters < ActiveSupport::HashWithIndifferentAccess
-
2
cattr_accessor :permit_all_parameters, instance_accessor: false
-
2
cattr_accessor :action_on_unpermitted_parameters, instance_accessor: false
-
-
# Never raise an UnpermittedParameters exception because of these params
-
# are present. They are added by Rails and it's of no concern.
-
2
NEVER_UNPERMITTED_PARAMS = %w( controller action )
-
-
# Returns a new instance of <tt>ActionController::Parameters</tt>.
-
# Also, sets the +permitted+ attribute to the default value of
-
# <tt>ActionController::Parameters.permit_all_parameters</tt>.
-
#
-
# class Person < ActiveRecord::Base
-
# end
-
#
-
# params = ActionController::Parameters.new(name: 'Francesco')
-
# params.permitted? # => false
-
# Person.new(params) # => ActiveModel::ForbiddenAttributesError
-
#
-
# ActionController::Parameters.permit_all_parameters = true
-
#
-
# params = ActionController::Parameters.new(name: 'Francesco')
-
# params.permitted? # => true
-
# Person.new(params) # => #<Person id: nil, name: "Francesco">
-
2
def initialize(attributes = nil)
-
36
super(attributes)
-
36
@permitted = self.class.permit_all_parameters
-
end
-
-
# Attribute that keeps track of converted arrays, if any, to avoid double
-
# looping in the common use case permit + mass-assignment. Defined in a
-
# method to instantiate it only if needed.
-
2
def converted_arrays
-
@converted_arrays ||= Set.new
-
end
-
-
# Returns +true+ if the parameter is permitted, +false+ otherwise.
-
#
-
# params = ActionController::Parameters.new
-
# params.permitted? # => false
-
# params.permit!
-
# params.permitted? # => true
-
2
def permitted?
-
2
@permitted
-
end
-
-
# Sets the +permitted+ attribute to +true+. This can be used to pass
-
# mass assignment. Returns +self+.
-
#
-
# class Person < ActiveRecord::Base
-
# end
-
#
-
# params = ActionController::Parameters.new(name: 'Francesco')
-
# params.permitted? # => false
-
# Person.new(params) # => ActiveModel::ForbiddenAttributesError
-
# params.permit!
-
# params.permitted? # => true
-
# Person.new(params) # => #<Person id: nil, name: "Francesco">
-
2
def permit!
-
2
each_pair do |key, value|
-
12
value = convert_hashes_to_parameters(key, value)
-
12
Array.wrap(value).each do |_|
-
12
_.permit! if _.respond_to? :permit!
-
end
-
end
-
-
2
@permitted = true
-
2
self
-
end
-
-
# Ensures that a parameter is present. If it's present, returns
-
# the parameter at the given +key+, otherwise raises an
-
# <tt>ActionController::ParameterMissing</tt> error.
-
#
-
# ActionController::Parameters.new(person: { name: 'Francesco' }).require(:person)
-
# # => {"name"=>"Francesco"}
-
#
-
# ActionController::Parameters.new(person: nil).require(:person)
-
# # => ActionController::ParameterMissing: param not found: person
-
#
-
# ActionController::Parameters.new(person: {}).require(:person)
-
# # => ActionController::ParameterMissing: param not found: person
-
2
def require(key)
-
2
value = self[key]
-
2
if value.present? || value == false
-
2
value
-
else
-
raise ParameterMissing.new(key)
-
end
-
end
-
-
# Alias of #require.
-
2
alias :required :require
-
-
# Returns a new <tt>ActionController::Parameters</tt> instance that
-
# includes only the given +filters+ and sets the +permitted+ attribute
-
# for the object to +true+. This is useful for limiting which attributes
-
# should be allowed for mass updating.
-
#
-
# params = ActionController::Parameters.new(user: { name: 'Francesco', age: 22, role: 'admin' })
-
# permitted = params.require(:user).permit(:name, :age)
-
# permitted.permitted? # => true
-
# permitted.has_key?(:name) # => true
-
# permitted.has_key?(:age) # => true
-
# permitted.has_key?(:role) # => false
-
#
-
# Only permitted scalars pass the filter. For example, given
-
#
-
# params.permit(:name)
-
#
-
# +:name+ passes it is a key of +params+ whose associated value is of type
-
# +String+, +Symbol+, +NilClass+, +Numeric+, +TrueClass+, +FalseClass+,
-
# +Date+, +Time+, +DateTime+, +StringIO+, +IO+,
-
# +ActionDispatch::Http::UploadedFile+ or +Rack::Test::UploadedFile+.
-
# Otherwise, the key +:name+ is filtered out.
-
#
-
# You may declare that the parameter should be an array of permitted scalars
-
# by mapping it to an empty array:
-
#
-
# params = ActionController::Parameters.new(tags: ['rails', 'parameters'])
-
# params.permit(tags: [])
-
#
-
# You can also use +permit+ on nested parameters, like:
-
#
-
# params = ActionController::Parameters.new({
-
# person: {
-
# name: 'Francesco',
-
# age: 22,
-
# pets: [{
-
# name: 'Purplish',
-
# category: 'dogs'
-
# }]
-
# }
-
# })
-
#
-
# permitted = params.permit(person: [ :name, { pets: :name } ])
-
# permitted.permitted? # => true
-
# permitted[:person][:name] # => "Francesco"
-
# permitted[:person][:age] # => nil
-
# permitted[:person][:pets][0][:name] # => "Purplish"
-
# permitted[:person][:pets][0][:category] # => nil
-
#
-
# Note that if you use +permit+ in a key that points to a hash,
-
# it won't allow all the hash. You also need to specify which
-
# attributes inside the hash should be whitelisted.
-
#
-
# params = ActionController::Parameters.new({
-
# person: {
-
# contact: {
-
# email: 'none@test.com',
-
# phone: '555-1234'
-
# }
-
# }
-
# })
-
#
-
# params.require(:person).permit(:contact)
-
# # => {}
-
#
-
# params.require(:person).permit(contact: :phone)
-
# # => {"contact"=>{"phone"=>"555-1234"}}
-
#
-
# params.require(:person).permit(contact: [ :email, :phone ])
-
# # => {"contact"=>{"email"=>"none@test.com", "phone"=>"555-1234"}}
-
2
def permit(*filters)
-
2
params = self.class.new
-
-
2
filters.flatten.each do |filter|
-
14
case filter
-
when Symbol, String
-
14
permitted_scalar_filter(params, filter)
-
when Hash then
-
hash_filter(params, filter)
-
end
-
end
-
-
2
unpermitted_parameters!(params) if self.class.action_on_unpermitted_parameters
-
-
2
params.permit!
-
end
-
-
# Returns a parameter for the given +key+. If not found,
-
# returns +nil+.
-
#
-
# params = ActionController::Parameters.new(person: { name: 'Francesco' })
-
# params[:person] # => {"name"=>"Francesco"}
-
# params[:none] # => nil
-
2
def [](key)
-
86
convert_hashes_to_parameters(key, super)
-
end
-
-
# Returns a parameter for the given +key+. If the +key+
-
# can't be found, there are several options: With no other arguments,
-
# it will raise an <tt>ActionController::ParameterMissing</tt> error;
-
# if more arguments are given, then that will be returned; if a block
-
# is given, then that will be run and its result returned.
-
#
-
# params = ActionController::Parameters.new(person: { name: 'Francesco' })
-
# params.fetch(:person) # => {"name"=>"Francesco"}
-
# params.fetch(:none) # => ActionController::ParameterMissing: param not found: none
-
# params.fetch(:none, 'Francesco') # => "Francesco"
-
# params.fetch(:none) { 'Francesco' } # => "Francesco"
-
2
def fetch(key, *args)
-
convert_hashes_to_parameters(key, super, false)
-
rescue KeyError
-
raise ActionController::ParameterMissing.new(key)
-
end
-
-
# Returns a new <tt>ActionController::Parameters</tt> instance that
-
# includes only the given +keys+. If the given +keys+
-
# don't exist, returns an empty hash.
-
#
-
# params = ActionController::Parameters.new(a: 1, b: 2, c: 3)
-
# params.slice(:a, :b) # => {"a"=>1, "b"=>2}
-
# params.slice(:d) # => {}
-
2
def slice(*keys)
-
self.class.new(super).tap do |new_instance|
-
new_instance.permitted = @permitted
-
end
-
end
-
-
# Returns an exact copy of the <tt>ActionController::Parameters</tt>
-
# instance. +permitted+ state is kept on the duped object.
-
#
-
# params = ActionController::Parameters.new(a: 1)
-
# params.permit!
-
# params.permitted? # => true
-
# copy_params = params.dup # => {"a"=>1}
-
# copy_params.permitted? # => true
-
2
def dup
-
2
super.tap do |duplicate|
-
2
duplicate.permitted = @permitted
-
end
-
end
-
-
2
protected
-
2
def permitted=(new_permitted)
-
2
@permitted = new_permitted
-
end
-
-
2
private
-
2
def convert_hashes_to_parameters(key, value, assign_if_converted=true)
-
98
converted = convert_value_to_parameters(value)
-
98
self[key] = converted if assign_if_converted && !converted.equal?(value)
-
98
converted
-
end
-
-
2
def convert_value_to_parameters(value)
-
98
if value.is_a?(Array) && !converted_arrays.member?(value)
-
converted = value.map { |_| convert_value_to_parameters(_) }
-
converted_arrays << converted
-
converted
-
98
elsif value.is_a?(Parameters) || !value.is_a?(Hash)
-
94
value
-
else
-
4
self.class.new(value)
-
end
-
end
-
-
2
def each_element(object)
-
if object.is_a?(Array)
-
object.map { |el| yield el }.compact
-
elsif fields_for_style?(object)
-
hash = object.class.new
-
object.each { |k,v| hash[k] = yield v }
-
hash
-
else
-
yield object
-
end
-
end
-
-
2
def fields_for_style?(object)
-
object.is_a?(Hash) && object.all? { |k, v| k =~ /\A-?\d+\z/ && v.is_a?(Hash) }
-
end
-
-
2
def unpermitted_parameters!(params)
-
2
unpermitted_keys = unpermitted_keys(params)
-
2
if unpermitted_keys.any?
-
case self.class.action_on_unpermitted_parameters
-
when :log
-
name = "unpermitted_parameters.action_controller"
-
ActiveSupport::Notifications.instrument(name, keys: unpermitted_keys)
-
when :raise
-
raise ActionController::UnpermittedParameters.new(unpermitted_keys)
-
end
-
end
-
end
-
-
2
def unpermitted_keys(params)
-
2
self.keys - params.keys - NEVER_UNPERMITTED_PARAMS
-
end
-
-
#
-
# --- Filtering ----------------------------------------------------------
-
#
-
-
# This is a white list of permitted scalar types that includes the ones
-
# supported in XML and JSON requests.
-
#
-
# This list is in particular used to filter ordinary requests, String goes
-
# as first element to quickly short-circuit the common case.
-
#
-
# If you modify this collection please update the API of +permit+ above.
-
2
PERMITTED_SCALAR_TYPES = [
-
String,
-
Symbol,
-
NilClass,
-
Numeric,
-
TrueClass,
-
FalseClass,
-
Date,
-
Time,
-
# DateTimes are Dates, we document the type but avoid the redundant check.
-
StringIO,
-
IO,
-
ActionDispatch::Http::UploadedFile,
-
Rack::Test::UploadedFile,
-
]
-
-
2
def permitted_scalar?(value)
-
24
PERMITTED_SCALAR_TYPES.any? {|type| value.is_a?(type)}
-
end
-
-
2
def permitted_scalar_filter(params, key)
-
14
if has_key?(key) && permitted_scalar?(self[key])
-
12
params[key] = self[key]
-
end
-
-
14
keys.grep(/\A#{Regexp.escape(key)}\(\d+[if]?\)\z/) do |k|
-
if permitted_scalar?(self[k])
-
params[k] = self[k]
-
end
-
end
-
end
-
-
2
def array_of_permitted_scalars?(value)
-
if value.is_a?(Array)
-
value.all? {|element| permitted_scalar?(element)}
-
end
-
end
-
-
2
def array_of_permitted_scalars_filter(params, key)
-
if has_key?(key) && array_of_permitted_scalars?(self[key])
-
params[key] = self[key]
-
end
-
end
-
-
2
EMPTY_ARRAY = []
-
2
def hash_filter(params, filter)
-
filter = filter.with_indifferent_access
-
-
# Slicing filters out non-declared keys.
-
slice(*filter.keys).each do |key, value|
-
next unless value
-
-
if filter[key] == EMPTY_ARRAY
-
# Declaration { comment_ids: [] }.
-
array_of_permitted_scalars_filter(params, key)
-
else
-
# Declaration { user: :name } or { user: [:name, :age, { address: ... }] }.
-
params[key] = each_element(value) do |element|
-
if element.is_a?(Hash)
-
element = self.class.new(element) unless element.respond_to?(:permit)
-
element.permit(*Array.wrap(filter[key]))
-
end
-
end
-
end
-
end
-
end
-
end
-
-
# == Strong \Parameters
-
#
-
# It provides an interface for protecting attributes from end-user
-
# assignment. This makes Action Controller parameters forbidden
-
# to be used in Active Model mass assignment until they have been
-
# whitelisted.
-
#
-
# In addition, parameters can be marked as required and flow through a
-
# predefined raise/rescue flow to end up as a 400 Bad Request with no
-
# effort.
-
#
-
# class PeopleController < ActionController::Base
-
# # Using "Person.create(params[:person])" would raise an
-
# # ActiveModel::ForbiddenAttributes exception because it'd
-
# # be using mass assignment without an explicit permit step.
-
# # This is the recommended form:
-
# def create
-
# Person.create(person_params)
-
# end
-
#
-
# # This will pass with flying colors as long as there's a person key in the
-
# # parameters, otherwise it'll raise an ActionController::MissingParameter
-
# # exception, which will get caught by ActionController::Base and turned
-
# # into a 400 Bad Request reply.
-
# def update
-
# redirect_to current_account.people.find(params[:id]).tap { |person|
-
# person.update!(person_params)
-
# }
-
# end
-
#
-
# private
-
# # Using a private method to encapsulate the permissible parameters is
-
# # just a good pattern since you'll be able to reuse the same permit
-
# # list between create and update. Also, you can specialize this method
-
# # with per-user checking of permissible attributes.
-
# def person_params
-
# params.require(:person).permit(:name, :age)
-
# end
-
# end
-
#
-
# In order to use <tt>accepts_nested_attributes_for</tt> with Strong \Parameters, you
-
# will need to specify which nested attributes should be whitelisted.
-
#
-
# class Person
-
# has_many :pets
-
# accepts_nested_attributes_for :pets
-
# end
-
#
-
# class PeopleController < ActionController::Base
-
# def create
-
# Person.create(person_params)
-
# end
-
#
-
# ...
-
#
-
# private
-
#
-
# def person_params
-
# # It's mandatory to specify the nested attributes that should be whitelisted.
-
# # If you use `permit` with just the key that points to the nested attributes hash,
-
# # it will return an empty hash.
-
# params.require(:person).permit(:name, :age, pets_attributes: [ :name, :category ])
-
# end
-
# end
-
#
-
# See ActionController::Parameters.require and ActionController::Parameters.permit
-
# for more information.
-
2
module StrongParameters
-
2
extend ActiveSupport::Concern
-
2
include ActiveSupport::Rescuable
-
-
# Returns a new ActionController::Parameters object that
-
# has been instantiated with the <tt>request.parameters</tt>.
-
2
def params
-
30
@_params ||= Parameters.new(request.parameters)
-
end
-
-
# Assigns the given +value+ to the +params+ hash. If +value+
-
# is a Hash, this will create an ActionController::Parameters
-
# object that has been instantiated with the given +value+ hash.
-
2
def params=(value)
-
37
@_params = value.is_a?(Hash) ? Parameters.new(value) : value
-
end
-
end
-
end
-
1
module ActionController
-
1
module Testing
-
1
extend ActiveSupport::Concern
-
-
1
include RackDelegation
-
-
# TODO : Rewrite tests using controller.headers= to use Rack env
-
1
def headers=(new_headers)
-
@_response ||= ActionDispatch::Response.new
-
@_response.headers.replace(new_headers)
-
end
-
-
# Behavior specific to functional tests
-
1
module Functional # :nodoc:
-
1
def set_response!(request)
-
end
-
-
1
def recycle!
-
22
@_url_options = nil
-
22
self.formats = nil
-
22
self.params = nil
-
end
-
end
-
-
1
module ClassMethods
-
1
def before_filters
-
_process_action_callbacks.find_all{|x| x.kind == :before}.map{|x| x.name}
-
end
-
end
-
end
-
end
-
2
module ActionController
-
# Includes +url_for+ into the host class. The class has to provide a +RouteSet+ by implementing
-
# the <tt>_routes</tt> method. Otherwise, an exception will be raised.
-
#
-
# In addition to <tt>AbstractController::UrlFor</tt>, this module accesses the HTTP layer to define
-
# url options like the +host+. In order to do so, this module requires the host class
-
# to implement +env+ and +request+, which need to be a Rack-compatible.
-
#
-
# class RootUrl
-
# include ActionController::UrlFor
-
# include Rails.application.routes.url_helpers
-
#
-
# delegate :env, :request, to: :controller
-
#
-
# def initialize(controller)
-
# @controller = controller
-
# @url = root_path # named route from the application.
-
# end
-
# end
-
2
module UrlFor
-
2
extend ActiveSupport::Concern
-
-
2
include AbstractController::UrlFor
-
-
2
def url_options
-
@_url_options ||= super.reverse_merge(
-
:host => request.host,
-
:port => request.optional_port,
-
:protocol => request.protocol,
-
:_recall => request.symbolized_path_parameters
-
72
).freeze
-
-
72
if (same_origin = _routes.equal?(env["action_dispatch.routes"])) ||
-
83
(script_name = env["ROUTES_#{_routes.object_id}_SCRIPT_NAME"]) ||
-
11
(original_script_name = env['ORIGINAL_SCRIPT_NAME'])
-
-
61
@_url_options.dup.tap do |options|
-
61
if original_script_name
-
options[:original_script_name] = original_script_name
-
else
-
61
options[:script_name] = same_origin ? request.script_name.dup : script_name
-
end
-
61
options.freeze
-
end
-
else
-
11
@_url_options
-
end
-
end
-
end
-
end
-
2
module ActionController
-
2
module ModelNaming
-
# Converts the given object to an ActiveModel compliant one.
-
2
def convert_to_model(object)
-
32
object.respond_to?(:to_model) ? object.to_model : object
-
end
-
-
2
def model_name_from_record_or_class(record_or_class)
-
16
(record_or_class.is_a?(Class) ? record_or_class : convert_to_model(record_or_class).class).model_name
-
end
-
end
-
end
-
2
require "rails"
-
2
require "action_controller"
-
2
require "action_dispatch/railtie"
-
2
require "abstract_controller/railties/routes_helpers"
-
2
require "action_controller/railties/helpers"
-
2
require "action_view/railtie"
-
-
2
module ActionController
-
2
class Railtie < Rails::Railtie #:nodoc:
-
2
config.action_controller = ActiveSupport::OrderedOptions.new
-
-
2
config.eager_load_namespaces << ActionController
-
-
2
initializer "action_controller.assets_config", :group => :all do |app|
-
2
app.config.action_controller.assets_dir ||= app.config.paths["public"].first
-
end
-
-
2
initializer "action_controller.set_helpers_path" do |app|
-
2
ActionController::Helpers.helpers_path = app.helpers_paths
-
end
-
-
2
initializer "action_controller.parameters_config" do |app|
-
2
options = app.config.action_controller
-
-
4
ActionController::Parameters.permit_all_parameters = options.delete(:permit_all_parameters) { false }
-
2
ActionController::Parameters.action_on_unpermitted_parameters = options.delete(:action_on_unpermitted_parameters) do
-
2
(Rails.env.test? || Rails.env.development?) ? :log : false
-
end
-
end
-
-
2
initializer "action_controller.set_configs" do |app|
-
2
paths = app.config.paths
-
2
options = app.config.action_controller
-
-
2
options.logger ||= Rails.logger
-
2
options.cache_store ||= Rails.cache
-
-
2
options.javascripts_dir ||= paths["public/javascripts"].first
-
2
options.stylesheets_dir ||= paths["public/stylesheets"].first
-
-
# Ensure readers methods get compiled
-
2
options.asset_host ||= app.config.asset_host
-
2
options.relative_url_root ||= app.config.relative_url_root
-
-
2
ActiveSupport.on_load(:action_controller) do
-
2
include app.routes.mounted_helpers
-
2
extend ::AbstractController::Railties::RoutesHelpers.with(app.routes)
-
2
extend ::ActionController::Railties::Helpers
-
-
2
options.each do |k,v|
-
18
k = "#{k}="
-
18
if respond_to?(k)
-
18
send(k, v)
-
elsif !Base.respond_to?(k)
-
raise "Invalid option key: #{k}"
-
end
-
end
-
end
-
end
-
-
2
initializer "action_controller.compile_config_methods" do
-
2
ActiveSupport.on_load(:action_controller) do
-
2
config.compile_methods! if config.respond_to?(:compile_methods!)
-
end
-
end
-
end
-
end
-
2
module ActionController
-
2
module Railties
-
2
module Helpers
-
2
def inherited(klass)
-
13
super
-
13
return unless klass.respond_to?(:helpers_path=)
-
-
28
if namespace = klass.parents.detect { |m| m.respond_to?(:railtie_helpers_paths) }
-
paths = namespace.railtie_helpers_paths
-
else
-
13
paths = ActionController::Helpers.helpers_path
-
end
-
-
13
klass.helpers_path = paths
-
-
13
if klass.superclass == ActionController::Base && ActionController::Base.include_all_helpers
-
3
klass.helper :all
-
end
-
end
-
end
-
end
-
end
-
2
require 'rack/session/abstract/id'
-
2
require 'active_support/core_ext/object/to_query'
-
2
require 'active_support/core_ext/module/anonymous'
-
2
require 'active_support/core_ext/hash/keys'
-
-
2
module ActionController
-
2
module TemplateAssertions
-
2
extend ActiveSupport::Concern
-
-
2
included do
-
11
setup :setup_subscriptions
-
11
teardown :teardown_subscriptions
-
end
-
-
2
def setup_subscriptions
-
15
@_partials = Hash.new(0)
-
15
@_templates = Hash.new(0)
-
15
@_layouts = Hash.new(0)
-
15
@_files = Hash.new(0)
-
-
15
ActiveSupport::Notifications.subscribe("render_template.action_view") do |_name, _start, _finish, _id, payload|
-
11
path = payload[:layout]
-
11
if path
-
11
@_layouts[path] += 1
-
11
if path =~ /^layouts\/(.*)/
-
11
@_layouts[$1] += 1
-
end
-
end
-
end
-
-
15
ActiveSupport::Notifications.subscribe("!render_template.action_view") do |_name, _start, _finish, _id, payload|
-
22
path = payload[:virtual_path]
-
22
next unless path
-
22
partial = path =~ /^.*\/_[^\/]*$/
-
-
22
if partial
-
@_partials[path] += 1
-
@_partials[path.split("/").last] += 1
-
end
-
-
22
@_templates[path] += 1
-
end
-
-
15
ActiveSupport::Notifications.subscribe("!render_template.action_view") do |_name, _start, _finish, _id, payload|
-
22
next if payload[:virtual_path] # files don't have virtual path
-
-
path = payload[:identifier]
-
if path
-
@_files[path] += 1
-
@_files[path.split("/").last] += 1
-
end
-
end
-
end
-
-
2
def teardown_subscriptions
-
15
ActiveSupport::Notifications.unsubscribe("render_template.action_view")
-
15
ActiveSupport::Notifications.unsubscribe("!render_template.action_view")
-
end
-
-
2
def process(*args)
-
11
@_partials = Hash.new(0)
-
11
@_templates = Hash.new(0)
-
11
@_layouts = Hash.new(0)
-
11
super
-
end
-
-
# Asserts that the request was rendered with the appropriate template file or partials.
-
#
-
# # assert that the "new" view template was rendered
-
# assert_template "new"
-
#
-
# # assert that the exact template "admin/posts/new" was rendered
-
# assert_template %r{\Aadmin/posts/new\Z}
-
#
-
# # assert that the layout 'admin' was rendered
-
# assert_template layout: 'admin'
-
# assert_template layout: 'layouts/admin'
-
# assert_template layout: :admin
-
#
-
# # assert that no layout was rendered
-
# assert_template layout: nil
-
# assert_template layout: false
-
#
-
# # assert that the "_customer" partial was rendered twice
-
# assert_template partial: '_customer', count: 2
-
#
-
# # assert that no partials were rendered
-
# assert_template partial: false
-
#
-
# In a view test case, you can also assert that specific locals are passed
-
# to partials:
-
#
-
# # assert that the "_customer" partial was rendered with a specific object
-
# assert_template partial: '_customer', locals: { customer: @customer }
-
2
def assert_template(options = {}, message = nil)
-
# Force body to be read in case the template is being streamed.
-
response.body
-
-
case options
-
when NilClass, Regexp, String, Symbol
-
options = options.to_s if Symbol === options
-
rendered = @_templates
-
msg = message || sprintf("expecting <%s> but rendering with <%s>",
-
options.inspect, rendered.keys)
-
matches_template =
-
case options
-
when String
-
!options.empty? && rendered.any? do |t, num|
-
options_splited = options.split(File::SEPARATOR)
-
t_splited = t.split(File::SEPARATOR)
-
t_splited.last(options_splited.size) == options_splited
-
end
-
when Regexp
-
rendered.any? { |t,num| t.match(options) }
-
when NilClass
-
rendered.blank?
-
end
-
assert matches_template, msg
-
when Hash
-
options.assert_valid_keys(:layout, :partial, :locals, :count, :file)
-
-
if options.key?(:layout)
-
expected_layout = options[:layout]
-
msg = message || sprintf("expecting layout <%s> but action rendered <%s>",
-
expected_layout, @_layouts.keys)
-
-
case expected_layout
-
when String, Symbol
-
assert_includes @_layouts.keys, expected_layout.to_s, msg
-
when Regexp
-
assert(@_layouts.keys.any? {|l| l =~ expected_layout }, msg)
-
when nil, false
-
assert(@_layouts.empty?, msg)
-
end
-
end
-
-
if options[:file]
-
assert_includes @_files.keys, options[:file]
-
end
-
-
if expected_partial = options[:partial]
-
if expected_locals = options[:locals]
-
if defined?(@_rendered_views)
-
view = expected_partial.to_s.sub(/^_/, '').sub(/\/_(?=[^\/]+\z)/, '/')
-
-
partial_was_not_rendered_msg = "expected %s to be rendered but it was not." % view
-
assert_includes @_rendered_views.rendered_views, view, partial_was_not_rendered_msg
-
-
msg = 'expecting %s to be rendered with %s but was with %s' % [expected_partial,
-
expected_locals,
-
@_rendered_views.locals_for(view)]
-
assert(@_rendered_views.view_rendered?(view, options[:locals]), msg)
-
else
-
warn "the :locals option to #assert_template is only supported in a ActionView::TestCase"
-
end
-
elsif expected_count = options[:count]
-
actual_count = @_partials[expected_partial]
-
msg = message || sprintf("expecting %s to be rendered %s time(s) but rendered %s time(s)",
-
expected_partial, expected_count, actual_count)
-
assert(actual_count == expected_count.to_i, msg)
-
else
-
msg = message || sprintf("expecting partial <%s> but action rendered <%s>",
-
options[:partial], @_partials.keys)
-
assert_includes @_partials, expected_partial, msg
-
end
-
elsif options.key?(:partial)
-
assert @_partials.empty?,
-
"Expected no partials to be rendered"
-
end
-
else
-
raise ArgumentError, "assert_template only accepts a String, Symbol, Hash, Regexp, or nil"
-
end
-
end
-
end
-
-
2
class TestRequest < ActionDispatch::TestRequest #:nodoc:
-
2
DEFAULT_ENV = ActionDispatch::TestRequest::DEFAULT_ENV.dup
-
2
DEFAULT_ENV.delete 'PATH_INFO'
-
-
2
def initialize(env = {})
-
15
super
-
-
15
self.session = TestSession.new
-
15
self.session_options = TestSession::DEFAULT_OPTIONS.merge(:id => SecureRandom.hex(16))
-
end
-
-
2
def assign_parameters(routes, controller_path, action, parameters = {})
-
11
parameters = parameters.symbolize_keys.merge(:controller => controller_path, :action => action)
-
11
extra_keys = routes.extra_keys(parameters)
-
11
non_path_parameters = get? ? query_parameters : request_parameters
-
11
parameters.each do |key, value|
-
22
if value.is_a?(Array) && (value.frozen? || value.any?(&:frozen?))
-
value = value.map{ |v| v.duplicable? ? v.dup : v }
-
elsif value.is_a?(Hash) && (value.frozen? || value.any?{ |k,v| v.frozen? })
-
value = Hash[value.map{ |k,v| [k, v.duplicable? ? v.dup : v] }]
-
elsif value.frozen? && value.duplicable?
-
value = value.dup
-
end
-
-
22
if extra_keys.include?(key.to_sym)
-
non_path_parameters[key] = value
-
else
-
22
if value.is_a?(Array)
-
value = value.map(&:to_param)
-
else
-
22
value = value.to_param
-
end
-
-
22
path_parameters[key.to_s] = value
-
end
-
end
-
-
# Clear the combined params hash in case it was already referenced.
-
11
@env.delete("action_dispatch.request.parameters")
-
-
# Clear the filter cache variables so they're not stale
-
11
@filtered_parameters = @filtered_env = @filtered_path = nil
-
-
11
params = self.request_parameters.dup
-
11
%w(controller action only_path).each do |k|
-
33
params.delete(k)
-
33
params.delete(k.to_sym)
-
end
-
11
data = params.to_query
-
-
11
@env['CONTENT_LENGTH'] = data.length.to_s
-
11
@env['rack.input'] = StringIO.new(data)
-
end
-
-
2
def recycle!
-
11
@formats = nil
-
385
@env.delete_if { |k, v| k =~ /^(action_dispatch|rack)\.request/ }
-
385
@env.delete_if { |k, v| k =~ /^action_dispatch\.rescue/ }
-
11
@symbolized_path_params = nil
-
11
@method = @request_method = nil
-
11
@fullpath = @ip = @remote_ip = @protocol = nil
-
11
@env['action_dispatch.request.query_parameters'] = {}
-
11
@set_cookies ||= {}
-
11
@set_cookies.update(Hash[cookie_jar.instance_variable_get("@set_cookies").map{ |k,o| [k,o[:value]] }])
-
11
deleted_cookies = cookie_jar.instance_variable_get("@delete_cookies")
-
11
@set_cookies.reject!{ |k,v| deleted_cookies.include?(k) }
-
11
cookie_jar.update(rack_cookies)
-
11
cookie_jar.update(cookies)
-
11
cookie_jar.update(@set_cookies)
-
11
cookie_jar.recycle!
-
end
-
-
2
private
-
-
2
def default_env
-
15
DEFAULT_ENV
-
end
-
end
-
-
2
class TestResponse < ActionDispatch::TestResponse
-
2
def recycle!
-
11
initialize
-
end
-
end
-
-
2
class LiveTestResponse < Live::Response
-
2
def recycle!
-
@body = nil
-
initialize
-
end
-
-
2
def body
-
@body ||= super
-
end
-
-
# Was the response successful?
-
2
alias_method :success?, :successful?
-
-
# Was the URL not found?
-
2
alias_method :missing?, :not_found?
-
-
# Were we redirected?
-
2
alias_method :redirect?, :redirection?
-
-
# Was there a server-side error?
-
2
alias_method :error?, :server_error?
-
end
-
-
# Methods #destroy and #load! are overridden to avoid calling methods on the
-
# @store object, which does not exist for the TestSession class.
-
2
class TestSession < Rack::Session::Abstract::SessionHash #:nodoc:
-
2
DEFAULT_OPTIONS = Rack::Session::Abstract::ID::DEFAULT_OPTIONS
-
-
2
def initialize(session = {})
-
15
super(nil, nil)
-
15
@id = SecureRandom.hex(16)
-
15
@data = stringify_keys(session)
-
15
@loaded = true
-
end
-
-
2
def exists?
-
true
-
end
-
-
2
def keys
-
@data.keys
-
end
-
-
2
def values
-
@data.values
-
end
-
-
2
def destroy
-
clear
-
end
-
-
2
private
-
-
2
def load!
-
@id
-
end
-
end
-
-
# Superclass for ActionController functional tests. Functional tests allow you to
-
# test a single controller action per test method. This should not be confused with
-
# integration tests (see ActionDispatch::IntegrationTest), which are more like
-
# "stories" that can involve multiple controllers and multiple actions (i.e. multiple
-
# different HTTP requests).
-
#
-
# == Basic example
-
#
-
# Functional tests are written as follows:
-
# 1. First, one uses the +get+, +post+, +patch+, +put+, +delete+ or +head+ method to simulate
-
# an HTTP request.
-
# 2. Then, one asserts whether the current state is as expected. "State" can be anything:
-
# the controller's HTTP response, the database contents, etc.
-
#
-
# For example:
-
#
-
# class BooksControllerTest < ActionController::TestCase
-
# def test_create
-
# # Simulate a POST response with the given HTTP parameters.
-
# post(:create, book: { title: "Love Hina" })
-
#
-
# # Assert that the controller tried to redirect us to
-
# # the created book's URI.
-
# assert_response :found
-
#
-
# # Assert that the controller really put the book in the database.
-
# assert_not_nil Book.find_by(title: "Love Hina")
-
# end
-
# end
-
#
-
# You can also send a real document in the simulated HTTP request.
-
#
-
# def test_create
-
# json = {book: { title: "Love Hina" }}.to_json
-
# post :create, json
-
# end
-
#
-
# == Special instance variables
-
#
-
# ActionController::TestCase will also automatically provide the following instance
-
# variables for use in the tests:
-
#
-
# <b>@controller</b>::
-
# The controller instance that will be tested.
-
# <b>@request</b>::
-
# An ActionController::TestRequest, representing the current HTTP
-
# request. You can modify this object before sending the HTTP request. For example,
-
# you might want to set some session properties before sending a GET request.
-
# <b>@response</b>::
-
# An ActionController::TestResponse object, representing the response
-
# of the last HTTP response. In the above example, <tt>@response</tt> becomes valid
-
# after calling +post+. If the various assert methods are not sufficient, then you
-
# may use this object to inspect the HTTP response in detail.
-
#
-
# (Earlier versions of \Rails required each functional test to subclass
-
# Test::Unit::TestCase and define @controller, @request, @response in +setup+.)
-
#
-
# == Controller is automatically inferred
-
#
-
# ActionController::TestCase will automatically infer the controller under test
-
# from the test class name. If the controller cannot be inferred from the test
-
# class name, you can explicitly set it with +tests+.
-
#
-
# class SpecialEdgeCaseWidgetsControllerTest < ActionController::TestCase
-
# tests WidgetController
-
# end
-
#
-
# == \Testing controller internals
-
#
-
# In addition to these specific assertions, you also have easy access to various collections that the regular test/unit assertions
-
# can be used against. These collections are:
-
#
-
# * assigns: Instance variables assigned in the action that are available for the view.
-
# * session: Objects being saved in the session.
-
# * flash: The flash objects currently in the session.
-
# * cookies: \Cookies being sent to the user on this request.
-
#
-
# These collections can be used just like any other hash:
-
#
-
# assert_not_nil assigns(:person) # makes sure that a @person instance variable was set
-
# assert_equal "Dave", cookies[:name] # makes sure that a cookie called :name was set as "Dave"
-
# assert flash.empty? # makes sure that there's nothing in the flash
-
#
-
# For historic reasons, the assigns hash uses string-based keys. So <tt>assigns[:person]</tt> won't work, but <tt>assigns["person"]</tt> will. To
-
# appease our yearning for symbols, though, an alternative accessor has been devised using a method call instead of index referencing.
-
# So <tt>assigns(:person)</tt> will work just like <tt>assigns["person"]</tt>, but again, <tt>assigns[:person]</tt> will not work.
-
#
-
# On top of the collections, you have the complete url that a given action redirected to available in <tt>redirect_to_url</tt>.
-
#
-
# For redirects within the same controller, you can even call follow_redirect and the redirect will be followed, triggering another
-
# action call which can then be asserted against.
-
#
-
# == Manipulating session and cookie variables
-
#
-
# Sometimes you need to set up the session and cookie variables for a test.
-
# To do this just assign a value to the session or cookie collection:
-
#
-
# session[:key] = "value"
-
# cookies[:key] = "value"
-
#
-
# To clear the cookies for a test just clear the cookie collection:
-
#
-
# cookies.clear
-
#
-
# == \Testing named routes
-
#
-
# If you're using named routes, they can be easily tested using the original named routes' methods straight in the test case.
-
#
-
# assert_redirected_to page_url(title: 'foo')
-
2
class TestCase < ActiveSupport::TestCase
-
2
module Behavior
-
2
extend ActiveSupport::Concern
-
2
include ActionDispatch::TestProcess
-
2
include ActiveSupport::Testing::ConstantLookup
-
-
2
attr_reader :response, :request
-
-
2
module ClassMethods
-
-
# Sets the controller class name. Useful if the name can't be inferred from test class.
-
# Normalizes +controller_class+ before using.
-
#
-
# tests WidgetController
-
# tests :widget
-
# tests 'widget'
-
2
def tests(controller_class)
-
case controller_class
-
when String, Symbol
-
self.controller_class = "#{controller_class.to_s.camelize}Controller".constantize
-
when Class
-
self.controller_class = controller_class
-
else
-
raise ArgumentError, "controller class must be a String, Symbol, or Class"
-
end
-
end
-
-
2
def controller_class=(new_class)
-
prepare_controller_class(new_class) if new_class
-
self._controller_class = new_class
-
end
-
-
2
def controller_class
-
if current_controller_class = self._controller_class
-
current_controller_class
-
else
-
self.controller_class = determine_default_controller_class(name)
-
end
-
end
-
-
2
def determine_default_controller_class(name)
-
determine_constant_from_test_name(name) do |constant|
-
Class === constant && constant < ActionController::Metal
-
end
-
end
-
-
2
def prepare_controller_class(new_class)
-
new_class.send :include, ActionController::TestCase::RaiseActionExceptions
-
end
-
-
end
-
-
# Simulate a GET request with the given parameters.
-
#
-
# - +action+: The controller action to call.
-
# - +parameters+: The HTTP parameters that you want to pass. This may
-
# be +nil+, a hash, or a string that is appropriately encoded
-
# (<tt>application/x-www-form-urlencoded</tt> or <tt>multipart/form-data</tt>).
-
# - +session+: A hash of parameters to store in the session. This may be +nil+.
-
# - +flash+: A hash of parameters to store in the flash. This may be +nil+.
-
#
-
# You can also simulate POST, PATCH, PUT, DELETE, HEAD, and OPTIONS requests with
-
# +post+, +patch+, +put+, +delete+, +head+, and +options+.
-
#
-
# Note that the request method is not verified. The different methods are
-
# available to make the tests more expressive.
-
2
def get(action, *args)
-
11
process(action, "GET", *args)
-
end
-
-
# Simulate a POST request with the given parameters and set/volley the response.
-
# See +get+ for more details.
-
2
def post(action, *args)
-
process(action, "POST", *args)
-
end
-
-
# Simulate a PATCH request with the given parameters and set/volley the response.
-
# See +get+ for more details.
-
2
def patch(action, *args)
-
process(action, "PATCH", *args)
-
end
-
-
# Simulate a PUT request with the given parameters and set/volley the response.
-
# See +get+ for more details.
-
2
def put(action, *args)
-
process(action, "PUT", *args)
-
end
-
-
# Simulate a DELETE request with the given parameters and set/volley the response.
-
# See +get+ for more details.
-
2
def delete(action, *args)
-
process(action, "DELETE", *args)
-
end
-
-
# Simulate a HEAD request with the given parameters and set/volley the response.
-
# See +get+ for more details.
-
2
def head(action, *args)
-
process(action, "HEAD", *args)
-
end
-
-
2
def xml_http_request(request_method, action, parameters = nil, session = nil, flash = nil)
-
@request.env['HTTP_X_REQUESTED_WITH'] = 'XMLHttpRequest'
-
@request.env['HTTP_ACCEPT'] ||= [Mime::JS, Mime::HTML, Mime::XML, 'text/xml', Mime::ALL].join(', ')
-
__send__(request_method, action, parameters, session, flash).tap do
-
@request.env.delete 'HTTP_X_REQUESTED_WITH'
-
@request.env.delete 'HTTP_ACCEPT'
-
end
-
end
-
2
alias xhr :xml_http_request
-
-
2
def paramify_values(hash_or_array_or_value)
-
11
case hash_or_array_or_value
-
when Hash
-
Hash[hash_or_array_or_value.map{|key, value| [key, paramify_values(value)] }]
-
when Array
-
hash_or_array_or_value.map {|i| paramify_values(i)}
-
when Rack::Test::UploadedFile, ActionDispatch::Http::UploadedFile
-
hash_or_array_or_value
-
else
-
11
hash_or_array_or_value.to_param
-
end
-
end
-
-
2
def process(action, http_method = 'GET', *args)
-
11
check_required_ivars
-
-
11
if args.first.is_a?(String) && http_method != 'HEAD'
-
@request.env['RAW_POST_DATA'] = args.shift
-
end
-
-
11
parameters, session, flash = args
-
-
# Ensure that numbers and symbols passed as params are converted to
-
# proper params, as is the case when engaging rack.
-
11
parameters = paramify_values(parameters) if html_format?(parameters)
-
-
11
@html_document = nil
-
-
11
unless @controller.respond_to?(:recycle!)
-
11
@controller.extend(Testing::Functional)
-
22
@controller.class.class_eval { include Testing }
-
end
-
-
11
@request.recycle!
-
11
@response.recycle!
-
11
@controller.recycle!
-
-
11
@request.env['REQUEST_METHOD'] = http_method
-
-
11
parameters ||= {}
-
11
controller_class_name = @controller.class.anonymous? ?
-
"anonymous" :
-
@controller.class.controller_path
-
-
11
@request.assign_parameters(@routes, controller_class_name, action.to_s, parameters)
-
-
11
@request.session.update(session) if session
-
11
@request.flash.update(flash || {})
-
-
11
@controller.request = @request
-
11
@controller.response = @response
-
-
11
build_request_uri(action, parameters)
-
-
11
name = @request.parameters[:action]
-
-
11
@controller.recycle!
-
11
@controller.process(name)
-
-
11
if cookies = @request.env['action_dispatch.cookies']
-
11
unless @response.committed?
-
11
cookies.write(@response)
-
end
-
end
-
11
@response.prepare!
-
-
11
@assigns = @controller.respond_to?(:view_assigns) ? @controller.view_assigns : {}
-
11
@request.session['flash'] = @request.flash.to_session_value
-
11
@request.session.delete('flash') if @request.session['flash'].blank?
-
11
@response
-
end
-
-
2
def setup_controller_request_and_response
-
15
@controller = nil unless defined? @controller
-
-
15
response_klass = TestResponse
-
-
15
if klass = self.class.controller_class
-
15
if klass < ActionController::Live
-
response_klass = LiveTestResponse
-
end
-
15
unless @controller
-
15
begin
-
15
@controller = klass.new
-
rescue
-
warn "could not construct controller #{klass}" if $VERBOSE
-
end
-
end
-
end
-
-
15
@request = build_request
-
15
@response = build_response response_klass
-
15
@response.request = @request
-
-
15
if @controller
-
15
@controller.request = @request
-
15
@controller.params = {}
-
end
-
end
-
-
2
def build_request
-
15
TestRequest.new
-
end
-
-
2
def build_response(klass)
-
15
klass.new
-
end
-
-
2
included do
-
8
include ActionController::TemplateAssertions
-
8
include ActionDispatch::Assertions
-
8
class_attribute :_controller_class
-
8
setup :setup_controller_request_and_response
-
end
-
-
2
private
-
2
def check_required_ivars
-
# Sanity check for required instance variables so we can give an
-
# understandable error message.
-
11
[:@routes, :@controller, :@request, :@response].each do |iv_name|
-
44
if !instance_variable_defined?(iv_name) || instance_variable_get(iv_name).nil?
-
raise "#{iv_name} is nil: make sure you set it in your test's setup method."
-
end
-
end
-
end
-
-
2
def build_request_uri(action, parameters)
-
11
unless @request.env["PATH_INFO"]
-
11
options = @controller.respond_to?(:url_options) ? @controller.__send__(:url_options).merge(parameters) : parameters
-
11
options.update(
-
:only_path => true,
-
:action => action,
-
:relative_url_root => nil,
-
:_recall => @request.symbolized_path_parameters)
-
-
11
url, query_string = @routes.url_for(options).split("?", 2)
-
-
11
@request.env["SCRIPT_NAME"] = @controller.config.relative_url_root
-
11
@request.env["PATH_INFO"] = url
-
11
@request.env["QUERY_STRING"] = query_string || ""
-
end
-
end
-
-
2
def html_format?(parameters)
-
11
return true unless parameters.is_a?(Hash)
-
Mime.fetch(parameters[:format]) { Mime['html'] }.html?
-
end
-
end
-
-
# When the request.remote_addr remains the default for testing, which is 0.0.0.0, the exception is simply raised inline
-
# (skipping the regular exception handling from rescue_action). If the request.remote_addr is anything else, the regular
-
# rescue_action process takes place. This means you can test your rescue_action code by setting remote_addr to something else
-
# than 0.0.0.0.
-
#
-
# The exception is stored in the exception accessor for further inspection.
-
2
module RaiseActionExceptions
-
2
def self.included(base) #:nodoc:
-
unless base.method_defined?(:exception) && base.method_defined?(:exception=)
-
base.class_eval do
-
attr_accessor :exception
-
protected :exception, :exception=
-
end
-
end
-
end
-
-
2
protected
-
2
def rescue_action_without_handler(e)
-
self.exception = e
-
-
if request.remote_addr == "0.0.0.0"
-
raise(e)
-
else
-
super(e)
-
end
-
end
-
end
-
-
2
include Behavior
-
end
-
end
-
#--
-
# Copyright (c) 2004-2014 David Heinemeier Hansson
-
#
-
# Permission is hereby granted, free of charge, to any person obtaining
-
# a copy of this software and associated documentation files (the
-
# "Software"), to deal in the Software without restriction, including
-
# without limitation the rights to use, copy, modify, merge, publish,
-
# distribute, sublicense, and/or sell copies of the Software, and to
-
# permit persons to whom the Software is furnished to do so, subject to
-
# the following conditions:
-
#
-
# The above copyright notice and this permission notice shall be
-
# included in all copies or substantial portions of the Software.
-
#
-
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
-
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
-
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
-
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-
#++
-
-
2
require 'active_support'
-
2
require 'active_support/rails'
-
2
require 'active_support/core_ext/module/attribute_accessors'
-
-
2
require 'action_pack'
-
2
require 'rack'
-
-
2
module Rack
-
2
autoload :Test, 'rack/test'
-
end
-
-
2
module ActionDispatch
-
2
extend ActiveSupport::Autoload
-
-
2
class IllegalStateError < StandardError
-
end
-
-
2
eager_autoload do
-
2
autoload_under 'http' do
-
2
autoload :Request
-
2
autoload :Response
-
end
-
end
-
-
2
autoload_under 'middleware' do
-
2
autoload :RequestId
-
2
autoload :Callbacks
-
2
autoload :Cookies
-
2
autoload :DebugExceptions
-
2
autoload :ExceptionWrapper
-
2
autoload :Flash
-
2
autoload :ParamsParser
-
2
autoload :PublicExceptions
-
2
autoload :Reloader
-
2
autoload :RemoteIp
-
2
autoload :ShowExceptions
-
2
autoload :SSL
-
2
autoload :Static
-
end
-
-
2
autoload :Journey
-
2
autoload :MiddlewareStack, 'action_dispatch/middleware/stack'
-
2
autoload :Routing
-
-
2
module Http
-
2
extend ActiveSupport::Autoload
-
-
2
autoload :Cache
-
2
autoload :Headers
-
2
autoload :MimeNegotiation
-
2
autoload :Parameters
-
2
autoload :ParameterFilter
-
2
autoload :Upload
-
2
autoload :UploadedFile, 'action_dispatch/http/upload'
-
2
autoload :URL
-
end
-
-
2
module Session
-
2
autoload :AbstractStore, 'action_dispatch/middleware/session/abstract_store'
-
2
autoload :CookieStore, 'action_dispatch/middleware/session/cookie_store'
-
2
autoload :MemCacheStore, 'action_dispatch/middleware/session/mem_cache_store'
-
2
autoload :CacheStore, 'action_dispatch/middleware/session/cache_store'
-
end
-
-
2
mattr_accessor :test_app
-
-
2
autoload_under 'testing' do
-
2
autoload :Assertions
-
2
autoload :Integration
-
2
autoload :IntegrationTest, 'action_dispatch/testing/integration'
-
2
autoload :TestProcess
-
2
autoload :TestRequest
-
2
autoload :TestResponse
-
end
-
end
-
-
2
autoload :Mime, 'action_dispatch/http/mime_type'
-
-
2
ActiveSupport.on_load(:action_view) do
-
2
ActionView::Base.default_formats ||= Mime::SET.symbols
-
2
ActionView::Template::Types.delegate_to Mime
-
end
-
-
2
module ActionDispatch
-
2
module Http
-
2
module Cache
-
2
module Request
-
-
2
HTTP_IF_MODIFIED_SINCE = 'HTTP_IF_MODIFIED_SINCE'.freeze
-
2
HTTP_IF_NONE_MATCH = 'HTTP_IF_NONE_MATCH'.freeze
-
-
2
def if_modified_since
-
if since = env[HTTP_IF_MODIFIED_SINCE]
-
Time.rfc2822(since) rescue nil
-
end
-
end
-
-
2
def if_none_match
-
env[HTTP_IF_NONE_MATCH]
-
end
-
-
2
def if_none_match_etags
-
(if_none_match ? if_none_match.split(/\s*,\s*/) : []).collect do |etag|
-
etag.gsub(/^\"|\"$/, "")
-
end
-
end
-
-
2
def not_modified?(modified_at)
-
if_modified_since && modified_at && if_modified_since >= modified_at
-
end
-
-
2
def etag_matches?(etag)
-
if etag
-
etag = etag.gsub(/^\"|\"$/, "")
-
if_none_match_etags.include?(etag)
-
end
-
end
-
-
# Check response freshness (Last-Modified and ETag) against request
-
# If-Modified-Since and If-None-Match conditions. If both headers are
-
# supplied, both must match, or the request is not considered fresh.
-
2
def fresh?(response)
-
last_modified = if_modified_since
-
etag = if_none_match
-
-
return false unless last_modified || etag
-
-
success = true
-
success &&= not_modified?(response.last_modified) if last_modified
-
success &&= etag_matches?(response.etag) if etag
-
success
-
end
-
end
-
-
2
module Response
-
2
attr_reader :cache_control, :etag
-
2
alias :etag? :etag
-
-
2
def last_modified
-
if last = headers[LAST_MODIFIED]
-
Time.httpdate(last)
-
end
-
end
-
-
2
def last_modified?
-
24
headers.include?(LAST_MODIFIED)
-
end
-
-
2
def last_modified=(utc_time)
-
headers[LAST_MODIFIED] = utc_time.httpdate
-
end
-
-
2
def date
-
if date_header = headers['Date']
-
Time.httpdate(date_header)
-
end
-
end
-
-
2
def date?
-
headers.include?('Date')
-
end
-
-
2
def date=(utc_time)
-
headers['Date'] = utc_time.httpdate
-
end
-
-
2
def etag=(etag)
-
key = ActiveSupport::Cache.expand_cache_key(etag)
-
@etag = self[ETAG] = %("#{Digest::MD5.hexdigest(key)}")
-
end
-
-
2
private
-
-
2
LAST_MODIFIED = "Last-Modified".freeze
-
2
ETAG = "ETag".freeze
-
2
CACHE_CONTROL = "Cache-Control".freeze
-
2
SPECIAL_KEYS = %w[extras no-cache max-age public must-revalidate]
-
-
2
def cache_control_segments
-
39
if cache_control = self[CACHE_CONTROL]
-
cache_control.delete(' ').split(',')
-
else
-
39
[]
-
end
-
end
-
-
2
def cache_control_headers
-
39
cache_control = {}
-
-
39
cache_control_segments.each do |segment|
-
directive, argument = segment.split('=', 2)
-
-
if SPECIAL_KEYS.include? directive
-
key = directive.tr('-', '_')
-
cache_control[key.to_sym] = argument || true
-
else
-
cache_control[:extras] ||= []
-
cache_control[:extras] << segment
-
end
-
end
-
-
39
cache_control
-
end
-
-
2
def prepare_cache_control!
-
39
@cache_control = cache_control_headers
-
39
@etag = self[ETAG]
-
end
-
-
2
def handle_conditional_get!
-
24
if etag? || last_modified? || !@cache_control.empty?
-
set_conditional_cache_control!
-
end
-
end
-
-
2
DEFAULT_CACHE_CONTROL = "max-age=0, private, must-revalidate".freeze
-
2
NO_CACHE = "no-cache".freeze
-
2
PUBLIC = "public".freeze
-
2
PRIVATE = "private".freeze
-
2
MUST_REVALIDATE = "must-revalidate".freeze
-
-
2
def set_conditional_cache_control!
-
control = {}
-
cc_headers = cache_control_headers
-
if extras = cc_headers.delete(:extras)
-
@cache_control[:extras] ||= []
-
@cache_control[:extras] += extras
-
@cache_control[:extras].uniq!
-
end
-
-
control.merge! cc_headers
-
control.merge! @cache_control
-
-
if control.empty?
-
headers[CACHE_CONTROL] = DEFAULT_CACHE_CONTROL
-
elsif control[:no_cache]
-
headers[CACHE_CONTROL] = NO_CACHE
-
if control[:extras]
-
headers[CACHE_CONTROL] += ", #{control[:extras].join(', ')}"
-
end
-
else
-
extras = control[:extras]
-
max_age = control[:max_age]
-
-
options = []
-
options << "max-age=#{max_age.to_i}" if max_age
-
options << (control[:public] ? PUBLIC : PRIVATE)
-
options << MUST_REVALIDATE if control[:must_revalidate]
-
options.concat(extras) if extras
-
-
headers[CACHE_CONTROL] = options.join(", ")
-
end
-
end
-
end
-
end
-
end
-
end
-
2
require 'active_support/core_ext/hash/keys'
-
2
require 'active_support/core_ext/object/duplicable'
-
2
require 'action_dispatch/http/parameter_filter'
-
-
2
module ActionDispatch
-
2
module Http
-
# Allows you to specify sensitive parameters which will be replaced from
-
# the request log by looking in the query string of the request and all
-
# subhashes of the params hash to filter. If a block is given, each key and
-
# value of the params hash and all subhashes is passed to it, the value
-
# or key can be replaced using String#replace or similar method.
-
#
-
# env["action_dispatch.parameter_filter"] = [:password]
-
# => replaces the value to all keys matching /password/i with "[FILTERED]"
-
#
-
# env["action_dispatch.parameter_filter"] = [:foo, "bar"]
-
# => replaces the value to all keys matching /foo|bar/i with "[FILTERED]"
-
#
-
# env["action_dispatch.parameter_filter"] = lambda do |k,v|
-
# v.reverse! if k =~ /secret/i
-
# end
-
# => reverses the value to all keys matching /secret/i
-
2
module FilterParameters
-
2
ENV_MATCH = [/RAW_POST_DATA/, "rack.request.form_vars"] # :nodoc:
-
2
NULL_PARAM_FILTER = ParameterFilter.new # :nodoc:
-
2
NULL_ENV_FILTER = ParameterFilter.new ENV_MATCH # :nodoc:
-
-
2
def initialize(env)
-
82
super
-
82
@filtered_parameters = nil
-
82
@filtered_env = nil
-
82
@filtered_path = nil
-
end
-
-
# Return a hash of parameters with all sensitive data replaced.
-
2
def filtered_parameters
-
24
@filtered_parameters ||= parameter_filter.filter(parameters)
-
end
-
-
# Return a hash of request.env with all sensitive data replaced.
-
2
def filtered_env
-
@filtered_env ||= env_filter.filter(@env)
-
end
-
-
# Reconstructed a path with all sensitive GET parameters replaced.
-
2
def filtered_path
-
13
@filtered_path ||= query_string.empty? ? path : "#{path}?#{filtered_query_string}"
-
end
-
-
2
protected
-
-
2
def parameter_filter
-
24
parameter_filter_for @env.fetch("action_dispatch.parameter_filter") {
-
return NULL_PARAM_FILTER
-
}
-
end
-
-
2
def env_filter
-
user_key = @env.fetch("action_dispatch.parameter_filter") {
-
return NULL_ENV_FILTER
-
}
-
parameter_filter_for(Array(user_key) + ENV_MATCH)
-
end
-
-
2
def parameter_filter_for(filters)
-
24
ParameterFilter.new(filters)
-
end
-
-
2
KV_RE = '[^&;=]+'
-
2
PAIR_RE = %r{(#{KV_RE})=(#{KV_RE})}
-
2
def filtered_query_string
-
query_string.gsub(PAIR_RE) do |_|
-
parameter_filter.filter([[$1, $2]]).first.join("=")
-
end
-
end
-
end
-
end
-
end
-
2
module ActionDispatch
-
2
module Http
-
2
module FilterRedirect
-
-
2
FILTERED = '[FILTERED]'.freeze # :nodoc:
-
-
2
def filtered_location
-
filters = location_filter
-
if !filters.empty? && location_filter_match?(filters)
-
FILTERED
-
else
-
location
-
end
-
end
-
-
2
private
-
-
2
def location_filter
-
if request
-
request.env['action_dispatch.redirect_filter'] || []
-
else
-
[]
-
end
-
end
-
-
2
def location_filter_match?(filters)
-
filters.any? do |filter|
-
if String === filter
-
location.include?(filter)
-
elsif Regexp === filter
-
location.match(filter)
-
end
-
end
-
end
-
-
end
-
end
-
end
-
2
module ActionDispatch
-
2
module Http
-
2
class Headers
-
2
CGI_VARIABLES = %w(
-
CONTENT_TYPE CONTENT_LENGTH
-
HTTPS AUTH_TYPE GATEWAY_INTERFACE
-
PATH_INFO PATH_TRANSLATED QUERY_STRING
-
REMOTE_ADDR REMOTE_HOST REMOTE_IDENT REMOTE_USER
-
REQUEST_METHOD SCRIPT_NAME
-
SERVER_NAME SERVER_PORT SERVER_PROTOCOL SERVER_SOFTWARE
-
)
-
2
HTTP_HEADER = /\A[A-Za-z0-9-]+\z/
-
-
2
include Enumerable
-
2
attr_reader :env
-
-
2
def initialize(env = {})
-
24
@env = env
-
end
-
-
2
def [](key)
-
24
@env[env_name(key)]
-
end
-
-
2
def []=(key, value)
-
@env[env_name(key)] = value
-
end
-
-
2
def key?(key)
-
@env.key? env_name(key)
-
end
-
2
alias :include? :key?
-
-
2
def fetch(key, *args, &block)
-
@env.fetch env_name(key), *args, &block
-
end
-
-
2
def each(&block)
-
@env.each(&block)
-
end
-
-
2
def merge(headers_or_env)
-
headers = Http::Headers.new(env.dup)
-
headers.merge!(headers_or_env)
-
headers
-
end
-
-
2
def merge!(headers_or_env)
-
headers_or_env.each do |key, value|
-
self[env_name(key)] = value
-
end
-
end
-
-
2
private
-
2
def env_name(key)
-
24
key = key.to_s
-
24
if key =~ HTTP_HEADER
-
24
key = key.upcase.tr('-', '_')
-
24
key = "HTTP_" + key unless CGI_VARIABLES.include?(key)
-
end
-
24
key
-
end
-
end
-
end
-
end
-
2
require 'active_support/core_ext/module/attribute_accessors'
-
-
2
module ActionDispatch
-
2
module Http
-
2
module MimeNegotiation
-
2
extend ActiveSupport::Concern
-
-
2
included do
-
2
mattr_accessor :ignore_accept_header
-
2
self.ignore_accept_header = false
-
end
-
-
2
attr_reader :variant
-
-
# The MIME type of the HTTP request, such as Mime::XML.
-
#
-
# For backward compatibility, the post \format is extracted from the
-
# X-Post-Data-Format HTTP header if present.
-
2
def content_mime_type
-
68
@env["action_dispatch.request.content_type"] ||= begin
-
64
if @env['CONTENT_TYPE'] =~ /^([^,\;]*)/
-
4
Mime::Type.lookup($1.strip.downcase)
-
else
-
60
nil
-
end
-
end
-
end
-
-
2
def content_type
-
content_mime_type && content_mime_type.to_s
-
end
-
-
# Returns the accepted MIME type for the request.
-
2
def accepts
-
@env["action_dispatch.request.accepts"] ||= begin
-
header = @env['HTTP_ACCEPT'].to_s.strip
-
-
if header.empty?
-
[content_mime_type]
-
else
-
Mime::Type.parse(header)
-
end
-
end
-
end
-
-
# Returns the MIME type for the \format used in the request.
-
#
-
# GET /posts/5.xml | request.format => Mime::XML
-
# GET /posts/5.xhtml | request.format => Mime::HTML
-
# GET /posts/5 | request.format => Mime::HTML or MIME::JS, or request.accepts.first
-
#
-
2
def format(view_path = [])
-
24
formats.first || Mime::NullType.instance
-
end
-
-
2
def formats
-
48
@env["action_dispatch.request.formats"] ||=
-
if parameters[:format]
-
Array(Mime[parameters[:format]])
-
elsif use_accept_header && valid_accept_header
-
accepts
-
elsif xhr?
-
[Mime::JS]
-
else
-
24
[Mime::HTML]
-
end
-
end
-
-
# Sets the \variant for template.
-
2
def variant=(variant)
-
if variant.is_a?(Symbol)
-
@variant = [variant]
-
elsif variant.is_a?(Array) && variant.any? && variant.all?{ |v| v.is_a?(Symbol) }
-
@variant = variant
-
else
-
raise ArgumentError, "request.variant must be set to a Symbol or an Array of Symbols, not a #{variant.class}. " \
-
"For security reasons, never directly set the variant to a user-provided value, " \
-
"like params[:variant].to_sym. Check user-provided value against a whitelist first, " \
-
"then set the variant: request.variant = :tablet if params[:variant] == 'tablet'"
-
end
-
end
-
-
# Sets the \format by string extension, which can be used to force custom formats
-
# that are not controlled by the extension.
-
#
-
# class ApplicationController < ActionController::Base
-
# before_action :adjust_format_for_iphone
-
#
-
# private
-
# def adjust_format_for_iphone
-
# request.format = :iphone if request.env["HTTP_USER_AGENT"][/iPhone/]
-
# end
-
# end
-
2
def format=(extension)
-
parameters[:format] = extension.to_s
-
@env["action_dispatch.request.formats"] = [Mime::Type.lookup_by_extension(parameters[:format])]
-
end
-
-
# Sets the \formats by string extensions. This differs from #format= by allowing you
-
# to set multiple, ordered formats, which is useful when you want to have a fallback.
-
#
-
# In this example, the :iphone format will be used if it's available, otherwise it'll fallback
-
# to the :html format.
-
#
-
# class ApplicationController < ActionController::Base
-
# before_action :adjust_format_for_iphone_with_html_fallback
-
#
-
# private
-
# def adjust_format_for_iphone_with_html_fallback
-
# request.formats = [ :iphone, :html ] if request.env["HTTP_USER_AGENT"][/iPhone/]
-
# end
-
# end
-
2
def formats=(extensions)
-
parameters[:format] = extensions.first.to_s
-
@env["action_dispatch.request.formats"] = extensions.collect do |extension|
-
Mime::Type.lookup_by_extension(extension)
-
end
-
end
-
-
# Receives an array of mimes and return the first user sent mime that
-
# matches the order array.
-
#
-
2
def negotiate_mime(order)
-
formats.each do |priority|
-
if priority == Mime::ALL
-
return order.first
-
elsif order.include?(priority)
-
return priority
-
end
-
end
-
-
order.include?(Mime::ALL) ? format : nil
-
end
-
-
2
protected
-
-
2
BROWSER_LIKE_ACCEPTS = /,\s*\*\/\*|\*\/\*\s*,/
-
-
2
def valid_accept_header
-
24
(xhr? && (accept.present? || content_mime_type)) ||
-
48
(accept.present? && accept !~ BROWSER_LIKE_ACCEPTS)
-
end
-
-
2
def use_accept_header
-
24
!self.class.ignore_accept_header
-
end
-
end
-
end
-
end
-
2
require 'set'
-
2
require 'singleton'
-
2
require 'active_support/core_ext/module/attribute_accessors'
-
2
require 'active_support/core_ext/string/starts_ends_with'
-
-
2
module Mime
-
2
class Mimes < Array
-
2
def symbols
-
70
@symbols ||= map { |m| m.to_sym }
-
end
-
-
%w(<< concat shift unshift push pop []= clear compact! collect!
-
delete delete_at delete_if flatten! map! insert reject! reverse!
-
2
replace slice! sort! uniq!).each do |method|
-
44
module_eval <<-CODE, __FILE__, __LINE__ + 1
-
def #{method}(*)
-
@symbols = nil
-
super
-
end
-
CODE
-
end
-
end
-
-
2
SET = Mimes.new
-
2
EXTENSION_LOOKUP = {}
-
2
LOOKUP = Hash.new { |h, k| h[k] = Type.new(k) unless k.blank? }
-
-
2
class << self
-
2
def [](type)
-
74
return type if type.is_a?(Type)
-
74
Type.lookup_by_extension(type)
-
end
-
-
2
def fetch(type)
-
return type if type.is_a?(Type)
-
EXTENSION_LOOKUP.fetch(type.to_s) { |k| yield k }
-
end
-
end
-
-
# Encapsulates the notion of a mime type. Can be used at render time, for example, with:
-
#
-
# class PostsController < ActionController::Base
-
# def show
-
# @post = Post.find(params[:id])
-
#
-
# respond_to do |format|
-
# format.html
-
# format.ics { render text: post.to_ics, mime_type: Mime::Type["text/calendar"] }
-
# format.xml { render xml: @people }
-
# end
-
# end
-
# end
-
2
class Type
-
2
@@html_types = Set.new [:html, :all]
-
2
cattr_reader :html_types
-
-
2
attr_reader :symbol
-
-
2
@register_callbacks = []
-
-
# A simple helper class used in parsing the accept header
-
2
class AcceptItem #:nodoc:
-
2
attr_accessor :index, :name, :q
-
2
alias :to_s :name
-
-
2
def initialize(index, name, q = nil)
-
@index = index
-
@name = name
-
q ||= 0.0 if @name == Mime::ALL.to_s # default wildcard match to end of list
-
@q = ((q || 1.0).to_f * 100).to_i
-
end
-
-
2
def <=>(item)
-
result = item.q <=> @q
-
result = @index <=> item.index if result == 0
-
result
-
end
-
-
2
def ==(item)
-
@name == item.to_s
-
end
-
end
-
-
2
class AcceptList < Array #:nodoc:
-
2
def assort!
-
sort!
-
-
# Take care of the broken text/xml entry by renaming or deleting it
-
if text_xml_idx && app_xml_idx
-
app_xml.q = [text_xml.q, app_xml.q].max # set the q value to the max of the two
-
exchange_xml_items if app_xml_idx > text_xml_idx # make sure app_xml is ahead of text_xml in the list
-
delete_at(text_xml_idx) # delete text_xml from the list
-
elsif text_xml_idx
-
text_xml.name = Mime::XML.to_s
-
end
-
-
# Look for more specific XML-based types and sort them ahead of app/xml
-
if app_xml_idx
-
idx = app_xml_idx
-
-
while idx < length
-
type = self[idx]
-
break if type.q < app_xml.q
-
-
if type.name.ends_with? '+xml'
-
self[app_xml_idx], self[idx] = self[idx], app_xml
-
@app_xml_idx = idx
-
end
-
idx += 1
-
end
-
end
-
-
map! { |i| Mime::Type.lookup(i.name) }.uniq!
-
to_a
-
end
-
-
2
private
-
2
def text_xml_idx
-
@text_xml_idx ||= index('text/xml')
-
end
-
-
2
def app_xml_idx
-
@app_xml_idx ||= index(Mime::XML.to_s)
-
end
-
-
2
def text_xml
-
self[text_xml_idx]
-
end
-
-
2
def app_xml
-
self[app_xml_idx]
-
end
-
-
2
def exchange_xml_items
-
self[app_xml_idx], self[text_xml_idx] = text_xml, app_xml
-
@app_xml_idx, @text_xml_idx = text_xml_idx, app_xml_idx
-
end
-
end
-
-
2
class << self
-
2
TRAILING_STAR_REGEXP = /(text|application)\/\*/
-
2
PARAMETER_SEPARATOR_REGEXP = /;\s*\w+="?\w+"?/
-
-
2
def register_callback(&block)
-
2
@register_callbacks << block
-
end
-
-
2
def lookup(string)
-
4
LOOKUP[string]
-
end
-
-
2
def lookup_by_extension(extension)
-
74
EXTENSION_LOOKUP[extension.to_s]
-
end
-
-
# Registers an alias that's not used on mime type lookup, but can be referenced directly. Especially useful for
-
# rendering different HTML versions depending on the user agent, like an iPhone.
-
2
def register_alias(string, symbol, extension_synonyms = [])
-
register(string, symbol, [], extension_synonyms, true)
-
end
-
-
2
def register(string, symbol, mime_type_synonyms = [], extension_synonyms = [], skip_lookup = false)
-
44
Mime.const_set(symbol.upcase, Type.new(string, symbol, mime_type_synonyms))
-
-
44
new_mime = Mime.const_get(symbol.upcase)
-
44
SET << new_mime
-
-
104
([string] + mime_type_synonyms).each { |str| LOOKUP[str] = SET.last } unless skip_lookup
-
120
([symbol] + extension_synonyms).each { |ext| EXTENSION_LOOKUP[ext.to_s] = SET.last }
-
-
44
@register_callbacks.each do |callback|
-
callback.call(new_mime)
-
end
-
end
-
-
2
def parse(accept_header)
-
if !accept_header.include?(',')
-
accept_header = accept_header.split(PARAMETER_SEPARATOR_REGEXP).first
-
parse_trailing_star(accept_header) || [Mime::Type.lookup(accept_header)].compact
-
else
-
list, index = AcceptList.new, 0
-
accept_header.split(',').each do |header|
-
params, q = header.split(PARAMETER_SEPARATOR_REGEXP)
-
if params.present?
-
params.strip!
-
-
params = parse_trailing_star(params) || [params]
-
-
params.each do |m|
-
list << AcceptItem.new(index, m.to_s, q)
-
index += 1
-
end
-
end
-
end
-
list.assort!
-
end
-
end
-
-
2
def parse_trailing_star(accept_header)
-
parse_data_with_trailing_star($1) if accept_header =~ TRAILING_STAR_REGEXP
-
end
-
-
# For an input of <tt>'text'</tt>, returns <tt>[Mime::JSON, Mime::XML, Mime::ICS,
-
# Mime::HTML, Mime::CSS, Mime::CSV, Mime::JS, Mime::YAML, Mime::TEXT]</tt>.
-
#
-
# For an input of <tt>'application'</tt>, returns <tt>[Mime::HTML, Mime::JS,
-
# Mime::XML, Mime::YAML, Mime::ATOM, Mime::JSON, Mime::RSS, Mime::URL_ENCODED_FORM]</tt>.
-
2
def parse_data_with_trailing_star(input)
-
Mime::SET.select { |m| m =~ input }
-
end
-
-
# This method is opposite of register method.
-
#
-
# Usage:
-
#
-
# Mime::Type.unregister(:mobile)
-
2
def unregister(symbol)
-
symbol = symbol.upcase
-
mime = Mime.const_get(symbol)
-
Mime.instance_eval { remove_const(symbol) }
-
-
SET.delete_if { |v| v.eql?(mime) }
-
LOOKUP.delete_if { |_,v| v.eql?(mime) }
-
EXTENSION_LOOKUP.delete_if { |_,v| v.eql?(mime) }
-
end
-
end
-
-
2
def initialize(string, symbol = nil, synonyms = [])
-
46
@symbol, @synonyms = symbol, synonyms
-
46
@string = string
-
end
-
-
2
def to_s
-
30
@string
-
end
-
-
2
def to_str
-
to_s
-
end
-
-
2
def to_sym
-
188
@symbol
-
end
-
-
2
def ref
-
70
to_sym || to_s
-
end
-
-
2
def ===(list)
-
if list.is_a?(Array)
-
(@synonyms + [ self ]).any? { |synonym| list.include?(synonym) }
-
else
-
super
-
end
-
end
-
-
2
def ==(mime_type)
-
6
return false if mime_type.blank?
-
6
(@synonyms + [ self ]).any? do |synonym|
-
12
synonym.to_s == mime_type.to_s || synonym.to_sym == mime_type.to_sym
-
end
-
end
-
-
2
def =~(mime_type)
-
return false if mime_type.blank?
-
regexp = Regexp.new(Regexp.quote(mime_type.to_s))
-
(@synonyms + [ self ]).any? do |synonym|
-
synonym.to_s =~ regexp
-
end
-
end
-
-
2
def html?
-
@@html_types.include?(to_sym) || @string =~ /html/
-
end
-
-
-
2
private
-
-
2
def to_ary; end
-
2
def to_a; end
-
-
2
def method_missing(method, *args)
-
if method.to_s.ends_with? '?'
-
method[0..-2].downcase.to_sym == to_sym
-
else
-
super
-
end
-
end
-
-
2
def respond_to_missing?(method, include_private = false) #:nodoc:
-
method.to_s.ends_with? '?'
-
end
-
end
-
-
2
class NullType
-
2
include Singleton
-
-
2
def nil?
-
true
-
end
-
-
2
def ref; end
-
-
2
def respond_to_missing?(method, include_private = false)
-
method.to_s.ends_with? '?'
-
end
-
-
2
private
-
2
def method_missing(method, *args)
-
false if method.to_s.ends_with? '?'
-
end
-
end
-
end
-
-
2
require 'action_dispatch/http/mime_types'
-
# Build list of Mime types for HTTP responses
-
# http://www.iana.org/assignments/media-types/
-
-
2
Mime::Type.register "text/html", :html, %w( application/xhtml+xml ), %w( xhtml )
-
2
Mime::Type.register "text/plain", :text, [], %w(txt)
-
2
Mime::Type.register "text/javascript", :js, %w( application/javascript application/x-javascript )
-
2
Mime::Type.register "text/css", :css
-
2
Mime::Type.register "text/calendar", :ics
-
2
Mime::Type.register "text/csv", :csv
-
2
Mime::Type.register "text/vcard", :vcf
-
-
2
Mime::Type.register "image/png", :png, [], %w(png)
-
2
Mime::Type.register "image/jpeg", :jpeg, [], %w(jpg jpeg jpe pjpeg)
-
2
Mime::Type.register "image/gif", :gif, [], %w(gif)
-
2
Mime::Type.register "image/bmp", :bmp, [], %w(bmp)
-
2
Mime::Type.register "image/tiff", :tiff, [], %w(tif tiff)
-
-
2
Mime::Type.register "video/mpeg", :mpeg, [], %w(mpg mpeg mpe)
-
-
2
Mime::Type.register "application/xml", :xml, %w( text/xml application/x-xml )
-
2
Mime::Type.register "application/rss+xml", :rss
-
2
Mime::Type.register "application/atom+xml", :atom
-
2
Mime::Type.register "application/x-yaml", :yaml, %w( text/yaml )
-
-
2
Mime::Type.register "multipart/form-data", :multipart_form
-
2
Mime::Type.register "application/x-www-form-urlencoded", :url_encoded_form
-
-
# http://www.ietf.org/rfc/rfc4627.txt
-
# http://www.json.org/JSONRequest.html
-
2
Mime::Type.register "application/json", :json, %w( text/x-json application/jsonrequest )
-
-
2
Mime::Type.register "application/pdf", :pdf, [], %w(pdf)
-
2
Mime::Type.register "application/zip", :zip, [], %w(zip)
-
-
# Create Mime::ALL but do not add it to the SET.
-
2
Mime::ALL = Mime::Type.new("*/*", :all, [])
-
2
module ActionDispatch
-
2
module Http
-
2
class ParameterFilter
-
2
FILTERED = '[FILTERED]'.freeze # :nodoc:
-
-
2
def initialize(filters = [])
-
28
@filters = filters
-
end
-
-
2
def filter(params)
-
24
compiled_filter.call(params)
-
end
-
-
2
private
-
-
2
def compiled_filter
-
24
@compiled_filter ||= CompiledFilter.compile(@filters)
-
end
-
-
2
class CompiledFilter # :nodoc:
-
2
def self.compile(filters)
-
24
return lambda { |params| params.dup } if filters.empty?
-
-
24
strings, regexps, blocks = [], [], []
-
-
24
filters.each do |item|
-
24
case item
-
when Proc
-
blocks << item
-
when Regexp
-
regexps << item
-
else
-
24
strings << item.to_s
-
end
-
end
-
-
24
regexps << Regexp.new(strings.join('|'), true) unless strings.empty?
-
24
new regexps, blocks
-
end
-
-
2
attr_reader :regexps, :blocks
-
-
2
def initialize(regexps, blocks)
-
24
@regexps = regexps
-
24
@blocks = blocks
-
end
-
-
2
def call(original_params)
-
28
filtered_params = {}
-
-
28
original_params.each do |key, value|
-
152
if regexps.any? { |r| key =~ r }
-
6
value = FILTERED
-
elsif value.is_a?(Hash)
-
4
value = call(value)
-
elsif value.is_a?(Array)
-
value = value.map { |v| v.is_a?(Hash) ? call(v) : v }
-
elsif blocks.any?
-
key = key.dup
-
value = value.dup if value.duplicable?
-
blocks.each { |b| b.call(key, value) }
-
end
-
-
76
filtered_params[key] = value
-
end
-
-
28
filtered_params
-
end
-
end
-
end
-
end
-
end
-
2
require 'active_support/core_ext/hash/keys'
-
2
require 'active_support/core_ext/hash/indifferent_access'
-
-
2
module ActionDispatch
-
2
module Http
-
2
module Parameters
-
2
def initialize(env)
-
82
super
-
82
@symbolized_path_params = nil
-
end
-
-
# Returns both GET and POST \parameters in a single hash.
-
2
def parameters
-
72
@env["action_dispatch.request.parameters"] ||= begin
-
24
params = begin
-
24
request_parameters.merge(query_parameters)
-
rescue EOFError
-
query_parameters.dup
-
end
-
24
params.merge!(path_parameters)
-
24
params.with_indifferent_access
-
end
-
end
-
2
alias :params :parameters
-
-
2
def path_parameters=(parameters) #:nodoc:
-
@symbolized_path_params = nil
-
@env.delete("action_dispatch.request.parameters")
-
@env["action_dispatch.request.path_parameters"] = parameters
-
end
-
-
# The same as <tt>path_parameters</tt> with explicitly symbolized keys.
-
2
def symbolized_path_parameters
-
35
@symbolized_path_params ||= path_parameters.symbolize_keys
-
end
-
-
# Returns a hash with the \parameters used to form the \path of the request.
-
# Returned hash keys are strings:
-
#
-
# {'action' => 'my_action', 'controller' => 'my_controller'}
-
#
-
# See <tt>symbolized_path_parameters</tt> for symbolized keys.
-
2
def path_parameters
-
70
@env["action_dispatch.request.path_parameters"] ||= {}
-
end
-
-
2
def reset_parameters #:nodoc:
-
@env.delete("action_dispatch.request.parameters")
-
end
-
-
2
private
-
-
# Convert nested Hash to HashWithIndifferentAccess
-
# and UTF-8 encode both keys and values in nested Hash.
-
#
-
# TODO: Validate that the characters are UTF-8. If they aren't,
-
# you'll get a weird error down the road, but our form handling
-
# should really prevent that from happening
-
2
def normalize_encode_params(params)
-
65
case params
-
when String
-
24
params.force_encoding(Encoding::UTF_8).encode!
-
when Hash
-
41
if params.has_key?(:tempfile)
-
UploadedFile.new(params)
-
else
-
params.each_with_object({}) do |(key, val), new_hash|
-
28
new_key = key.is_a?(String) ? key.dup.force_encoding(Encoding::UTF_8).encode! : key
-
28
new_hash[new_key] = if val.is_a?(Array)
-
val.map! { |el| normalize_encode_params(el) }
-
else
-
28
normalize_encode_params(val)
-
end
-
41
end.with_indifferent_access
-
end
-
else
-
params
-
end
-
end
-
end
-
end
-
end
-
2
require 'stringio'
-
-
2
require 'active_support/inflector'
-
2
require 'action_dispatch/http/headers'
-
2
require 'action_controller/metal/exceptions'
-
2
require 'rack/request'
-
2
require 'action_dispatch/http/cache'
-
2
require 'action_dispatch/http/mime_negotiation'
-
2
require 'action_dispatch/http/parameters'
-
2
require 'action_dispatch/http/filter_parameters'
-
2
require 'action_dispatch/http/upload'
-
2
require 'action_dispatch/http/url'
-
2
require 'active_support/core_ext/array/conversions'
-
-
2
module ActionDispatch
-
2
class Request < Rack::Request
-
2
include ActionDispatch::Http::Cache::Request
-
2
include ActionDispatch::Http::MimeNegotiation
-
2
include ActionDispatch::Http::Parameters
-
2
include ActionDispatch::Http::FilterParameters
-
2
include ActionDispatch::Http::URL
-
-
2
autoload :Session, 'action_dispatch/request/session'
-
2
autoload :Utils, 'action_dispatch/request/utils'
-
-
2
LOCALHOST = Regexp.union [/^127\.0\.0\.\d{1,3}$/, /^::1$/, /^0:0:0:0:0:0:0:1(%.*)?$/]
-
-
2
ENV_METHODS = %w[ AUTH_TYPE GATEWAY_INTERFACE
-
PATH_TRANSLATED REMOTE_HOST
-
REMOTE_IDENT REMOTE_USER REMOTE_ADDR
-
SERVER_NAME SERVER_PROTOCOL
-
-
HTTP_ACCEPT HTTP_ACCEPT_CHARSET HTTP_ACCEPT_ENCODING
-
HTTP_ACCEPT_LANGUAGE HTTP_CACHE_CONTROL HTTP_FROM
-
HTTP_NEGOTIATE HTTP_PRAGMA ].freeze
-
-
2
ENV_METHODS.each do |env|
-
34
class_eval <<-METHOD, __FILE__, __LINE__ + 1
-
def #{env.sub(/^HTTP_/n, '').downcase} # def accept_charset
-
@env["#{env}"] # @env["HTTP_ACCEPT_CHARSET"]
-
end # end
-
METHOD
-
end
-
-
2
def initialize(env)
-
82
super
-
82
@method = nil
-
82
@request_method = nil
-
82
@remote_ip = nil
-
82
@original_fullpath = nil
-
82
@fullpath = nil
-
82
@ip = nil
-
82
@uuid = nil
-
end
-
-
2
def key?(key)
-
@env.key?(key)
-
end
-
-
# List of HTTP request methods from the following RFCs:
-
# Hypertext Transfer Protocol -- HTTP/1.1 (http://www.ietf.org/rfc/rfc2616.txt)
-
# HTTP Extensions for Distributed Authoring -- WEBDAV (http://www.ietf.org/rfc/rfc2518.txt)
-
# Versioning Extensions to WebDAV (http://www.ietf.org/rfc/rfc3253.txt)
-
# Ordered Collections Protocol (WebDAV) (http://www.ietf.org/rfc/rfc3648.txt)
-
# Web Distributed Authoring and Versioning (WebDAV) Access Control Protocol (http://www.ietf.org/rfc/rfc3744.txt)
-
# Web Distributed Authoring and Versioning (WebDAV) SEARCH (http://www.ietf.org/rfc/rfc5323.txt)
-
# PATCH Method for HTTP (http://www.ietf.org/rfc/rfc5789.txt)
-
2
RFC2616 = %w(OPTIONS GET HEAD POST PUT DELETE TRACE CONNECT)
-
2
RFC2518 = %w(PROPFIND PROPPATCH MKCOL COPY MOVE LOCK UNLOCK)
-
2
RFC3253 = %w(VERSION-CONTROL REPORT CHECKOUT CHECKIN UNCHECKOUT MKWORKSPACE UPDATE LABEL MERGE BASELINE-CONTROL MKACTIVITY)
-
2
RFC3648 = %w(ORDERPATCH)
-
2
RFC3744 = %w(ACL)
-
2
RFC5323 = %w(SEARCH)
-
2
RFC5789 = %w(PATCH)
-
-
2
HTTP_METHODS = RFC2616 + RFC2518 + RFC3253 + RFC3648 + RFC3744 + RFC5323 + RFC5789
-
-
2
HTTP_METHOD_LOOKUP = {}
-
-
# Populate the HTTP method lookup cache
-
2
HTTP_METHODS.each { |method|
-
60
HTTP_METHOD_LOOKUP[method] = method.underscore.to_sym
-
}
-
-
# Returns the HTTP \method that the application should see.
-
# In the case where the \method was overridden by a middleware
-
# (for instance, if a HEAD request was converted to a GET,
-
# or if a _method parameter was used to determine the \method
-
# the application should use), this \method returns the overridden
-
# value, not the original.
-
2
def request_method
-
119
@request_method ||= check_method(env["REQUEST_METHOD"])
-
end
-
-
# Returns a symbol form of the #request_method
-
2
def request_method_symbol
-
HTTP_METHOD_LOOKUP[request_method]
-
end
-
-
# Returns the original value of the environment's REQUEST_METHOD,
-
# even if it was overridden by middleware. See #request_method for
-
# more information.
-
2
def method
-
24
@method ||= check_method(env["rack.methodoverride.original_method"] || env['REQUEST_METHOD'])
-
end
-
-
# Returns a symbol form of the #method
-
2
def method_symbol
-
HTTP_METHOD_LOOKUP[method]
-
end
-
-
# Is this a GET (or HEAD) request?
-
# Equivalent to <tt>request.request_method_symbol == :get</tt>.
-
2
def get?
-
59
HTTP_METHOD_LOOKUP[request_method] == :get
-
end
-
-
# Is this a POST request?
-
# Equivalent to <tt>request.request_method_symbol == :post</tt>.
-
2
def post?
-
HTTP_METHOD_LOOKUP[request_method] == :post
-
end
-
-
# Is this a PATCH request?
-
# Equivalent to <tt>request.request_method == :patch</tt>.
-
2
def patch?
-
HTTP_METHOD_LOOKUP[request_method] == :patch
-
end
-
-
# Is this a PUT request?
-
# Equivalent to <tt>request.request_method_symbol == :put</tt>.
-
2
def put?
-
HTTP_METHOD_LOOKUP[request_method] == :put
-
end
-
-
# Is this a DELETE request?
-
# Equivalent to <tt>request.request_method_symbol == :delete</tt>.
-
2
def delete?
-
HTTP_METHOD_LOOKUP[request_method] == :delete
-
end
-
-
# Is this a HEAD request?
-
# Equivalent to <tt>request.request_method_symbol == :head</tt>.
-
2
def head?
-
HTTP_METHOD_LOOKUP[request_method] == :head
-
end
-
-
# Provides access to the request's HTTP headers, for example:
-
#
-
# request.headers["Content-Type"] # => "text/plain"
-
2
def headers
-
24
Http::Headers.new(@env)
-
end
-
-
2
def original_fullpath
-
@original_fullpath ||= (env["ORIGINAL_FULLPATH"] || fullpath)
-
end
-
-
# Returns the +String+ full path including params of the last URL requested.
-
#
-
# # get "/articles"
-
# request.fullpath # => "/articles"
-
#
-
# # get "/articles?page=2"
-
# request.fullpath # => "/articles?page=2"
-
2
def fullpath
-
24
@fullpath ||= super
-
end
-
-
# Returns the original request URL as a +String+.
-
#
-
# # get "/articles?page=2"
-
# request.original_url # => "http://www.example.com/articles?page=2"
-
2
def original_url
-
base_url + original_fullpath
-
end
-
-
# The +String+ MIME type of the request.
-
#
-
# # get "/articles"
-
# request.media_type # => "application/x-www-form-urlencoded"
-
2
def media_type
-
20
content_mime_type.to_s
-
end
-
-
# Returns the content length of the request as an integer.
-
2
def content_length
-
13
super.to_i
-
end
-
-
# Returns true if the "X-Requested-With" header contains "XMLHttpRequest"
-
# (case-insensitive). All major JavaScript libraries send this header with
-
# every Ajax request.
-
2
def xml_http_request?
-
48
@env['HTTP_X_REQUESTED_WITH'] =~ /XMLHttpRequest/i
-
end
-
2
alias :xhr? :xml_http_request?
-
-
2
def ip
-
13
@ip ||= super
-
end
-
-
# Originating IP address, usually set by the RemoteIp middleware.
-
2
def remote_ip
-
@remote_ip ||= (@env["action_dispatch.remote_ip"] || ip).to_s
-
end
-
-
# Returns the unique request id, which is based off either the X-Request-Id header that can
-
# be generated by a firewall, load balancer, or web server or by the RequestId middleware
-
# (which sets the action_dispatch.request_id environment variable).
-
#
-
# This unique ID is useful for tracing a request from end-to-end as part of logging or debugging.
-
# This relies on the rack variable set by the ActionDispatch::RequestId middleware.
-
2
def uuid
-
@uuid ||= env["action_dispatch.request_id"]
-
end
-
-
# Returns the lowercase name of the HTTP server software.
-
2
def server_software
-
(@env['SERVER_SOFTWARE'] && /^([a-zA-Z]+)/ =~ @env['SERVER_SOFTWARE']) ? $1.downcase : nil
-
end
-
-
# Read the request \body. This is useful for web services that need to
-
# work with raw requests directly.
-
2
def raw_post
-
unless @env.include? 'RAW_POST_DATA'
-
raw_post_body = body
-
@env['RAW_POST_DATA'] = raw_post_body.read(content_length)
-
raw_post_body.rewind if raw_post_body.respond_to?(:rewind)
-
end
-
@env['RAW_POST_DATA']
-
end
-
-
# The request body is an IO input stream. If the RAW_POST_DATA environment
-
# variable is already set, wrap it in a StringIO.
-
2
def body
-
if raw_post = @env['RAW_POST_DATA']
-
raw_post.force_encoding(Encoding::BINARY)
-
StringIO.new(raw_post)
-
else
-
@env['rack.input']
-
end
-
end
-
-
2
def form_data?
-
20
FORM_DATA_MEDIA_TYPES.include?(content_mime_type.to_s)
-
end
-
-
2
def body_stream #:nodoc:
-
@env['rack.input']
-
end
-
-
# TODO This should be broken apart into AD::Request::Session and probably
-
# be included by the session middleware.
-
2
def reset_session
-
if session && session.respond_to?(:destroy)
-
session.destroy
-
else
-
self.session = {}
-
end
-
@env['action_dispatch.request.flash_hash'] = nil
-
end
-
-
2
def session=(session) #:nodoc:
-
15
Session.set @env, session
-
end
-
-
2
def session_options=(options)
-
15
Session::Options.set @env, options
-
end
-
-
# Override Rack's GET method to support indifferent access
-
2
def GET
-
35
@env["action_dispatch.request.query_parameters"] ||= Utils.deep_munge((normalize_encode_params(super) || {}))
-
rescue TypeError => e
-
raise ActionController::BadRequest.new(:query, e)
-
end
-
2
alias :query_parameters :GET
-
-
# Override Rack's POST method to support indifferent access
-
2
def POST
-
35
@env["action_dispatch.request.request_parameters"] ||= Utils.deep_munge((normalize_encode_params(super) || {}))
-
rescue TypeError => e
-
raise ActionController::BadRequest.new(:request, e)
-
end
-
2
alias :request_parameters :POST
-
-
# Returns the authorization header regardless of whether it was specified directly or through one of the
-
# proxy alternatives.
-
2
def authorization
-
@env['HTTP_AUTHORIZATION'] ||
-
@env['X-HTTP_AUTHORIZATION'] ||
-
@env['X_HTTP_AUTHORIZATION'] ||
-
@env['REDIRECT_X_HTTP_AUTHORIZATION']
-
end
-
-
# True if the request came from localhost, 127.0.0.1.
-
2
def local?
-
LOCALHOST =~ remote_addr && LOCALHOST =~ remote_ip
-
end
-
-
# Extracted into ActionDispatch::Request::Utils.deep_munge, but kept here for backwards compatibility.
-
2
def deep_munge(hash)
-
ActiveSupport::Deprecation.warn(
-
"This method has been extracted into ActionDispatch::Request::Utils.deep_munge. Please start using that instead."
-
)
-
-
Utils.deep_munge(hash)
-
end
-
-
2
protected
-
2
def parse_query(qs)
-
13
Utils.deep_munge(super)
-
end
-
-
2
private
-
2
def check_method(name)
-
74
HTTP_METHOD_LOOKUP[name] || raise(ActionController::UnknownHttpMethod, "#{name}, accepted HTTP methods are #{HTTP_METHODS[0...-1].join(', ')}, and #{HTTP_METHODS[-1]}")
-
74
name
-
end
-
end
-
end
-
2
require 'active_support/core_ext/module/attribute_accessors'
-
2
require 'action_dispatch/http/filter_redirect'
-
2
require 'monitor'
-
-
2
module ActionDispatch # :nodoc:
-
# Represents an HTTP response generated by a controller action. Use it to
-
# retrieve the current state of the response, or customize the response. It can
-
# either represent a real HTTP response (i.e. one that is meant to be sent
-
# back to the web browser) or a TestResponse (i.e. one that is generated
-
# from integration tests).
-
#
-
# \Response is mostly a Ruby on \Rails framework implementation detail, and
-
# should never be used directly in controllers. Controllers should use the
-
# methods defined in ActionController::Base instead. For example, if you want
-
# to set the HTTP response's content MIME type, then use
-
# ActionControllerBase#headers instead of Response#headers.
-
#
-
# Nevertheless, integration tests may want to inspect controller responses in
-
# more detail, and that's when \Response can be useful for application
-
# developers. Integration test methods such as
-
# ActionDispatch::Integration::Session#get and
-
# ActionDispatch::Integration::Session#post return objects of type
-
# TestResponse (which are of course also of type \Response).
-
#
-
# For example, the following demo integration test prints the body of the
-
# controller response to the console:
-
#
-
# class DemoControllerTest < ActionDispatch::IntegrationTest
-
# def test_print_root_path_to_console
-
# get('/')
-
# puts response.body
-
# end
-
# end
-
2
class Response
-
# The request that the response is responding to.
-
2
attr_accessor :request
-
-
# The HTTP status code.
-
2
attr_reader :status
-
-
2
attr_writer :sending_file
-
-
# Get and set headers for this response.
-
2
attr_accessor :header
-
-
2
alias_method :headers=, :header=
-
2
alias_method :headers, :header
-
-
2
delegate :[], :[]=, :to => :@header
-
2
delegate :each, :to => :@stream
-
-
# Sets the HTTP response's content MIME type. For example, in the controller
-
# you could write this:
-
#
-
# response.content_type = "text/plain"
-
#
-
# If a character set has been defined for this response (see charset=) then
-
# the character set information will also be included in the content type
-
# information.
-
2
attr_reader :content_type
-
-
# The charset of the response. HTML wants to know the encoding of the
-
# content you're giving them, so we need to send that along.
-
2
attr_accessor :charset
-
-
2
CONTENT_TYPE = "Content-Type".freeze
-
2
SET_COOKIE = "Set-Cookie".freeze
-
2
LOCATION = "Location".freeze
-
2
NO_CONTENT_CODES = [204, 304]
-
-
6
cattr_accessor(:default_charset) { "utf-8" }
-
2
cattr_accessor(:default_headers)
-
-
2
include Rack::Response::Helpers
-
2
include ActionDispatch::Http::FilterRedirect
-
2
include ActionDispatch::Http::Cache::Response
-
2
include MonitorMixin
-
-
2
class Buffer # :nodoc:
-
2
def initialize(response, buf)
-
63
@response = response
-
63
@buf = buf
-
63
@closed = false
-
end
-
-
2
def write(string)
-
raise IOError, "closed stream" if closed?
-
-
@response.commit!
-
@buf.push string
-
end
-
-
2
def each(&block)
-
13
@response.sending!
-
13
x = @buf.each(&block)
-
13
@response.sent!
-
13
x
-
end
-
-
2
def close
-
@response.commit!
-
@closed = true
-
end
-
-
2
def closed?
-
@closed
-
end
-
end
-
-
# The underlying body, as a streamable object.
-
2
attr_reader :stream
-
-
2
def initialize(status = 200, header = {}, body = [])
-
39
super()
-
-
39
header = merge_default_headers(header, self.class.default_headers)
-
-
39
self.body, self.header, self.status = body, header, status
-
-
39
@sending_file = false
-
39
@blank = false
-
39
@cv = new_cond
-
39
@committed = false
-
39
@sending = false
-
39
@sent = false
-
39
@content_type = nil
-
39
@charset = nil
-
-
39
if content_type = self[CONTENT_TYPE]
-
type, charset = content_type.split(/;\s*charset=/)
-
@content_type = Mime::Type.lookup(type)
-
@charset = charset || self.class.default_charset
-
end
-
-
39
prepare_cache_control!
-
-
39
yield self if block_given?
-
end
-
-
2
def await_commit
-
synchronize do
-
@cv.wait_until { @committed }
-
end
-
end
-
-
2
def await_sent
-
synchronize { @cv.wait_until { @sent } }
-
end
-
-
2
def commit!
-
synchronize do
-
before_committed
-
@committed = true
-
@cv.broadcast
-
end
-
end
-
-
2
def sending!
-
13
synchronize do
-
13
before_sending
-
13
@sending = true
-
13
@cv.broadcast
-
end
-
end
-
-
2
def sent!
-
13
synchronize do
-
13
@sent = true
-
13
@cv.broadcast
-
end
-
end
-
-
2
def sending?; synchronize { @sending }; end
-
64
def committed?; synchronize { @committed }; end
-
2
def sent?; synchronize { @sent }; end
-
-
# Sets the HTTP status code.
-
2
def status=(status)
-
39
@status = Rack::Utils.status_code(status)
-
end
-
-
# Sets the HTTP content type.
-
2
def content_type=(content_type)
-
24
@content_type = content_type.to_s
-
end
-
-
# The response code of the request.
-
2
def response_code
-
@status
-
end
-
-
# Returns a string to ensure compatibility with <tt>Net::HTTPResponse</tt>.
-
2
def code
-
@status.to_s
-
end
-
-
# Returns the corresponding message for the current HTTP status code:
-
#
-
# response.status = 200
-
# response.message # => "OK"
-
#
-
# response.status = 404
-
# response.message # => "Not Found"
-
#
-
2
def message
-
Rack::Utils::HTTP_STATUS_CODES[@status]
-
end
-
2
alias_method :status_message, :message
-
-
2
def respond_to?(method, include_private = false)
-
35
if method.to_s == 'to_path'
-
13
stream.respond_to?(method)
-
else
-
22
super
-
end
-
end
-
-
2
def to_path
-
stream.to_path
-
end
-
-
# Returns the content of the response as a string. This contains the contents
-
# of any calls to <tt>render</tt>.
-
2
def body
-
strings = []
-
each { |part| strings << part.to_s }
-
strings.join
-
end
-
-
2
EMPTY = " "
-
-
# Allows you to manually set or override the response body.
-
2
def body=(body)
-
63
@blank = true if body == EMPTY
-
-
63
if body.respond_to?(:to_path)
-
@stream = body
-
else
-
63
synchronize do
-
63
@stream = build_buffer self, munge_body_object(body)
-
end
-
end
-
end
-
-
2
def body_parts
-
parts = []
-
@stream.each { |x| parts << x }
-
parts
-
end
-
-
2
def set_cookie(key, value)
-
::Rack::Utils.set_cookie_header!(header, key, value)
-
end
-
-
2
def delete_cookie(key, value={})
-
::Rack::Utils.delete_cookie_header!(header, key, value)
-
end
-
-
# The location header we'll be responding with.
-
2
def location
-
headers[LOCATION]
-
end
-
2
alias_method :redirect_url, :location
-
-
# Sets the location header we'll be responding with.
-
2
def location=(url)
-
headers[LOCATION] = url
-
end
-
-
2
def close
-
stream.close if stream.respond_to?(:close)
-
end
-
-
# Turns the Response into a Rack-compatible array of the status, headers,
-
# and body.
-
2
def to_a
-
24
rack_response @status, @header.to_hash
-
end
-
2
alias prepare! to_a
-
2
alias to_ary to_a
-
-
# Returns the response cookies, converted to a Hash of (name => value) pairs
-
#
-
# assert_equal 'AuthorOfNewPage', r.cookies['author']
-
2
def cookies
-
cookies = {}
-
if header = self[SET_COOKIE]
-
header = header.split("\n") if header.respond_to?(:to_str)
-
header.each do |cookie|
-
if pair = cookie.split(';').first
-
key, value = pair.split("=").map { |v| Rack::Utils.unescape(v) }
-
cookies[key] = value
-
end
-
end
-
end
-
cookies
-
end
-
-
2
def _status_code
-
@status
-
end
-
2
private
-
-
2
def before_committed
-
end
-
-
2
def before_sending
-
end
-
-
2
def merge_default_headers(original, default)
-
39
return original unless default.respond_to?(:merge)
-
-
39
default.merge(original)
-
end
-
-
2
def build_buffer(response, body)
-
63
Buffer.new response, body
-
end
-
-
2
def munge_body_object(body)
-
63
body.respond_to?(:each) ? body : [body]
-
end
-
-
2
def assign_default_content_type_and_charset!(headers)
-
24
return if headers[CONTENT_TYPE].present?
-
-
24
@content_type ||= Mime::HTML
-
24
@charset ||= self.class.default_charset unless @charset == false
-
-
24
type = @content_type.to_s.dup
-
24
type << "; charset=#{@charset}" if append_charset?
-
-
24
headers[CONTENT_TYPE] = type
-
end
-
-
2
def append_charset?
-
24
!@sending_file && @charset != false
-
end
-
-
2
def rack_response(status, header)
-
24
assign_default_content_type_and_charset!(header)
-
24
handle_conditional_get!
-
-
24
header[SET_COOKIE] = header[SET_COOKIE].join("\n") if header[SET_COOKIE].respond_to?(:join)
-
-
24
if NO_CONTENT_CODES.include?(@status)
-
header.delete CONTENT_TYPE
-
[status, header, []]
-
else
-
24
[status, header, Rack::BodyProxy.new(self){}]
-
end
-
end
-
end
-
end
-
2
module ActionDispatch
-
2
module Http
-
# Models uploaded files.
-
#
-
# The actual file is accessible via the +tempfile+ accessor, though some
-
# of its interface is available directly for convenience.
-
#
-
# Uploaded files are temporary files whose lifespan is one request. When
-
# the object is finalized Ruby unlinks the file, so there is no need to
-
# clean them with a separate maintenance task.
-
2
class UploadedFile
-
# The basename of the file in the client.
-
2
attr_accessor :original_filename
-
-
# A string with the MIME type of the file.
-
2
attr_accessor :content_type
-
-
# A +Tempfile+ object with the actual uploaded file. Note that some of
-
# its interface is available directly.
-
2
attr_accessor :tempfile
-
-
# A string with the headers of the multipart request.
-
2
attr_accessor :headers
-
-
2
def initialize(hash) # :nodoc:
-
@tempfile = hash[:tempfile]
-
raise(ArgumentError, ':tempfile is required') unless @tempfile
-
-
@original_filename = encode_filename(hash[:filename])
-
@content_type = hash[:type]
-
@headers = hash[:head]
-
end
-
-
# Shortcut for +tempfile.read+.
-
2
def read(length=nil, buffer=nil)
-
@tempfile.read(length, buffer)
-
end
-
-
# Shortcut for +tempfile.open+.
-
2
def open
-
@tempfile.open
-
end
-
-
# Shortcut for +tempfile.close+.
-
2
def close(unlink_now=false)
-
@tempfile.close(unlink_now)
-
end
-
-
# Shortcut for +tempfile.path+.
-
2
def path
-
@tempfile.path
-
end
-
-
# Shortcut for +tempfile.rewind+.
-
2
def rewind
-
@tempfile.rewind
-
end
-
-
# Shortcut for +tempfile.size+.
-
2
def size
-
@tempfile.size
-
end
-
-
# Shortcut for +tempfile.eof?+.
-
2
def eof?
-
@tempfile.eof?
-
end
-
-
2
private
-
-
2
def encode_filename(filename)
-
# Encode the filename in the utf8 encoding, unless it is nil
-
filename.force_encoding(Encoding::UTF_8).encode! if filename
-
end
-
end
-
end
-
end
-
2
require 'active_support/core_ext/module/attribute_accessors'
-
2
require 'active_support/core_ext/hash/slice'
-
-
2
module ActionDispatch
-
2
module Http
-
2
module URL
-
2
IP_HOST_REGEXP = /\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/
-
2
HOST_REGEXP = /(^.*:\/\/)?([^:]+)(?::(\d+$))?/
-
2
PROTOCOL_REGEXP = /^([^:]+)(:)?(\/\/)?$/
-
-
2
mattr_accessor :tld_length
-
2
self.tld_length = 1
-
-
2
class << self
-
2
def extract_domain(host, tld_length = @@tld_length)
-
host.split('.').last(1 + tld_length).join('.') if named_host?(host)
-
end
-
-
2
def extract_subdomains(host, tld_length = @@tld_length)
-
if named_host?(host)
-
parts = host.split('.')
-
parts[0..-(tld_length + 2)]
-
else
-
[]
-
end
-
end
-
-
2
def extract_subdomain(host, tld_length = @@tld_length)
-
extract_subdomains(host, tld_length).join('.')
-
end
-
-
2
def url_for(options = {})
-
78
options = options.dup
-
78
path = options.delete(:script_name).to_s.chomp("/")
-
78
path << options.delete(:path).to_s
-
-
78
add_trailing_slash(path) if options[:trailing_slash]
-
-
78
params = options[:params].is_a?(Hash) ? options[:params] : options.slice(:params)
-
93
params.reject! { |_,v| v.to_param.nil? }
-
-
78
result = build_host_url(options)
-
-
78
result << path
-
-
78
result << "?#{params.to_query}" unless params.empty?
-
78
result << "##{Journey::Router::Utils.escape_fragment(options[:anchor].to_param.to_s)}" if options[:anchor]
-
78
result
-
end
-
-
2
private
-
-
2
def add_trailing_slash(path)
-
# includes querysting
-
if path.include?('?')
-
path.sub!(/\?/, '/\&')
-
# does not have a .format
-
elsif !path.include?(".")
-
path.sub!(/[^\/]\z|\A\z/, '\&/')
-
end
-
-
path
-
end
-
-
2
def build_host_url(options)
-
78
if options[:host].blank? && options[:only_path].blank?
-
raise ArgumentError, 'Missing host to link to! Please provide the :host parameter, set default_url_options[:host], or set :only_path to true'
-
end
-
-
78
result = ""
-
-
78
unless options[:only_path]
-
if match = options[:host].match(HOST_REGEXP)
-
options[:protocol] ||= match[1] unless options[:protocol] == false
-
options[:host] = match[2]
-
options[:port] = match[3] unless options.key?(:port)
-
end
-
-
options[:protocol] = normalize_protocol(options)
-
options[:host] = normalize_host(options)
-
options[:port] = normalize_port(options)
-
-
result << options[:protocol]
-
result << rewrite_authentication(options)
-
result << options[:host]
-
result << ":#{options[:port]}" if options[:port]
-
end
-
78
result
-
end
-
-
2
def named_host?(host)
-
host && IP_HOST_REGEXP !~ host
-
end
-
-
2
def same_host?(options)
-
(options[:subdomain] == true || !options.key?(:subdomain)) && options[:domain].nil?
-
end
-
-
2
def rewrite_authentication(options)
-
if options[:user] && options[:password]
-
"#{Rack::Utils.escape(options[:user])}:#{Rack::Utils.escape(options[:password])}@"
-
else
-
""
-
end
-
end
-
-
2
def normalize_protocol(options)
-
case options[:protocol]
-
when nil
-
"http://"
-
when false, "//"
-
"//"
-
when PROTOCOL_REGEXP
-
"#{$1}://"
-
else
-
raise ArgumentError, "Invalid :protocol option: #{options[:protocol].inspect}"
-
end
-
end
-
-
2
def normalize_host(options)
-
return options[:host] if !named_host?(options[:host]) || same_host?(options)
-
-
tld_length = options[:tld_length] || @@tld_length
-
-
host = ""
-
if options[:subdomain] == true || !options.key?(:subdomain)
-
host << extract_subdomain(options[:host], tld_length).to_param
-
elsif options[:subdomain].present?
-
host << options[:subdomain].to_param
-
end
-
host << "." unless host.empty?
-
host << (options[:domain] || extract_domain(options[:host], tld_length))
-
host
-
end
-
-
2
def normalize_port(options)
-
return nil if options[:port].nil? || options[:port] == false
-
-
case options[:protocol]
-
when "//"
-
options[:port]
-
when "https://"
-
options[:port].to_i == 443 ? nil : options[:port]
-
else
-
options[:port].to_i == 80 ? nil : options[:port]
-
end
-
end
-
end
-
-
2
def initialize(env)
-
82
super
-
82
@protocol = nil
-
82
@port = nil
-
end
-
-
# Returns the complete URL used for this request.
-
2
def url
-
protocol + host_with_port + fullpath
-
end
-
-
# Returns 'https://' if this is an SSL request and 'http://' otherwise.
-
2
def protocol
-
72
@protocol ||= ssl? ? 'https://' : 'http://'
-
end
-
-
# Returns the \host for this request, such as "example.com".
-
2
def raw_host_with_port
-
72
if forwarded = env["HTTP_X_FORWARDED_HOST"]
-
forwarded.split(/,\s?/).last
-
else
-
72
env['HTTP_HOST'] || "#{env['SERVER_NAME'] || env['SERVER_ADDR']}:#{env['SERVER_PORT']}"
-
end
-
end
-
-
# Returns the host for this request, such as example.com.
-
2
def host
-
48
raw_host_with_port.sub(/:\d+$/, '')
-
end
-
-
# Returns a \host:\port string for this request, such as "example.com" or
-
# "example.com:8080".
-
2
def host_with_port
-
"#{host}#{port_string}"
-
end
-
-
# Returns the port number of this request as an integer.
-
2
def port
-
@port ||= begin
-
24
if raw_host_with_port =~ /:(\d+)$/
-
$1.to_i
-
else
-
24
standard_port
-
end
-
24
end
-
end
-
-
# Returns the standard \port number for this request's protocol.
-
2
def standard_port
-
48
case protocol
-
when 'https://' then 443
-
48
else 80
-
end
-
end
-
-
# Returns whether this request is using the standard port
-
2
def standard_port?
-
24
port == standard_port
-
end
-
-
# Returns a number \port suffix like 8080 if the \port number of this request
-
# is not the default HTTP \port 80 or HTTPS \port 443.
-
2
def optional_port
-
24
standard_port? ? nil : port
-
end
-
-
# Returns a string \port suffix, including colon, like ":8080" if the \port
-
# number of this request is not the default HTTP \port 80 or HTTPS \port 443.
-
2
def port_string
-
standard_port? ? '' : ":#{port}"
-
end
-
-
2
def server_port
-
@env['SERVER_PORT'].to_i
-
end
-
-
# Returns the \domain part of a \host, such as "rubyonrails.org" in "www.rubyonrails.org". You can specify
-
# a different <tt>tld_length</tt>, such as 2 to catch rubyonrails.co.uk in "www.rubyonrails.co.uk".
-
2
def domain(tld_length = @@tld_length)
-
ActionDispatch::Http::URL.extract_domain(host, tld_length)
-
end
-
-
# Returns all the \subdomains as an array, so <tt>["dev", "www"]</tt> would be
-
# returned for "dev.www.rubyonrails.org". You can specify a different <tt>tld_length</tt>,
-
# such as 2 to catch <tt>["www"]</tt> instead of <tt>["www", "rubyonrails"]</tt>
-
# in "www.rubyonrails.co.uk".
-
2
def subdomains(tld_length = @@tld_length)
-
ActionDispatch::Http::URL.extract_subdomains(host, tld_length)
-
end
-
-
# Returns all the \subdomains as a string, so <tt>"dev.www"</tt> would be
-
# returned for "dev.www.rubyonrails.org". You can specify a different <tt>tld_length</tt>,
-
# such as 2 to catch <tt>"www"</tt> instead of <tt>"www.rubyonrails"</tt>
-
# in "www.rubyonrails.co.uk".
-
2
def subdomain(tld_length = @@tld_length)
-
ActionDispatch::Http::URL.extract_subdomain(host, tld_length)
-
end
-
end
-
end
-
end
-
2
require 'action_dispatch/journey/router'
-
2
require 'action_dispatch/journey/gtg/builder'
-
2
require 'action_dispatch/journey/gtg/simulator'
-
2
require 'action_dispatch/journey/nfa/builder'
-
2
require 'action_dispatch/journey/nfa/simulator'
-
2
require 'action_controller/metal/exceptions'
-
-
2
module ActionDispatch
-
2
module Journey
-
# The Formatter class is used for formatting URLs. For example, parameters
-
# passed to +url_for+ in Rails will eventually call Formatter#generate.
-
2
class Formatter # :nodoc:
-
2
attr_reader :routes
-
-
2
def initialize(routes)
-
2
@routes = routes
-
2
@cache = nil
-
end
-
-
2
def generate(type, name, options, recall = {}, parameterize = nil)
-
34
constraints = recall.merge(options)
-
34
missing_keys = []
-
-
34
match_route(name, constraints) do |route|
-
34
parameterized_parts = extract_parameterized_parts(route, options, recall, parameterize)
-
-
# Skip this route unless a name has been provided or it is a
-
# standard Rails route since we can't determine whether an options
-
# hash passed to url_for matches a Rack application or a redirect.
-
34
next unless name || route.dispatcher?
-
-
34
missing_keys = missing_keys(route, parameterized_parts)
-
34
next unless missing_keys.empty?
-
34
params = options.dup.delete_if do |key, _|
-
77
parameterized_parts.key?(key) || route.defaults.key?(key)
-
end
-
-
34
return [route.format(parameterized_parts), params]
-
end
-
-
message = "No route matches #{Hash[constraints.sort].inspect}"
-
message << " missing required keys: #{missing_keys.sort.inspect}" unless missing_keys.empty?
-
-
raise ActionController::UrlGenerationError, message
-
end
-
-
2
def clear
-
2
@cache = nil
-
end
-
-
2
private
-
-
2
def extract_parameterized_parts(route, options, recall, parameterize = nil)
-
34
parameterized_parts = recall.merge(options)
-
-
34
keys_to_keep = route.parts.reverse.drop_while { |part|
-
32
!options.key?(part) || (options[part] || recall[part]).nil?
-
} | route.required_parts
-
-
34
(parameterized_parts.keys - keys_to_keep).each do |bad_key|
-
83
parameterized_parts.delete(bad_key)
-
end
-
-
34
if parameterize
-
34
parameterized_parts.each do |k, v|
-
parameterized_parts[k] = parameterize.call(k, v)
-
end
-
end
-
-
34
parameterized_parts.keep_if { |_, v| v }
-
34
parameterized_parts
-
end
-
-
2
def named_routes
-
38
routes.named_routes
-
end
-
-
2
def match_route(name, options)
-
34
if named_routes.key?(name)
-
4
yield named_routes[name]
-
else
-
30
routes = non_recursive(cache, options.to_a)
-
-
104
hash = routes.group_by { |_, r| r.score(options) }
-
-
30
hash.keys.sort.reverse_each do |score|
-
30
next if score < 0
-
-
64
hash[score].sort_by { |i, _| i }.each do |_, route|
-
30
yield route
-
end
-
end
-
end
-
end
-
-
2
def non_recursive(cache, options)
-
30
routes = []
-
30
stack = [cache]
-
-
30
while stack.any?
-
118
c = stack.shift
-
118
routes.concat(c[:___routes]) if c.key?(:___routes)
-
-
118
options.each do |pair|
-
279
stack << c[pair] if c.key?(pair)
-
end
-
end
-
-
30
routes
-
end
-
-
# Returns an array populated with missing keys if any are present.
-
2
def missing_keys(route, parts)
-
34
missing_keys = []
-
34
tests = route.path.requirements
-
34
route.required_parts.each { |key|
-
if tests.key?(key)
-
missing_keys << key unless /\A#{tests[key]}\Z/ === parts[key]
-
else
-
missing_keys << key unless parts[key]
-
end
-
}
-
34
missing_keys
-
end
-
-
2
def possibles(cache, options, depth = 0)
-
cache.fetch(:___routes) { [] } + options.find_all { |pair|
-
cache.key?(pair)
-
}.map { |pair|
-
possibles(cache[pair], options, depth + 1)
-
}.flatten(1)
-
end
-
-
# Returns +true+ if no missing keys are present, otherwise +false+.
-
2
def verify_required_parts!(route, parts)
-
missing_keys(route, parts).empty?
-
end
-
-
2
def build_cache
-
2
root = { ___routes: [] }
-
2
routes.each_with_index do |route, i|
-
266
leaf = route.required_defaults.inject(root) do |h, tuple|
-
528
h[tuple] ||= {}
-
end
-
266
(leaf[:___routes] ||= []) << [i, route]
-
end
-
2
root
-
end
-
-
2
def cache
-
30
@cache ||= build_cache
-
end
-
end
-
end
-
end
-
2
require 'action_dispatch/journey/gtg/transition_table'
-
-
2
module ActionDispatch
-
2
module Journey # :nodoc:
-
2
module GTG # :nodoc:
-
2
class Builder # :nodoc:
-
2
DUMMY = Nodes::Dummy.new
-
-
2
attr_reader :root, :ast, :endpoints
-
-
2
def initialize(root)
-
267
@root = root
-
267
@ast = Nodes::Cat.new root, DUMMY
-
267
@followpos = nil
-
end
-
-
2
def transition_table
-
1
dtrans = TransitionTable.new
-
1
marked = {}
-
277
state_id = Hash.new { |h,k| h[k] = h.length }
-
-
1
start = firstpos(root)
-
1
dstates = [start]
-
1
until dstates.empty?
-
276
s = dstates.shift
-
276
next if marked[s]
-
204
marked[s] = true # mark s
-
-
1137
s.group_by { |state| symbol(state) }.each do |sym, ps|
-
1289
u = ps.map { |l| followpos(l) }.flatten
-
356
next if u.empty?
-
-
275
if u.uniq == [DUMMY]
-
76
from = state_id[s]
-
76
to = state_id[Object.new]
-
76
dtrans[from, to] = sym
-
-
76
dtrans.add_accepting(to)
-
207
ps.each { |state| dtrans.add_memo(to, state.memo) }
-
else
-
199
dtrans[state_id[s], state_id[u]] = sym
-
-
199
if u.include?(DUMMY)
-
77
to = state_id[u]
-
-
447
accepting = ps.find_all { |l| followpos(l).include?(DUMMY) }
-
-
77
accepting.each { |accepting_state|
-
132
dtrans.add_memo(to, accepting_state.memo)
-
}
-
-
77
dtrans.add_accepting(state_id[u])
-
end
-
end
-
-
275
dstates << u
-
end
-
end
-
-
1
dtrans
-
end
-
-
2
def nullable?(node)
-
9901
case node
-
when Nodes::Group
-
393
true
-
when Nodes::Star
-
true
-
when Nodes::Or
-
node.children.any? { |c| nullable?(c) }
-
when Nodes::Cat
-
940
nullable?(node.left) && nullable?(node.right)
-
when Nodes::Terminal
-
8568
!node.left
-
when Nodes::Unary
-
nullable?(node.left)
-
else
-
raise ArgumentError, 'unknown nullable: %s' % node.class.name
-
end
-
end
-
-
2
def firstpos(node)
-
4215
case node
-
when Nodes::Star
-
firstpos(node.left)
-
when Nodes::Cat
-
921
if nullable?(node.left)
-
firstpos(node.left) | firstpos(node.right)
-
else
-
921
firstpos(node.left)
-
end
-
when Nodes::Or
-
133
node.children.map { |c| firstpos(c) }.flatten.uniq
-
when Nodes::Unary
-
393
firstpos(node.left)
-
when Nodes::Terminal
-
2900
nullable?(node) ? [] : [node]
-
else
-
raise ArgumentError, 'unknown firstpos: %s' % node.class.name
-
end
-
end
-
-
2
def lastpos(node)
-
5534
case node
-
when Nodes::Star
-
firstpos(node.left)
-
when Nodes::Or
-
133
node.children.map { |c| lastpos(c) }.flatten.uniq
-
when Nodes::Cat
-
2372
if nullable?(node.right)
-
393
lastpos(node.left) | lastpos(node.right)
-
else
-
1979
lastpos(node.right)
-
end
-
when Nodes::Terminal
-
2768
nullable?(node) ? [] : [node]
-
when Nodes::Unary
-
393
lastpos(node.left)
-
else
-
raise ArgumentError, 'unknown lastpos: %s' % node.class.name
-
end
-
end
-
-
2
def followpos(node)
-
2095
followpos_table[node]
-
end
-
-
2
private
-
-
2
def followpos_table
-
2095
@followpos ||= build_followpos
-
end
-
-
2
def build_followpos
-
2641
table = Hash.new { |h, k| h[k] = [] }
-
265
@ast.each do |n|
-
5278
case n
-
when Nodes::Cat
-
2244
lastpos(n.left).each do |i|
-
2768
table[i] += firstpos(n.right)
-
end
-
when Nodes::Star
-
lastpos(n).each do |i|
-
table[i] += firstpos(n)
-
end
-
end
-
end
-
265
table
-
end
-
-
2
def symbol(edge)
-
933
case edge
-
when Journey::Nodes::Symbol
-
205
edge.regexp
-
else
-
728
edge.left
-
end
-
end
-
end
-
end
-
end
-
end
-
2
require 'strscan'
-
-
2
module ActionDispatch
-
2
module Journey # :nodoc:
-
2
module GTG # :nodoc:
-
2
class MatchData # :nodoc:
-
2
attr_reader :memos
-
-
2
def initialize(memos)
-
13
@memos = memos
-
end
-
end
-
-
2
class Simulator # :nodoc:
-
2
attr_reader :tt
-
-
2
def initialize(transition_table)
-
1
@tt = transition_table
-
end
-
-
2
def simulate(string)
-
13
input = StringScanner.new(string)
-
13
state = [0]
-
13
while sym = input.scan(%r([/.?]|[^/.?]+))
-
48
state = tt.move(state, sym)
-
end
-
-
13
acceptance_states = state.find_all { |s|
-
15
tt.accepting? s
-
}
-
-
13
return if acceptance_states.empty?
-
-
28
memos = acceptance_states.map { |x| tt.memo(x) }.flatten.compact
-
-
13
MatchData.new(memos)
-
end
-
-
2
alias :=~ :simulate
-
2
alias :match :simulate
-
end
-
end
-
end
-
end
-
2
require 'action_dispatch/journey/nfa/dot'
-
-
2
module ActionDispatch
-
2
module Journey # :nodoc:
-
2
module GTG # :nodoc:
-
2
class TransitionTable # :nodoc:
-
2
include Journey::NFA::Dot
-
-
2
attr_reader :memos
-
-
2
def initialize
-
1
@regexp_states = {}
-
1
@string_states = {}
-
1
@accepting = {}
-
154
@memos = Hash.new { |h,k| h[k] = [] }
-
end
-
-
2
def add_accepting(state)
-
153
@accepting[state] = true
-
end
-
-
2
def accepting_states
-
@accepting.keys
-
end
-
-
2
def accepting?(state)
-
15
@accepting[state]
-
end
-
-
2
def add_memo(idx, memo)
-
263
@memos[idx] << memo
-
end
-
-
2
def memo(idx)
-
15
@memos[idx]
-
end
-
-
2
def eclosure(t)
-
Array(t)
-
end
-
-
2
def move(t, a)
-
48
move_string(t, a).concat(move_regexp(t, a))
-
end
-
-
2
def as_json(options = nil)
-
simple_regexp = Hash.new { |h,k| h[k] = {} }
-
-
@regexp_states.each do |from, hash|
-
hash.each do |re, to|
-
simple_regexp[from][re.source] = to
-
end
-
end
-
-
{
-
regexp_states: simple_regexp,
-
string_states: @string_states,
-
accepting: @accepting
-
}
-
end
-
-
2
def to_svg
-
svg = IO.popen('dot -Tsvg', 'w+') { |f|
-
f.write(to_dot)
-
f.close_write
-
f.readlines
-
}
-
3.times { svg.shift }
-
svg.join.sub(/width="[^"]*"/, '').sub(/height="[^"]*"/, '')
-
end
-
-
2
def visualizer(paths, title = 'FSM')
-
viz_dir = File.join File.dirname(__FILE__), '..', 'visualizer'
-
fsm_js = File.read File.join(viz_dir, 'fsm.js')
-
fsm_css = File.read File.join(viz_dir, 'fsm.css')
-
erb = File.read File.join(viz_dir, 'index.html.erb')
-
states = "function tt() { return #{to_json}; }"
-
-
fun_routes = paths.shuffle.first(3).map do |ast|
-
ast.map { |n|
-
case n
-
when Nodes::Symbol
-
case n.left
-
when ':id' then rand(100).to_s
-
when ':format' then %w{ xml json }.shuffle.first
-
else
-
'omg'
-
end
-
when Nodes::Terminal then n.symbol
-
else
-
nil
-
end
-
}.compact.join
-
end
-
-
stylesheets = [fsm_css]
-
svg = to_svg
-
javascripts = [states, fsm_js]
-
-
# Annoying hack for 1.9 warnings
-
fun_routes = fun_routes
-
stylesheets = stylesheets
-
svg = svg
-
javascripts = javascripts
-
-
require 'erb'
-
template = ERB.new erb
-
template.result(binding)
-
end
-
-
2
def []=(from, to, sym)
-
275
to_mappings = states_hash_for(sym)[from] ||= {}
-
275
to_mappings[sym] = to
-
end
-
-
2
def states
-
ss = @string_states.keys + @string_states.values.map(&:values).flatten
-
rs = @regexp_states.keys + @regexp_states.values.map(&:values).flatten
-
(ss + rs).uniq
-
end
-
-
2
def transitions
-
@string_states.map { |from, hash|
-
hash.map { |s, to| [from, s, to] }
-
}.flatten(1) + @regexp_states.map { |from, hash|
-
hash.map { |s, to| [from, s, to] }
-
}.flatten(1)
-
end
-
-
2
private
-
-
2
def states_hash_for(sym)
-
275
case sym
-
when String
-
181
@string_states
-
when Regexp
-
94
@regexp_states
-
else
-
raise ArgumentError, 'unknown symbol: %s' % sym.class
-
end
-
end
-
-
2
def move_regexp(t, a)
-
48
return [] if t.empty?
-
-
t.map { |s|
-
48
if states = @regexp_states[s]
-
4
states.map { |re, v| re === a ? v : nil }
-
end
-
48
}.flatten.compact.uniq
-
end
-
-
2
def move_string(t, a)
-
48
return [] if t.empty?
-
-
t.map do |s|
-
48
if states = @string_states[s]
-
48
states[a]
-
end
-
48
end.compact
-
end
-
end
-
end
-
end
-
end
-
2
require 'action_dispatch/journey/nfa/transition_table'
-
2
require 'action_dispatch/journey/gtg/transition_table'
-
-
2
module ActionDispatch
-
2
module Journey # :nodoc:
-
2
module NFA # :nodoc:
-
2
class Visitor < Visitors::Visitor # :nodoc:
-
2
def initialize(tt)
-
@tt = tt
-
@i = -1
-
end
-
-
2
def visit_CAT(node)
-
left = visit(node.left)
-
right = visit(node.right)
-
-
@tt.merge(left.last, right.first)
-
-
[left.first, right.last]
-
end
-
-
2
def visit_GROUP(node)
-
from = @i += 1
-
left = visit(node.left)
-
to = @i += 1
-
-
@tt.accepting = to
-
-
@tt[from, left.first] = nil
-
@tt[left.last, to] = nil
-
@tt[from, to] = nil
-
-
[from, to]
-
end
-
-
2
def visit_OR(node)
-
from = @i += 1
-
children = node.children.map { |c| visit(c) }
-
to = @i += 1
-
-
children.each do |child|
-
@tt[from, child.first] = nil
-
@tt[child.last, to] = nil
-
end
-
-
@tt.accepting = to
-
-
[from, to]
-
end
-
-
2
def terminal(node)
-
from_i = @i += 1 # new state
-
to_i = @i += 1 # new state
-
-
@tt[from_i, to_i] = node
-
@tt.accepting = to_i
-
@tt.add_memo(to_i, node.memo)
-
-
[from_i, to_i]
-
end
-
end
-
-
2
class Builder # :nodoc:
-
2
def initialize(ast)
-
@ast = ast
-
end
-
-
2
def transition_table
-
tt = TransitionTable.new
-
Visitor.new(tt).accept(@ast)
-
tt
-
end
-
end
-
end
-
end
-
end
-
# encoding: utf-8
-
-
2
module ActionDispatch
-
2
module Journey # :nodoc:
-
2
module NFA # :nodoc:
-
2
module Dot # :nodoc:
-
2
def to_dot
-
edges = transitions.map { |from, sym, to|
-
" #{from} -> #{to} [label=\"#{sym || 'ε'}\"];"
-
}
-
-
#memo_nodes = memos.values.flatten.map { |n|
-
# label = n
-
# if Journey::Route === n
-
# label = "#{n.verb.source} #{n.path.spec}"
-
# end
-
# " #{n.object_id} [label=\"#{label}\", shape=box];"
-
#}
-
#memo_edges = memos.map { |k, memos|
-
# (memos || []).map { |v| " #{k} -> #{v.object_id};" }
-
#}.flatten.uniq
-
-
<<-eodot
-
digraph nfa {
-
rankdir=LR;
-
node [shape = doublecircle];
-
#{accepting_states.join ' '};
-
node [shape = circle];
-
#{edges.join "\n"}
-
}
-
eodot
-
end
-
end
-
end
-
end
-
end
-
2
require 'strscan'
-
-
2
module ActionDispatch
-
2
module Journey # :nodoc:
-
2
module NFA # :nodoc:
-
2
class MatchData # :nodoc:
-
2
attr_reader :memos
-
-
2
def initialize(memos)
-
@memos = memos
-
end
-
end
-
-
2
class Simulator # :nodoc:
-
2
attr_reader :tt
-
-
2
def initialize(transition_table)
-
@tt = transition_table
-
end
-
-
2
def simulate(string)
-
input = StringScanner.new(string)
-
state = tt.eclosure(0)
-
until input.eos?
-
sym = input.scan(%r([/.?]|[^/.?]+))
-
-
# FIXME: tt.eclosure is not needed for the GTG
-
state = tt.eclosure(tt.move(state, sym))
-
end
-
-
acceptance_states = state.find_all { |s|
-
tt.accepting?(tt.eclosure(s).sort.last)
-
}
-
-
return if acceptance_states.empty?
-
-
memos = acceptance_states.map { |x| tt.memo(x) }.flatten.compact
-
-
MatchData.new(memos)
-
end
-
-
2
alias :=~ :simulate
-
2
alias :match :simulate
-
end
-
end
-
end
-
end
-
2
require 'action_dispatch/journey/nfa/dot'
-
-
2
module ActionDispatch
-
2
module Journey # :nodoc:
-
2
module NFA # :nodoc:
-
2
class TransitionTable # :nodoc:
-
2
include Journey::NFA::Dot
-
-
2
attr_accessor :accepting
-
2
attr_reader :memos
-
-
2
def initialize
-
@table = Hash.new { |h,f| h[f] = {} }
-
@memos = {}
-
@accepting = nil
-
@inverted = nil
-
end
-
-
2
def accepting?(state)
-
accepting == state
-
end
-
-
2
def accepting_states
-
[accepting]
-
end
-
-
2
def add_memo(idx, memo)
-
@memos[idx] = memo
-
end
-
-
2
def memo(idx)
-
@memos[idx]
-
end
-
-
2
def []=(i, f, s)
-
@table[f][i] = s
-
end
-
-
2
def merge(left, right)
-
@memos[right] = @memos.delete(left)
-
@table[right] = @table.delete(left)
-
end
-
-
2
def states
-
(@table.keys + @table.values.map(&:keys).flatten).uniq
-
end
-
-
# Returns a generalized transition graph with reduced states. The states
-
# are reduced like a DFA, but the table must be simulated like an NFA.
-
#
-
# Edges of the GTG are regular expressions.
-
2
def generalized_table
-
gt = GTG::TransitionTable.new
-
marked = {}
-
state_id = Hash.new { |h,k| h[k] = h.length }
-
alphabet = self.alphabet
-
-
stack = [eclosure(0)]
-
-
until stack.empty?
-
state = stack.pop
-
next if marked[state] || state.empty?
-
-
marked[state] = true
-
-
alphabet.each do |alpha|
-
next_state = eclosure(following_states(state, alpha))
-
next if next_state.empty?
-
-
gt[state_id[state], state_id[next_state]] = alpha
-
stack << next_state
-
end
-
end
-
-
final_groups = state_id.keys.find_all { |s|
-
s.sort.last == accepting
-
}
-
-
final_groups.each do |states|
-
id = state_id[states]
-
-
gt.add_accepting(id)
-
save = states.find { |s|
-
@memos.key?(s) && eclosure(s).sort.last == accepting
-
}
-
-
gt.add_memo(id, memo(save))
-
end
-
-
gt
-
end
-
-
# Returns set of NFA states to which there is a transition on ast symbol
-
# +a+ from some state +s+ in +t+.
-
2
def following_states(t, a)
-
Array(t).map { |s| inverted[s][a] }.flatten.uniq
-
end
-
-
# Returns set of NFA states to which there is a transition on ast symbol
-
# +a+ from some state +s+ in +t+.
-
2
def move(t, a)
-
Array(t).map { |s|
-
inverted[s].keys.compact.find_all { |sym|
-
sym === a
-
}.map { |sym| inverted[s][sym] }
-
}.flatten.uniq
-
end
-
-
2
def alphabet
-
inverted.values.map(&:keys).flatten.compact.uniq.sort_by { |x| x.to_s }
-
end
-
-
# Returns a set of NFA states reachable from some NFA state +s+ in set
-
# +t+ on nil-transitions alone.
-
2
def eclosure(t)
-
stack = Array(t)
-
seen = {}
-
children = []
-
-
until stack.empty?
-
s = stack.pop
-
next if seen[s]
-
-
seen[s] = true
-
children << s
-
-
stack.concat(inverted[s][nil])
-
end
-
-
children.uniq
-
end
-
-
2
def transitions
-
@table.map { |to, hash|
-
hash.map { |from, sym| [from, sym, to] }
-
}.flatten(1)
-
end
-
-
2
private
-
-
2
def inverted
-
return @inverted if @inverted
-
-
@inverted = Hash.new { |h, from|
-
h[from] = Hash.new { |j, s| j[s] = [] }
-
}
-
-
@table.each { |to, hash|
-
hash.each { |from, sym|
-
if sym
-
sym = Nodes::Symbol === sym ? sym.regexp : sym.left
-
end
-
-
@inverted[from][sym] << to
-
}
-
}
-
-
@inverted
-
end
-
end
-
end
-
end
-
end
-
#
-
# DO NOT MODIFY!!!!
-
# This file is automatically generated by Racc 1.4.9
-
# from Racc grammar file "".
-
#
-
-
2
require 'racc/parser.rb'
-
-
-
2
require 'action_dispatch/journey/parser_extras'
-
2
module ActionDispatch
-
2
module Journey # :nodoc:
-
2
class Parser < Racc::Parser # :nodoc:
-
##### State transition tables begin ###
-
-
2
racc_action_table = [
-
17, 21, 13, 15, 14, 7, nil, 16, 8, 19,
-
13, 15, 14, 7, 23, 16, 8, 19, 13, 15,
-
14, 7, nil, 16, 8, 13, 15, 14, 7, nil,
-
16, 8, 13, 15, 14, 7, nil, 16, 8 ]
-
-
2
racc_action_check = [
-
1, 17, 1, 1, 1, 1, nil, 1, 1, 1,
-
20, 20, 20, 20, 20, 20, 20, 20, 7, 7,
-
7, 7, nil, 7, 7, 19, 19, 19, 19, nil,
-
19, 19, 0, 0, 0, 0, nil, 0, 0 ]
-
-
2
racc_action_pointer = [
-
30, 0, nil, nil, nil, nil, nil, 16, nil, nil,
-
nil, nil, nil, nil, nil, nil, nil, 1, nil, 23,
-
8, nil, nil, nil ]
-
-
2
racc_action_default = [
-
-18, -18, -2, -3, -4, -5, -6, -18, -9, -10,
-
-11, -12, -13, -14, -15, -16, -17, -18, -1, -18,
-
-18, 24, -8, -7 ]
-
-
2
racc_goto_table = [
-
18, 1, nil, nil, nil, nil, nil, nil, 20, nil,
-
nil, nil, nil, nil, nil, nil, nil, nil, 22, 18 ]
-
-
2
racc_goto_check = [
-
2, 1, nil, nil, nil, nil, nil, nil, 1, nil,
-
nil, nil, nil, nil, nil, nil, nil, nil, 2, 2 ]
-
-
2
racc_goto_pointer = [
-
nil, 1, -1, nil, nil, nil, nil, nil, nil, nil,
-
nil ]
-
-
2
racc_goto_default = [
-
nil, nil, 2, 3, 4, 5, 6, 9, 10, 11,
-
12 ]
-
-
2
racc_reduce_table = [
-
0, 0, :racc_error,
-
2, 11, :_reduce_1,
-
1, 11, :_reduce_2,
-
1, 11, :_reduce_none,
-
1, 12, :_reduce_none,
-
1, 12, :_reduce_none,
-
1, 12, :_reduce_none,
-
3, 15, :_reduce_7,
-
3, 13, :_reduce_8,
-
1, 16, :_reduce_9,
-
1, 14, :_reduce_none,
-
1, 14, :_reduce_none,
-
1, 14, :_reduce_none,
-
1, 14, :_reduce_none,
-
1, 19, :_reduce_14,
-
1, 17, :_reduce_15,
-
1, 18, :_reduce_16,
-
1, 20, :_reduce_17 ]
-
-
2
racc_reduce_n = 18
-
-
2
racc_shift_n = 24
-
-
2
racc_token_table = {
-
false => 0,
-
:error => 1,
-
:SLASH => 2,
-
:LITERAL => 3,
-
:SYMBOL => 4,
-
:LPAREN => 5,
-
:RPAREN => 6,
-
:DOT => 7,
-
:STAR => 8,
-
:OR => 9 }
-
-
2
racc_nt_base = 10
-
-
2
racc_use_result_var = true
-
-
2
Racc_arg = [
-
racc_action_table,
-
racc_action_check,
-
racc_action_default,
-
racc_action_pointer,
-
racc_goto_table,
-
racc_goto_check,
-
racc_goto_default,
-
racc_goto_pointer,
-
racc_nt_base,
-
racc_reduce_table,
-
racc_token_table,
-
racc_shift_n,
-
racc_reduce_n,
-
racc_use_result_var ]
-
-
2
Racc_token_to_s_table = [
-
"$end",
-
"error",
-
"SLASH",
-
"LITERAL",
-
"SYMBOL",
-
"LPAREN",
-
"RPAREN",
-
"DOT",
-
"STAR",
-
"OR",
-
"$start",
-
"expressions",
-
"expression",
-
"or",
-
"terminal",
-
"group",
-
"star",
-
"symbol",
-
"literal",
-
"slash",
-
"dot" ]
-
-
2
Racc_debug_parser = false
-
-
##### State transition tables end #####
-
-
# reduce 0 omitted
-
-
2
def _reduce_1(val, _values, result)
-
2640
result = Cat.new(val.first, val.last)
-
2640
result
-
end
-
-
2
def _reduce_2(val, _values, result)
-
1056
result = val.first
-
1056
result
-
end
-
-
# reduce 3 omitted
-
-
# reduce 4 omitted
-
-
# reduce 5 omitted
-
-
# reduce 6 omitted
-
-
2
def _reduce_7(val, _values, result)
-
524
result = Group.new(val[1])
-
524
result
-
end
-
-
2
def _reduce_8(val, _values, result)
-
result = Or.new([val.first, val.last])
-
result
-
end
-
-
2
def _reduce_9(val, _values, result)
-
result = Star.new(Symbol.new(val.last))
-
result
-
end
-
-
# reduce 10 omitted
-
-
# reduce 11 omitted
-
-
# reduce 12 omitted
-
-
# reduce 13 omitted
-
-
2
def _reduce_14(val, _values, result)
-
1064
result = Slash.new('/')
-
1064
result
-
end
-
-
2
def _reduce_15(val, _values, result)
-
820
result = Symbol.new(val.first)
-
820
result
-
end
-
-
2
def _reduce_16(val, _values, result)
-
764
result = Literal.new(val.first)
-
764
result
-
end
-
-
2
def _reduce_17(val, _values, result)
-
524
result = Dot.new(val.first)
-
524
result
-
end
-
-
2
def _reduce_none(val, _values, result)
-
val[0]
-
end
-
-
end # class Parser
-
end # module Journey
-
end # module ActionDispatch
-
2
require 'action_dispatch/journey/scanner'
-
2
require 'action_dispatch/journey/nodes/node'
-
-
2
module ActionDispatch
-
2
module Journey # :nodoc:
-
2
class Parser < Racc::Parser # :nodoc:
-
2
include Journey::Nodes
-
-
2
def initialize
-
532
@scanner = Scanner.new
-
end
-
-
2
def parse(string)
-
532
@scanner.scan_setup(string)
-
532
do_parse
-
end
-
-
2
def next_token
-
4752
@scanner.next_token
-
end
-
end
-
end
-
end
-
2
module ActionDispatch
-
2
module Journey # :nodoc:
-
2
module Path # :nodoc:
-
2
class Pattern # :nodoc:
-
2
attr_reader :spec, :requirements, :anchored
-
-
2
def initialize(strexp)
-
532
parser = Journey::Parser.new
-
-
532
@anchored = true
-
-
532
case strexp
-
when String
-
@spec = parser.parse(strexp)
-
@requirements = {}
-
@separators = "/.?"
-
when Router::Strexp
-
532
@spec = parser.parse(strexp.path)
-
532
@requirements = strexp.requirements
-
532
@separators = strexp.separators.join
-
532
@anchored = strexp.anchor
-
else
-
raise ArgumentError, "Bad expression: #{strexp}"
-
end
-
-
532
@names = nil
-
532
@optional_names = nil
-
532
@required_names = nil
-
532
@re = nil
-
532
@offsets = nil
-
end
-
-
2
def ast
-
132
@spec.grep(Nodes::Symbol).each do |node|
-
205
re = @requirements[node.to_sym]
-
205
node.regexp = re if re
-
end
-
-
132
@spec.grep(Nodes::Star).each do |node|
-
node = node.left
-
node.regexp = @requirements[node.to_sym] || /(.+)/
-
end
-
-
132
@spec
-
end
-
-
2
def names
-
1849
@names ||= spec.grep(Nodes::Symbol).map { |n| n.name }
-
end
-
-
2
def required_names
-
222
@required_names ||= names - optional_names
-
end
-
-
2
def optional_names
-
@optional_names ||= spec.grep(Nodes::Group).map { |group|
-
150
group.grep(Nodes::Symbol)
-
304
}.flatten.map { |n| n.name }.uniq
-
end
-
-
2
class RegexpOffsets < Journey::Visitors::Visitor # :nodoc:
-
2
attr_reader :offsets
-
-
2
def initialize(matchers)
-
9
@matchers = matchers
-
9
@capture_count = [0]
-
end
-
-
2
def visit(node)
-
100
super
-
100
@capture_count
-
end
-
-
2
def visit_SYMBOL(node)
-
11
node = node.to_sym
-
-
11
if @matchers.key?(node)
-
re = /#{@matchers[node]}|/
-
@capture_count.push((re.match('').length - 1) + (@capture_count.last || 0))
-
else
-
11
@capture_count << (@capture_count.last || 0)
-
end
-
end
-
end
-
-
2
class AnchoredRegexp < Journey::Visitors::Visitor # :nodoc:
-
2
def initialize(separator, matchers)
-
10
@separator = separator
-
10
@matchers = matchers
-
10
@separator_re = "([^#{separator}]+)"
-
10
super()
-
end
-
-
2
def accept(node)
-
9
%r{\A#{visit node}\Z}
-
end
-
-
2
def visit_CAT(node)
-
42
[visit(node.left), visit(node.right)].join
-
end
-
-
2
def visit_SYMBOL(node)
-
11
node = node.to_sym
-
-
11
return @separator_re unless @matchers.key?(node)
-
-
re = @matchers[node]
-
"(#{re})"
-
end
-
-
2
def visit_GROUP(node)
-
9
"(?:#{visit node.left})?"
-
end
-
-
2
def visit_LITERAL(node)
-
24
Regexp.escape(node.left)
-
end
-
2
alias :visit_DOT :visit_LITERAL
-
-
2
def visit_SLASH(node)
-
17
node.left
-
end
-
-
2
def visit_STAR(node)
-
re = @matchers[node.left.to_sym] || '.+'
-
"(#{re})"
-
end
-
end
-
-
2
class UnanchoredRegexp < AnchoredRegexp # :nodoc:
-
2
def accept(node)
-
1
%r{\A#{visit node}}
-
end
-
end
-
-
2
class MatchData # :nodoc:
-
2
attr_reader :names
-
-
2
def initialize(names, offsets, match)
-
15
@names = names
-
15
@offsets = offsets
-
15
@match = match
-
end
-
-
2
def captures
-
32
(length - 1).times.map { |i| self[i + 1] }
-
end
-
-
2
def [](x)
-
17
idx = @offsets[x - 1] + x
-
17
@match[idx]
-
end
-
-
2
def length
-
15
@offsets.length
-
end
-
-
2
def post_match
-
@match.post_match
-
end
-
-
2
def to_s
-
@match.to_s
-
end
-
end
-
-
2
def match(other)
-
28
return unless match = to_regexp.match(other)
-
15
MatchData.new(names, offsets, match)
-
end
-
2
alias :=~ :match
-
-
2
def source
-
to_regexp.source
-
end
-
-
2
def to_regexp
-
28
@re ||= regexp_visitor.new(@separators, @requirements).accept spec
-
end
-
-
2
private
-
-
2
def regexp_visitor
-
10
@anchored ? AnchoredRegexp : UnanchoredRegexp
-
end
-
-
2
def offsets
-
15
return @offsets if @offsets
-
-
9
viz = RegexpOffsets.new(@requirements)
-
9
@offsets = viz.accept(spec)
-
end
-
end
-
end
-
end
-
end
-
2
module ActionDispatch
-
2
module Journey # :nodoc:
-
2
class Route # :nodoc:
-
2
attr_reader :app, :path, :defaults, :name
-
-
2
attr_reader :constraints
-
2
alias :conditions :constraints
-
-
2
attr_accessor :precedence
-
-
##
-
# +path+ is a path constraint.
-
# +constraints+ is a hash of constraints to be applied to this route.
-
2
def initialize(name, app, path, constraints, defaults = {})
-
281
@name = name
-
281
@app = app
-
281
@path = path
-
-
# Unwrap any constraints so we can see what's inside for route generation.
-
# This allows the formatter to skip over any mounted applications or redirects
-
# that shouldn't be matched when using a url_for without a route name.
-
281
while app.is_a?(Routing::Mapper::Constraints) do
-
app = app.app
-
end
-
281
@dispatcher = app.is_a?(Routing::RouteSet::Dispatcher)
-
-
281
@constraints = constraints
-
281
@defaults = defaults
-
281
@required_defaults = nil
-
281
@required_parts = nil
-
281
@parts = nil
-
281
@decorated_ast = nil
-
281
@precedence = 0
-
end
-
-
2
def ast
-
@decorated_ast ||= begin
-
132
decorated_ast = path.ast
-
923
decorated_ast.grep(Nodes::Terminal).each { |n| n.memo = self }
-
132
decorated_ast
-
264
end
-
end
-
-
2
def requirements # :nodoc:
-
# needed for rails `rake routes`
-
296
path.requirements.merge(@defaults).delete_if { |_,v|
-
592
/.+?/ == v
-
}
-
end
-
-
2
def segments
-
264
path.names
-
end
-
-
2
def required_keys
-
required_parts + required_defaults.keys
-
end
-
-
2
def score(constraints)
-
74
required_keys = path.required_names
-
251
supplied_keys = constraints.map { |k,v| v && k.to_s }.compact
-
-
74
return -1 unless (required_keys - supplied_keys).empty?
-
-
64
score = (supplied_keys & path.names).length
-
64
score + (required_defaults.length * 2)
-
end
-
-
2
def parts
-
1272
@parts ||= segments.map { |n| n.to_sym }
-
end
-
2
alias :segment_keys :parts
-
-
2
def format(path_options)
-
34
path_options.delete_if do |key, value|
-
value.to_s == defaults[key].to_s && !required_parts.include?(key)
-
end
-
-
34
Visitors::Formatter.new(path_options).accept(path.spec)
-
end
-
-
2
def optimized_path
-
296
Visitors::OptimizedPath.new.accept(path.spec)
-
end
-
-
2
def optional_parts
-
path.optional_names.map { |n| n.to_sym }
-
end
-
-
2
def required_parts
-
420
@required_parts ||= path.required_names.map { |n| n.to_sym }
-
end
-
-
2
def required_default?(key)
-
528
(constraints[:required_defaults] || []).include?(key)
-
end
-
-
2
def required_defaults
-
@required_defaults ||= @defaults.dup.delete_if do |k,_|
-
528
parts.include?(k) || !required_default?(k)
-
330
end
-
end
-
-
2
def glob?
-
296
!path.spec.grep(Nodes::Star).empty?
-
end
-
-
2
def dispatcher?
-
30
@dispatcher
-
end
-
-
2
def matches?(request)
-
43
constraints.all? do |method, value|
-
86
next true unless request.respond_to?(method)
-
-
43
case value
-
when Regexp, String
-
43
value === request.send(method).to_s
-
when Array
-
value.include?(request.send(method))
-
when TrueClass
-
request.send(method).present?
-
when FalseClass
-
request.send(method).blank?
-
else
-
value === request.send(method)
-
end
-
end
-
end
-
-
2
def ip
-
constraints[:ip] || //
-
end
-
-
2
def verb
-
43
constraints[:request_method] || //
-
end
-
end
-
end
-
end
-
2
require 'action_dispatch/journey/router/utils'
-
2
require 'action_dispatch/journey/router/strexp'
-
2
require 'action_dispatch/journey/routes'
-
2
require 'action_dispatch/journey/formatter'
-
-
2
before = $-w
-
2
$-w = false
-
2
require 'action_dispatch/journey/parser'
-
2
$-w = before
-
-
2
require 'action_dispatch/journey/route'
-
2
require 'action_dispatch/journey/path/pattern'
-
-
2
module ActionDispatch
-
2
module Journey # :nodoc:
-
2
class Router # :nodoc:
-
2
class RoutingError < ::StandardError # :nodoc:
-
end
-
-
# :nodoc:
-
2
VERSION = '2.0.0'
-
-
2
class NullReq # :nodoc:
-
2
attr_reader :env
-
2
def initialize(env)
-
@env = env
-
end
-
-
2
def request_method
-
env['REQUEST_METHOD']
-
end
-
-
2
def path_info
-
env['PATH_INFO']
-
end
-
-
2
def ip
-
env['REMOTE_ADDR']
-
end
-
-
2
def [](k)
-
env[k]
-
end
-
end
-
-
2
attr_reader :request_class, :formatter
-
2
attr_accessor :routes
-
-
2
def initialize(routes, options)
-
2
@options = options
-
2
@params_key = options[:parameters_key]
-
2
@request_class = options[:request_class] || NullReq
-
2
@routes = routes
-
end
-
-
2
def call(env)
-
13
env['PATH_INFO'] = Utils.normalize_path(env['PATH_INFO'])
-
-
13
find_routes(env).each do |match, parameters, route|
-
13
script_name, path_info, set_params = env.values_at('SCRIPT_NAME',
-
'PATH_INFO',
-
@params_key)
-
-
13
unless route.path.anchored
-
env['SCRIPT_NAME'] = (script_name.to_s + match.to_s).chomp('/')
-
matched_path = match.post_match
-
env['PATH_INFO'] = matched_path
-
env['PATH_INFO'] = "/" + matched_path unless matched_path.start_with? "/"
-
end
-
-
13
env[@params_key] = (set_params || {}).merge parameters
-
-
13
status, headers, body = route.app.call(env)
-
-
13
if 'pass' == headers['X-Cascade']
-
env['SCRIPT_NAME'] = script_name
-
env['PATH_INFO'] = path_info
-
env[@params_key] = set_params
-
next
-
end
-
-
13
return [status, headers, body]
-
end
-
-
return [404, {'X-Cascade' => 'pass'}, ['Not Found']]
-
end
-
-
2
def recognize(req)
-
find_routes(req.env).each do |match, parameters, route|
-
unless route.path.anchored
-
req.env['SCRIPT_NAME'] = match.to_s
-
req.env['PATH_INFO'] = match.post_match.sub(/^([^\/])/, '/\1')
-
end
-
-
yield(route, nil, parameters)
-
end
-
end
-
-
2
def visualizer
-
tt = GTG::Builder.new(ast).transition_table
-
groups = partitioned_routes.first.map(&:ast).group_by { |a| a.to_s }
-
asts = groups.values.map { |v| v.first }
-
tt.visualizer(asts)
-
end
-
-
2
private
-
-
2
def partitioned_routes
-
13
routes.partitioned_routes
-
end
-
-
2
def ast
-
13
routes.ast
-
end
-
-
2
def simulator
-
13
routes.simulator
-
end
-
-
2
def custom_routes
-
13
partitioned_routes.last
-
end
-
-
2
def filter_routes(path)
-
13
return [] unless ast
-
13
data = simulator.match(path)
-
13
data ? data.memos : []
-
end
-
-
2
def find_routes env
-
13
req = request_class.new(env)
-
-
13
routes = filter_routes(req.path_info).concat custom_routes.find_all { |r|
-
13
r.path.match(req.path_info)
-
}
-
13
routes.concat get_routes_as_head(routes)
-
-
56
routes.sort_by!(&:precedence).select! { |r| r.matches?(req) }
-
-
13
routes.map! { |r|
-
15
match_data = r.path.match(req.path_info)
-
32
match_names = match_data.names.map { |n| n.to_sym }
-
32
match_values = match_data.captures.map { |v| v && Utils.unescape_uri(v) }
-
32
info = Hash[match_names.zip(match_values).find_all { |_, y| y }]
-
-
15
[match_data, r.defaults.merge(info), r]
-
}
-
end
-
-
2
def get_routes_as_head(routes)
-
13
precedence = (routes.map(&:precedence).max || 0) + 1
-
13
routes = routes.select { |r|
-
28
r.verb === "GET" && !(r.verb === "HEAD")
-
}.map! { |r|
-
Route.new(r.name,
-
r.app,
-
r.path,
-
r.conditions.merge(request_method: "HEAD"),
-
15
r.defaults).tap do |route|
-
15
route.precedence = r.precedence + precedence
-
end
-
}
-
13
routes.flatten!
-
13
routes
-
end
-
end
-
end
-
end
-
2
module ActionDispatch
-
2
module Journey # :nodoc:
-
2
class Router # :nodoc:
-
2
class Strexp # :nodoc:
-
2
class << self
-
2
alias :compile :new
-
end
-
-
2
attr_reader :path, :requirements, :separators, :anchor
-
-
2
def initialize(path, requirements, separators, anchor = true)
-
532
@path = path
-
532
@requirements = requirements
-
532
@separators = separators
-
532
@anchor = anchor
-
end
-
-
2
def names
-
@path.scan(/:\w+/).map { |s| s.tr(':', '') }
-
end
-
end
-
end
-
end
-
end
-
2
module ActionDispatch
-
2
module Journey # :nodoc:
-
2
class Router # :nodoc:
-
2
class Utils # :nodoc:
-
# Normalizes URI path.
-
#
-
# Strips off trailing slash and ensures there is a leading slash.
-
# Also converts downcase url encoded string to uppercase.
-
#
-
# normalize_path("/foo") # => "/foo"
-
# normalize_path("/foo/") # => "/foo"
-
# normalize_path("foo") # => "/foo"
-
# normalize_path("") # => "/"
-
# normalize_path("/%ab") # => "/%AB"
-
2
def self.normalize_path(path)
-
513
path = "/#{path}"
-
513
path.squeeze!('/')
-
513
path.sub!(%r{/+\Z}, '')
-
513
path.gsub!(/(%[a-f0-9]{2})/) { $1.upcase }
-
513
path = '/' if path == ''
-
513
path
-
end
-
-
# URI path and fragment escaping
-
# http://tools.ietf.org/html/rfc3986
-
2
class UriEncoder # :nodoc:
-
2
ENCODE = "%%%02X".freeze
-
2
US_ASCII = Encoding::US_ASCII
-
2
UTF_8 = Encoding::UTF_8
-
2
EMPTY = "".force_encoding(US_ASCII).freeze
-
1026
DEC2HEX = (0..255).to_a.map{ |i| ENCODE % i }.map{ |s| s.force_encoding(US_ASCII) }
-
-
2
ALPHA = "a-zA-Z".freeze
-
2
DIGIT = "0-9".freeze
-
2
UNRESERVED = "#{ALPHA}#{DIGIT}\\-\\._~".freeze
-
2
SUB_DELIMS = "!\\$&'\\(\\)\\*\\+,;=".freeze
-
-
2
ESCAPED = /%[a-zA-Z0-9]{2}/.freeze
-
-
2
FRAGMENT = /[^#{UNRESERVED}#{SUB_DELIMS}:@\/\?]/.freeze
-
2
SEGMENT = /[^#{UNRESERVED}#{SUB_DELIMS}:@]/.freeze
-
2
PATH = /[^#{UNRESERVED}#{SUB_DELIMS}:@\/]/.freeze
-
-
2
def escape_fragment(fragment)
-
escape(fragment, FRAGMENT)
-
end
-
-
2
def escape_path(path)
-
escape(path, PATH)
-
end
-
-
2
def escape_segment(segment)
-
escape(segment, SEGMENT)
-
end
-
-
2
def unescape_uri(uri)
-
2
encoding = uri.encoding == US_ASCII ? UTF_8 : uri.encoding
-
2
uri.gsub(ESCAPED) { [$&[1, 2].hex].pack('C') }.force_encoding(encoding)
-
end
-
-
2
protected
-
2
def escape(component, pattern)
-
component.gsub(pattern){ |unsafe| percent_encode(unsafe) }.force_encoding(US_ASCII)
-
end
-
-
2
def percent_encode(unsafe)
-
safe = EMPTY.dup
-
unsafe.each_byte { |b| safe << DEC2HEX[b] }
-
safe
-
end
-
end
-
-
2
ENCODER = UriEncoder.new
-
-
2
def self.escape_path(path)
-
ENCODER.escape_path(path.to_s)
-
end
-
-
2
def self.escape_segment(segment)
-
ENCODER.escape_segment(segment.to_s)
-
end
-
-
2
def self.escape_fragment(fragment)
-
ENCODER.escape_fragment(fragment.to_s)
-
end
-
-
2
def self.unescape_uri(uri)
-
2
ENCODER.unescape_uri(uri)
-
end
-
end
-
end
-
end
-
end
-
2
module ActionDispatch
-
2
module Journey # :nodoc:
-
# The Routing table. Contains all routes for a system. Routes can be
-
# added to the table by calling Routes#add_route.
-
2
class Routes # :nodoc:
-
2
include Enumerable
-
-
2
attr_reader :routes, :named_routes
-
-
2
def initialize
-
2
@routes = []
-
2
@named_routes = {}
-
2
@ast = nil
-
2
@partitioned_routes = nil
-
2
@simulator = nil
-
end
-
-
2
def length
-
routes.length
-
end
-
2
alias :size :length
-
-
2
def last
-
routes.last
-
end
-
-
2
def each(&block)
-
256
routes.each(&block)
-
end
-
-
2
def clear
-
2
routes.clear
-
2
named_routes.clear
-
end
-
-
2
def partitioned_routes
-
@partitioned_routes ||= routes.partition do |r|
-
133
r.path.anchored && r.ast.grep(Nodes::Symbol).all?(&:default_regexp?)
-
14
end
-
end
-
-
2
def ast
-
@ast ||= begin
-
1
asts = partitioned_routes.first.map(&:ast)
-
1
Nodes::Or.new(asts) unless asts.empty?
-
14
end
-
end
-
-
2
def simulator
-
@simulator ||= begin
-
1
gtg = GTG::Builder.new(ast).transition_table
-
1
GTG::Simulator.new(gtg)
-
13
end
-
end
-
-
# Add a route to the routing table.
-
2
def add_route(app, path, conditions, defaults, name = nil)
-
266
route = Route.new(name, app, path, conditions, defaults)
-
-
266
route.precedence = routes.length
-
266
routes << route
-
266
named_routes[name] = route if name && !named_routes[name]
-
266
clear_cache!
-
266
route
-
end
-
-
2
private
-
-
2
def clear_cache!
-
266
@ast = nil
-
266
@partitioned_routes = nil
-
266
@simulator = nil
-
end
-
end
-
end
-
end
-
2
require 'strscan'
-
-
2
module ActionDispatch
-
2
module Journey # :nodoc:
-
2
class Scanner # :nodoc:
-
2
def initialize
-
532
@ss = nil
-
end
-
-
2
def scan_setup(str)
-
532
@ss = StringScanner.new(str)
-
end
-
-
2
def eos?
-
@ss.eos?
-
end
-
-
2
def pos
-
@ss.pos
-
end
-
-
2
def pre_match
-
@ss.pre_match
-
end
-
-
2
def next_token
-
4752
return if @ss.eos?
-
-
4220
until token = scan || @ss.eos?; end
-
4220
token
-
end
-
-
2
private
-
-
2
def scan
-
case
-
# /
-
when text = @ss.scan(/\//)
-
1064
[:SLASH, text]
-
when text = @ss.scan(/\*\w+/)
-
[:STAR, text]
-
when text = @ss.scan(/\(/)
-
524
[:LPAREN, text]
-
when text = @ss.scan(/\)/)
-
524
[:RPAREN, text]
-
when text = @ss.scan(/\|/)
-
[:OR, text]
-
when text = @ss.scan(/\./)
-
524
[:DOT, text]
-
when text = @ss.scan(/:\w+/)
-
820
[:SYMBOL, text]
-
when text = @ss.scan(/[\w%\-~]+/)
-
764
[:LITERAL, text]
-
# any char
-
when text = @ss.scan(/./)
-
[:LITERAL, text]
-
4220
end
-
end
-
end
-
end
-
end
-
# encoding: utf-8
-
-
2
require 'thread_safe'
-
-
2
module ActionDispatch
-
2
module Journey # :nodoc:
-
2
module Visitors # :nodoc:
-
2
class Visitor # :nodoc:
-
2
DISPATCH_CACHE = ThreadSafe::Cache.new { |h,k|
-
13
h[k] = :"visit_#{k}"
-
}
-
-
2
def accept(node)
-
2500
visit(node)
-
end
-
-
2
private
-
-
2
def visit node
-
33249
send(DISPATCH_CACHE[node.type], node)
-
end
-
-
2
def binary(node)
-
12635
visit(node.left)
-
12635
visit(node.right)
-
end
-
12637
def visit_CAT(n); binary(n); end
-
-
2
def nary(node)
-
133
node.children.each { |c| visit(c) }
-
end
-
3
def visit_OR(n); nary(n); end
-
-
2
def unary(node)
-
2566
visit(node.left)
-
end
-
2568
def visit_GROUP(n); unary(n); end
-
2
def visit_STAR(n); unary(n); end
-
-
2
def terminal(node); end
-
2
%w{ LITERAL SYMBOL SLASH DOT }.each do |t|
-
8
class_eval %{ def visit_#{t}(n); terminal(n); end }, __FILE__, __LINE__
-
end
-
end
-
-
# Loop through the requirements AST
-
2
class Each < Visitor # :nodoc:
-
2
attr_reader :block
-
-
2
def initialize(block)
-
2457
@block = block
-
end
-
-
2
def visit(node)
-
30334
super
-
30334
block.call(node)
-
end
-
end
-
-
2
class String < Visitor # :nodoc:
-
2
private
-
-
2
def binary(node)
-
[visit(node.left), visit(node.right)].join
-
end
-
-
2
def nary(node)
-
node.children.map { |c| visit(c) }.join '|'
-
end
-
-
2
def terminal(node)
-
node.left
-
end
-
-
2
def visit_GROUP(node)
-
"(#{visit(node.left)})"
-
end
-
end
-
-
2
class OptimizedPath < Visitor # :nodoc:
-
2
def accept(node)
-
296
Array(visit(node))
-
end
-
-
2
private
-
-
2
def visit_CAT(node)
-
1208
[visit(node.left), visit(node.right)].flatten
-
end
-
-
2
def visit_SYMBOL(node)
-
112
node.left[1..-1].to_sym
-
end
-
-
2
def visit_STAR(node)
-
visit(node.left)
-
end
-
-
2
def visit_GROUP(node)
-
292
[]
-
end
-
-
2
%w{ LITERAL SLASH DOT }.each do |t|
-
6
class_eval %{ def visit_#{t}(n); n.left; end }, __FILE__, __LINE__
-
end
-
end
-
-
# Used for formatting urls (url_for)
-
2
class Formatter < Visitor # :nodoc:
-
2
attr_reader :options
-
-
2
def initialize(options)
-
34
@options = options
-
end
-
-
2
private
-
2
def escape_path(value)
-
Router::Utils.escape_path(value)
-
end
-
-
2
def escape_segment(value)
-
Router::Utils.escape_segment(value)
-
end
-
-
2
def visit(node, optional = false)
-
370
case node.type
-
when :LITERAL, :SLASH, :DOT
-
154
node.left
-
when :STAR
-
visit_STAR(node.left)
-
when :GROUP
-
32
visit(node.left, true)
-
when :CAT
-
152
visit_CAT(node, optional)
-
when :SYMBOL
-
32
visit_SYMBOL(node, node.to_sym)
-
end
-
end
-
-
2
def visit_CAT(node, optional)
-
152
left = visit(node.left, optional)
-
152
right = visit(node.right, optional)
-
-
152
if optional && !(right && left)
-
32
""
-
else
-
120
[left, right].join
-
end
-
end
-
-
2
def visit_STAR(node)
-
if value = options[node.to_sym]
-
escape_path(value)
-
end
-
end
-
-
2
def visit_SYMBOL(node, name)
-
32
if value = options[name]
-
name == :controller ? escape_path(value) : escape_segment(value)
-
end
-
end
-
end
-
-
2
class Dot < Visitor # :nodoc:
-
2
def initialize
-
@nodes = []
-
@edges = []
-
end
-
-
2
def accept(node)
-
super
-
<<-eodot
-
digraph parse_tree {
-
size="8,5"
-
node [shape = none];
-
edge [dir = none];
-
#{@nodes.join "\n"}
-
#{@edges.join("\n")}
-
}
-
eodot
-
end
-
-
2
private
-
-
2
def binary(node)
-
node.children.each do |c|
-
@edges << "#{node.object_id} -> #{c.object_id};"
-
end
-
super
-
end
-
-
2
def nary(node)
-
node.children.each do |c|
-
@edges << "#{node.object_id} -> #{c.object_id};"
-
end
-
super
-
end
-
-
2
def unary(node)
-
@edges << "#{node.object_id} -> #{node.left.object_id};"
-
super
-
end
-
-
2
def visit_GROUP(node)
-
@nodes << "#{node.object_id} [label=\"()\"];"
-
super
-
end
-
-
2
def visit_CAT(node)
-
@nodes << "#{node.object_id} [label=\"○\"];"
-
super
-
end
-
-
2
def visit_STAR(node)
-
@nodes << "#{node.object_id} [label=\"*\"];"
-
super
-
end
-
-
2
def visit_OR(node)
-
@nodes << "#{node.object_id} [label=\"|\"];"
-
super
-
end
-
-
2
def terminal(node)
-
value = node.left
-
-
@nodes << "#{node.object_id} [label=\"#{value}\"];"
-
end
-
end
-
end
-
end
-
end
-
-
2
module ActionDispatch
-
# Provide callbacks to be executed before and after the request dispatch.
-
2
class Callbacks
-
2
include ActiveSupport::Callbacks
-
-
2
define_callbacks :call
-
-
2
class << self
-
2
delegate :to_prepare, :to_cleanup, :to => "ActionDispatch::Reloader"
-
-
2
def before(*args, &block)
-
set_callback(:call, :before, *args, &block)
-
end
-
-
2
def after(*args, &block)
-
set_callback(:call, :after, *args, &block)
-
end
-
end
-
-
2
def initialize(app)
-
2
@app = app
-
end
-
-
2
def call(env)
-
13
error = nil
-
13
result = run_callbacks :call do
-
13
begin
-
13
@app.call(env)
-
rescue => error
-
end
-
end
-
13
raise error if error
-
13
result
-
end
-
end
-
end
-
2
require 'active_support/core_ext/hash/keys'
-
2
require 'active_support/core_ext/module/attribute_accessors'
-
2
require 'active_support/core_ext/object/blank'
-
2
require 'active_support/key_generator'
-
2
require 'active_support/message_verifier'
-
-
2
module ActionDispatch
-
2
class Request < Rack::Request
-
2
def cookie_jar
-
105
env['action_dispatch.cookies'] ||= Cookies::CookieJar.build(self)
-
end
-
end
-
-
# \Cookies are read and written through ActionController#cookies.
-
#
-
# The cookies being read are the ones received along with the request, the cookies
-
# being written will be sent out with the response. Reading a cookie does not get
-
# the cookie object itself back, just the value it holds.
-
#
-
# Examples of writing:
-
#
-
# # Sets a simple session cookie.
-
# # This cookie will be deleted when the user's browser is closed.
-
# cookies[:user_name] = "david"
-
#
-
# # Cookie values are String based. Other data types need to be serialized.
-
# cookies[:lat_lon] = JSON.generate([47.68, -122.37])
-
#
-
# # Sets a cookie that expires in 1 hour.
-
# cookies[:login] = { value: "XJ-122", expires: 1.hour.from_now }
-
#
-
# # Sets a signed cookie, which prevents users from tampering with its value.
-
# # The cookie is signed by your app's `secrets.secret_key_base` value.
-
# # It can be read using the signed method `cookies.signed[:name]`
-
# cookies.signed[:user_id] = current_user.id
-
#
-
# # Sets a "permanent" cookie (which expires in 20 years from now).
-
# cookies.permanent[:login] = "XJ-122"
-
#
-
# # You can also chain these methods:
-
# cookies.permanent.signed[:login] = "XJ-122"
-
#
-
# Examples of reading:
-
#
-
# cookies[:user_name] # => "david"
-
# cookies.size # => 2
-
# JSON.parse(cookies[:lat_lon]) # => [47.68, -122.37]
-
# cookies.signed[:login] # => "XJ-122"
-
#
-
# Example for deleting:
-
#
-
# cookies.delete :user_name
-
#
-
# Please note that if you specify a :domain when setting a cookie, you must also specify the domain when deleting the cookie:
-
#
-
# cookies[:name] = {
-
# value: 'a yummy cookie',
-
# expires: 1.year.from_now,
-
# domain: 'domain.com'
-
# }
-
#
-
# cookies.delete(:name, domain: 'domain.com')
-
#
-
# The option symbols for setting cookies are:
-
#
-
# * <tt>:value</tt> - The cookie's value.
-
# * <tt>:path</tt> - The path for which this cookie applies. Defaults to the root
-
# of the application.
-
# * <tt>:domain</tt> - The domain for which this cookie applies so you can
-
# restrict to the domain level. If you use a schema like www.example.com
-
# and want to share session with user.example.com set <tt>:domain</tt>
-
# to <tt>:all</tt>. Make sure to specify the <tt>:domain</tt> option with
-
# <tt>:all</tt> again when deleting cookies.
-
#
-
# domain: nil # Does not sets cookie domain. (default)
-
# domain: :all # Allow the cookie for the top most level
-
# domain and subdomains.
-
#
-
# * <tt>:expires</tt> - The time at which this cookie expires, as a \Time object.
-
# * <tt>:secure</tt> - Whether this cookie is only transmitted to HTTPS servers.
-
# Default is +false+.
-
# * <tt>:httponly</tt> - Whether this cookie is accessible via scripting or
-
# only HTTP. Defaults to +false+.
-
2
class Cookies
-
2
HTTP_HEADER = "Set-Cookie".freeze
-
2
GENERATOR_KEY = "action_dispatch.key_generator".freeze
-
2
SIGNED_COOKIE_SALT = "action_dispatch.signed_cookie_salt".freeze
-
2
ENCRYPTED_COOKIE_SALT = "action_dispatch.encrypted_cookie_salt".freeze
-
2
ENCRYPTED_SIGNED_COOKIE_SALT = "action_dispatch.encrypted_signed_cookie_salt".freeze
-
2
SECRET_TOKEN = "action_dispatch.secret_token".freeze
-
2
SECRET_KEY_BASE = "action_dispatch.secret_key_base".freeze
-
2
COOKIES_SERIALIZER = "action_dispatch.cookies_serializer".freeze
-
-
# Cookies can typically store 4096 bytes.
-
2
MAX_COOKIE_SIZE = 4096
-
-
# Raised when storing more than 4K of session data.
-
2
CookieOverflow = Class.new StandardError
-
-
# Include in a cookie jar to allow chaining, e.g. cookies.permanent.signed
-
2
module ChainedCookieJars
-
# Returns a jar that'll automatically set the assigned cookies to have an expiration date 20 years from now. Example:
-
#
-
# cookies.permanent[:prefers_open_id] = true
-
# # => Set-Cookie: prefers_open_id=true; path=/; expires=Sun, 16-Dec-2029 03:24:16 GMT
-
#
-
# This jar is only meant for writing. You'll read permanent cookies through the regular accessor.
-
#
-
# This jar allows chaining with the signed jar as well, so you can set permanent, signed cookies. Examples:
-
#
-
# cookies.permanent.signed[:remember_me] = current_user.id
-
# # => Set-Cookie: remember_me=BAhU--848956038e692d7046deab32b7131856ab20e14e; path=/; expires=Sun, 16-Dec-2029 03:24:16 GMT
-
2
def permanent
-
@permanent ||= PermanentCookieJar.new(self, @key_generator, @options)
-
end
-
-
# Returns a jar that'll automatically generate a signed representation of cookie value and verify it when reading from
-
# the cookie again. This is useful for creating cookies with values that the user is not supposed to change. If a signed
-
# cookie was tampered with by the user (or a 3rd party), nil will be returned.
-
#
-
# If +secrets.secret_key_base+ and +config.secret_token+ (deprecated) are both set,
-
# legacy cookies signed with the old key generator will be transparently upgraded.
-
#
-
# This jar requires that you set a suitable secret for the verification on your app's +secrets.secret_key_base+.
-
#
-
# Example:
-
#
-
# cookies.signed[:discount] = 45
-
# # => Set-Cookie: discount=BAhpMg==--2c1c6906c90a3bc4fd54a51ffb41dffa4bf6b5f7; path=/
-
#
-
# cookies.signed[:discount] # => 45
-
2
def signed
-
@signed ||=
-
if @options[:upgrade_legacy_signed_cookies]
-
UpgradeLegacySignedCookieJar.new(self, @key_generator, @options)
-
else
-
SignedCookieJar.new(self, @key_generator, @options)
-
end
-
end
-
-
# Returns a jar that'll automatically encrypt cookie values before sending them to the client and will decrypt them for read.
-
# If the cookie was tampered with by the user (or a 3rd party), nil will be returned.
-
#
-
# If +secrets.secret_key_base+ and +config.secret_token+ (deprecated) are both set,
-
# legacy cookies signed with the old key generator will be transparently upgraded.
-
#
-
# This jar requires that you set a suitable secret for the verification on your app's +secrets.secret_key_base+.
-
#
-
# Example:
-
#
-
# cookies.encrypted[:discount] = 45
-
# # => Set-Cookie: discount=ZS9ZZ1R4cG1pcUJ1bm80anhQang3dz09LS1mbDZDSU5scGdOT3ltQ2dTdlhSdWpRPT0%3D--ab54663c9f4e3bc340c790d6d2b71e92f5b60315; path=/
-
#
-
# cookies.encrypted[:discount] # => 45
-
2
def encrypted
-
@encrypted ||=
-
if @options[:upgrade_legacy_signed_cookies]
-
UpgradeLegacyEncryptedCookieJar.new(self, @key_generator, @options)
-
else
-
13
EncryptedCookieJar.new(self, @key_generator, @options)
-
13
end
-
end
-
-
# Returns the +signed+ or +encrypted+ jar, preferring +encrypted+ if +secret_key_base+ is set.
-
# Used by ActionDispatch::Session::CookieStore to avoid the need to introduce new cookie stores.
-
2
def signed_or_encrypted
-
@signed_or_encrypted ||=
-
if @options[:secret_key_base].present?
-
13
encrypted
-
else
-
signed
-
15
end
-
end
-
end
-
-
2
module VerifyAndUpgradeLegacySignedMessage
-
2
def initialize(*args)
-
super
-
@legacy_verifier = ActiveSupport::MessageVerifier.new(@options[:secret_token], serializer: NullSerializer)
-
end
-
-
2
def verify_and_upgrade_legacy_signed_message(name, signed_message)
-
deserialize(name, @legacy_verifier.verify(signed_message)).tap do |value|
-
self[name] = { value: value }
-
end
-
rescue ActiveSupport::MessageVerifier::InvalidSignature
-
nil
-
end
-
end
-
-
2
class CookieJar #:nodoc:
-
2
include Enumerable, ChainedCookieJars
-
-
# This regular expression is used to split the levels of a domain.
-
# The top level domain can be any string without a period or
-
# **.**, ***.** style TLDs like co.uk or com.au
-
#
-
# www.example.co.uk gives:
-
# $& => example.co.uk
-
#
-
# example.com gives:
-
# $& => example.com
-
#
-
# lots.of.subdomains.example.local gives:
-
# $& => example.local
-
2
DOMAIN_REGEXP = /[^.]*\.([^.]*|..\...|...\...)$/
-
-
2
def self.options_for_env(env) #:nodoc:
-
{ signed_cookie_salt: env[SIGNED_COOKIE_SALT] || '',
-
encrypted_cookie_salt: env[ENCRYPTED_COOKIE_SALT] || '',
-
encrypted_signed_cookie_salt: env[ENCRYPTED_SIGNED_COOKIE_SALT] || '',
-
secret_token: env[SECRET_TOKEN],
-
secret_key_base: env[SECRET_KEY_BASE],
-
upgrade_legacy_signed_cookies: env[SECRET_TOKEN].present? && env[SECRET_KEY_BASE].present?,
-
serializer: env[COOKIES_SERIALIZER]
-
24
}
-
end
-
-
2
def self.build(request)
-
24
env = request.env
-
24
key_generator = env[GENERATOR_KEY]
-
24
options = options_for_env env
-
-
24
host = request.host
-
24
secure = request.ssl?
-
-
24
new(key_generator, host, secure, options).tap do |hash|
-
24
hash.update(request.cookies)
-
end
-
end
-
-
2
def initialize(key_generator, host = nil, secure = false, options = {})
-
24
@key_generator = key_generator
-
24
@set_cookies = {}
-
24
@delete_cookies = {}
-
24
@host = host
-
24
@secure = secure
-
24
@options = options
-
24
@cookies = {}
-
24
@committed = false
-
end
-
-
15
def committed?; @committed; end
-
-
2
def commit!
-
@committed = true
-
@set_cookies.freeze
-
@delete_cookies.freeze
-
end
-
-
2
def each(&block)
-
@cookies.each(&block)
-
end
-
-
# Returns the value of the cookie by +name+, or +nil+ if no such cookie exists.
-
2
def [](name)
-
13
@cookies[name.to_s]
-
end
-
-
2
def fetch(name, *args, &block)
-
@cookies.fetch(name.to_s, *args, &block)
-
end
-
-
2
def key?(name)
-
@cookies.key?(name.to_s)
-
end
-
2
alias :has_key? :key?
-
-
2
def update(other_hash)
-
57
@cookies.update other_hash.stringify_keys
-
57
self
-
end
-
-
2
def handle_options(options) #:nodoc:
-
6
options[:path] ||= "/"
-
-
6
if options[:domain] == :all
-
# if there is a provided tld length then we use it otherwise default domain regexp
-
domain_regexp = options[:tld_length] ? /([^.]+\.?){#{options[:tld_length]}}$/ : DOMAIN_REGEXP
-
-
# if host is not ip and matches domain regexp
-
# (ip confirms to domain regexp so we explicitly check for ip)
-
options[:domain] = if (@host !~ /^[\d.]+$/) && (@host =~ domain_regexp)
-
".#{$&}"
-
end
-
6
elsif options[:domain].is_a? Array
-
# if host matches one of the supplied domains without a dot in front of it
-
options[:domain] = options[:domain].find {|domain| @host.include? domain.sub(/^\./, '') }
-
end
-
end
-
-
# Sets the cookie named +name+. The second argument may be the very cookie
-
# value, or a hash of options as documented above.
-
2
def []=(name, options)
-
6
if options.is_a?(Hash)
-
2
options.symbolize_keys!
-
2
value = options[:value]
-
else
-
4
value = options
-
4
options = { :value => value }
-
end
-
-
6
handle_options(options)
-
-
6
if @cookies[name.to_s] != value or options[:expires]
-
6
@cookies[name.to_s] = value
-
6
@set_cookies[name.to_s] = options
-
6
@delete_cookies.delete(name.to_s)
-
end
-
-
6
value
-
end
-
-
# Removes the cookie on the client machine by setting the value to an empty string
-
# and the expiration date in the past. Like <tt>[]=</tt>, you can pass in
-
# an options hash to delete cookies with extra data such as a <tt>:path</tt>.
-
2
def delete(name, options = {})
-
20
return unless @cookies.has_key? name.to_s
-
-
options.symbolize_keys!
-
handle_options(options)
-
-
value = @cookies.delete(name.to_s)
-
@delete_cookies[name.to_s] = options
-
value
-
end
-
-
# Whether the given cookie is to be deleted by this CookieJar.
-
# Like <tt>[]=</tt>, you can pass in an options hash to test if a
-
# deletion applies to a specific <tt>:path</tt>, <tt>:domain</tt> etc.
-
2
def deleted?(name, options = {})
-
options.symbolize_keys!
-
handle_options(options)
-
@delete_cookies[name.to_s] == options
-
end
-
-
# Removes all cookies on the client machine by calling <tt>delete</tt> for each cookie
-
2
def clear(options = {})
-
@cookies.each_key{ |k| delete(k, options) }
-
end
-
-
2
def write(headers)
-
30
@set_cookies.each { |k, v| ::Rack::Utils.set_cookie_header!(headers, k, v) if write_cookie?(v) }
-
24
@delete_cookies.each { |k, v| ::Rack::Utils.delete_cookie_header!(headers, k, v) }
-
end
-
-
2
def recycle! #:nodoc:
-
11
@set_cookies = {}
-
11
@delete_cookies = {}
-
end
-
-
2
mattr_accessor :always_write_cookie
-
2
self.always_write_cookie = false
-
-
2
private
-
2
def write_cookie?(cookie)
-
6
@secure || !cookie[:secure] || always_write_cookie
-
end
-
end
-
-
2
class PermanentCookieJar #:nodoc:
-
2
include ChainedCookieJars
-
-
2
def initialize(parent_jar, key_generator, options = {})
-
@parent_jar = parent_jar
-
@key_generator = key_generator
-
@options = options
-
end
-
-
2
def [](name)
-
@parent_jar[name.to_s]
-
end
-
-
2
def []=(name, options)
-
if options.is_a?(Hash)
-
options.symbolize_keys!
-
else
-
options = { :value => options }
-
end
-
-
options[:expires] = 20.years.from_now
-
@parent_jar[name] = options
-
end
-
end
-
-
2
class JsonSerializer
-
2
def self.load(value)
-
JSON.parse(value, quirks_mode: true)
-
end
-
-
2
def self.dump(value)
-
2
JSON.generate(value, quirks_mode: true)
-
end
-
end
-
-
# Passing the NullSerializer downstream to the Message{Encryptor,Verifier}
-
# allows us to handle the (de)serialization step within the cookie jar,
-
# which gives us the opportunity to detect and migrate legacy cookies.
-
2
class NullSerializer
-
2
def self.load(value)
-
value
-
end
-
-
2
def self.dump(value)
-
2
value
-
end
-
end
-
-
2
module SerializedCookieJars
-
2
MARSHAL_SIGNATURE = "\x04\x08".freeze
-
-
2
protected
-
2
def needs_migration?(value)
-
@options[:serializer] == :hybrid && value.start_with?(MARSHAL_SIGNATURE)
-
end
-
-
2
def serialize(name, value)
-
2
serializer.dump(value)
-
end
-
-
2
def deserialize(name, value)
-
if value
-
if needs_migration?(value)
-
Marshal.load(value).tap do |v|
-
self[name] = { value: v }
-
end
-
else
-
serializer.load(value)
-
end
-
end
-
end
-
-
2
def serializer
-
2
serializer = @options[:serializer] || :marshal
-
2
case serializer
-
when :marshal
-
Marshal
-
when :json, :hybrid
-
2
JsonSerializer
-
else
-
serializer
-
end
-
end
-
end
-
-
2
class SignedCookieJar #:nodoc:
-
2
include ChainedCookieJars
-
2
include SerializedCookieJars
-
-
2
def initialize(parent_jar, key_generator, options = {})
-
@parent_jar = parent_jar
-
@options = options
-
secret = key_generator.generate_key(@options[:signed_cookie_salt])
-
@verifier = ActiveSupport::MessageVerifier.new(secret, serializer: NullSerializer)
-
end
-
-
2
def [](name)
-
if signed_message = @parent_jar[name]
-
deserialize name, verify(signed_message)
-
end
-
end
-
-
2
def []=(name, options)
-
if options.is_a?(Hash)
-
options.symbolize_keys!
-
options[:value] = @verifier.generate(serialize(name, options[:value]))
-
else
-
options = { :value => @verifier.generate(serialize(name, options)) }
-
end
-
-
raise CookieOverflow if options[:value].size > MAX_COOKIE_SIZE
-
@parent_jar[name] = options
-
end
-
-
2
private
-
2
def verify(signed_message)
-
@verifier.verify(signed_message)
-
rescue ActiveSupport::MessageVerifier::InvalidSignature
-
nil
-
end
-
end
-
-
# UpgradeLegacySignedCookieJar is used instead of SignedCookieJar if
-
# config.secret_token and secrets.secret_key_base are both set. It reads
-
# legacy cookies signed with the old dummy key generator and re-saves
-
# them using the new key generator to provide a smooth upgrade path.
-
2
class UpgradeLegacySignedCookieJar < SignedCookieJar #:nodoc:
-
2
include VerifyAndUpgradeLegacySignedMessage
-
-
2
def [](name)
-
if signed_message = @parent_jar[name]
-
deserialize(name, verify(signed_message)) || verify_and_upgrade_legacy_signed_message(name, signed_message)
-
end
-
end
-
end
-
-
2
class EncryptedCookieJar #:nodoc:
-
2
include ChainedCookieJars
-
2
include SerializedCookieJars
-
-
2
def initialize(parent_jar, key_generator, options = {})
-
13
if ActiveSupport::LegacyKeyGenerator === key_generator
-
raise "You didn't set secrets.secret_key_base, which is required for this cookie jar. " +
-
"Read the upgrade documentation to learn more about this new config option."
-
end
-
-
13
@parent_jar = parent_jar
-
13
@options = options
-
13
secret = key_generator.generate_key(@options[:encrypted_cookie_salt])
-
13
sign_secret = key_generator.generate_key(@options[:encrypted_signed_cookie_salt])
-
13
@encryptor = ActiveSupport::MessageEncryptor.new(secret, sign_secret, serializer: NullSerializer)
-
end
-
-
2
def [](name)
-
13
if encrypted_message = @parent_jar[name]
-
deserialize name, decrypt_and_verify(encrypted_message)
-
end
-
end
-
-
2
def []=(name, options)
-
2
if options.is_a?(Hash)
-
2
options.symbolize_keys!
-
else
-
options = { :value => options }
-
end
-
-
2
options[:value] = @encryptor.encrypt_and_sign(serialize(name, options[:value]))
-
-
2
raise CookieOverflow if options[:value].size > MAX_COOKIE_SIZE
-
2
@parent_jar[name] = options
-
end
-
-
2
private
-
2
def decrypt_and_verify(encrypted_message)
-
@encryptor.decrypt_and_verify(encrypted_message)
-
rescue ActiveSupport::MessageVerifier::InvalidSignature, ActiveSupport::MessageEncryptor::InvalidMessage
-
nil
-
end
-
end
-
-
# UpgradeLegacyEncryptedCookieJar is used by ActionDispatch::Session::CookieStore
-
# instead of EncryptedCookieJar if config.secret_token and secrets.secret_key_base
-
# are both set. It reads legacy cookies signed with the old dummy key generator and
-
# encrypts and re-saves them using the new key generator to provide a smooth upgrade path.
-
2
class UpgradeLegacyEncryptedCookieJar < EncryptedCookieJar #:nodoc:
-
2
include VerifyAndUpgradeLegacySignedMessage
-
-
2
def [](name)
-
if encrypted_or_signed_message = @parent_jar[name]
-
deserialize(name, decrypt_and_verify(encrypted_or_signed_message)) || verify_and_upgrade_legacy_signed_message(name, encrypted_or_signed_message)
-
end
-
end
-
end
-
-
2
def initialize(app)
-
2
@app = app
-
end
-
-
2
def call(env)
-
13
status, headers, body = @app.call(env)
-
-
13
if cookie_jar = env['action_dispatch.cookies']
-
13
unless cookie_jar.committed?
-
13
cookie_jar.write(headers)
-
13
if headers[HTTP_HEADER].respond_to?(:join)
-
headers[HTTP_HEADER] = headers[HTTP_HEADER].join("\n")
-
end
-
end
-
end
-
-
13
[status, headers, body]
-
end
-
end
-
end
-
2
require 'action_dispatch/http/request'
-
2
require 'action_dispatch/middleware/exception_wrapper'
-
2
require 'action_dispatch/routing/inspector'
-
-
2
module ActionDispatch
-
# This middleware is responsible for logging exceptions and
-
# showing a debugging page in case the request is local.
-
2
class DebugExceptions
-
2
RESCUES_TEMPLATE_PATH = File.expand_path('../templates', __FILE__)
-
-
2
def initialize(app, routes_app = nil)
-
2
@app = app
-
2
@routes_app = routes_app
-
end
-
-
2
def call(env)
-
13
_, headers, body = response = @app.call(env)
-
-
13
if headers['X-Cascade'] == 'pass'
-
body.close if body.respond_to?(:close)
-
raise ActionController::RoutingError, "No route matches [#{env['REQUEST_METHOD']}] #{env['PATH_INFO'].inspect}"
-
end
-
-
13
response
-
rescue Exception => exception
-
raise exception if env['action_dispatch.show_exceptions'] == false
-
render_exception(env, exception)
-
end
-
-
2
private
-
-
2
def render_exception(env, exception)
-
wrapper = ExceptionWrapper.new(env, exception)
-
log_error(env, wrapper)
-
-
if env['action_dispatch.show_detailed_exceptions']
-
request = Request.new(env)
-
template = ActionView::Base.new([RESCUES_TEMPLATE_PATH],
-
request: request,
-
exception: wrapper.exception,
-
application_trace: wrapper.application_trace,
-
framework_trace: wrapper.framework_trace,
-
full_trace: wrapper.full_trace,
-
routes_inspector: routes_inspector(exception),
-
source_extract: wrapper.source_extract,
-
line_number: wrapper.line_number,
-
file: wrapper.file
-
)
-
file = "rescues/#{wrapper.rescue_template}"
-
-
if request.xhr?
-
body = template.render(template: file, layout: false, formats: [:text])
-
format = "text/plain"
-
else
-
body = template.render(template: file, layout: 'rescues/layout')
-
format = "text/html"
-
end
-
render(wrapper.status_code, body, format)
-
else
-
raise exception
-
end
-
end
-
-
2
def render(status, body, format)
-
[status, {'Content-Type' => "#{format}; charset=#{Response.default_charset}", 'Content-Length' => body.bytesize.to_s}, [body]]
-
end
-
-
2
def log_error(env, wrapper)
-
logger = logger(env)
-
return unless logger
-
-
exception = wrapper.exception
-
-
trace = wrapper.application_trace
-
trace = wrapper.framework_trace if trace.empty?
-
-
ActiveSupport::Deprecation.silence do
-
message = "\n#{exception.class} (#{exception.message}):\n"
-
message << exception.annoted_source_code.to_s if exception.respond_to?(:annoted_source_code)
-
message << " " << trace.join("\n ")
-
logger.fatal("#{message}\n\n")
-
end
-
end
-
-
2
def logger(env)
-
env['action_dispatch.logger'] || stderr_logger
-
end
-
-
2
def stderr_logger
-
@stderr_logger ||= ActiveSupport::Logger.new($stderr)
-
end
-
-
2
def routes_inspector(exception)
-
if @routes_app.respond_to?(:routes) && (exception.is_a?(ActionController::RoutingError) || exception.is_a?(ActionView::Template::Error))
-
ActionDispatch::Routing::RoutesInspector.new(@routes_app.routes.routes)
-
end
-
end
-
end
-
end
-
2
require 'action_controller/metal/exceptions'
-
2
require 'active_support/core_ext/module/attribute_accessors'
-
-
2
module ActionDispatch
-
2
class ExceptionWrapper
-
2
cattr_accessor :rescue_responses
-
2
@@rescue_responses = Hash.new(:internal_server_error)
-
2
@@rescue_responses.merge!(
-
'ActionController::RoutingError' => :not_found,
-
'AbstractController::ActionNotFound' => :not_found,
-
'ActionController::MethodNotAllowed' => :method_not_allowed,
-
'ActionController::UnknownHttpMethod' => :method_not_allowed,
-
'ActionController::NotImplemented' => :not_implemented,
-
'ActionController::UnknownFormat' => :not_acceptable,
-
'ActionController::InvalidAuthenticityToken' => :unprocessable_entity,
-
'ActionController::InvalidCrossOriginRequest' => :unprocessable_entity,
-
'ActionDispatch::ParamsParser::ParseError' => :bad_request,
-
'ActionController::BadRequest' => :bad_request,
-
'ActionController::ParameterMissing' => :bad_request
-
)
-
-
2
cattr_accessor :rescue_templates
-
2
@@rescue_templates = Hash.new('diagnostics')
-
2
@@rescue_templates.merge!(
-
'ActionView::MissingTemplate' => 'missing_template',
-
'ActionController::RoutingError' => 'routing_error',
-
'AbstractController::ActionNotFound' => 'unknown_action',
-
'ActionView::Template::Error' => 'template_error'
-
)
-
-
2
attr_reader :env, :exception, :line_number, :file
-
-
2
def initialize(env, exception)
-
@env = env
-
@exception = original_exception(exception)
-
-
expand_backtrace if exception.is_a?(SyntaxError) || exception.try(:original_exception).try(:is_a?, SyntaxError)
-
end
-
-
2
def rescue_template
-
@@rescue_templates[@exception.class.name]
-
end
-
-
2
def status_code
-
self.class.status_code_for_exception(@exception.class.name)
-
end
-
-
2
def application_trace
-
clean_backtrace(:silent)
-
end
-
-
2
def framework_trace
-
clean_backtrace(:noise)
-
end
-
-
2
def full_trace
-
clean_backtrace(:all)
-
end
-
-
2
def self.status_code_for_exception(class_name)
-
Rack::Utils.status_code(@@rescue_responses[class_name])
-
end
-
-
2
def source_extract
-
if application_trace && trace = application_trace.first
-
file, line, _ = trace.split(":")
-
@file = file
-
@line_number = line.to_i
-
source_fragment(@file, @line_number)
-
end
-
end
-
-
2
private
-
-
2
def original_exception(exception)
-
if registered_original_exception?(exception)
-
exception.original_exception
-
else
-
exception
-
end
-
end
-
-
2
def registered_original_exception?(exception)
-
exception.respond_to?(:original_exception) && @@rescue_responses.has_key?(exception.original_exception.class.name)
-
end
-
-
2
def clean_backtrace(*args)
-
if backtrace_cleaner
-
backtrace_cleaner.clean(@exception.backtrace, *args)
-
else
-
@exception.backtrace
-
end
-
end
-
-
2
def backtrace_cleaner
-
@backtrace_cleaner ||= @env['action_dispatch.backtrace_cleaner']
-
end
-
-
2
def source_fragment(path, line)
-
return unless Rails.respond_to?(:root) && Rails.root
-
full_path = Rails.root.join(path)
-
if File.exist?(full_path)
-
File.open(full_path, "r") do |file|
-
start = [line - 3, 0].max
-
lines = file.each_line.drop(start).take(6)
-
Hash[*(start+1..(lines.count+start)).zip(lines).flatten]
-
end
-
end
-
end
-
-
2
def expand_backtrace
-
@exception.backtrace.unshift(
-
@exception.to_s.split("\n")
-
).flatten!
-
end
-
end
-
end
-
2
require 'active_support/core_ext/hash/keys'
-
-
2
module ActionDispatch
-
2
class Request < Rack::Request
-
# Access the contents of the flash. Use <tt>flash["notice"]</tt> to
-
# read a notice you put there or <tt>flash["notice"] = "hello"</tt>
-
# to put a new one.
-
2
def flash
-
24
@env[Flash::KEY] ||= Flash::FlashHash.from_session_value(session["flash"])
-
end
-
end
-
-
# The flash provides a way to pass temporary objects between actions. Anything you place in the flash will be exposed
-
# to the very next action and then cleared out. This is a great way of doing notices and alerts, such as a create
-
# action that sets <tt>flash[:notice] = "Post successfully created"</tt> before redirecting to a display action that can
-
# then expose the flash to its template. Actually, that exposure is automatically done.
-
#
-
# class PostsController < ActionController::Base
-
# def create
-
# # save post
-
# flash[:notice] = "Post successfully created"
-
# redirect_to @post
-
# end
-
#
-
# def show
-
# # doesn't need to assign the flash notice to the template, that's done automatically
-
# end
-
# end
-
#
-
# show.html.erb
-
# <% if flash[:notice] %>
-
# <div class="notice"><%= flash[:notice] %></div>
-
# <% end %>
-
#
-
# Since the +notice+ and +alert+ keys are a common idiom, convenience accessors are available:
-
#
-
# flash.alert = "You must be logged in"
-
# flash.notice = "Post successfully created"
-
#
-
# This example just places a string in the flash, but you can put any object in there. And of course, you can put as
-
# many as you like at a time too. Just remember: They'll be gone by the time the next action has been performed.
-
#
-
# See docs on the FlashHash class for more details about the flash.
-
2
class Flash
-
2
KEY = 'action_dispatch.request.flash_hash'.freeze
-
-
2
class FlashNow #:nodoc:
-
2
attr_accessor :flash
-
-
2
def initialize(flash)
-
2
@flash = flash
-
end
-
-
2
def []=(k, v)
-
2
k = k.to_s
-
2
@flash[k] = v
-
2
@flash.discard(k)
-
2
v
-
end
-
-
2
def [](k)
-
@flash[k.to_s]
-
end
-
-
# Convenience accessor for <tt>flash.now[:alert]=</tt>.
-
2
def alert=(message)
-
self[:alert] = message
-
end
-
-
# Convenience accessor for <tt>flash.now[:notice]=</tt>.
-
2
def notice=(message)
-
self[:notice] = message
-
end
-
end
-
-
2
class FlashHash
-
2
include Enumerable
-
-
2
def self.from_session_value(value)
-
13
flash = case value
-
when FlashHash # Rails 3.1, 3.2
-
new(value.instance_variable_get(:@flashes), value.instance_variable_get(:@used))
-
when Hash # Rails 4.0
-
new(value['flashes'], value['discard'])
-
else
-
13
new
-
end
-
-
13
flash.tap(&:sweep)
-
end
-
-
2
def to_session_value
-
13
return nil if empty?
-
2
{'discard' => @discard.to_a, 'flashes' => @flashes}
-
end
-
-
2
def initialize(flashes = {}, discard = []) #:nodoc:
-
13
@discard = Set.new(stringify_array(discard))
-
13
@flashes = flashes.stringify_keys
-
13
@now = nil
-
end
-
-
2
def initialize_copy(other)
-
2
if other.now_is_loaded?
-
2
@now = other.now.dup
-
2
@now.flash = self
-
end
-
2
super
-
end
-
-
2
def []=(k, v)
-
2
k = k.to_s
-
2
@discard.delete k
-
2
@flashes[k] = v
-
end
-
-
2
def [](k)
-
2
@flashes[k.to_s]
-
end
-
-
2
def update(h) #:nodoc:
-
11
@discard.subtract stringify_array(h.keys)
-
11
@flashes.update h.stringify_keys
-
11
self
-
end
-
-
2
def keys
-
@flashes.keys
-
end
-
-
2
def key?(name)
-
@flashes.key? name
-
end
-
-
2
def delete(key)
-
key = key.to_s
-
@discard.delete key
-
@flashes.delete key
-
self
-
end
-
-
2
def to_hash
-
@flashes.dup
-
end
-
-
2
def empty?
-
15
@flashes.empty?
-
end
-
-
2
def clear
-
@discard.clear
-
@flashes.clear
-
end
-
-
2
def each(&block)
-
@flashes.each(&block)
-
end
-
-
2
alias :merge! :update
-
-
2
def replace(h) #:nodoc:
-
@discard.clear
-
@flashes.replace h.stringify_keys
-
self
-
end
-
-
# Sets a flash that will not be available to the next action, only to the current.
-
#
-
# flash.now[:message] = "Hello current action"
-
#
-
# This method enables you to use the flash as a central messaging system in your app.
-
# When you need to pass an object to the next action, you use the standard flash assign (<tt>[]=</tt>).
-
# When you need to pass an object to the current action, you use <tt>now</tt>, and your object will
-
# vanish when the current action is done.
-
#
-
# Entries set via <tt>now</tt> are accessed the same way as standard entries: <tt>flash['my-key']</tt>.
-
#
-
# Also, brings two convenience accessors:
-
#
-
# flash.now.alert = "Beware now!"
-
# # Equivalent to flash.now[:alert] = "Beware now!"
-
#
-
# flash.now.notice = "Good luck now!"
-
# # Equivalent to flash.now[:notice] = "Good luck now!"
-
2
def now
-
4
@now ||= FlashNow.new(self)
-
end
-
-
# Keeps either the entire current flash or a specific flash entry available for the next action:
-
#
-
# flash.keep # keeps the entire flash
-
# flash.keep(:notice) # keeps only the "notice" entry, the rest of the flash is discarded
-
2
def keep(k = nil)
-
k = k.to_s if k
-
@discard.subtract Array(k || keys)
-
k ? self[k] : self
-
end
-
-
# Marks the entire flash or a single flash entry to be discarded by the end of the current action:
-
#
-
# flash.discard # discard the entire flash at the end of the current action
-
# flash.discard(:warning) # discard only the "warning" entry at the end of the current action
-
2
def discard(k = nil)
-
2
k = k.to_s if k
-
2
@discard.merge Array(k || keys)
-
2
k ? self[k] : self
-
end
-
-
# Mark for removal entries that were kept, and delete unkept ones.
-
#
-
# This method is called automatically by filters, so you generally don't need to care about it.
-
2
def sweep #:nodoc:
-
13
@discard.each { |k| @flashes.delete k }
-
13
@discard.replace @flashes.keys
-
end
-
-
# Convenience accessor for <tt>flash[:alert]</tt>.
-
2
def alert
-
self[:alert]
-
end
-
-
# Convenience accessor for <tt>flash[:alert]=</tt>.
-
2
def alert=(message)
-
self[:alert] = message
-
end
-
-
# Convenience accessor for <tt>flash[:notice]</tt>.
-
2
def notice
-
self[:notice]
-
end
-
-
# Convenience accessor for <tt>flash[:notice]=</tt>.
-
2
def notice=(message)
-
self[:notice] = message
-
end
-
-
2
protected
-
2
def now_is_loaded?
-
2
@now
-
end
-
-
2
def stringify_array(array)
-
24
array.map do |item|
-
item.kind_of?(Symbol) ? item.to_s : item
-
end
-
end
-
end
-
-
2
def initialize(app)
-
2
@app = app
-
end
-
-
2
def call(env)
-
13
@app.call(env)
-
ensure
-
13
session = Request::Session.find(env) || {}
-
13
flash_hash = env[KEY]
-
-
13
if flash_hash && (flash_hash.present? || session.key?('flash'))
-
2
session["flash"] = flash_hash.to_session_value
-
2
env[KEY] = flash_hash.dup
-
end
-
-
if (!session.respond_to?(:loaded?) || session.loaded?) && # (reset_session uses {}, which doesn't implement #loaded?)
-
13
session.key?('flash') && session['flash'].nil?
-
session.delete('flash')
-
end
-
end
-
end
-
end
-
2
require 'active_support/core_ext/hash/conversions'
-
2
require 'action_dispatch/http/request'
-
2
require 'active_support/core_ext/hash/indifferent_access'
-
-
2
module ActionDispatch
-
2
class ParamsParser
-
2
class ParseError < StandardError
-
2
attr_reader :original_exception
-
-
2
def initialize(message, original_exception)
-
super(message)
-
@original_exception = original_exception
-
end
-
end
-
-
2
DEFAULT_PARSERS = { Mime::JSON => :json }
-
-
2
def initialize(app, parsers = {})
-
2
@app, @parsers = app, DEFAULT_PARSERS.merge(parsers)
-
end
-
-
2
def call(env)
-
13
if params = parse_formatted_parameters(env)
-
env["action_dispatch.request.request_parameters"] = params
-
end
-
-
13
@app.call(env)
-
end
-
-
2
private
-
2
def parse_formatted_parameters(env)
-
13
request = Request.new(env)
-
-
13
return false if request.content_length.zero?
-
-
4
strategy = @parsers[request.content_mime_type]
-
-
4
return false unless strategy
-
-
case strategy
-
when Proc
-
strategy.call(request.raw_post)
-
when :json
-
data = ActiveSupport::JSON.decode(request.raw_post)
-
data = {:_json => data} unless data.is_a?(Hash)
-
Request::Utils.deep_munge(data).with_indifferent_access
-
else
-
false
-
end
-
rescue Exception => e # JSON or Ruby code block errors
-
logger(env).debug "Error occurred while parsing request parameters.\nContents:\n\n#{request.raw_post}"
-
-
raise ParseError.new(e.message, e)
-
end
-
-
2
def logger(env)
-
env['action_dispatch.logger'] || ActiveSupport::Logger.new($stderr)
-
end
-
end
-
end
-
2
module ActionDispatch
-
2
class PublicExceptions
-
2
attr_accessor :public_path
-
-
2
def initialize(public_path)
-
2
@public_path = public_path
-
end
-
-
2
def call(env)
-
status = env["PATH_INFO"][1..-1]
-
request = ActionDispatch::Request.new(env)
-
body = { :status => status, :error => Rack::Utils::HTTP_STATUS_CODES.fetch(status.to_i, Rack::Utils::HTTP_STATUS_CODES[500]) }
-
content_type = begin
-
request.formats.first
-
rescue ActionController::BadRequest
-
Mime::HTML
-
end
-
-
render(status, content_type, body)
-
end
-
-
2
private
-
-
2
def render(status, content_type, body)
-
format = "to_#{content_type.to_sym}" if content_type
-
if format && body.respond_to?(format)
-
render_format(status, content_type, body.public_send(format))
-
else
-
render_html(status)
-
end
-
end
-
-
2
def render_format(status, content_type, body)
-
[status, {'Content-Type' => "#{content_type}; charset=#{ActionDispatch::Response.default_charset}",
-
'Content-Length' => body.bytesize.to_s}, [body]]
-
end
-
-
2
def render_html(status)
-
found = false
-
path = "#{public_path}/#{status}.#{I18n.locale}.html" if I18n.locale
-
path = "#{public_path}/#{status}.html" unless path && (found = File.exist?(path))
-
-
if found || File.exist?(path)
-
render_format(status, 'text/html', File.read(path))
-
else
-
[404, { "X-Cascade" => "pass" }, []]
-
end
-
end
-
end
-
end
-
2
require 'active_support/deprecation/reporting'
-
-
2
module ActionDispatch
-
# ActionDispatch::Reloader provides prepare and cleanup callbacks,
-
# intended to assist with code reloading during development.
-
#
-
# Prepare callbacks are run before each request, and cleanup callbacks
-
# after each request. In this respect they are analogs of ActionDispatch::Callback's
-
# before and after callbacks. However, cleanup callbacks are not called until the
-
# request is fully complete -- that is, after #close has been called on
-
# the response body. This is important for streaming responses such as the
-
# following:
-
#
-
# self.response_body = lambda { |response, output|
-
# # code here which refers to application models
-
# }
-
#
-
# Cleanup callbacks will not be called until after the response_body lambda
-
# is evaluated, ensuring that it can refer to application models and other
-
# classes before they are unloaded.
-
#
-
# By default, ActionDispatch::Reloader is included in the middleware stack
-
# only in the development environment; specifically, when +config.cache_classes+
-
# is false. Callbacks may be registered even when it is not included in the
-
# middleware stack, but are executed only when <tt>ActionDispatch::Reloader.prepare!</tt>
-
# or <tt>ActionDispatch::Reloader.cleanup!</tt> are called manually.
-
#
-
2
class Reloader
-
2
include ActiveSupport::Callbacks
-
2
include ActiveSupport::Deprecation::Reporting
-
-
2
define_callbacks :prepare
-
2
define_callbacks :cleanup
-
-
# Add a prepare callback. Prepare callbacks are run before each request, prior
-
# to ActionDispatch::Callback's before callbacks.
-
2
def self.to_prepare(*args, &block)
-
20
unless block_given?
-
warn "to_prepare without a block is deprecated. Please use a block"
-
end
-
20
set_callback(:prepare, *args, &block)
-
end
-
-
# Add a cleanup callback. Cleanup callbacks are run after each request is
-
# complete (after #close is called on the response body).
-
2
def self.to_cleanup(*args, &block)
-
unless block_given?
-
warn "to_cleanup without a block is deprecated. Please use a block"
-
end
-
set_callback(:cleanup, *args, &block)
-
end
-
-
# Execute all prepare callbacks.
-
2
def self.prepare!
-
2
new(nil).prepare!
-
end
-
-
# Execute all cleanup callbacks.
-
2
def self.cleanup!
-
new(nil).cleanup!
-
end
-
-
2
def initialize(app, condition=nil)
-
2
@app = app
-
2
@condition = condition || lambda { true }
-
2
@validated = true
-
end
-
-
2
def call(env)
-
@validated = @condition.call
-
prepare!
-
-
response = @app.call(env)
-
response[2] = ::Rack::BodyProxy.new(response[2]) { cleanup! }
-
-
response
-
rescue Exception
-
cleanup!
-
raise
-
end
-
-
2
def prepare! #:nodoc:
-
2
run_callbacks :prepare if validated?
-
end
-
-
2
def cleanup! #:nodoc:
-
run_callbacks :cleanup if validated?
-
ensure
-
@validated = true
-
end
-
-
2
private
-
-
2
def validated? #:nodoc:
-
2
@validated
-
end
-
end
-
end
-
2
module ActionDispatch
-
# This middleware calculates the IP address of the remote client that is
-
# making the request. It does this by checking various headers that could
-
# contain the address, and then picking the last-set address that is not
-
# on the list of trusted IPs. This follows the precedent set by e.g.
-
# {the Tomcat server}[https://issues.apache.org/bugzilla/show_bug.cgi?id=50453],
-
# with {reasoning explained at length}[http://blog.gingerlime.com/2012/rails-ip-spoofing-vulnerabilities-and-protection]
-
# by @gingerlime. A more detailed explanation of the algorithm is given
-
# at GetIp#calculate_ip.
-
#
-
# Some Rack servers concatenate repeated headers, like {HTTP RFC 2616}[http://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.2]
-
# requires. Some Rack servers simply drop preceding headers, and only report
-
# the value that was {given in the last header}[http://andre.arko.net/2011/12/26/repeated-headers-and-ruby-web-servers].
-
# If you are behind multiple proxy servers (like Nginx to HAProxy to Unicorn)
-
# then you should test your Rack server to make sure your data is good.
-
#
-
# IF YOU DON'T USE A PROXY, THIS MAKES YOU VULNERABLE TO IP SPOOFING.
-
# This middleware assumes that there is at least one proxy sitting around
-
# and setting headers with the client's remote IP address. If you don't use
-
# a proxy, because you are hosted on e.g. Heroku without SSL, any client can
-
# claim to have any IP address by setting the X-Forwarded-For header. If you
-
# care about that, then you need to explicitly drop or ignore those headers
-
# sometime before this middleware runs.
-
2
class RemoteIp
-
2
class IpSpoofAttackError < StandardError; end
-
-
# The default trusted IPs list simply includes IP addresses that are
-
# guaranteed by the IP specification to be private addresses. Those will
-
# not be the ultimate client IP in production, and so are discarded. See
-
# http://en.wikipedia.org/wiki/Private_network for details.
-
2
TRUSTED_PROXIES = %r{
-
^127\.0\.0\.1$ | # localhost IPv4
-
^::1$ | # localhost IPv6
-
^fc00: | # private IPv6 range fc00
-
^10\. | # private IPv4 range 10.x.x.x
-
^172\.(1[6-9]|2[0-9]|3[0-1])\.| # private IPv4 range 172.16.0.0 .. 172.31.255.255
-
^192\.168\. # private IPv4 range 192.168.x.x
-
}x
-
-
2
attr_reader :check_ip, :proxies
-
-
# Create a new +RemoteIp+ middleware instance.
-
#
-
# The +check_ip_spoofing+ option is on by default. When on, an exception
-
# is raised if it looks like the client is trying to lie about its own IP
-
# address. It makes sense to turn off this check on sites aimed at non-IP
-
# clients (like WAP devices), or behind proxies that set headers in an
-
# incorrect or confusing way (like AWS ELB).
-
#
-
# The +custom_proxies+ argument can take a regex, which will be used
-
# instead of +TRUSTED_PROXIES+, or a string, which will be used in addition
-
# to +TRUSTED_PROXIES+. Any proxy setup will put the value you want in the
-
# middle (or at the beginning) of the X-Forwarded-For list, with your proxy
-
# servers after it. If your proxies aren't removed, pass them in via the
-
# +custom_proxies+ parameter. That way, the middleware will ignore those
-
# IP addresses, and return the one that you want.
-
2
def initialize(app, check_ip_spoofing = true, custom_proxies = nil)
-
2
@app = app
-
2
@check_ip = check_ip_spoofing
-
2
@proxies = case custom_proxies
-
when Regexp
-
custom_proxies
-
when nil
-
2
TRUSTED_PROXIES
-
else
-
Regexp.union(TRUSTED_PROXIES, custom_proxies)
-
end
-
end
-
-
# Since the IP address may not be needed, we store the object here
-
# without calculating the IP to keep from slowing down the majority of
-
# requests. For those requests that do need to know the IP, the
-
# GetIp#calculate_ip method will calculate the memoized client IP address.
-
2
def call(env)
-
13
env["action_dispatch.remote_ip"] = GetIp.new(env, self)
-
13
@app.call(env)
-
end
-
-
# The GetIp class exists as a way to defer processing of the request data
-
# into an actual IP address. If the ActionDispatch::Request#remote_ip method
-
# is called, this class will calculate the value and then memoize it.
-
2
class GetIp
-
-
# This constant contains a regular expression that validates every known
-
# form of IP v4 and v6 address, with or without abbreviations, adapted
-
# from {this gist}[https://gist.github.com/gazay/1289635].
-
2
VALID_IP = %r{
-
(^(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[0-9]{1,2})(\.(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[0-9]{1,2})){3}$) | # ip v4
-
(^(
-
(([0-9A-Fa-f]{1,4}:){7}[0-9A-Fa-f]{1,4}) | # ip v6 not abbreviated
-
(([0-9A-Fa-f]{1,4}:){6}:[0-9A-Fa-f]{1,4}) | # ip v6 with double colon in the end
-
(([0-9A-Fa-f]{1,4}:){5}:([0-9A-Fa-f]{1,4}:)?[0-9A-Fa-f]{1,4}) | # - ip addresses v6
-
(([0-9A-Fa-f]{1,4}:){4}:([0-9A-Fa-f]{1,4}:){0,2}[0-9A-Fa-f]{1,4}) | # - with
-
(([0-9A-Fa-f]{1,4}:){3}:([0-9A-Fa-f]{1,4}:){0,3}[0-9A-Fa-f]{1,4}) | # - double colon
-
(([0-9A-Fa-f]{1,4}:){2}:([0-9A-Fa-f]{1,4}:){0,4}[0-9A-Fa-f]{1,4}) | # - in the middle
-
(([0-9A-Fa-f]{1,4}:){6} ((\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b)\.){3} (\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b)) | # ip v6 with compatible to v4
-
(([0-9A-Fa-f]{1,4}:){1,5}:((\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b)\.){3}(\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b)) | # ip v6 with compatible to v4
-
(([0-9A-Fa-f]{1,4}:){1}:([0-9A-Fa-f]{1,4}:){0,4}((\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b)\.){3}(\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b)) | # ip v6 with compatible to v4
-
(([0-9A-Fa-f]{1,4}:){0,2}:([0-9A-Fa-f]{1,4}:){0,3}((\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b)\.){3}(\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b)) | # ip v6 with compatible to v4
-
(([0-9A-Fa-f]{1,4}:){0,3}:([0-9A-Fa-f]{1,4}:){0,2}((\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b)\.){3}(\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b)) | # ip v6 with compatible to v4
-
(([0-9A-Fa-f]{1,4}:){0,4}:([0-9A-Fa-f]{1,4}:){1}((\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b)\.){3}(\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b)) | # ip v6 with compatible to v4
-
(::([0-9A-Fa-f]{1,4}:){0,5}((\b((25[0-5])|(1\d{2})|(2[0-4]\d) |(\d{1,2}))\b)\.){3}(\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b)) | # ip v6 with compatible to v4
-
([0-9A-Fa-f]{1,4}::([0-9A-Fa-f]{1,4}:){0,5}[0-9A-Fa-f]{1,4}) | # ip v6 with compatible to v4
-
(::([0-9A-Fa-f]{1,4}:){0,6}[0-9A-Fa-f]{1,4}) | # ip v6 with double colon at the beginning
-
(([0-9A-Fa-f]{1,4}:){1,7}:) # ip v6 without ending
-
)$)
-
}x
-
-
2
def initialize(env, middleware)
-
13
@env = env
-
13
@check_ip = middleware.check_ip
-
13
@proxies = middleware.proxies
-
end
-
-
# Sort through the various IP address headers, looking for the IP most
-
# likely to be the address of the actual remote client making this
-
# request.
-
#
-
# REMOTE_ADDR will be correct if the request is made directly against the
-
# Ruby process, on e.g. Heroku. When the request is proxied by another
-
# server like HAProxy or Nginx, the IP address that made the original
-
# request will be put in an X-Forwarded-For header. If there are multiple
-
# proxies, that header may contain a list of IPs. Other proxy services
-
# set the Client-Ip header instead, so we check that too.
-
#
-
# As discussed in {this post about Rails IP Spoofing}[http://blog.gingerlime.com/2012/rails-ip-spoofing-vulnerabilities-and-protection/],
-
# while the first IP in the list is likely to be the "originating" IP,
-
# it could also have been set by the client maliciously.
-
#
-
# In order to find the first address that is (probably) accurate, we
-
# take the list of IPs, remove known and trusted proxies, and then take
-
# the last address left, which was presumably set by one of those proxies.
-
2
def calculate_ip
-
# Set by the Rack web server, this is a single value.
-
remote_addr = ips_from('REMOTE_ADDR').last
-
-
# Could be a CSV list and/or repeated headers that were concatenated.
-
client_ips = ips_from('HTTP_CLIENT_IP').reverse
-
forwarded_ips = ips_from('HTTP_X_FORWARDED_FOR').reverse
-
-
# +Client-Ip+ and +X-Forwarded-For+ should not, generally, both be set.
-
# If they are both set, it means that this request passed through two
-
# proxies with incompatible IP header conventions, and there is no way
-
# for us to determine which header is the right one after the fact.
-
# Since we have no idea, we give up and explode.
-
should_check_ip = @check_ip && client_ips.last && forwarded_ips.last
-
if should_check_ip && !forwarded_ips.include?(client_ips.last)
-
# We don't know which came from the proxy, and which from the user
-
raise IpSpoofAttackError, "IP spoofing attack?! " +
-
"HTTP_CLIENT_IP=#{@env['HTTP_CLIENT_IP'].inspect} " +
-
"HTTP_X_FORWARDED_FOR=#{@env['HTTP_X_FORWARDED_FOR'].inspect}"
-
end
-
-
# We assume these things about the IP headers:
-
#
-
# - X-Forwarded-For will be a list of IPs, one per proxy, or blank
-
# - Client-Ip is propagated from the outermost proxy, or is blank
-
# - REMOTE_ADDR will be the IP that made the request to Rack
-
ips = [forwarded_ips, client_ips, remote_addr].flatten.compact
-
-
# If every single IP option is in the trusted list, just return REMOTE_ADDR
-
filter_proxies(ips).first || remote_addr
-
end
-
-
# Memoizes the value returned by #calculate_ip and returns it for
-
# ActionDispatch::Request to use.
-
2
def to_s
-
@ip ||= calculate_ip
-
end
-
-
2
protected
-
-
2
def ips_from(header)
-
# Split the comma-separated list into an array of strings
-
ips = @env[header] ? @env[header].strip.split(/[,\s]+/) : []
-
# Only return IPs that are valid according to the regex
-
ips.select{ |ip| ip =~ VALID_IP }
-
end
-
-
2
def filter_proxies(ips)
-
ips.reject { |ip| ip =~ @proxies }
-
end
-
-
end
-
-
end
-
end
-
2
require 'securerandom'
-
2
require 'active_support/core_ext/string/access'
-
-
2
module ActionDispatch
-
# Makes a unique request id available to the action_dispatch.request_id env variable (which is then accessible through
-
# ActionDispatch::Request#uuid) and sends the same id to the client via the X-Request-Id header.
-
#
-
# The unique request id is either based off the X-Request-Id header in the request, which would typically be generated
-
# by a firewall, load balancer, or the web server, or, if this header is not available, a random uuid. If the
-
# header is accepted from the outside world, we sanitize it to a max of 255 chars and alphanumeric and dashes only.
-
#
-
# The unique request id can be used to trace a request end-to-end and would typically end up being part of log files
-
# from multiple pieces of the stack.
-
2
class RequestId
-
2
def initialize(app)
-
2
@app = app
-
end
-
-
2
def call(env)
-
13
env["action_dispatch.request_id"] = external_request_id(env) || internal_request_id
-
26
@app.call(env).tap { |_status, headers, _body| headers["X-Request-Id"] = env["action_dispatch.request_id"] }
-
end
-
-
2
private
-
2
def external_request_id(env)
-
13
if request_id = env["HTTP_X_REQUEST_ID"].presence
-
request_id.gsub(/[^\w\-]/, "").first(255)
-
end
-
end
-
-
2
def internal_request_id
-
13
SecureRandom.uuid
-
end
-
end
-
end
-
2
require 'rack/utils'
-
2
require 'rack/request'
-
2
require 'rack/session/abstract/id'
-
2
require 'action_dispatch/middleware/cookies'
-
2
require 'action_dispatch/request/session'
-
-
2
module ActionDispatch
-
2
module Session
-
2
class SessionRestoreError < StandardError #:nodoc:
-
2
attr_reader :original_exception
-
-
2
def initialize(const_error)
-
@original_exception = const_error
-
-
super("Session contains objects whose class definition isn't available.\n" +
-
"Remember to require the classes for all objects kept in the session.\n" +
-
"(Original exception: #{const_error.message} [#{const_error.class}])\n")
-
end
-
end
-
-
2
module Compatibility
-
2
def initialize(app, options = {})
-
2
options[:key] ||= '_session_id'
-
2
super
-
end
-
-
2
def generate_sid
-
2
sid = SecureRandom.hex(16)
-
2
sid.encode!(Encoding::UTF_8)
-
2
sid
-
end
-
-
2
protected
-
-
2
def initialize_sid
-
2
@default_options.delete(:sidbits)
-
2
@default_options.delete(:secure_random)
-
end
-
end
-
-
2
module StaleSessionCheck
-
2
def load_session(env)
-
stale_session_check! { super }
-
end
-
-
2
def extract_session_id(env)
-
stale_session_check! { super }
-
end
-
-
2
def stale_session_check!
-
28
yield
-
rescue ArgumentError => argument_error
-
if argument_error.message =~ %r{undefined class/module ([\w:]*\w)}
-
begin
-
# Note that the regexp does not allow $1 to end with a ':'
-
$1.constantize
-
rescue LoadError, NameError => e
-
raise ActionDispatch::Session::SessionRestoreError, e, e.backtrace
-
end
-
retry
-
else
-
raise
-
end
-
end
-
end
-
-
2
module SessionObject # :nodoc:
-
2
def prepare_session(env)
-
13
Request::Session.create(self, env, @default_options)
-
end
-
-
2
def loaded_session?(session)
-
15
!session.is_a?(Request::Session) || session.loaded?
-
end
-
end
-
-
2
class AbstractStore < Rack::Session::Abstract::ID
-
2
include Compatibility
-
2
include StaleSessionCheck
-
2
include SessionObject
-
-
2
private
-
-
2
def set_cookie(env, session_id, cookie)
-
request = ActionDispatch::Request.new(env)
-
request.cookie_jar[key] = cookie
-
end
-
end
-
end
-
end
-
2
require 'active_support/core_ext/hash/keys'
-
2
require 'action_dispatch/middleware/session/abstract_store'
-
2
require 'rack/session/cookie'
-
-
2
module ActionDispatch
-
2
module Session
-
# This cookie-based session store is the Rails default. It is
-
# dramatically faster than the alternatives.
-
#
-
# Sessions typically contain at most a user_id and flash message; both fit
-
# within the 4K cookie size limit. A CookieOverflow exception is raised if
-
# you attempt to store more than 4K of data.
-
#
-
# The cookie jar used for storage is automatically configured to be the
-
# best possible option given your application's configuration.
-
#
-
# If you only have secret_token set, your cookies will be signed, but
-
# not encrypted. This means a user cannot alter their +user_id+ without
-
# knowing your app's secret key, but can easily read their +user_id+. This
-
# was the default for Rails 3 apps.
-
#
-
# If you have secret_key_base set, your cookies will be encrypted. This
-
# goes a step further than signed cookies in that encrypted cookies cannot
-
# be altered or read by users. This is the default starting in Rails 4.
-
#
-
# If you have both secret_token and secret_key base set, your cookies will
-
# be encrypted, and signed cookies generated by Rails 3 will be
-
# transparently read and encrypted to provide a smooth upgrade path.
-
#
-
# Configure your session store in config/initializers/session_store.rb:
-
#
-
# Rails.application.config.session_store :cookie_store, key: '_your_app_session'
-
#
-
# Configure your secret key in config/secrets.yml:
-
#
-
# development:
-
# secret_key_base: 'secret key'
-
#
-
# To generate a secret key for an existing application, run `rake secret`.
-
#
-
# If you are upgrading an existing Rails 3 app, you should leave your
-
# existing secret_token in place and simply add the new secret_key_base.
-
# Note that you should wait to set secret_key_base until you have 100% of
-
# your userbase on Rails 4 and are reasonably sure you will not need to
-
# rollback to Rails 3. This is because cookies signed based on the new
-
# secret_key_base in Rails 4 are not backwards compatible with Rails 3.
-
# You are free to leave your existing secret_token in place, not set the
-
# new secret_key_base, and ignore the deprecation warnings until you are
-
# reasonably sure that your upgrade is otherwise complete. Additionally,
-
# you should take care to make sure you are not relying on the ability to
-
# decode signed cookies generated by your app in external applications or
-
# Javascript before upgrading.
-
#
-
# Note that changing the secret key will invalidate all existing sessions!
-
2
class CookieStore < Rack::Session::Abstract::ID
-
2
include Compatibility
-
2
include StaleSessionCheck
-
2
include SessionObject
-
-
2
def initialize(app, options={})
-
2
super(app, options.merge!(:cookie_only => true))
-
end
-
-
2
def destroy_session(env, session_id, options)
-
new_sid = generate_sid unless options[:drop]
-
# Reset hash and Assign the new session id
-
env["action_dispatch.request.unsigned_session_cookie"] = new_sid ? { "session_id" => new_sid } : {}
-
new_sid
-
end
-
-
2
def load_session(env)
-
2
stale_session_check! do
-
2
data = unpacked_cookie_data(env)
-
2
data = persistent_session_id!(data)
-
2
[data["session_id"], data]
-
end
-
end
-
-
2
private
-
-
2
def extract_session_id(env)
-
13
stale_session_check! do
-
13
unpacked_cookie_data(env)["session_id"]
-
end
-
end
-
-
2
def unpacked_cookie_data(env)
-
15
env["action_dispatch.request.unsigned_session_cookie"] ||= begin
-
13
stale_session_check! do
-
13
if data = get_cookie(env)
-
data.stringify_keys!
-
end
-
13
data || {}
-
end
-
end
-
end
-
-
2
def persistent_session_id!(data, sid=nil)
-
2
data ||= {}
-
2
data["session_id"] ||= sid || generate_sid
-
2
data
-
end
-
-
2
def set_session(env, sid, session_data, options)
-
2
session_data["session_id"] = sid
-
2
session_data
-
end
-
-
2
def set_cookie(env, session_id, cookie)
-
2
cookie_jar(env)[@key] = cookie
-
end
-
-
2
def get_cookie(env)
-
13
cookie_jar(env)[@key]
-
end
-
-
2
def cookie_jar(env)
-
15
request = ActionDispatch::Request.new(env)
-
15
request.cookie_jar.signed_or_encrypted
-
end
-
end
-
end
-
end
-
2
require 'action_dispatch/http/request'
-
2
require 'action_dispatch/middleware/exception_wrapper'
-
-
2
module ActionDispatch
-
# This middleware rescues any exception returned by the application
-
# and calls an exceptions app that will wrap it in a format for the end user.
-
#
-
# The exceptions app should be passed as parameter on initialization
-
# of ShowExceptions. Every time there is an exception, ShowExceptions will
-
# store the exception in env["action_dispatch.exception"], rewrite the
-
# PATH_INFO to the exception status code and call the rack app.
-
#
-
# If the application returns a "X-Cascade" pass response, this middleware
-
# will send an empty response as result with the correct status code.
-
# If any exception happens inside the exceptions app, this middleware
-
# catches the exceptions and returns a FAILSAFE_RESPONSE.
-
2
class ShowExceptions
-
2
FAILSAFE_RESPONSE = [500, { 'Content-Type' => 'text/plain' },
-
["500 Internal Server Error\n" \
-
"If you are the administrator of this website, then please read this web " \
-
"application's log file and/or the web server's log file to find out what " \
-
"went wrong."]]
-
-
2
def initialize(app, exceptions_app)
-
2
@app = app
-
2
@exceptions_app = exceptions_app
-
end
-
-
2
def call(env)
-
13
@app.call(env)
-
rescue Exception => exception
-
if env['action_dispatch.show_exceptions'] == false
-
raise exception
-
else
-
render_exception(env, exception)
-
end
-
end
-
-
2
private
-
-
2
def render_exception(env, exception)
-
wrapper = ExceptionWrapper.new(env, exception)
-
status = wrapper.status_code
-
env["action_dispatch.exception"] = wrapper.exception
-
env["PATH_INFO"] = "/#{status}"
-
response = @exceptions_app.call(env)
-
response[1]['X-Cascade'] == 'pass' ? pass_response(status) : response
-
rescue Exception => failsafe_error
-
$stderr.puts "Error during failsafe response: #{failsafe_error}\n #{failsafe_error.backtrace * "\n "}"
-
FAILSAFE_RESPONSE
-
end
-
-
2
def pass_response(status)
-
[status, {"Content-Type" => "text/html; charset=#{Response.default_charset}", "Content-Length" => "0"}, []]
-
end
-
end
-
end
-
2
require "active_support/inflector/methods"
-
2
require "active_support/dependencies"
-
-
2
module ActionDispatch
-
2
class MiddlewareStack
-
2
class Middleware
-
2
attr_reader :args, :block, :name, :classcache
-
-
2
def initialize(klass_or_name, *args, &block)
-
42
@klass = nil
-
-
42
if klass_or_name.respond_to?(:name)
-
38
@klass = klass_or_name
-
38
@name = @klass.name
-
else
-
4
@name = klass_or_name.to_s
-
end
-
-
42
@classcache = ActiveSupport::Dependencies::Reference
-
42
@args, @block = args, block
-
end
-
-
2
def klass
-
42
@klass || classcache[@name]
-
end
-
-
2
def ==(middleware)
-
46
case middleware
-
when Middleware
-
klass == middleware.klass
-
when Class
-
klass == middleware
-
else
-
46
normalize(@name) == normalize(middleware)
-
end
-
end
-
-
2
def inspect
-
klass.to_s
-
end
-
-
2
def build(app)
-
42
klass.new(app, *args, &block)
-
end
-
-
2
private
-
-
2
def normalize(object)
-
92
object.to_s.strip.sub(/^::/, '')
-
end
-
end
-
-
2
include Enumerable
-
-
2
attr_accessor :middlewares
-
-
2
def initialize(*args)
-
4
@middlewares = []
-
4
yield(self) if block_given?
-
end
-
-
2
def each
-
@middlewares.each { |x| yield x }
-
end
-
-
2
def size
-
middlewares.size
-
end
-
-
2
def last
-
middlewares.last
-
end
-
-
2
def [](i)
-
middlewares[i]
-
end
-
-
2
def unshift(*args, &block)
-
middleware = self.class::Middleware.new(*args, &block)
-
middlewares.unshift(middleware)
-
end
-
-
2
def initialize_copy(other)
-
15
self.middlewares = other.middlewares.dup
-
end
-
-
2
def insert(index, *args, &block)
-
6
index = assert_index(index, :before)
-
6
middleware = self.class::Middleware.new(*args, &block)
-
6
middlewares.insert(index, middleware)
-
end
-
-
2
alias_method :insert_before, :insert
-
-
2
def insert_after(index, *args, &block)
-
4
index = assert_index(index, :after)
-
4
insert(index + 1, *args, &block)
-
end
-
-
2
def swap(target, *args, &block)
-
index = assert_index(target, :before)
-
insert(index, *args, &block)
-
middlewares.delete_at(index + 1)
-
end
-
-
2
def delete(target)
-
middlewares.delete target
-
end
-
-
2
def use(*args, &block)
-
36
middleware = self.class::Middleware.new(*args, &block)
-
36
middlewares.push(middleware)
-
end
-
-
2
def build(app = nil, &block)
-
2
app ||= block
-
2
raise "MiddlewareStack#build requires an app" unless app
-
44
middlewares.freeze.reverse.inject(app) { |a, e| e.build(a) }
-
end
-
-
2
protected
-
-
2
def assert_index(index, where)
-
10
i = index.is_a?(Integer) ? index : middlewares.index(index)
-
10
raise "No such middleware to insert #{where}: #{index.inspect}" unless i
-
10
i
-
end
-
end
-
end
-
2
require 'rack/utils'
-
2
require 'active_support/core_ext/uri'
-
-
2
module ActionDispatch
-
2
class FileHandler
-
2
def initialize(root, cache_control)
-
2
@root = root.chomp('/')
-
2
@compiled_root = /^#{Regexp.escape(root)}/
-
2
headers = cache_control && { 'Cache-Control' => cache_control }
-
2
@file_server = ::Rack::File.new(@root, headers)
-
end
-
-
2
def match?(path)
-
9
path = unescape_path(path)
-
9
return false unless path.valid_encoding?
-
-
9
full_path = path.empty? ? @root : File.join(@root,
-
clean_path_info(escape_glob_chars(path)))
-
9
paths = "#{full_path}#{ext}"
-
-
9
matches = Dir[paths]
-
9
match = matches.detect { |m| File.file?(m) && File.readable?(m) }
-
9
if match
-
match.sub!(@compiled_root, '')
-
::Rack::Utils.escape(match)
-
end
-
end
-
-
2
def call(env)
-
@file_server.call(env)
-
end
-
-
2
def ext
-
@ext ||= begin
-
1
ext = ::ActionController::Base.default_static_extension
-
1
"{,#{ext},/index#{ext}}"
-
9
end
-
end
-
-
2
def unescape_path(path)
-
9
URI.parser.unescape(path)
-
end
-
-
2
def escape_glob_chars(path)
-
9
path.gsub(/[*?{}\[\]\\]/, "\\\\\\&")
-
end
-
-
2
private
-
-
2
PATH_SEPS = Regexp.union(*[::File::SEPARATOR, ::File::ALT_SEPARATOR].compact)
-
-
2
def clean_path_info(path_info)
-
9
parts = path_info.split PATH_SEPS
-
-
9
clean = []
-
-
9
parts.each do |part|
-
27
next if part.empty? || part == '.'
-
18
part == '..' ? clean.pop : clean << part
-
end
-
-
9
clean.unshift '/' if parts.empty? || parts.first.empty?
-
-
9
::File.join(*clean)
-
end
-
end
-
-
2
class Static
-
2
def initialize(app, path, cache_control=nil)
-
2
@app = app
-
2
@file_handler = FileHandler.new(path, cache_control)
-
end
-
-
2
def call(env)
-
13
case env['REQUEST_METHOD']
-
when 'GET', 'HEAD'
-
9
path = env['PATH_INFO'].chomp('/')
-
9
if match = @file_handler.match?(path)
-
env["PATH_INFO"] = match
-
return @file_handler.call(env)
-
end
-
end
-
-
13
@app.call(env)
-
end
-
end
-
end
-
2
require "action_dispatch"
-
-
2
module ActionDispatch
-
2
class Railtie < Rails::Railtie # :nodoc:
-
2
config.action_dispatch = ActiveSupport::OrderedOptions.new
-
2
config.action_dispatch.x_sendfile_header = nil
-
2
config.action_dispatch.ip_spoofing_check = true
-
2
config.action_dispatch.show_exceptions = true
-
2
config.action_dispatch.tld_length = 1
-
2
config.action_dispatch.ignore_accept_header = false
-
2
config.action_dispatch.rescue_templates = { }
-
2
config.action_dispatch.rescue_responses = { }
-
2
config.action_dispatch.default_charset = nil
-
2
config.action_dispatch.rack_cache = false
-
2
config.action_dispatch.http_auth_salt = 'http authentication'
-
2
config.action_dispatch.signed_cookie_salt = 'signed cookie'
-
2
config.action_dispatch.encrypted_cookie_salt = 'encrypted cookie'
-
2
config.action_dispatch.encrypted_signed_cookie_salt = 'signed encrypted cookie'
-
2
config.action_dispatch.perform_deep_munge = true
-
-
2
config.action_dispatch.default_headers = {
-
'X-Frame-Options' => 'SAMEORIGIN',
-
'X-XSS-Protection' => '1; mode=block',
-
'X-Content-Type-Options' => 'nosniff'
-
}
-
-
2
config.eager_load_namespaces << ActionDispatch
-
-
2
initializer "action_dispatch.configure" do |app|
-
2
ActionDispatch::Http::URL.tld_length = app.config.action_dispatch.tld_length
-
2
ActionDispatch::Request.ignore_accept_header = app.config.action_dispatch.ignore_accept_header
-
2
ActionDispatch::Request::Utils.perform_deep_munge = app.config.action_dispatch.perform_deep_munge
-
2
ActionDispatch::Response.default_charset = app.config.action_dispatch.default_charset || app.config.encoding
-
2
ActionDispatch::Response.default_headers = app.config.action_dispatch.default_headers
-
-
2
ActionDispatch::ExceptionWrapper.rescue_responses.merge!(config.action_dispatch.rescue_responses)
-
2
ActionDispatch::ExceptionWrapper.rescue_templates.merge!(config.action_dispatch.rescue_templates)
-
-
2
config.action_dispatch.always_write_cookie = Rails.env.development? if config.action_dispatch.always_write_cookie.nil?
-
2
ActionDispatch::Cookies::CookieJar.always_write_cookie = config.action_dispatch.always_write_cookie
-
-
2
ActionDispatch.test_app = app
-
end
-
end
-
end
-
2
require 'rack/session/abstract/id'
-
-
2
module ActionDispatch
-
2
class Request < Rack::Request
-
# Session is responsible for lazily loading the session from store.
-
2
class Session # :nodoc:
-
2
ENV_SESSION_KEY = Rack::Session::Abstract::ENV_SESSION_KEY # :nodoc:
-
2
ENV_SESSION_OPTIONS_KEY = Rack::Session::Abstract::ENV_SESSION_OPTIONS_KEY # :nodoc:
-
-
# Singleton object used to determine if an optional param wasn't specified
-
2
Unspecified = Object.new
-
-
2
def self.create(store, env, default_options)
-
13
session_was = find env
-
13
session = Request::Session.new(store, env)
-
13
session.merge! session_was if session_was
-
-
13
set(env, session)
-
13
Options.set(env, Request::Session::Options.new(store, env, default_options))
-
13
session
-
end
-
-
2
def self.find(env)
-
26
env[ENV_SESSION_KEY]
-
end
-
-
2
def self.set(env, session)
-
28
env[ENV_SESSION_KEY] = session
-
end
-
-
2
class Options #:nodoc:
-
2
def self.set(env, options)
-
28
env[ENV_SESSION_OPTIONS_KEY] = options
-
end
-
-
2
def self.find(env)
-
45
env[ENV_SESSION_OPTIONS_KEY]
-
end
-
-
2
def initialize(by, env, default_options)
-
13
@by = by
-
13
@env = env
-
13
@delegate = default_options.dup
-
end
-
-
2
def [](key)
-
75
if key == :id
-
30
@delegate.fetch(key) {
-
13
@delegate[:id] = @by.send(:extract_session_id, @env)
-
}
-
else
-
45
@delegate[key]
-
end
-
end
-
-
4
def []=(k,v); @delegate[k] = v; end
-
4
def to_hash; @delegate.dup; end
-
13
def values_at(*args); @delegate.values_at(*args); end
-
end
-
-
2
def initialize(by, env)
-
13
@by = by
-
13
@env = env
-
13
@delegate = {}
-
13
@loaded = false
-
13
@exists = nil # we haven't checked yet
-
end
-
-
2
def id
-
30
options[:id]
-
end
-
-
2
def options
-
45
Options.find @env
-
end
-
-
2
def destroy
-
clear
-
options = self.options || {}
-
new_sid = @by.send(:destroy_session, @env, options[:id], options)
-
options[:id] = new_sid # Reset session id with a new value or nil
-
-
# Load the new sid to be written with the response
-
@loaded = false
-
load_for_write!
-
end
-
-
2
def [](key)
-
30
load_for_read!
-
30
@delegate[key.to_s]
-
end
-
-
2
def has_key?(key)
-
2
load_for_read!
-
2
@delegate.key?(key.to_s)
-
end
-
2
alias :key? :has_key?
-
2
alias :include? :has_key?
-
-
2
def keys
-
@delegate.keys
-
end
-
-
2
def values
-
@delegate.values
-
end
-
-
2
def []=(key, value)
-
2
load_for_write!
-
2
@delegate[key.to_s] = value
-
end
-
-
2
def clear
-
load_for_write!
-
@delegate.clear
-
end
-
-
2
def to_hash
-
2
load_for_read!
-
6
@delegate.dup.delete_if { |_,v| v.nil? }
-
end
-
-
2
def update(hash)
-
load_for_write!
-
@delegate.update stringify_keys(hash)
-
end
-
-
2
def delete(key)
-
load_for_write!
-
@delegate.delete key.to_s
-
end
-
-
2
def fetch(key, default=Unspecified, &block)
-
load_for_read!
-
if default == Unspecified
-
@delegate.fetch(key.to_s, &block)
-
else
-
@delegate.fetch(key.to_s, default, &block)
-
end
-
end
-
-
2
def inspect
-
if loaded?
-
super
-
else
-
"#<#{self.class}:0x#{(object_id << 1).to_s(16)} not yet loaded>"
-
end
-
end
-
-
2
def exists?
-
28
return @exists unless @exists.nil?
-
28
@exists = @by.send(:session_exists?, @env)
-
end
-
-
2
def loaded?
-
64
@loaded
-
end
-
-
2
def empty?
-
load_for_read!
-
@delegate.empty?
-
end
-
-
2
def merge!(other)
-
load_for_write!
-
@delegate.merge!(other)
-
end
-
-
2
private
-
-
2
def load_for_read!
-
34
load! if !loaded? && exists?
-
end
-
-
2
def load_for_write!
-
2
load! unless loaded?
-
end
-
-
2
def load!
-
2
id, session = @by.load_session @env
-
2
options[:id] = id
-
2
@delegate.replace(stringify_keys(session))
-
2
@loaded = true
-
end
-
-
2
def stringify_keys(other)
-
2
other.each_with_object({}) { |(key, value), hash|
-
2
hash[key.to_s] = value
-
}
-
end
-
end
-
end
-
end
-
2
module ActionDispatch
-
2
class Request < Rack::Request
-
2
class Utils # :nodoc:
-
-
2
mattr_accessor :perform_deep_munge
-
2
self.perform_deep_munge = true
-
-
2
class << self
-
# Remove nils from the params hash
-
2
def deep_munge(hash, keys = [])
-
54
return hash unless perform_deep_munge
-
-
54
hash.each do |k, v|
-
28
keys << k
-
28
case v
-
when Array
-
v.grep(Hash) { |x| deep_munge(x, keys) }
-
v.compact!
-
if v.empty?
-
hash[k] = nil
-
ActiveSupport::Notifications.instrument("deep_munge.action_controller", keys: keys)
-
end
-
when Hash
-
4
deep_munge(v, keys)
-
end
-
28
keys.pop
-
end
-
-
54
hash
-
end
-
end
-
end
-
end
-
end
-
-
# encoding: UTF-8
-
2
require 'active_support/core_ext/object/to_param'
-
2
require 'active_support/core_ext/regexp'
-
2
require 'active_support/dependencies/autoload'
-
-
2
module ActionDispatch
-
# The routing module provides URL rewriting in native Ruby. It's a way to
-
# redirect incoming requests to controllers and actions. This replaces
-
# mod_rewrite rules. Best of all, Rails' \Routing works with any web server.
-
# Routes are defined in <tt>config/routes.rb</tt>.
-
#
-
# Think of creating routes as drawing a map for your requests. The map tells
-
# them where to go based on some predefined pattern:
-
#
-
# Rails.application.routes.draw do
-
# Pattern 1 tells some request to go to one place
-
# Pattern 2 tell them to go to another
-
# ...
-
# end
-
#
-
# The following symbols are special:
-
#
-
# :controller maps to your controller name
-
# :action maps to an action with your controllers
-
#
-
# Other names simply map to a parameter as in the case of <tt>:id</tt>.
-
#
-
# == Resources
-
#
-
# Resource routing allows you to quickly declare all of the common routes
-
# for a given resourceful controller. Instead of declaring separate routes
-
# for your +index+, +show+, +new+, +edit+, +create+, +update+ and +destroy+
-
# actions, a resourceful route declares them in a single line of code:
-
#
-
# resources :photos
-
#
-
# Sometimes, you have a resource that clients always look up without
-
# referencing an ID. A common example, /profile always shows the profile of
-
# the currently logged in user. In this case, you can use a singular resource
-
# to map /profile (rather than /profile/:id) to the show action.
-
#
-
# resource :profile
-
#
-
# It's common to have resources that are logically children of other
-
# resources:
-
#
-
# resources :magazines do
-
# resources :ads
-
# end
-
#
-
# You may wish to organize groups of controllers under a namespace. Most
-
# commonly, you might group a number of administrative controllers under
-
# an +admin+ namespace. You would place these controllers under the
-
# <tt>app/controllers/admin</tt> directory, and you can group them together
-
# in your router:
-
#
-
# namespace "admin" do
-
# resources :posts, :comments
-
# end
-
#
-
# Alternately, you can add prefixes to your path without using a separate
-
# directory by using +scope+. +scope+ takes additional options which
-
# apply to all enclosed routes.
-
#
-
# scope path: "/cpanel", as: 'admin' do
-
# resources :posts, :comments
-
# end
-
#
-
# For more, see <tt>Routing::Mapper::Resources#resources</tt>,
-
# <tt>Routing::Mapper::Scoping#namespace</tt>, and
-
# <tt>Routing::Mapper::Scoping#scope</tt>.
-
#
-
# == Non-resourceful routes
-
#
-
# For routes that don't fit the <tt>resources</tt> mold, you can use the HTTP helper
-
# methods <tt>get</tt>, <tt>post</tt>, <tt>patch</tt>, <tt>put</tt> and <tt>delete</tt>.
-
#
-
# get 'post/:id' => 'posts#show'
-
# post 'post/:id' => 'posts#create_comment'
-
#
-
# If your route needs to respond to more than one HTTP method (or all methods) then using the
-
# <tt>:via</tt> option on <tt>match</tt> is preferable.
-
#
-
# match 'post/:id' => 'posts#show', via: [:get, :post]
-
#
-
# Now, if you POST to <tt>/posts/:id</tt>, it will route to the <tt>create_comment</tt> action. A GET on the same
-
# URL will route to the <tt>show</tt> action.
-
#
-
# == Named routes
-
#
-
# Routes can be named by passing an <tt>:as</tt> option,
-
# allowing for easy reference within your source as +name_of_route_url+
-
# for the full URL and +name_of_route_path+ for the URI path.
-
#
-
# Example:
-
#
-
# # In routes.rb
-
# get '/login' => 'accounts#login', as: 'login'
-
#
-
# # With render, redirect_to, tests, etc.
-
# redirect_to login_url
-
#
-
# Arguments can be passed as well.
-
#
-
# redirect_to show_item_path(id: 25)
-
#
-
# Use <tt>root</tt> as a shorthand to name a route for the root path "/".
-
#
-
# # In routes.rb
-
# root to: 'blogs#index'
-
#
-
# # would recognize http://www.example.com/ as
-
# params = { controller: 'blogs', action: 'index' }
-
#
-
# # and provide these named routes
-
# root_url # => 'http://www.example.com/'
-
# root_path # => '/'
-
#
-
# Note: when using +controller+, the route is simply named after the
-
# method you call on the block parameter rather than map.
-
#
-
# # In routes.rb
-
# controller :blog do
-
# get 'blog/show' => :list
-
# get 'blog/delete' => :delete
-
# get 'blog/edit/:id' => :edit
-
# end
-
#
-
# # provides named routes for show, delete, and edit
-
# link_to @article.title, show_path(id: @article.id)
-
#
-
# == Pretty URLs
-
#
-
# Routes can generate pretty URLs. For example:
-
#
-
# get '/articles/:year/:month/:day' => 'articles#find_by_id', constraints: {
-
# year: /\d{4}/,
-
# month: /\d{1,2}/,
-
# day: /\d{1,2}/
-
# }
-
#
-
# Using the route above, the URL "http://localhost:3000/articles/2005/11/06"
-
# maps to
-
#
-
# params = {year: '2005', month: '11', day: '06'}
-
#
-
# == Regular Expressions and parameters
-
# You can specify a regular expression to define a format for a parameter.
-
#
-
# controller 'geocode' do
-
# get 'geocode/:postalcode' => :show, constraints: {
-
# postalcode: /\d{5}(-\d{4})?/
-
# }
-
#
-
# Constraints can include the 'ignorecase' and 'extended syntax' regular
-
# expression modifiers:
-
#
-
# controller 'geocode' do
-
# get 'geocode/:postalcode' => :show, constraints: {
-
# postalcode: /hx\d\d\s\d[a-z]{2}/i
-
# }
-
# end
-
#
-
# controller 'geocode' do
-
# get 'geocode/:postalcode' => :show, constraints: {
-
# postalcode: /# Postcode format
-
# \d{5} #Prefix
-
# (-\d{4})? #Suffix
-
# /x
-
# }
-
# end
-
#
-
# Using the multiline modifier will raise an +ArgumentError+.
-
# Encoding regular expression modifiers are silently ignored. The
-
# match will always use the default encoding or ASCII.
-
#
-
# == External redirects
-
#
-
# You can redirect any path to another path using the redirect helper in your router:
-
#
-
# get "/stories" => redirect("/posts")
-
#
-
# == Unicode character routes
-
#
-
# You can specify unicode character routes in your router:
-
#
-
# get "こんにちは" => "welcome#index"
-
#
-
# == Routing to Rack Applications
-
#
-
# Instead of a String, like <tt>posts#index</tt>, which corresponds to the
-
# index action in the PostsController, you can specify any Rack application
-
# as the endpoint for a matcher:
-
#
-
# get "/application.js" => Sprockets
-
#
-
# == Reloading routes
-
#
-
# You can reload routes if you feel you must:
-
#
-
# Rails.application.reload_routes!
-
#
-
# This will clear all named routes and reload routes.rb if the file has been modified from
-
# last load. To absolutely force reloading, use <tt>reload!</tt>.
-
#
-
# == Testing Routes
-
#
-
# The two main methods for testing your routes:
-
#
-
# === +assert_routing+
-
#
-
# def test_movie_route_properly_splits
-
# opts = {controller: "plugin", action: "checkout", id: "2"}
-
# assert_routing "plugin/checkout/2", opts
-
# end
-
#
-
# +assert_routing+ lets you test whether or not the route properly resolves into options.
-
#
-
# === +assert_recognizes+
-
#
-
# def test_route_has_options
-
# opts = {controller: "plugin", action: "show", id: "12"}
-
# assert_recognizes opts, "/plugins/show/12"
-
# end
-
#
-
# Note the subtle difference between the two: +assert_routing+ tests that
-
# a URL fits options while +assert_recognizes+ tests that a URL
-
# breaks into parameters properly.
-
#
-
# In tests you can simply pass the URL or named route to +get+ or +post+.
-
#
-
# def send_to_jail
-
# get '/jail'
-
# assert_response :success
-
# assert_template "jail/front"
-
# end
-
#
-
# def goes_to_login
-
# get login_url
-
# #...
-
# end
-
#
-
# == View a list of all your routes
-
#
-
# rake routes
-
#
-
# Target specific controllers by prefixing the command with <tt>CONTROLLER=x</tt>.
-
#
-
2
module Routing
-
2
extend ActiveSupport::Autoload
-
-
2
autoload :Mapper
-
2
autoload :RouteSet
-
2
autoload :RoutesProxy
-
2
autoload :UrlFor
-
2
autoload :PolymorphicRoutes
-
-
2
SEPARATORS = %w( / . ? ) #:nodoc:
-
2
HTTP_METHODS = [:get, :head, :post, :patch, :put, :delete, :options] #:nodoc:
-
end
-
end
-
2
require 'delegate'
-
2
require 'active_support/core_ext/string/strip'
-
-
2
module ActionDispatch
-
2
module Routing
-
2
class RouteWrapper < SimpleDelegator
-
2
def endpoint
-
rack_app ? rack_app.inspect : "#{controller}##{action}"
-
end
-
-
2
def constraints
-
requirements.except(:controller, :action)
-
end
-
-
2
def rack_app(app = self.app)
-
@rack_app ||= begin
-
class_name = app.class.name.to_s
-
if class_name == "ActionDispatch::Routing::Mapper::Constraints"
-
rack_app(app.app)
-
elsif ActionDispatch::Routing::Redirect === app || class_name !~ /^ActionDispatch::Routing/
-
app
-
end
-
end
-
end
-
-
2
def verb
-
super.source.gsub(/[$^]/, '')
-
end
-
-
2
def path
-
super.spec.to_s
-
end
-
-
2
def name
-
super.to_s
-
end
-
-
2
def regexp
-
__getobj__.path.to_regexp
-
end
-
-
2
def json_regexp
-
str = regexp.inspect.
-
sub('\\A' , '^').
-
sub('\\Z' , '$').
-
sub('\\z' , '$').
-
sub(/^\// , '').
-
sub(/\/[a-z]*$/ , '').
-
gsub(/\(\?#.+\)/ , '').
-
gsub(/\(\?-\w+:/ , '(').
-
gsub(/\s/ , '')
-
Regexp.new(str).source
-
end
-
-
2
def reqs
-
@reqs ||= begin
-
reqs = endpoint
-
reqs += " #{constraints.to_s}" unless constraints.empty?
-
reqs
-
end
-
end
-
-
2
def controller
-
requirements[:controller] || ':controller'
-
end
-
-
2
def action
-
requirements[:action] || ':action'
-
end
-
-
2
def internal?
-
controller.to_s =~ %r{\Arails/(info|mailers|welcome)} || path =~ %r{\A#{Rails.application.config.assets.prefix}\z}
-
end
-
-
2
def engine?
-
rack_app && rack_app.respond_to?(:routes)
-
end
-
end
-
-
##
-
# This class is just used for displaying route information when someone
-
# executes `rake routes` or looks at the RoutingError page.
-
# People should not use this class.
-
2
class RoutesInspector # :nodoc:
-
2
def initialize(routes)
-
@engines = {}
-
@routes = routes
-
end
-
-
2
def format(formatter, filter = nil)
-
routes_to_display = filter_routes(filter)
-
-
routes = collect_routes(routes_to_display)
-
-
if routes.none?
-
formatter.no_routes
-
return formatter.result
-
end
-
-
formatter.header routes
-
formatter.section routes
-
-
@engines.each do |name, engine_routes|
-
formatter.section_title "Routes for #{name}"
-
formatter.section engine_routes
-
end
-
-
formatter.result
-
end
-
-
2
private
-
-
2
def filter_routes(filter)
-
if filter
-
@routes.select { |route| route.defaults[:controller] == filter }
-
else
-
@routes
-
end
-
end
-
-
2
def collect_routes(routes)
-
routes.collect do |route|
-
RouteWrapper.new(route)
-
end.reject do |route|
-
route.internal?
-
end.collect do |route|
-
collect_engine_routes(route)
-
-
{ name: route.name,
-
verb: route.verb,
-
path: route.path,
-
reqs: route.reqs,
-
regexp: route.json_regexp }
-
end
-
end
-
-
2
def collect_engine_routes(route)
-
name = route.endpoint
-
return unless route.engine?
-
return if @engines[name]
-
-
routes = route.rack_app.routes
-
if routes.is_a?(ActionDispatch::Routing::RouteSet)
-
@engines[name] = collect_routes(routes.routes)
-
end
-
end
-
end
-
-
2
class ConsoleFormatter
-
2
def initialize
-
@buffer = []
-
end
-
-
2
def result
-
@buffer.join("\n")
-
end
-
-
2
def section_title(title)
-
@buffer << "\n#{title}:"
-
end
-
-
2
def section(routes)
-
@buffer << draw_section(routes)
-
end
-
-
2
def header(routes)
-
@buffer << draw_header(routes)
-
end
-
-
2
def no_routes
-
@buffer << <<-MESSAGE.strip_heredoc
-
You don't have any routes defined!
-
-
Please add some routes in config/routes.rb.
-
-
For more information about routes, see the Rails guide: http://guides.rubyonrails.org/routing.html.
-
MESSAGE
-
end
-
-
2
private
-
2
def draw_section(routes)
-
header_lengths = ['Prefix', 'Verb', 'URI Pattern'].map(&:length)
-
name_width, verb_width, path_width = widths(routes).zip(header_lengths).map(&:max)
-
-
routes.map do |r|
-
"#{r[:name].rjust(name_width)} #{r[:verb].ljust(verb_width)} #{r[:path].ljust(path_width)} #{r[:reqs]}"
-
end
-
end
-
-
2
def draw_header(routes)
-
name_width, verb_width, path_width = widths(routes)
-
-
"#{"Prefix".rjust(name_width)} #{"Verb".ljust(verb_width)} #{"URI Pattern".ljust(path_width)} Controller#Action"
-
end
-
-
2
def widths(routes)
-
[routes.map { |r| r[:name].length }.max || 0,
-
routes.map { |r| r[:verb].length }.max || 0,
-
routes.map { |r| r[:path].length }.max || 0]
-
end
-
end
-
-
2
class HtmlTableFormatter
-
2
def initialize(view)
-
@view = view
-
@buffer = []
-
end
-
-
2
def section_title(title)
-
@buffer << %(<tr><th colspan="4">#{title}</th></tr>)
-
end
-
-
2
def section(routes)
-
@buffer << @view.render(partial: "routes/route", collection: routes)
-
end
-
-
# the header is part of the HTML page, so we don't construct it here.
-
2
def header(routes)
-
end
-
-
2
def no_routes
-
@buffer << <<-MESSAGE.strip_heredoc
-
<p>You don't have any routes defined!</p>
-
<ul>
-
<li>Please add some routes in <tt>config/routes.rb</tt>.</li>
-
<li>
-
For more information about routes, please see the Rails guide
-
<a href="http://guides.rubyonrails.org/routing.html">Rails Routing from the Outside In</a>.
-
</li>
-
</ul>
-
MESSAGE
-
end
-
-
2
def result
-
@view.raw @view.render(layout: "routes/table") {
-
@view.raw @buffer.join("\n")
-
}
-
end
-
end
-
end
-
end
-
2
require 'active_support/core_ext/hash/except'
-
2
require 'active_support/core_ext/hash/reverse_merge'
-
2
require 'active_support/core_ext/hash/slice'
-
2
require 'active_support/core_ext/enumerable'
-
2
require 'active_support/core_ext/array/extract_options'
-
2
require 'active_support/core_ext/module/remove_method'
-
2
require 'active_support/inflector'
-
2
require 'action_dispatch/routing/redirection'
-
-
2
module ActionDispatch
-
2
module Routing
-
2
class Mapper
-
2
URL_OPTIONS = [:protocol, :subdomain, :domain, :host, :port]
-
2
SCOPE_OPTIONS = [:path, :shallow_path, :as, :shallow_prefix, :module,
-
:controller, :action, :path_names, :constraints,
-
:shallow, :blocks, :defaults, :options]
-
-
2
class Constraints #:nodoc:
-
2
def self.new(app, constraints, request = Rack::Request)
-
266
if constraints.any?
-
super(app, constraints, request)
-
else
-
266
app
-
end
-
end
-
-
2
attr_reader :app, :constraints
-
-
2
def initialize(app, constraints, request)
-
@app, @constraints, @request = app, constraints, request
-
end
-
-
2
def matches?(env)
-
req = @request.new(env)
-
-
@constraints.all? do |constraint|
-
(constraint.respond_to?(:matches?) && constraint.matches?(req)) ||
-
(constraint.respond_to?(:call) && constraint.call(*constraint_args(constraint, req)))
-
end
-
ensure
-
req.reset_parameters
-
end
-
-
2
def call(env)
-
matches?(env) ? @app.call(env) : [ 404, {'X-Cascade' => 'pass'}, [] ]
-
end
-
-
2
private
-
2
def constraint_args(constraint, request)
-
constraint.arity == 1 ? [request] : [request.symbolized_path_parameters, request]
-
end
-
end
-
-
2
class Mapping #:nodoc:
-
2
IGNORE_OPTIONS = [:to, :as, :via, :on, :constraints, :defaults, :only, :except, :anchor, :shallow, :shallow_path, :shallow_prefix, :format]
-
2
ANCHOR_CHARACTERS_REGEX = %r{\A(\\A|\^)|(\\Z|\\z|\$)\Z}
-
2
WILDCARD_PATH = %r{\*([^/\)]+)\)?$}
-
-
2
attr_reader :scope, :path, :options, :requirements, :conditions, :defaults
-
-
2
def initialize(set, scope, path, options)
-
266
@set, @scope, @path, @options = set, scope, path, options
-
266
@requirements, @conditions, @defaults = {}, {}, {}
-
-
266
normalize_options!
-
266
normalize_path!
-
266
normalize_requirements!
-
266
normalize_conditions!
-
266
normalize_defaults!
-
end
-
-
2
def to_route
-
266
[ app, conditions, requirements, defaults, options[:as], options[:anchor] ]
-
end
-
-
2
private
-
-
2
def normalize_path!
-
266
raise ArgumentError, "path is required" if @path.blank?
-
266
@path = Mapper.normalize_path(@path)
-
-
266
if required_format?
-
@path = "#{@path}.:format"
-
266
elsif optional_format?
-
262
@path = "#{@path}(.:format)"
-
end
-
end
-
-
2
def required_format?
-
266
options[:format] == true
-
end
-
-
2
def optional_format?
-
266
options[:format] != false && !path.include?(':format') && !path.end_with?('/')
-
end
-
-
2
def normalize_options!
-
266
@options.reverse_merge!(scope[:options]) if scope[:options]
-
266
path_without_format = path.sub(/\(\.:format\)$/, '')
-
-
# Add a constraint for wildcard route to make it non-greedy and match the
-
# optional format part of the route by default
-
266
if path_without_format.match(WILDCARD_PATH) && @options[:format] != false
-
@options[$1.to_sym] ||= /.+?/
-
end
-
-
266
if path_without_format.match(':controller')
-
raise ArgumentError, ":controller segment is not allowed within a namespace block" if scope[:module]
-
-
# Add a default constraint for :controller path segments that matches namespaced
-
# controllers with default routes like :controller/:action/:id(.:format), e.g:
-
# GET /admin/products/show/1
-
# => { controller: 'admin/products', action: 'show', id: '1' }
-
@options[:controller] ||= /.+?/
-
end
-
-
266
@options.merge!(default_controller_and_action)
-
end
-
-
2
def normalize_requirements!
-
266
constraints.each do |key, requirement|
-
next unless segment_keys.include?(key) || key == :controller
-
verify_regexp_requirement(requirement) if requirement.is_a?(Regexp)
-
@requirements[key] = requirement
-
end
-
-
266
if options[:format] == true
-
@requirements[:format] ||= /.+/
-
266
elsif Regexp === options[:format]
-
@requirements[:format] = options[:format]
-
266
elsif String === options[:format]
-
@requirements[:format] = Regexp.compile(options[:format])
-
end
-
end
-
-
2
def verify_regexp_requirement(requirement)
-
if requirement.source =~ ANCHOR_CHARACTERS_REGEX
-
raise ArgumentError, "Regexp anchor characters are not allowed in routing requirements: #{requirement.inspect}"
-
end
-
-
if requirement.multiline?
-
raise ArgumentError, "Regexp multiline option is not allowed in routing requirements: #{requirement.inspect}"
-
end
-
end
-
-
2
def normalize_defaults!
-
266
@defaults.merge!(scope[:defaults]) if scope[:defaults]
-
266
@defaults.merge!(options[:defaults]) if options[:defaults]
-
-
266
options.each do |key, default|
-
1398
unless Regexp === default || IGNORE_OPTIONS.include?(key)
-
528
@defaults[key] = default
-
end
-
end
-
-
266
if options[:constraints].is_a?(Hash)
-
options[:constraints].each do |key, default|
-
if URL_OPTIONS.include?(key) && (String === default || Fixnum === default)
-
@defaults[key] ||= default
-
end
-
end
-
end
-
-
266
if Regexp === options[:format]
-
@defaults[:format] = nil
-
266
elsif String === options[:format]
-
@defaults[:format] = options[:format]
-
end
-
end
-
-
2
def normalize_conditions!
-
266
@conditions[:path_info] = path
-
-
266
constraints.each do |key, condition|
-
unless segment_keys.include?(key) || key == :controller
-
@conditions[key] = condition
-
end
-
end
-
-
266
required_defaults = []
-
266
options.each do |key, required_default|
-
1400
unless segment_keys.include?(key) || IGNORE_OPTIONS.include?(key) || Regexp === required_default
-
528
required_defaults << key
-
end
-
end
-
266
@conditions[:required_defaults] = required_defaults
-
-
266
via_all = options.delete(:via) if options[:via] == :all
-
-
266
if !via_all && options[:via].blank?
-
msg = "You should not use the `match` method in your router without specifying an HTTP method.\n" \
-
"If you want to expose your action to both GET and POST, add `via: [:get, :post]` option.\n" \
-
"If you want to expose your action to GET, use `get` in the router:\n" \
-
" Instead of: match \"controller#action\"\n" \
-
" Do: get \"controller#action\""
-
raise msg
-
end
-
-
266
if via = options[:via]
-
528
@conditions[:request_method] = Array(via).map { |m| m.to_s.dasherize.upcase }
-
end
-
end
-
-
2
def app
-
266
Constraints.new(endpoint, blocks, @set.request_class)
-
end
-
-
2
def default_controller_and_action
-
266
if to.respond_to?(:call)
-
2
{ }
-
else
-
264
if to.is_a?(String)
-
72
controller, action = to.split('#')
-
elsif to.is_a?(Symbol)
-
action = to.to_s
-
end
-
-
264
controller ||= default_controller
-
264
action ||= default_action
-
-
264
if @scope[:module] && !controller.is_a?(Regexp)
-
if controller =~ %r{\A/}
-
controller = controller[1..-1]
-
else
-
controller = [@scope[:module], controller].compact.join("/").presence
-
end
-
end
-
-
264
if controller.is_a?(String) && controller =~ %r{\A/}
-
raise ArgumentError, "controller name should not start with a slash"
-
end
-
-
264
controller = controller.to_s unless controller.is_a?(Regexp)
-
264
action = action.to_s unless action.is_a?(Regexp)
-
-
264
if controller.blank? && segment_keys.exclude?(:controller)
-
message = "Missing :controller key on routes definition, please check your routes."
-
raise ArgumentError, message
-
end
-
-
264
if action.blank? && segment_keys.exclude?(:action)
-
message = "Missing :action key on routes definition, please check your routes."
-
raise ArgumentError, message
-
end
-
-
264
if controller.is_a?(String) && controller !~ /\A[a-z_0-9\/]*\z/
-
message = "'#{controller}' is not a supported controller name. This can lead to potential routing problems."
-
message << " See http://guides.rubyonrails.org/routing.html#specifying-a-controller-to-use"
-
raise ArgumentError, message
-
end
-
-
264
hash = {}
-
264
hash[:controller] = controller unless controller.blank?
-
264
hash[:action] = action unless action.blank?
-
264
hash
-
end
-
end
-
-
2
def blocks
-
266
if options[:constraints].present? && !options[:constraints].is_a?(Hash)
-
[options[:constraints]]
-
else
-
266
scope[:blocks] || []
-
end
-
end
-
-
2
def constraints
-
@constraints ||= {}.tap do |constraints|
-
266
constraints.merge!(scope[:constraints]) if scope[:constraints]
-
-
266
options.except(*IGNORE_OPTIONS).each do |key, option|
-
528
constraints[key] = option if Regexp === option
-
end
-
-
266
constraints.merge!(options[:constraints]) if options[:constraints].is_a?(Hash)
-
532
end
-
end
-
-
2
def segment_keys
-
1810
@segment_keys ||= path_pattern.names.map{ |s| s.to_sym }
-
end
-
-
2
def path_pattern
-
266
Journey::Path::Pattern.new(strexp)
-
end
-
-
2
def strexp
-
266
Journey::Router::Strexp.compile(path, requirements, SEPARATORS)
-
end
-
-
2
def endpoint
-
266
to.respond_to?(:call) ? to : dispatcher
-
end
-
-
2
def dispatcher
-
264
Routing::RouteSet::Dispatcher.new(:defaults => defaults)
-
end
-
-
2
def to
-
1062
options[:to]
-
end
-
-
2
def default_controller
-
192
options[:controller] || scope[:controller]
-
end
-
-
2
def default_action
-
192
options[:action] || scope[:action]
-
end
-
end
-
-
# Invokes Journey::Router::Utils.normalize_path and ensure that
-
# (:locale) becomes (/:locale) instead of /(:locale). Except
-
# for root cases, where the latter is the correct one.
-
2
def self.normalize_path(path)
-
500
path = Journey::Router::Utils.normalize_path(path)
-
500
path.gsub!(%r{/(\(+)/?}, '\1/') unless path =~ %r{^/\(+[^)]+\)$}
-
500
path
-
end
-
-
2
def self.normalize_name(name)
-
88
normalize_path(name)[1..-1].tr("/", "_")
-
end
-
-
2
module Base
-
# You can specify what Rails should route "/" to with the root method:
-
#
-
# root to: 'pages#main'
-
#
-
# For options, see +match+, as +root+ uses it internally.
-
#
-
# You can also pass a string which will expand
-
#
-
# root 'pages#main'
-
#
-
# You should put the root route at the top of <tt>config/routes.rb</tt>,
-
# because this means it will be matched first. As this is the most popular route
-
# of most Rails applications, this is beneficial.
-
2
def root(options = {})
-
2
match '/', { :as => :root, :via => :get }.merge!(options)
-
end
-
-
# Matches a url pattern to one or more routes.
-
#
-
# You should not use the `match` method in your router
-
# without specifying an HTTP method.
-
#
-
# If you want to expose your action to both GET and POST, use:
-
#
-
# # sets :controller, :action and :id in params
-
# match ':controller/:action/:id', via: [:get, :post]
-
#
-
# Note that +:controller+, +:action+, +:id+ are interpreted as url query
-
# parameters and thus available as +params+
-
# in an action.
-
#
-
# If you want to expose your action to GET, use `get` in the router:
-
#
-
# Instead of:
-
#
-
# match ":controller/:action/:id"
-
#
-
# Do:
-
#
-
# get ":controller/:action/:id"
-
#
-
# Two of these symbols are special, +:controller+ maps to the controller
-
# and +:action+ to the controller's action. A pattern can also map
-
# wildcard segments (globs) to params:
-
#
-
# get 'songs/*category/:title', to: 'songs#show'
-
#
-
# # 'songs/rock/classic/stairway-to-heaven' sets
-
# # params[:category] = 'rock/classic'
-
# # params[:title] = 'stairway-to-heaven'
-
#
-
# When a pattern points to an internal route, the route's +:action+ and
-
# +:controller+ should be set in options or hash shorthand. Examples:
-
#
-
# match 'photos/:id' => 'photos#show', via: [:get]
-
# match 'photos/:id', to: 'photos#show', via: [:get]
-
# match 'photos/:id', controller: 'photos', action: 'show', via: [:get]
-
#
-
# A pattern can also point to a +Rack+ endpoint i.e. anything that
-
# responds to +call+:
-
#
-
# match 'photos/:id', to: lambda {|hash| [200, {}, ["Coming soon"]] }, via: [:get]
-
# match 'photos/:id', to: PhotoRackApp, via: [:get]
-
# # Yes, controller actions are just rack endpoints
-
# match 'photos/:id', to: PhotosController.action(:show), via: [:get]
-
#
-
# Because requesting various HTTP verbs with a single action has security
-
# implications, you must either specify the actions in
-
# the via options or use one of the HtttpHelpers[rdoc-ref:HttpHelpers]
-
# instead +match+
-
#
-
# === Options
-
#
-
# Any options not seen here are passed on as params with the url.
-
#
-
# [:controller]
-
# The route's controller.
-
#
-
# [:action]
-
# The route's action.
-
#
-
# [:param]
-
# Overrides the default resource identifier `:id` (name of the
-
# dynamic segment used to generate the routes).
-
# You can access that segment from your controller using
-
# <tt>params[<:param>]</tt>.
-
#
-
# [:path]
-
# The path prefix for the routes.
-
#
-
# [:module]
-
# The namespace for :controller.
-
#
-
# match 'path', to: 'c#a', module: 'sekret', controller: 'posts', via: [:get]
-
# # => Sekret::PostsController
-
#
-
# See <tt>Scoping#namespace</tt> for its scope equivalent.
-
#
-
# [:as]
-
# The name used to generate routing helpers.
-
#
-
# [:via]
-
# Allowed HTTP verb(s) for route.
-
#
-
# match 'path', to: 'c#a', via: :get
-
# match 'path', to: 'c#a', via: [:get, :post]
-
# match 'path', to: 'c#a', via: :all
-
#
-
# [:to]
-
# Points to a +Rack+ endpoint. Can be an object that responds to
-
# +call+ or a string representing a controller's action.
-
#
-
# match 'path', to: 'controller#action', via: [:get]
-
# match 'path', to: lambda { |env| [200, {}, ["Success!"]] }, via: [:get]
-
# match 'path', to: RackApp, via: [:get]
-
#
-
# [:on]
-
# Shorthand for wrapping routes in a specific RESTful context. Valid
-
# values are +:member+, +:collection+, and +:new+. Only use within
-
# <tt>resource(s)</tt> block. For example:
-
#
-
# resource :bar do
-
# match 'foo', to: 'c#a', on: :member, via: [:get, :post]
-
# end
-
#
-
# Is equivalent to:
-
#
-
# resource :bar do
-
# member do
-
# match 'foo', to: 'c#a', via: [:get, :post]
-
# end
-
# end
-
#
-
# [:constraints]
-
# Constrains parameters with a hash of regular expressions
-
# or an object that responds to <tt>matches?</tt>. In addition, constraints
-
# other than path can also be specified with any object
-
# that responds to <tt>===</tt> (eg. String, Array, Range, etc.).
-
#
-
# match 'path/:id', constraints: { id: /[A-Z]\d{5}/ }, via: [:get]
-
#
-
# match 'json_only', constraints: { format: 'json' }, via: [:get]
-
#
-
# class Whitelist
-
# def matches?(request) request.remote_ip == '1.2.3.4' end
-
# end
-
# match 'path', to: 'c#a', constraints: Whitelist.new, via: [:get]
-
#
-
# See <tt>Scoping#constraints</tt> for more examples with its scope
-
# equivalent.
-
#
-
# [:defaults]
-
# Sets defaults for parameters
-
#
-
# # Sets params[:format] to 'jpg' by default
-
# match 'path', to: 'c#a', defaults: { format: 'jpg' }, via: [:get]
-
#
-
# See <tt>Scoping#defaults</tt> for its scope equivalent.
-
#
-
# [:anchor]
-
# Boolean to anchor a <tt>match</tt> pattern. Default is true. When set to
-
# false, the pattern matches any request prefixed with the given path.
-
#
-
# # Matches any request starting with 'path'
-
# match 'path', to: 'c#a', anchor: false, via: [:get]
-
#
-
# [:format]
-
# Allows you to specify the default value for optional +format+
-
# segment or disable it by supplying +false+.
-
2
def match(path, options=nil)
-
end
-
-
# Mount a Rack-based application to be used within the application.
-
#
-
# mount SomeRackApp, at: "some_route"
-
#
-
# Alternatively:
-
#
-
# mount(SomeRackApp => "some_route")
-
#
-
# For options, see +match+, as +mount+ uses it internally.
-
#
-
# All mounted applications come with routing helpers to access them.
-
# These are named after the class specified, so for the above example
-
# the helper is either +some_rack_app_path+ or +some_rack_app_url+.
-
# To customize this helper's name, use the +:as+ option:
-
#
-
# mount(SomeRackApp => "some_route", as: "exciting")
-
#
-
# This will generate the +exciting_path+ and +exciting_url+ helpers
-
# which can be used to navigate to this mounted app.
-
2
def mount(app, options = nil)
-
2
if options
-
path = options.delete(:at)
-
else
-
2
unless Hash === app
-
raise ArgumentError, "must be called with mount point"
-
end
-
-
2
options = app
-
4
app, path = options.find { |k, _| k.respond_to?(:call) }
-
2
options.delete(app) if app
-
end
-
-
2
raise "A rack application must be specified" unless path
-
-
2
options[:as] ||= app_name(app)
-
2
target_as = name_for_action(options[:as], path)
-
2
options[:via] ||= :all
-
-
2
match(path, options.merge(:to => app, :anchor => false, :format => false))
-
-
2
define_generate_prefix(app, target_as)
-
2
self
-
end
-
-
2
def default_url_options=(options)
-
@set.default_url_options = options
-
end
-
2
alias_method :default_url_options, :default_url_options=
-
-
2
def with_default_scope(scope, &block)
-
scope(scope) do
-
instance_exec(&block)
-
end
-
end
-
-
# Query if the following named route was already defined.
-
2
def has_named_route?(name)
-
@set.named_routes.routes[name.to_sym]
-
end
-
-
2
private
-
2
def app_name(app)
-
2
return unless app.respond_to?(:routes)
-
-
if app.respond_to?(:railtie_name)
-
app.railtie_name
-
else
-
class_name = app.class.is_a?(Class) ? app.name : app.class.name
-
ActiveSupport::Inflector.underscore(class_name).tr("/", "_")
-
end
-
end
-
-
2
def define_generate_prefix(app, name)
-
2
return unless app.respond_to?(:routes) && app.routes.respond_to?(:define_mounted_helper)
-
-
_route = @set.named_routes.routes[name.to_sym]
-
_routes = @set
-
app.routes.define_mounted_helper(name)
-
app.routes.singleton_class.class_eval do
-
redefine_method :mounted? do
-
true
-
end
-
-
redefine_method :_generate_prefix do |options|
-
prefix_options = options.slice(*_route.segment_keys)
-
# we must actually delete prefix segment keys to avoid passing them to next url_for
-
_route.segment_keys.each { |k| options.delete(k) }
-
_routes.url_helpers.send("#{name}_path", prefix_options)
-
end
-
end
-
end
-
end
-
-
2
module HttpHelpers
-
# Define a route that only recognizes HTTP GET.
-
# For supported arguments, see match[rdoc-ref:Base#match]
-
#
-
# get 'bacon', to: 'food#bacon'
-
2
def get(*args, &block)
-
158
map_method(:get, args, &block)
-
end
-
-
# Define a route that only recognizes HTTP POST.
-
# For supported arguments, see match[rdoc-ref:Base#match]
-
#
-
# post 'bacon', to: 'food#bacon'
-
2
def post(*args, &block)
-
28
map_method(:post, args, &block)
-
end
-
-
# Define a route that only recognizes HTTP PATCH.
-
# For supported arguments, see match[rdoc-ref:Base#match]
-
#
-
# patch 'bacon', to: 'food#bacon'
-
2
def patch(*args, &block)
-
24
map_method(:patch, args, &block)
-
end
-
-
# Define a route that only recognizes HTTP PUT.
-
# For supported arguments, see match[rdoc-ref:Base#match]
-
#
-
# put 'bacon', to: 'food#bacon'
-
2
def put(*args, &block)
-
24
map_method(:put, args, &block)
-
end
-
-
# Define a route that only recognizes HTTP DELETE.
-
# For supported arguments, see match[rdoc-ref:Base#match]
-
#
-
# delete 'broccoli', to: 'food#broccoli'
-
2
def delete(*args, &block)
-
28
map_method(:delete, args, &block)
-
end
-
-
2
private
-
2
def map_method(method, args, &block)
-
262
options = args.extract_options!
-
262
options[:via] = method
-
262
match(*args, options, &block)
-
262
self
-
end
-
end
-
-
# You may wish to organize groups of controllers under a namespace.
-
# Most commonly, you might group a number of administrative controllers
-
# under an +admin+ namespace. You would place these controllers under
-
# the <tt>app/controllers/admin</tt> directory, and you can group them
-
# together in your router:
-
#
-
# namespace "admin" do
-
# resources :posts, :comments
-
# end
-
#
-
# This will create a number of routes for each of the posts and comments
-
# controller. For <tt>Admin::PostsController</tt>, Rails will create:
-
#
-
# GET /admin/posts
-
# GET /admin/posts/new
-
# POST /admin/posts
-
# GET /admin/posts/1
-
# GET /admin/posts/1/edit
-
# PATCH/PUT /admin/posts/1
-
# DELETE /admin/posts/1
-
#
-
# If you want to route /posts (without the prefix /admin) to
-
# <tt>Admin::PostsController</tt>, you could use
-
#
-
# scope module: "admin" do
-
# resources :posts
-
# end
-
#
-
# or, for a single case
-
#
-
# resources :posts, module: "admin"
-
#
-
# If you want to route /admin/posts to +PostsController+
-
# (without the Admin:: module prefix), you could use
-
#
-
# scope "/admin" do
-
# resources :posts
-
# end
-
#
-
# or, for a single case
-
#
-
# resources :posts, path: "/admin/posts"
-
#
-
# In each of these cases, the named routes remain the same as if you did
-
# not use scope. In the last case, the following paths map to
-
# +PostsController+:
-
#
-
# GET /admin/posts
-
# GET /admin/posts/new
-
# POST /admin/posts
-
# GET /admin/posts/1
-
# GET /admin/posts/1/edit
-
# PATCH/PUT /admin/posts/1
-
# DELETE /admin/posts/1
-
2
module Scoping
-
# Scopes a set of routes to the given default options.
-
#
-
# Take the following route definition as an example:
-
#
-
# scope path: ":account_id", as: "account" do
-
# resources :projects
-
# end
-
#
-
# This generates helpers such as +account_projects_path+, just like +resources+ does.
-
# The difference here being that the routes generated are like /:account_id/projects,
-
# rather than /accounts/:account_id/projects.
-
#
-
# === Options
-
#
-
# Takes same options as <tt>Base#match</tt> and <tt>Resources#resources</tt>.
-
#
-
# # route /posts (without the prefix /admin) to <tt>Admin::PostsController</tt>
-
# scope module: "admin" do
-
# resources :posts
-
# end
-
#
-
# # prefix the posts resource's requests with '/admin'
-
# scope path: "/admin" do
-
# resources :posts
-
# end
-
#
-
# # prefix the routing helper name: +sekret_posts_path+ instead of +posts_path+
-
# scope as: "sekret" do
-
# resources :posts
-
# end
-
2
def scope(*args)
-
98
options = args.extract_options!.dup
-
98
recover = {}
-
-
98
options[:path] = args.flatten.join('/') if args.any?
-
98
options[:constraints] ||= {}
-
-
98
unless nested_scope?
-
96
options[:shallow_path] ||= options[:path] if options.key?(:path)
-
96
options[:shallow_prefix] ||= options[:as] if options.key?(:as)
-
end
-
-
98
if options[:constraints].is_a?(Hash)
-
98
defaults = options[:constraints].select do
-
|k, v| URL_OPTIONS.include?(k) && (v.is_a?(String) || v.is_a?(Fixnum))
-
end
-
-
98
(options[:defaults] ||= {}).reverse_merge!(defaults)
-
else
-
block, options[:constraints] = options[:constraints], {}
-
end
-
-
98
SCOPE_OPTIONS.each do |option|
-
1274
if option == :blocks
-
98
value = block
-
elsif option == :options
-
98
value = options
-
else
-
1078
value = options.delete(option)
-
end
-
-
1274
if value
-
466
recover[option] = @scope[option]
-
466
@scope[option] = send("merge_#{option}_scope", @scope[option], value)
-
end
-
end
-
-
98
yield
-
98
self
-
ensure
-
98
@scope.merge!(recover)
-
end
-
-
# Scopes routes to a specific controller
-
#
-
# controller "food" do
-
# match "bacon", action: "bacon"
-
# end
-
2
def controller(controller, options={})
-
options[:controller] = controller
-
scope(options) { yield }
-
end
-
-
# Scopes routes to a specific namespace. For example:
-
#
-
# namespace :admin do
-
# resources :posts
-
# end
-
#
-
# This generates the following routes:
-
#
-
# admin_posts GET /admin/posts(.:format) admin/posts#index
-
# admin_posts POST /admin/posts(.:format) admin/posts#create
-
# new_admin_post GET /admin/posts/new(.:format) admin/posts#new
-
# edit_admin_post GET /admin/posts/:id/edit(.:format) admin/posts#edit
-
# admin_post GET /admin/posts/:id(.:format) admin/posts#show
-
# admin_post PATCH/PUT /admin/posts/:id(.:format) admin/posts#update
-
# admin_post DELETE /admin/posts/:id(.:format) admin/posts#destroy
-
#
-
# === Options
-
#
-
# The +:path+, +:as+, +:module+, +:shallow_path+ and +:shallow_prefix+
-
# options all default to the name of the namespace.
-
#
-
# For options, see <tt>Base#match</tt>. For +:shallow_path+ option, see
-
# <tt>Resources#resources</tt>.
-
#
-
# # accessible through /sekret/posts rather than /admin/posts
-
# namespace :admin, path: "sekret" do
-
# resources :posts
-
# end
-
#
-
# # maps to <tt>Sekret::PostsController</tt> rather than <tt>Admin::PostsController</tt>
-
# namespace :admin, module: "sekret" do
-
# resources :posts
-
# end
-
#
-
# # generates +sekret_posts_path+ rather than +admin_posts_path+
-
# namespace :admin, as: "sekret" do
-
# resources :posts
-
# end
-
2
def namespace(path, options = {})
-
path = path.to_s
-
-
defaults = {
-
module: path,
-
path: options.fetch(:path, path),
-
as: options.fetch(:as, path),
-
shallow_path: options.fetch(:path, path),
-
shallow_prefix: options.fetch(:as, path)
-
}
-
-
scope(defaults.merge!(options)) { yield }
-
end
-
-
# === Parameter Restriction
-
# Allows you to constrain the nested routes based on a set of rules.
-
# For instance, in order to change the routes to allow for a dot character in the +id+ parameter:
-
#
-
# constraints(id: /\d+\.\d+/) do
-
# resources :posts
-
# end
-
#
-
# Now routes such as +/posts/1+ will no longer be valid, but +/posts/1.1+ will be.
-
# The +id+ parameter must match the constraint passed in for this example.
-
#
-
# You may use this to also restrict other parameters:
-
#
-
# resources :posts do
-
# constraints(post_id: /\d+\.\d+/) do
-
# resources :comments
-
# end
-
# end
-
#
-
# === Restricting based on IP
-
#
-
# Routes can also be constrained to an IP or a certain range of IP addresses:
-
#
-
# constraints(ip: /192\.168\.\d+\.\d+/) do
-
# resources :posts
-
# end
-
#
-
# Any user connecting from the 192.168.* range will be able to see this resource,
-
# where as any user connecting outside of this range will be told there is no such route.
-
#
-
# === Dynamic request matching
-
#
-
# Requests to routes can be constrained based on specific criteria:
-
#
-
# constraints(lambda { |req| req.env["HTTP_USER_AGENT"] =~ /iPhone/ }) do
-
# resources :iphones
-
# end
-
#
-
# You are able to move this logic out into a class if it is too complex for routes.
-
# This class must have a +matches?+ method defined on it which either returns +true+
-
# if the user should be given access to that route, or +false+ if the user should not.
-
#
-
# class Iphone
-
# def self.matches?(request)
-
# request.env["HTTP_USER_AGENT"] =~ /iPhone/
-
# end
-
# end
-
#
-
# An expected place for this code would be +lib/constraints+.
-
#
-
# This class is then used like this:
-
#
-
# constraints(Iphone) do
-
# resources :iphones
-
# end
-
2
def constraints(constraints = {})
-
scope(:constraints => constraints) { yield }
-
end
-
-
# Allows you to set default parameters for a route, such as this:
-
# defaults id: 'home' do
-
# match 'scoped_pages/(:id)', to: 'pages#show'
-
# end
-
# Using this, the +:id+ parameter here will default to 'home'.
-
2
def defaults(defaults = {})
-
scope(:defaults => defaults) { yield }
-
end
-
-
2
private
-
2
def merge_path_scope(parent, child) #:nodoc:
-
74
Mapper.normalize_path("#{parent}/#{child}")
-
end
-
-
2
def merge_shallow_path_scope(parent, child) #:nodoc:
-
72
Mapper.normalize_path("#{parent}/#{child}")
-
end
-
-
2
def merge_as_scope(parent, child) #:nodoc:
-
2
parent ? "#{parent}_#{child}" : child
-
end
-
-
2
def merge_shallow_prefix_scope(parent, child) #:nodoc:
-
parent ? "#{parent}_#{child}" : child
-
end
-
-
2
def merge_module_scope(parent, child) #:nodoc:
-
parent ? "#{parent}/#{child}" : child
-
end
-
-
2
def merge_controller_scope(parent, child) #:nodoc:
-
24
child
-
end
-
-
2
def merge_action_scope(parent, child) #:nodoc:
-
child
-
end
-
-
2
def merge_path_names_scope(parent, child) #:nodoc:
-
merge_options_scope(parent, child)
-
end
-
-
2
def merge_constraints_scope(parent, child) #:nodoc:
-
98
merge_options_scope(parent, child)
-
end
-
-
2
def merge_defaults_scope(parent, child) #:nodoc:
-
98
merge_options_scope(parent, child)
-
end
-
-
2
def merge_blocks_scope(parent, child) #:nodoc:
-
merged = parent ? parent.dup : []
-
merged << child if child
-
merged
-
end
-
-
2
def merge_options_scope(parent, child) #:nodoc:
-
294
(parent || {}).except(*override_keys(child)).merge!(child)
-
end
-
-
2
def merge_shallow_scope(parent, child) #:nodoc:
-
child ? true : false
-
end
-
-
2
def override_keys(child) #:nodoc:
-
294
child.key?(:only) || child.key?(:except) ? [:only, :except] : []
-
end
-
end
-
-
# Resource routing allows you to quickly declare all of the common routes
-
# for a given resourceful controller. Instead of declaring separate routes
-
# for your +index+, +show+, +new+, +edit+, +create+, +update+ and +destroy+
-
# actions, a resourceful route declares them in a single line of code:
-
#
-
# resources :photos
-
#
-
# Sometimes, you have a resource that clients always look up without
-
# referencing an ID. A common example, /profile always shows the profile of
-
# the currently logged in user. In this case, you can use a singular resource
-
# to map /profile (rather than /profile/:id) to the show action.
-
#
-
# resource :profile
-
#
-
# It's common to have resources that are logically children of other
-
# resources:
-
#
-
# resources :magazines do
-
# resources :ads
-
# end
-
#
-
# You may wish to organize groups of controllers under a namespace. Most
-
# commonly, you might group a number of administrative controllers under
-
# an +admin+ namespace. You would place these controllers under the
-
# <tt>app/controllers/admin</tt> directory, and you can group them together
-
# in your router:
-
#
-
# namespace "admin" do
-
# resources :posts, :comments
-
# end
-
#
-
# By default the +:id+ parameter doesn't accept dots. If you need to
-
# use dots as part of the +:id+ parameter add a constraint which
-
# overrides this restriction, e.g:
-
#
-
# resources :articles, id: /[^\/]+/
-
#
-
# This allows any character other than a slash as part of your +:id+.
-
#
-
2
module Resources
-
# CANONICAL_ACTIONS holds all actions that does not need a prefix or
-
# a path appended since they fit properly in their scope level.
-
2
VALID_ON_OPTIONS = [:new, :collection, :member]
-
2
RESOURCE_OPTIONS = [:as, :controller, :path, :only, :except, :param, :concerns]
-
2
CANONICAL_ACTIONS = %w(index create new show update destroy)
-
2
RESOURCE_METHOD_SCOPES = [:collection, :member, :new]
-
2
RESOURCE_SCOPES = [:resource, :resources]
-
-
2
class Resource #:nodoc:
-
2
attr_reader :controller, :path, :options, :param
-
-
2
def initialize(entities, options = {})
-
24
@name = entities.to_s
-
24
@path = (options[:path] || @name).to_s
-
24
@controller = (options[:controller] || @name).to_s
-
24
@as = options[:as]
-
24
@param = (options[:param] || :id).to_sym
-
24
@options = options
-
24
@shallow = false
-
end
-
-
2
def default_actions
-
168
[:index, :create, :new, :show, :update, :destroy, :edit]
-
end
-
-
2
def actions
-
168
if only = @options[:only]
-
Array(only).map(&:to_sym)
-
168
elsif except = @options[:except]
-
default_actions - Array(except).map(&:to_sym)
-
else
-
168
default_actions
-
end
-
end
-
-
2
def name
-
48
@as || @name
-
end
-
-
2
def plural
-
384
@plural ||= name.to_s
-
end
-
-
2
def singular
-
388
@singular ||= name.to_s.singularize
-
end
-
-
2
alias :member_name :singular
-
-
# Checks for uncountable plurals, and appends "_index" if the plural
-
# and singular form are the same.
-
2
def collection_name
-
192
singular == plural ? "#{plural}_index" : plural
-
end
-
-
2
def resource_scope
-
24
{ :controller => controller }
-
end
-
-
2
alias :collection_scope :path
-
-
2
def member_scope
-
24
"#{path}/:#{param}"
-
end
-
-
2
alias :shallow_scope :member_scope
-
-
2
def new_scope(new_path)
-
24
"#{path}/#{new_path}"
-
end
-
-
2
def nested_param
-
2
:"#{singular}_#{param}"
-
end
-
-
2
def nested_scope
-
2
"#{path}/:#{nested_param}"
-
end
-
-
2
def shallow=(value)
-
24
@shallow = value
-
end
-
-
2
def shallow?
-
@shallow
-
end
-
end
-
-
2
class SingletonResource < Resource #:nodoc:
-
2
def initialize(entities, options)
-
super
-
@as = nil
-
@controller = (options[:controller] || plural).to_s
-
@as = options[:as]
-
end
-
-
2
def default_actions
-
[:show, :create, :update, :destroy, :new, :edit]
-
end
-
-
2
def plural
-
@plural ||= name.to_s.pluralize
-
end
-
-
2
def singular
-
@singular ||= name.to_s
-
end
-
-
2
alias :member_name :singular
-
2
alias :collection_name :singular
-
-
2
alias :member_scope :path
-
2
alias :nested_scope :path
-
end
-
-
2
def resources_path_names(options)
-
@scope[:path_names].merge!(options)
-
end
-
-
# Sometimes, you have a resource that clients always look up without
-
# referencing an ID. A common example, /profile always shows the
-
# profile of the currently logged in user. In this case, you can use
-
# a singular resource to map /profile (rather than /profile/:id) to
-
# the show action:
-
#
-
# resource :profile
-
#
-
# creates six different routes in your application, all mapping to
-
# the +Profiles+ controller (note that the controller is named after
-
# the plural):
-
#
-
# GET /profile/new
-
# POST /profile
-
# GET /profile
-
# GET /profile/edit
-
# PATCH/PUT /profile
-
# DELETE /profile
-
#
-
# === Options
-
# Takes same options as +resources+.
-
2
def resource(*resources, &block)
-
options = resources.extract_options!.dup
-
-
if apply_common_behavior_for(:resource, resources, options, &block)
-
return self
-
end
-
-
resource_scope(:resource, SingletonResource.new(resources.pop, options)) do
-
yield if block_given?
-
-
concerns(options[:concerns]) if options[:concerns]
-
-
collection do
-
post :create
-
end if parent_resource.actions.include?(:create)
-
-
new do
-
get :new
-
end if parent_resource.actions.include?(:new)
-
-
set_member_mappings_for_resource
-
end
-
-
self
-
end
-
-
# In Rails, a resourceful route provides a mapping between HTTP verbs
-
# and URLs and controller actions. By convention, each action also maps
-
# to particular CRUD operations in a database. A single entry in the
-
# routing file, such as
-
#
-
# resources :photos
-
#
-
# creates seven different routes in your application, all mapping to
-
# the +Photos+ controller:
-
#
-
# GET /photos
-
# GET /photos/new
-
# POST /photos
-
# GET /photos/:id
-
# GET /photos/:id/edit
-
# PATCH/PUT /photos/:id
-
# DELETE /photos/:id
-
#
-
# Resources can also be nested infinitely by using this block syntax:
-
#
-
# resources :photos do
-
# resources :comments
-
# end
-
#
-
# This generates the following comments routes:
-
#
-
# GET /photos/:photo_id/comments
-
# GET /photos/:photo_id/comments/new
-
# POST /photos/:photo_id/comments
-
# GET /photos/:photo_id/comments/:id
-
# GET /photos/:photo_id/comments/:id/edit
-
# PATCH/PUT /photos/:photo_id/comments/:id
-
# DELETE /photos/:photo_id/comments/:id
-
#
-
# === Options
-
# Takes same options as <tt>Base#match</tt> as well as:
-
#
-
# [:path_names]
-
# Allows you to change the segment component of the +edit+ and +new+ actions.
-
# Actions not specified are not changed.
-
#
-
# resources :posts, path_names: { new: "brand_new" }
-
#
-
# The above example will now change /posts/new to /posts/brand_new
-
#
-
# [:path]
-
# Allows you to change the path prefix for the resource.
-
#
-
# resources :posts, path: 'postings'
-
#
-
# The resource and all segments will now route to /postings instead of /posts
-
#
-
# [:only]
-
# Only generate routes for the given actions.
-
#
-
# resources :cows, only: :show
-
# resources :cows, only: [:show, :index]
-
#
-
# [:except]
-
# Generate all routes except for the given actions.
-
#
-
# resources :cows, except: :show
-
# resources :cows, except: [:show, :index]
-
#
-
# [:shallow]
-
# Generates shallow routes for nested resource(s). When placed on a parent resource,
-
# generates shallow routes for all nested resources.
-
#
-
# resources :posts, shallow: true do
-
# resources :comments
-
# end
-
#
-
# Is the same as:
-
#
-
# resources :posts do
-
# resources :comments, except: [:show, :edit, :update, :destroy]
-
# end
-
# resources :comments, only: [:show, :edit, :update, :destroy]
-
#
-
# This allows URLs for resources that otherwise would be deeply nested such
-
# as a comment on a blog post like <tt>/posts/a-long-permalink/comments/1234</tt>
-
# to be shortened to just <tt>/comments/1234</tt>.
-
#
-
# [:shallow_path]
-
# Prefixes nested shallow routes with the specified path.
-
#
-
# scope shallow_path: "sekret" do
-
# resources :posts do
-
# resources :comments, shallow: true
-
# end
-
# end
-
#
-
# The +comments+ resource here will have the following routes generated for it:
-
#
-
# post_comments GET /posts/:post_id/comments(.:format)
-
# post_comments POST /posts/:post_id/comments(.:format)
-
# new_post_comment GET /posts/:post_id/comments/new(.:format)
-
# edit_comment GET /sekret/comments/:id/edit(.:format)
-
# comment GET /sekret/comments/:id(.:format)
-
# comment PATCH/PUT /sekret/comments/:id(.:format)
-
# comment DELETE /sekret/comments/:id(.:format)
-
#
-
# [:shallow_prefix]
-
# Prefixes nested shallow route names with specified prefix.
-
#
-
# scope shallow_prefix: "sekret" do
-
# resources :posts do
-
# resources :comments, shallow: true
-
# end
-
# end
-
#
-
# The +comments+ resource here will have the following routes generated for it:
-
#
-
# post_comments GET /posts/:post_id/comments(.:format)
-
# post_comments POST /posts/:post_id/comments(.:format)
-
# new_post_comment GET /posts/:post_id/comments/new(.:format)
-
# edit_sekret_comment GET /comments/:id/edit(.:format)
-
# sekret_comment GET /comments/:id(.:format)
-
# sekret_comment PATCH/PUT /comments/:id(.:format)
-
# sekret_comment DELETE /comments/:id(.:format)
-
#
-
# [:format]
-
# Allows you to specify the default value for optional +format+
-
# segment or disable it by supplying +false+.
-
#
-
# === Examples
-
#
-
# # routes call <tt>Admin::PostsController</tt>
-
# resources :posts, module: "admin"
-
#
-
# # resource actions are at /admin/posts.
-
# resources :posts, path: "admin/posts"
-
2
def resources(*resources, &block)
-
26
options = resources.extract_options!.dup
-
-
26
if apply_common_behavior_for(:resources, resources, options, &block)
-
2
return self
-
end
-
-
24
resource_scope(:resources, Resource.new(resources.pop, options)) do
-
24
yield if block_given?
-
-
24
concerns(options[:concerns]) if options[:concerns]
-
-
24
collection do
-
24
get :index if parent_resource.actions.include?(:index)
-
24
post :create if parent_resource.actions.include?(:create)
-
end
-
-
new do
-
24
get :new
-
24
end if parent_resource.actions.include?(:new)
-
-
24
set_member_mappings_for_resource
-
end
-
-
24
self
-
end
-
-
# To add a route to the collection:
-
#
-
# resources :photos do
-
# collection do
-
# get 'search'
-
# end
-
# end
-
#
-
# This will enable Rails to recognize paths such as <tt>/photos/search</tt>
-
# with GET, and route to the search action of +PhotosController+. It will also
-
# create the <tt>search_photos_url</tt> and <tt>search_photos_path</tt>
-
# route helpers.
-
2
def collection
-
24
unless resource_scope?
-
raise ArgumentError, "can't use collection outside resource(s) scope"
-
end
-
-
24
with_scope_level(:collection) do
-
24
scope(parent_resource.collection_scope) do
-
24
yield
-
end
-
end
-
end
-
-
# To add a member route, add a member block into the resource block:
-
#
-
# resources :photos do
-
# member do
-
# get 'preview'
-
# end
-
# end
-
#
-
# This will recognize <tt>/photos/1/preview</tt> with GET, and route to the
-
# preview action of +PhotosController+. It will also create the
-
# <tt>preview_photo_url</tt> and <tt>preview_photo_path</tt> helpers.
-
2
def member
-
24
unless resource_scope?
-
raise ArgumentError, "can't use member outside resource(s) scope"
-
end
-
-
24
with_scope_level(:member) do
-
24
if shallow?
-
shallow_scope(parent_resource.member_scope) { yield }
-
else
-
48
scope(parent_resource.member_scope) { yield }
-
end
-
end
-
end
-
-
2
def new
-
24
unless resource_scope?
-
raise ArgumentError, "can't use new outside resource(s) scope"
-
end
-
-
24
with_scope_level(:new) do
-
24
scope(parent_resource.new_scope(action_path(:new))) do
-
24
yield
-
end
-
end
-
end
-
-
2
def nested
-
2
unless resource_scope?
-
raise ArgumentError, "can't use nested outside resource(s) scope"
-
end
-
-
2
with_scope_level(:nested) do
-
2
if shallow? && shallow_nesting_depth >= 1
-
shallow_scope(parent_resource.nested_scope, nested_options) { yield }
-
else
-
4
scope(parent_resource.nested_scope, nested_options) { yield }
-
end
-
end
-
end
-
-
# See ActionDispatch::Routing::Mapper::Scoping#namespace
-
2
def namespace(path, options = {})
-
if resource_scope?
-
nested { super }
-
else
-
super
-
end
-
end
-
-
2
def shallow
-
scope(:shallow => true) do
-
yield
-
end
-
end
-
-
2
def shallow?
-
26
parent_resource.instance_of?(Resource) && @scope[:shallow]
-
end
-
-
# match 'path' => 'controller#action'
-
# match 'path', to: 'controller#action'
-
# match 'path', 'otherpath', on: :member, via: :get
-
2
def match(path, *rest)
-
266
if rest.empty? && Hash === path
-
30
options = path
-
60
path, to = options.find { |name, _value| name.is_a?(String) }
-
30
options[:to] = to
-
30
options.delete(path)
-
30
paths = [path]
-
else
-
236
options = rest.pop || {}
-
236
paths = [path] + rest
-
end
-
-
266
options[:anchor] = true unless options.key?(:anchor)
-
-
266
if options[:on] && !VALID_ON_OPTIONS.include?(options[:on])
-
raise ArgumentError, "Unknown scope #{on.inspect} given to :on"
-
end
-
-
266
if @scope[:controller] && @scope[:action]
-
options[:to] ||= "#{@scope[:controller]}##{@scope[:action]}"
-
end
-
-
266
paths.each do |_path|
-
266
route_options = options.dup
-
266
route_options[:path] ||= _path if _path.is_a?(String)
-
-
266
path_without_format = _path.to_s.sub(/\(\.:format\)$/, '')
-
266
if using_match_shorthand?(path_without_format, route_options)
-
40
route_options[:to] ||= path_without_format.gsub(%r{^/}, "").sub(%r{/([^/]*)$}, '#\1')
-
40
route_options[:to].tr!("-", "_")
-
end
-
-
266
decomposed_match(_path, route_options)
-
end
-
266
self
-
end
-
-
2
def using_match_shorthand?(path, options)
-
266
path && (options[:to] || options[:action]).nil? && path =~ %r{/[\w/]+$}
-
end
-
-
2
def decomposed_match(path, options) # :nodoc:
-
266
if on = options.delete(:on)
-
send(on) { decomposed_match(path, options) }
-
else
-
266
case @scope[:scope_level]
-
when :resources
-
nested { decomposed_match(path, options) }
-
when :resource
-
member { decomposed_match(path, options) }
-
else
-
266
add_route(path, options)
-
end
-
end
-
end
-
-
2
def add_route(action, options) # :nodoc:
-
266
path = path_for_action(action, options.delete(:path))
-
266
action = action.to_s.dup
-
-
266
if action =~ /^[\w\-\/]+$/
-
256
options[:action] ||= action.tr('-', '_') unless action.include?("/")
-
else
-
10
action = nil
-
end
-
-
266
if !options.fetch(:as, true)
-
2
options.delete(:as)
-
else
-
264
options[:as] = name_for_action(options[:as], action)
-
end
-
-
266
mapping = Mapping.new(@set, @scope, URI.parser.escape(path), options)
-
266
app, conditions, requirements, defaults, as, anchor = mapping.to_route
-
266
@set.add_route(app, conditions, requirements, defaults, as, anchor)
-
end
-
-
2
def root(path, options={})
-
2
if path.is_a?(String)
-
2
options[:to] = path
-
elsif path.is_a?(Hash) and options.empty?
-
options = path
-
else
-
raise ArgumentError, "must be called with a path and/or options"
-
end
-
-
2
if @scope[:scope_level] == :resources
-
with_scope_level(:root) do
-
scope(parent_resource.path) do
-
super(options)
-
end
-
end
-
else
-
2
super(options)
-
end
-
end
-
-
2
protected
-
-
2
def parent_resource #:nodoc:
-
946
@scope[:scope_level_resource]
-
end
-
-
2
def apply_common_behavior_for(method, resources, options, &block) #:nodoc:
-
26
if resources.length > 1
-
resources.each { |r| send(method, r, options, &block) }
-
return true
-
end
-
-
26
if options.delete(:shallow)
-
shallow do
-
send(method, resources.pop, options, &block)
-
end
-
return true
-
end
-
-
26
if resource_scope?
-
4
nested { send(method, resources.pop, options, &block) }
-
2
return true
-
end
-
-
24
options.keys.each do |k|
-
(options[:constraints] ||= {})[k] = options.delete(k) if options[k].is_a?(Regexp)
-
end
-
-
24
scope_options = options.slice!(*RESOURCE_OPTIONS)
-
24
unless scope_options.empty?
-
scope(scope_options) do
-
send(method, resources.pop, options, &block)
-
end
-
return true
-
end
-
-
24
unless action_options?(options)
-
24
options.merge!(scope_action_options) if scope_action_options?
-
end
-
-
24
false
-
end
-
-
2
def action_options?(options) #:nodoc:
-
24
options[:only] || options[:except]
-
end
-
-
2
def scope_action_options? #:nodoc:
-
24
@scope[:options] && (@scope[:options][:only] || @scope[:options][:except])
-
end
-
-
2
def scope_action_options #:nodoc:
-
@scope[:options].slice(:only, :except)
-
end
-
-
2
def resource_scope? #:nodoc:
-
100
RESOURCE_SCOPES.include? @scope[:scope_level]
-
end
-
-
2
def resource_method_scope? #:nodoc:
-
384
RESOURCE_METHOD_SCOPES.include? @scope[:scope_level]
-
end
-
-
2
def nested_scope? #:nodoc:
-
98
@scope[:scope_level] == :nested
-
end
-
-
2
def with_exclusive_scope
-
begin
-
old_name_prefix, old_path = @scope[:as], @scope[:path]
-
@scope[:as], @scope[:path] = nil, nil
-
-
with_scope_level(:exclusive) do
-
yield
-
end
-
ensure
-
@scope[:as], @scope[:path] = old_name_prefix, old_path
-
end
-
end
-
-
2
def with_scope_level(kind)
-
98
old, @scope[:scope_level] = @scope[:scope_level], kind
-
98
yield
-
ensure
-
98
@scope[:scope_level] = old
-
end
-
-
2
def resource_scope(kind, resource) #:nodoc:
-
24
resource.shallow = @scope[:shallow]
-
24
old_resource, @scope[:scope_level_resource] = @scope[:scope_level_resource], resource
-
24
@nesting.push(resource)
-
-
24
with_scope_level(kind) do
-
48
scope(parent_resource.resource_scope) { yield }
-
end
-
ensure
-
24
@nesting.pop
-
24
@scope[:scope_level_resource] = old_resource
-
end
-
-
2
def nested_options #:nodoc:
-
2
options = { :as => parent_resource.member_name }
-
options[:constraints] = {
-
parent_resource.nested_param => param_constraint
-
2
} if param_constraint?
-
-
2
options
-
end
-
-
2
def nesting_depth #:nodoc:
-
@nesting.size
-
end
-
-
2
def shallow_nesting_depth #:nodoc:
-
@nesting.select(&:shallow?).size
-
end
-
-
2
def param_constraint? #:nodoc:
-
2
@scope[:constraints] && @scope[:constraints][parent_resource.param].is_a?(Regexp)
-
end
-
-
2
def param_constraint #:nodoc:
-
@scope[:constraints][parent_resource.param]
-
end
-
-
2
def canonical_action?(action, flag) #:nodoc:
-
530
flag && resource_method_scope? && CANONICAL_ACTIONS.include?(action.to_s)
-
end
-
-
2
def shallow_scope(path, options = {}) #:nodoc:
-
old_name_prefix, old_path = @scope[:as], @scope[:path]
-
@scope[:as], @scope[:path] = @scope[:shallow_prefix], @scope[:shallow_path]
-
-
scope(path, options) { yield }
-
ensure
-
@scope[:as], @scope[:path] = old_name_prefix, old_path
-
end
-
-
2
def path_for_action(action, path) #:nodoc:
-
266
if canonical_action?(action, path.blank?)
-
168
@scope[:path].to_s
-
else
-
98
"#{@scope[:path]}/#{action_path(action, path)}"
-
end
-
end
-
-
2
def action_path(name, path = nil) #:nodoc:
-
122
name = name.to_sym if name.is_a?(String)
-
122
path || @scope[:path_names][name] || name.to_s
-
end
-
-
2
def prefix_name_for_action(as, action) #:nodoc:
-
266
if as
-
2
prefix = as
-
elsif !canonical_action?(action, @scope[:scope_level])
-
96
prefix = action
-
end
-
266
prefix.to_s.tr('-', '_') if prefix
-
end
-
-
2
def name_for_action(as, action) #:nodoc:
-
266
prefix = prefix_name_for_action(as, action)
-
266
prefix = Mapper.normalize_name(prefix) if prefix
-
266
name_prefix = @scope[:as]
-
-
266
if parent_resource
-
192
return nil unless as || action
-
-
192
collection_name = parent_resource.collection_name
-
192
member_name = parent_resource.member_name
-
end
-
-
266
name = case @scope[:scope_level]
-
when :nested
-
[name_prefix, prefix]
-
when :collection
-
48
[prefix, name_prefix, collection_name]
-
when :new
-
24
[prefix, :new, name_prefix, member_name]
-
when :member
-
120
[prefix, name_prefix, member_name]
-
when :root
-
[name_prefix, collection_name, prefix]
-
else
-
74
[name_prefix, member_name, prefix]
-
end
-
-
266
if candidate = name.select(&:present?).join("_").presence
-
# If a name was not explicitly given, we check if it is valid
-
# and return nil in case it isn't. Otherwise, we pass the invalid name
-
# forward so the underlying router engine treats it and raises an exception.
-
256
if as.nil?
-
17360
candidate unless @set.routes.find { |r| r.name == candidate } || candidate !~ /\A[_a-z]/i
-
else
-
2
candidate
-
end
-
end
-
end
-
-
2
def set_member_mappings_for_resource
-
24
member do
-
24
get :edit if parent_resource.actions.include?(:edit)
-
24
get :show if parent_resource.actions.include?(:show)
-
24
if parent_resource.actions.include?(:update)
-
24
patch :update
-
24
put :update
-
end
-
24
delete :destroy if parent_resource.actions.include?(:destroy)
-
end
-
end
-
end
-
-
# Routing Concerns allow you to declare common routes that can be reused
-
# inside others resources and routes.
-
#
-
# concern :commentable do
-
# resources :comments
-
# end
-
#
-
# concern :image_attachable do
-
# resources :images, only: :index
-
# end
-
#
-
# These concerns are used in Resources routing:
-
#
-
# resources :messages, concerns: [:commentable, :image_attachable]
-
#
-
# or in a scope or namespace:
-
#
-
# namespace :posts do
-
# concerns :commentable
-
# end
-
2
module Concerns
-
# Define a routing concern using a name.
-
#
-
# Concerns may be defined inline, using a block, or handled by
-
# another object, by passing that object as the second parameter.
-
#
-
# The concern object, if supplied, should respond to <tt>call</tt>,
-
# which will receive two parameters:
-
#
-
# * The current mapper
-
# * A hash of options which the concern object may use
-
#
-
# Options may also be used by concerns defined in a block by accepting
-
# a block parameter. So, using a block, you might do something as
-
# simple as limit the actions available on certain resources, passing
-
# standard resource options through the concern:
-
#
-
# concern :commentable do |options|
-
# resources :comments, options
-
# end
-
#
-
# resources :posts, concerns: :commentable
-
# resources :archived_posts do
-
# # Don't allow comments on archived posts
-
# concerns :commentable, only: [:index, :show]
-
# end
-
#
-
# Or, using a callable object, you might implement something more
-
# specific to your application, which would be out of place in your
-
# routes file.
-
#
-
# # purchasable.rb
-
# class Purchasable
-
# def initialize(defaults = {})
-
# @defaults = defaults
-
# end
-
#
-
# def call(mapper, options = {})
-
# options = @defaults.merge(options)
-
# mapper.resources :purchases
-
# mapper.resources :receipts
-
# mapper.resources :returns if options[:returnable]
-
# end
-
# end
-
#
-
# # routes.rb
-
# concern :purchasable, Purchasable.new(returnable: true)
-
#
-
# resources :toys, concerns: :purchasable
-
# resources :electronics, concerns: :purchasable
-
# resources :pets do
-
# concerns :purchasable, returnable: false
-
# end
-
#
-
# Any routing helpers can be used inside a concern. If using a
-
# callable, they're accessible from the Mapper that's passed to
-
# <tt>call</tt>.
-
2
def concern(name, callable = nil, &block)
-
callable ||= lambda { |mapper, options| mapper.instance_exec(options, &block) }
-
@concerns[name] = callable
-
end
-
-
# Use the named concerns
-
#
-
# resources :posts do
-
# concerns :commentable
-
# end
-
#
-
# concerns also work in any routes helper that you want to use:
-
#
-
# namespace :posts do
-
# concerns :commentable
-
# end
-
2
def concerns(*args)
-
options = args.extract_options!
-
args.flatten.each do |name|
-
if concern = @concerns[name]
-
concern.call(self, options)
-
else
-
raise ArgumentError, "No concern named #{name} was found!"
-
end
-
end
-
end
-
end
-
-
2
def initialize(set) #:nodoc:
-
4
@set = set
-
4
@scope = { :path_names => @set.resources_path_names }
-
4
@concerns = {}
-
4
@nesting = []
-
end
-
-
2
include Base
-
2
include HttpHelpers
-
2
include Redirection
-
2
include Scoping
-
2
include Concerns
-
2
include Resources
-
end
-
end
-
end
-
2
require 'action_controller/model_naming'
-
-
2
module ActionDispatch
-
2
module Routing
-
# Polymorphic URL helpers are methods for smart resolution to a named route call when
-
# given an Active Record model instance. They are to be used in combination with
-
# ActionController::Resources.
-
#
-
# These methods are useful when you want to generate correct URL or path to a RESTful
-
# resource without having to know the exact type of the record in question.
-
#
-
# Nested resources and/or namespaces are also supported, as illustrated in the example:
-
#
-
# polymorphic_url([:admin, @article, @comment])
-
#
-
# results in:
-
#
-
# admin_article_comment_url(@article, @comment)
-
#
-
# == Usage within the framework
-
#
-
# Polymorphic URL helpers are used in a number of places throughout the \Rails framework:
-
#
-
# * <tt>url_for</tt>, so you can use it with a record as the argument, e.g.
-
# <tt>url_for(@article)</tt>;
-
# * ActionView::Helpers::FormHelper uses <tt>polymorphic_path</tt>, so you can write
-
# <tt>form_for(@article)</tt> without having to specify <tt>:url</tt> parameter for the form
-
# action;
-
# * <tt>redirect_to</tt> (which, in fact, uses <tt>url_for</tt>) so you can write
-
# <tt>redirect_to(post)</tt> in your controllers;
-
# * ActionView::Helpers::AtomFeedHelper, so you don't have to explicitly specify URLs
-
# for feed entries.
-
#
-
# == Prefixed polymorphic helpers
-
#
-
# In addition to <tt>polymorphic_url</tt> and <tt>polymorphic_path</tt> methods, a
-
# number of prefixed helpers are available as a shorthand to <tt>action: "..."</tt>
-
# in options. Those are:
-
#
-
# * <tt>edit_polymorphic_url</tt>, <tt>edit_polymorphic_path</tt>
-
# * <tt>new_polymorphic_url</tt>, <tt>new_polymorphic_path</tt>
-
#
-
# Example usage:
-
#
-
# edit_polymorphic_path(@post) # => "/posts/1/edit"
-
# polymorphic_path(@post, format: :pdf) # => "/posts/1.pdf"
-
#
-
# == Usage with mounted engines
-
#
-
# If you are using a mounted engine and you need to use a polymorphic_url
-
# pointing at the engine's routes, pass in the engine's route proxy as the first
-
# argument to the method. For example:
-
#
-
# polymorphic_url([blog, @post]) # calls blog.post_path(@post)
-
# form_for([blog, @post]) # => "/blog/posts/1"
-
#
-
2
module PolymorphicRoutes
-
2
include ActionController::ModelNaming
-
-
# Constructs a call to a named RESTful route for the given record and returns the
-
# resulting URL string. For example:
-
#
-
# # calls post_url(post)
-
# polymorphic_url(post) # => "http://example.com/posts/1"
-
# polymorphic_url([blog, post]) # => "http://example.com/blogs/1/posts/1"
-
# polymorphic_url([:admin, blog, post]) # => "http://example.com/admin/blogs/1/posts/1"
-
# polymorphic_url([user, :blog, post]) # => "http://example.com/users/1/blog/posts/1"
-
# polymorphic_url(Comment) # => "http://example.com/comments"
-
#
-
# ==== Options
-
#
-
# * <tt>:action</tt> - Specifies the action prefix for the named route:
-
# <tt>:new</tt> or <tt>:edit</tt>. Default is no prefix.
-
# * <tt>:routing_type</tt> - Allowed values are <tt>:path</tt> or <tt>:url</tt>.
-
# Default is <tt>:url</tt>.
-
#
-
# Also includes all the options from <tt>url_for</tt>. These include such
-
# things as <tt>:anchor</tt> or <tt>:trailing_slash</tt>. Example usage
-
# is given below:
-
#
-
# polymorphic_url([blog, post], anchor: 'my_anchor')
-
# # => "http://example.com/blogs/1/posts/1#my_anchor"
-
# polymorphic_url([blog, post], anchor: 'my_anchor', script_name: "/my_app")
-
# # => "http://example.com/my_app/blogs/1/posts/1#my_anchor"
-
#
-
# For all of these options, see the documentation for <tt>url_for</tt>.
-
#
-
# ==== Functionality
-
#
-
# # an Article record
-
# polymorphic_url(record) # same as article_url(record)
-
#
-
# # a Comment record
-
# polymorphic_url(record) # same as comment_url(record)
-
#
-
# # it recognizes new records and maps to the collection
-
# record = Comment.new
-
# polymorphic_url(record) # same as comments_url()
-
#
-
# # the class of a record will also map to the collection
-
# polymorphic_url(Comment) # same as comments_url()
-
#
-
2
def polymorphic_url(record_or_hash_or_array, options = {})
-
4
if record_or_hash_or_array.kind_of?(Array)
-
record_or_hash_or_array = record_or_hash_or_array.compact
-
if record_or_hash_or_array.first.is_a?(ActionDispatch::Routing::RoutesProxy)
-
proxy = record_or_hash_or_array.shift
-
end
-
record_or_hash_or_array = record_or_hash_or_array[0] if record_or_hash_or_array.size == 1
-
end
-
-
4
record = extract_record(record_or_hash_or_array)
-
4
record = convert_to_model(record)
-
-
4
args = Array === record_or_hash_or_array ?
-
record_or_hash_or_array.dup :
-
[ record_or_hash_or_array ]
-
-
4
inflection = if options[:action] && options[:action].to_s == "new"
-
args.pop
-
:singular
-
elsif (record.respond_to?(:persisted?) && !record.persisted?)
-
4
args.pop
-
4
:plural
-
elsif record.is_a?(Class)
-
args.pop
-
:plural
-
else
-
:singular
-
end
-
-
4
args.delete_if {|arg| arg.is_a?(Symbol) || arg.is_a?(String)}
-
4
named_route = build_named_route_call(record_or_hash_or_array, inflection, options)
-
-
4
url_options = options.except(:action, :routing_type)
-
4
unless url_options.empty?
-
4
args.last.kind_of?(Hash) ? args.last.merge!(url_options) : args << url_options
-
end
-
-
8
args.collect! { |a| convert_to_model(a) }
-
-
4
(proxy || self).send(named_route, *args)
-
end
-
-
# Returns the path component of a URL for the given record. It uses
-
# <tt>polymorphic_url</tt> with <tt>routing_type: :path</tt>.
-
2
def polymorphic_path(record_or_hash_or_array, options = {})
-
4
polymorphic_url(record_or_hash_or_array, options.merge(:routing_type => :path))
-
end
-
-
2
%w(edit new).each do |action|
-
4
module_eval <<-EOT, __FILE__, __LINE__ + 1
-
def #{action}_polymorphic_url(record_or_hash, options = {}) # def edit_polymorphic_url(record_or_hash, options = {})
-
polymorphic_url( # polymorphic_url(
-
record_or_hash, # record_or_hash,
-
options.merge(:action => "#{action}")) # options.merge(:action => "edit"))
-
end # end
-
#
-
def #{action}_polymorphic_path(record_or_hash, options = {}) # def edit_polymorphic_path(record_or_hash, options = {})
-
polymorphic_url( # polymorphic_url(
-
record_or_hash, # record_or_hash,
-
options.merge(:action => "#{action}", :routing_type => :path)) # options.merge(:action => "edit", :routing_type => :path))
-
end # end
-
EOT
-
end
-
-
2
private
-
2
def action_prefix(options)
-
4
options[:action] ? "#{options[:action]}_" : ''
-
end
-
-
2
def routing_type(options)
-
4
options[:routing_type] || :url
-
end
-
-
2
def build_named_route_call(records, inflection, options = {})
-
4
if records.is_a?(Array)
-
record = records.pop
-
route = records.map do |parent|
-
if parent.is_a?(Symbol) || parent.is_a?(String)
-
parent
-
else
-
model_name_from_record_or_class(parent).singular_route_key
-
end
-
end
-
else
-
4
record = extract_record(records)
-
4
route = []
-
end
-
-
4
if record.is_a?(Symbol) || record.is_a?(String)
-
route << record
-
elsif record
-
4
if inflection == :singular
-
route << model_name_from_record_or_class(record).singular_route_key
-
else
-
4
route << model_name_from_record_or_class(record).route_key
-
end
-
else
-
raise ArgumentError, "Nil location provided. Can't build URI."
-
end
-
-
4
route << routing_type(options)
-
-
4
action_prefix(options) + route.join("_")
-
end
-
-
2
def extract_record(record_or_hash_or_array)
-
8
case record_or_hash_or_array
-
when Array; record_or_hash_or_array.last
-
when Hash; record_or_hash_or_array[:id]
-
8
else record_or_hash_or_array
-
end
-
end
-
end
-
end
-
end
-
-
2
require 'action_dispatch/http/request'
-
2
require 'active_support/core_ext/uri'
-
2
require 'active_support/core_ext/array/extract_options'
-
2
require 'rack/utils'
-
2
require 'action_controller/metal/exceptions'
-
-
2
module ActionDispatch
-
2
module Routing
-
2
class Redirect # :nodoc:
-
2
attr_reader :status, :block
-
-
2
def initialize(status, block)
-
@status = status
-
@block = block
-
end
-
-
2
def call(env)
-
req = Request.new(env)
-
-
# If any of the path parameters has an invalid encoding then
-
# raise since it's likely to trigger errors further on.
-
req.symbolized_path_parameters.each do |key, value|
-
unless value.valid_encoding?
-
raise ActionController::BadRequest, "Invalid parameter: #{key} => #{value}"
-
end
-
end
-
-
uri = URI.parse(path(req.symbolized_path_parameters, req))
-
-
unless uri.host
-
if relative_path?(uri.path)
-
uri.path = "#{req.script_name}/#{uri.path}"
-
elsif uri.path.empty?
-
uri.path = req.script_name.empty? ? "/" : req.script_name
-
end
-
end
-
-
uri.scheme ||= req.scheme
-
uri.host ||= req.host
-
uri.port ||= req.port unless req.standard_port?
-
-
body = %(<html><body>You are being <a href="#{ERB::Util.h(uri.to_s)}">redirected</a>.</body></html>)
-
-
headers = {
-
'Location' => uri.to_s,
-
'Content-Type' => 'text/html',
-
'Content-Length' => body.length.to_s
-
}
-
-
[ status, headers, [body] ]
-
end
-
-
2
def path(params, request)
-
block.call params, request
-
end
-
-
2
def inspect
-
"redirect(#{status})"
-
end
-
-
2
private
-
2
def relative_path?(path)
-
path && !path.empty? && path[0] != '/'
-
end
-
-
2
def escape(params)
-
Hash[params.map{ |k,v| [k, Rack::Utils.escape(v)] }]
-
end
-
-
2
def escape_fragment(params)
-
Hash[params.map{ |k,v| [k, Journey::Router::Utils.escape_fragment(v)] }]
-
end
-
-
2
def escape_path(params)
-
Hash[params.map{ |k,v| [k, Journey::Router::Utils.escape_path(v)] }]
-
end
-
end
-
-
2
class PathRedirect < Redirect
-
2
URL_PARTS = /\A([^?]+)?(\?[^#]+)?(#.+)?\z/
-
-
2
def path(params, request)
-
if block.match(URL_PARTS)
-
path = interpolation_required?($1, params) ? $1 % escape_path(params) : $1
-
query = interpolation_required?($2, params) ? $2 % escape(params) : $2
-
fragment = interpolation_required?($3, params) ? $3 % escape_fragment(params) : $3
-
-
"#{path}#{query}#{fragment}"
-
else
-
interpolation_required?(block, params) ? block % escape(params) : block
-
end
-
end
-
-
2
def inspect
-
"redirect(#{status}, #{block})"
-
end
-
-
2
private
-
2
def interpolation_required?(string, params)
-
!params.empty? && string && string.match(/%\{\w*\}/)
-
end
-
end
-
-
2
class OptionRedirect < Redirect # :nodoc:
-
2
alias :options :block
-
-
2
def path(params, request)
-
url_options = {
-
:protocol => request.protocol,
-
:host => request.host,
-
:port => request.optional_port,
-
:path => request.path,
-
:params => request.query_parameters
-
}.merge! options
-
-
if !params.empty? && url_options[:path].match(/%\{\w*\}/)
-
url_options[:path] = (url_options[:path] % escape_path(params))
-
end
-
-
unless options[:host] || options[:domain]
-
if relative_path?(url_options[:path])
-
url_options[:path] = "/#{url_options[:path]}"
-
url_options[:script_name] = request.script_name
-
elsif url_options[:path].empty?
-
url_options[:path] = request.script_name.empty? ? "/" : ""
-
url_options[:script_name] = request.script_name
-
end
-
end
-
-
ActionDispatch::Http::URL.url_for url_options
-
end
-
-
2
def inspect
-
"redirect(#{status}, #{options.map{ |k,v| "#{k}: #{v}" }.join(', ')})"
-
end
-
end
-
-
2
module Redirection
-
-
# Redirect any path to another path:
-
#
-
# get "/stories" => redirect("/posts")
-
#
-
# You can also use interpolation in the supplied redirect argument:
-
#
-
# get 'docs/:article', to: redirect('/wiki/%{article}')
-
#
-
# Note that if you return a path without a leading slash then the url is prefixed with the
-
# current SCRIPT_NAME environment variable. This is typically '/' but may be different in
-
# a mounted engine or where the application is deployed to a subdirectory of a website.
-
#
-
# Alternatively you can use one of the other syntaxes:
-
#
-
# The block version of redirect allows for the easy encapsulation of any logic associated with
-
# the redirect in question. Either the params and request are supplied as arguments, or just
-
# params, depending of how many arguments your block accepts. A string is required as a
-
# return value.
-
#
-
# get 'jokes/:number', to: redirect { |params, request|
-
# path = (params[:number].to_i.even? ? "wheres-the-beef" : "i-love-lamp")
-
# "http://#{request.host_with_port}/#{path}"
-
# }
-
#
-
# Note that the +do end+ syntax for the redirect block wouldn't work, as Ruby would pass
-
# the block to +get+ instead of +redirect+. Use <tt>{ ... }</tt> instead.
-
#
-
# The options version of redirect allows you to supply only the parts of the url which need
-
# to change, it also supports interpolation of the path similar to the first example.
-
#
-
# get 'stores/:name', to: redirect(subdomain: 'stores', path: '/%{name}')
-
# get 'stores/:name(*all)', to: redirect(subdomain: 'stores', path: '/%{name}%{all}')
-
#
-
# Finally, an object which responds to call can be supplied to redirect, allowing you to reuse
-
# common redirect routes. The call method must accept two arguments, params and request, and return
-
# a string.
-
#
-
# get 'accounts/:name' => redirect(SubdomainRedirector.new('api'))
-
#
-
2
def redirect(*args, &block)
-
options = args.extract_options!
-
status = options.delete(:status) || 301
-
path = args.shift
-
-
return OptionRedirect.new(status, options) if options.any?
-
return PathRedirect.new(status, path) if String === path
-
-
block = path if path.respond_to? :call
-
raise ArgumentError, "redirection argument not supported" unless block
-
Redirect.new status, block
-
end
-
end
-
end
-
end
-
2
require 'action_dispatch/journey'
-
2
require 'forwardable'
-
2
require 'thread_safe'
-
2
require 'active_support/concern'
-
2
require 'active_support/core_ext/object/to_query'
-
2
require 'active_support/core_ext/hash/slice'
-
2
require 'active_support/core_ext/module/remove_method'
-
2
require 'active_support/core_ext/array/extract_options'
-
2
require 'action_controller/metal/exceptions'
-
2
require 'action_dispatch/http/request'
-
-
2
module ActionDispatch
-
2
module Routing
-
2
class RouteSet #:nodoc:
-
# Since the router holds references to many parts of the system
-
# like engines, controllers and the application itself, inspecting
-
# the route set can actually be really slow, therefore we default
-
# alias inspect to to_s.
-
2
alias inspect to_s
-
-
2
PARAMETERS_KEY = 'action_dispatch.request.path_parameters'
-
-
2
class Dispatcher #:nodoc:
-
2
def initialize(options={})
-
264
@defaults = options[:defaults]
-
264
@glob_param = options.delete(:glob)
-
264
@controller_class_names = ThreadSafe::Cache.new
-
end
-
-
2
def call(env)
-
13
params = env[PARAMETERS_KEY]
-
-
# If any of the path parameters has an invalid encoding then
-
# raise since it's likely to trigger errors further on.
-
13
params.each do |key, value|
-
26
next unless value.respond_to?(:valid_encoding?)
-
-
26
unless value.valid_encoding?
-
raise ActionController::BadRequest, "Invalid parameter: #{key} => #{value}"
-
end
-
end
-
-
13
prepare_params!(params)
-
-
# Just raise undefined constant errors if a controller was specified as default.
-
13
unless controller = controller(params, @defaults.key?(:controller))
-
return [404, {'X-Cascade' => 'pass'}, []]
-
end
-
-
13
dispatch(controller, params[:action], env)
-
end
-
-
2
def prepare_params!(params)
-
13
normalize_controller!(params)
-
13
merge_default_action!(params)
-
13
split_glob_param!(params) if @glob_param
-
end
-
-
# If this is a default_controller (i.e. a controller specified by the user)
-
# we should raise an error in case it's not found, because it usually means
-
# a user error. However, if the controller was retrieved through a dynamic
-
# segment, as in :controller(/:action), we should simply return nil and
-
# delegate the control back to Rack cascade. Besides, if this is not a default
-
# controller, it means we should respect the @scope[:module] parameter.
-
2
def controller(params, default_controller=true)
-
13
if params && params.key?(:controller)
-
13
controller_param = params[:controller]
-
13
controller_reference(controller_param)
-
end
-
rescue NameError => e
-
raise ActionController::RoutingError, e.message, e.backtrace if default_controller
-
end
-
-
2
private
-
-
2
def controller_reference(controller_param)
-
13
const_name = @controller_class_names[controller_param] ||= "#{controller_param.camelize}Controller"
-
13
ActiveSupport::Dependencies.constantize(const_name)
-
end
-
-
2
def dispatch(controller, action, env)
-
13
controller.action(action).call(env)
-
end
-
-
2
def normalize_controller!(params)
-
13
params[:controller] = params[:controller].underscore if params.key?(:controller)
-
end
-
-
2
def merge_default_action!(params)
-
13
params[:action] ||= 'index'
-
end
-
-
2
def split_glob_param!(params)
-
params[@glob_param] = params[@glob_param].split('/').map { |v| URI.parser.unescape(v) }
-
end
-
end
-
-
# A NamedRouteCollection instance is a collection of named routes, and also
-
# maintains an anonymous module that can be used to install helpers for the
-
# named routes.
-
2
class NamedRouteCollection #:nodoc:
-
2
include Enumerable
-
2
attr_reader :routes, :helpers, :module
-
-
2
def initialize
-
2
@routes = {}
-
2
@helpers = []
-
2
@module = Module.new
-
end
-
-
2
def helper_names
-
8
@helpers.map(&:to_s)
-
end
-
-
2
def clear!
-
2
@helpers.each do |helper|
-
@module.remove_possible_method helper
-
end
-
-
2
@routes.clear
-
2
@helpers.clear
-
end
-
-
2
def add(name, route)
-
148
routes[name.to_sym] = route
-
148
define_named_route_methods(name, route)
-
end
-
-
2
def get(name)
-
156
routes[name.to_sym]
-
end
-
-
2
alias []= add
-
2
alias [] get
-
2
alias clear clear!
-
-
2
def each
-
routes.each { |name, route| yield name, route }
-
self
-
end
-
-
2
def names
-
routes.keys
-
end
-
-
2
def length
-
routes.length
-
end
-
-
2
class UrlHelper # :nodoc:
-
2
def self.create(route, options)
-
296
if optimize_helper?(route)
-
296
OptimizedUrlHelper.new(route, options)
-
else
-
new route, options
-
end
-
end
-
-
2
def self.optimize_helper?(route)
-
296
!route.glob? && route.requirements.except(:controller, :action).empty?
-
end
-
-
2
class OptimizedUrlHelper < UrlHelper # :nodoc:
-
2
attr_reader :arg_size
-
-
2
def initialize(route, options)
-
296
super
-
296
@klass = Journey::Router::Utils
-
296
@required_parts = @route.required_parts
-
296
@arg_size = @required_parts.size
-
296
@optimized_path = @route.optimized_path
-
end
-
-
2
def call(t, args)
-
59
if args.size == arg_size && !args.last.is_a?(Hash) && optimize_routes_generation?(t)
-
55
options = @options.dup
-
55
options.merge!(t.url_options) if t.respond_to?(:url_options)
-
55
options[:path] = optimized_helper(args)
-
55
ActionDispatch::Http::URL.url_for(options)
-
else
-
4
super
-
end
-
end
-
-
2
private
-
-
2
def optimized_helper(args)
-
55
params = Hash[parameterize_args(args)]
-
55
missing_keys = missing_keys(params)
-
-
55
unless missing_keys.empty?
-
raise_generation_error(params, missing_keys)
-
end
-
-
275
@optimized_path.map{ |segment| replace_segment(params, segment) }.join
-
end
-
-
2
def replace_segment(params, segment)
-
220
Symbol === segment ? @klass.escape_segment(params[segment]) : segment
-
end
-
-
2
def optimize_routes_generation?(t)
-
55
t.send(:optimize_routes_generation?)
-
end
-
-
2
def parameterize_args(args)
-
55
@required_parts.zip(args.map(&:to_param))
-
end
-
-
2
def missing_keys(args)
-
55
args.select{ |part, arg| arg.nil? || arg.empty? }.keys
-
end
-
-
2
def raise_generation_error(args, missing_keys)
-
constraints = Hash[@route.requirements.merge(args).sort]
-
message = "No route matches #{constraints.inspect}"
-
message << " missing required keys: #{missing_keys.sort.inspect}"
-
-
raise ActionController::UrlGenerationError, message
-
end
-
end
-
-
2
def initialize(route, options)
-
296
@options = options
-
296
@segment_keys = route.segment_keys.uniq
-
296
@route = route
-
end
-
-
2
def call(t, args)
-
4
t.url_for(handle_positional_args(t, args, @options, @segment_keys))
-
end
-
-
2
def handle_positional_args(t, args, options, keys)
-
4
inner_options = args.extract_options!
-
4
result = options.dup
-
-
4
if args.size > 0
-
if args.size < keys.size - 1 # take format into account
-
keys -= t.url_options.keys if t.respond_to?(:url_options)
-
keys -= options.keys
-
end
-
keys -= inner_options.keys
-
result.merge!(Hash[keys.zip(args)])
-
end
-
-
4
result.merge!(inner_options)
-
end
-
end
-
-
2
private
-
# Create a url helper allowing ordered parameters to be associated
-
# with corresponding dynamic segments, so you can do:
-
#
-
# foo_url(bar, baz, bang)
-
#
-
# Instead of:
-
#
-
# foo_url(bar: bar, baz: baz, bang: bang)
-
#
-
# Also allow options hash, so you can do:
-
#
-
# foo_url(bar, baz, bang, sort_by: 'baz')
-
#
-
2
def define_url_helper(route, name, options)
-
296
helper = UrlHelper.create(route, options.dup)
-
-
296
@module.remove_possible_method name
-
296
@module.module_eval do
-
296
define_method(name) do |*args|
-
59
helper.call self, args
-
end
-
end
-
-
296
helpers << name
-
end
-
-
2
def define_named_route_methods(name, route)
-
148
define_url_helper route, :"#{name}_path",
-
route.defaults.merge(:use_route => name, :only_path => true)
-
148
define_url_helper route, :"#{name}_url",
-
route.defaults.merge(:use_route => name, :only_path => false)
-
end
-
end
-
-
2
attr_accessor :formatter, :set, :named_routes, :default_scope, :router
-
2
attr_accessor :disable_clear_and_finalize, :resources_path_names
-
2
attr_accessor :default_url_options, :request_class
-
-
2
alias :routes :set
-
-
2
def self.default_resources_path_names
-
2
{ :new => 'new', :edit => 'edit' }
-
end
-
-
2
def initialize(request_class = ActionDispatch::Request)
-
2
self.named_routes = NamedRouteCollection.new
-
2
self.resources_path_names = self.class.default_resources_path_names.dup
-
2
self.default_url_options = {}
-
2
self.request_class = request_class
-
-
2
@append = []
-
2
@prepend = []
-
2
@disable_clear_and_finalize = false
-
2
@finalized = false
-
-
2
@set = Journey::Routes.new
-
2
@router = Journey::Router.new(@set, {
-
:parameters_key => PARAMETERS_KEY,
-
:request_class => request_class})
-
2
@formatter = Journey::Formatter.new @set
-
end
-
-
2
def draw(&block)
-
2
clear! unless @disable_clear_and_finalize
-
2
eval_block(block)
-
2
finalize! unless @disable_clear_and_finalize
-
nil
-
end
-
-
2
def append(&block)
-
@append << block
-
end
-
-
2
def prepend(&block)
-
2
@prepend << block
-
end
-
-
2
def eval_block(block)
-
4
if block.arity == 1
-
raise "You are using the old router DSL which has been removed in Rails 3.1. " <<
-
"Please check how to update your routes file at: http://www.engineyard.com/blog/2010/the-lowdown-on-routes-in-rails-3/"
-
end
-
4
mapper = Mapper.new(self)
-
4
if default_scope
-
mapper.with_default_scope(default_scope, &block)
-
else
-
4
mapper.instance_exec(&block)
-
end
-
end
-
-
2
def finalize!
-
2
return if @finalized
-
2
@append.each { |blk| eval_block(blk) }
-
2
@finalized = true
-
end
-
-
2
def clear!
-
2
@finalized = false
-
2
named_routes.clear
-
2
set.clear
-
2
formatter.clear
-
4
@prepend.each { |blk| eval_block(blk) }
-
end
-
-
2
module MountedHelpers #:nodoc:
-
2
extend ActiveSupport::Concern
-
2
include UrlFor
-
end
-
-
# Contains all the mounted helpers across different
-
# engines and the `main_app` helper for the application.
-
# You can include this in your classes if you want to
-
# access routes for other engines.
-
2
def mounted_helpers
-
18
MountedHelpers
-
end
-
-
2
def define_mounted_helper(name)
-
2
return if MountedHelpers.method_defined?(name)
-
-
2
routes = self
-
2
MountedHelpers.class_eval do
-
2
define_method "_#{name}" do
-
RoutesProxy.new(routes, _routes_context)
-
end
-
end
-
-
2
MountedHelpers.class_eval(<<-RUBY, __FILE__, __LINE__ + 1)
-
def #{name}
-
@_#{name} ||= _#{name}
-
end
-
RUBY
-
end
-
-
2
def url_helpers
-
@url_helpers ||= begin
-
2
routes = self
-
-
2
Module.new do
-
2
extend ActiveSupport::Concern
-
2
include UrlFor
-
-
# Define url_for in the singleton level so one can do:
-
# Rails.application.routes.url_helpers.url_for(args)
-
2
@_routes = routes
-
2
class << self
-
2
delegate :url_for, :optimize_routes_generation?, :to => '@_routes'
-
end
-
-
# Make named_routes available in the module singleton
-
# as well, so one can do:
-
# Rails.application.routes.url_helpers.posts_path
-
2
extend routes.named_routes.module
-
-
# Any class that includes this module will get all
-
# named routes...
-
2
include routes.named_routes.module
-
-
# plus a singleton class method called _routes ...
-
2
included do
-
41
singleton_class.send(:redefine_method, :_routes) { routes }
-
end
-
-
# And an instance method _routes. Note that
-
# UrlFor (included in this module) add extra
-
# conveniences for working with @_routes.
-
116
define_method(:_routes) { @_routes || routes }
-
end
-
27
end
-
end
-
-
2
def empty?
-
routes.empty?
-
end
-
-
2
def add_route(app, conditions = {}, requirements = {}, defaults = {}, name = nil, anchor = true)
-
266
raise ArgumentError, "Invalid route name: '#{name}'" unless name.blank? || name.to_s.match(/^[_a-z]\w*$/i)
-
-
266
if name && named_routes[name]
-
raise ArgumentError, "Invalid route name, already in use: '#{name}' \n" \
-
"You may have defined two routes with the same name using the `:as` option, or " \
-
"you may be overriding a route already defined by a resource with the same naming. " \
-
"For the latter, you can restrict the routes created with `resources` as explained here: \n" \
-
"http://guides.rubyonrails.org/routing.html#restricting-the-routes-created"
-
end
-
-
266
path = build_path(conditions.delete(:path_info), requirements, SEPARATORS, anchor)
-
676
conditions = build_conditions(conditions, path.names.map { |x| x.to_sym })
-
-
266
route = @set.add_route(app, path, conditions, defaults, name)
-
266
named_routes[name] = route if name
-
266
route
-
end
-
-
2
def build_path(path, requirements, separators, anchor)
-
266
strexp = Journey::Router::Strexp.new(
-
path,
-
requirements,
-
SEPARATORS,
-
anchor)
-
-
266
pattern = Journey::Path::Pattern.new(strexp)
-
-
266
builder = Journey::GTG::Builder.new pattern.spec
-
-
# Get all the symbol nodes followed by literals that are not the
-
# dummy node.
-
266
symbols = pattern.spec.grep(Journey::Nodes::Symbol).find_all { |n|
-
410
builder.followpos(n).first.literal?
-
}
-
-
# Get all the symbol nodes preceded by literals.
-
266
symbols.concat pattern.spec.find_all(&:literal?).map { |n|
-
382
builder.followpos(n).first
-
}.find_all(&:symbol?)
-
-
266
symbols.each { |x|
-
x.regexp = /(?:#{Regexp.union(x.regexp, '-')})+/
-
}
-
-
266
pattern
-
end
-
2
private :build_path
-
-
2
def build_conditions(current_conditions, path_values)
-
266
conditions = current_conditions.dup
-
-
# Rack-Mount requires that :request_method be a regular expression.
-
# :request_method represents the HTTP verb that matches this route.
-
#
-
# Here we munge values before they get sent on to rack-mount.
-
266
verbs = conditions[:request_method] || []
-
266
unless verbs.empty?
-
264
conditions[:request_method] = %r[^#{verbs.join('|')}$]
-
end
-
-
266
conditions.keep_if do |k, _|
-
530
k == :action || k == :controller || k == :required_defaults ||
-
@request_class.public_method_defined?(k) || path_values.include?(k)
-
end
-
end
-
2
private :build_conditions
-
-
2
class Generator #:nodoc:
-
2
PARAMETERIZE = lambda do |name, value|
-
if name == :controller
-
value
-
elsif value.is_a?(Array)
-
value.map { |v| v.to_param }.join('/')
-
elsif param = value.to_param
-
param
-
end
-
end
-
-
2
attr_reader :options, :recall, :set, :named_route
-
-
2
def initialize(options, recall, set)
-
34
@named_route = options.delete(:use_route)
-
34
@options = options.dup
-
34
@recall = recall.dup
-
34
@set = set
-
-
34
normalize_recall!
-
34
normalize_options!
-
34
normalize_controller_action_id!
-
34
use_relative_controller!
-
34
normalize_controller!
-
34
normalize_action!
-
end
-
-
2
def controller
-
100
@options[:controller]
-
end
-
-
2
def current_controller
-
46
@recall[:controller]
-
end
-
-
2
def use_recall_for(key)
-
56
if @recall[key] && (!@options.key?(key) || @options[key] == @recall[key])
-
26
if !named_route_exists? || segment_keys.include?(key)
-
22
@options[key] = @recall.delete(key)
-
end
-
end
-
end
-
-
# Set 'index' as default action for recall
-
2
def normalize_recall!
-
34
@recall[:action] ||= 'index'
-
end
-
-
2
def normalize_options!
-
# If an explicit :controller was given, always make :action explicit
-
# too, so that action expiry works as expected for things like
-
#
-
# generate({controller: 'content'}, {controller: 'content', action: 'show'})
-
#
-
# (the above is from the unit tests). In the above case, because the
-
# controller was explicitly given, but no action, the action is implied to
-
# be "index", not the recalled action of "show".
-
-
34
if options[:controller]
-
23
options[:action] ||= 'index'
-
23
options[:controller] = options[:controller].to_s
-
end
-
-
34
if options.key?(:action)
-
34
options[:action] = (options[:action] || 'index').to_s
-
end
-
end
-
-
# This pulls :controller, :action, and :id out of the recall.
-
# The recall key is only used if there is no key in the options
-
# or if the key in the options is identical. If any of
-
# :controller, :action or :id is not found, don't pull any
-
# more keys from the recall.
-
2
def normalize_controller_action_id!
-
34
use_recall_for(:controller) or return
-
11
use_recall_for(:action) or return
-
11
use_recall_for(:id)
-
end
-
-
# if the current controller is "foo/bar/baz" and controller: "baz/bat"
-
# is specified, the controller becomes "foo/baz/bat"
-
2
def use_relative_controller!
-
34
if !named_route && different_controller? && !controller.start_with?("/")
-
8
old_parts = current_controller.split('/')
-
8
size = controller.count("/") + 1
-
8
parts = old_parts[0...-size] << controller
-
8
@options[:controller] = parts.join("/")
-
end
-
end
-
-
# Remove leading slashes from controllers
-
2
def normalize_controller!
-
34
@options[:controller] = controller.sub(%r{^/}, '') if controller
-
end
-
-
# Move 'index' action from options to recall
-
2
def normalize_action!
-
34
if @options[:action] == 'index'
-
6
@recall[:action] = @options.delete(:action)
-
end
-
end
-
-
# Generates a path from routes, returns [path, params].
-
# If no route is generated the formatter will raise ActionController::UrlGenerationError
-
2
def generate
-
34
@set.formatter.generate(:path_info, named_route, options, recall, PARAMETERIZE)
-
end
-
-
2
def different_controller?
-
30
return false unless current_controller
-
8
controller.to_param != current_controller.to_param
-
end
-
-
2
private
-
2
def named_route_exists?
-
26
named_route && set.named_routes[named_route]
-
end
-
-
2
def segment_keys
-
4
set.named_routes[named_route].segment_keys
-
end
-
end
-
-
# Generate the path indicated by the arguments, and return an array of
-
# the keys that were not used to generate it.
-
2
def extra_keys(options, recall={})
-
11
generate_extras(options, recall).last
-
end
-
-
2
def generate_extras(options, recall={})
-
11
path, params = generate(options, recall)
-
11
return path, params.keys
-
end
-
-
2
def generate(options, recall = {})
-
34
Generator.new(options, recall, self).generate
-
end
-
-
2
RESERVED_OPTIONS = [:host, :protocol, :port, :subdomain, :domain, :tld_length,
-
:trailing_slash, :anchor, :params, :only_path, :script_name,
-
:original_script_name]
-
-
2
def mounted?
-
19
false
-
end
-
-
2
def optimize_routes_generation?
-
19
!mounted? && default_url_options.empty?
-
end
-
-
2
def _generate_prefix(options = {})
-
nil
-
end
-
-
# The +options+ argument must be +nil+ or a hash whose keys are *symbols*.
-
2
def url_for(options)
-
23
options = default_url_options.merge(options || {})
-
-
23
user, password = extract_authentication(options)
-
23
recall = options.delete(:_recall)
-
-
23
original_script_name = options.delete(:original_script_name).presence
-
23
script_name = options.delete(:script_name).presence || _generate_prefix(options)
-
-
23
if script_name && original_script_name
-
script_name = original_script_name + script_name
-
end
-
-
23
path_options = options.except(*RESERVED_OPTIONS)
-
23
path_options = yield(path_options) if block_given?
-
-
23
path, params = generate(path_options, recall || {})
-
23
params.merge!(options[:params] || {})
-
-
23
ActionDispatch::Http::URL.url_for(options.merge!({
-
:path => path,
-
:script_name => script_name,
-
:params => params,
-
:user => user,
-
:password => password
-
}))
-
end
-
-
2
def call(env)
-
13
@router.call(env)
-
end
-
-
2
def recognize_path(path, environment = {})
-
method = (environment[:method] || "GET").to_s.upcase
-
path = Journey::Router::Utils.normalize_path(path) unless path =~ %r{://}
-
extras = environment[:extras] || {}
-
-
begin
-
env = Rack::MockRequest.env_for(path, {:method => method})
-
rescue URI::InvalidURIError => e
-
raise ActionController::RoutingError, e.message
-
end
-
-
req = @request_class.new(env)
-
@router.recognize(req) do |route, _matches, params|
-
params.merge!(extras)
-
params.each do |key, value|
-
if value.is_a?(String)
-
value = value.dup.force_encoding(Encoding::BINARY)
-
params[key] = URI.parser.unescape(value)
-
end
-
end
-
old_params = env[::ActionDispatch::Routing::RouteSet::PARAMETERS_KEY]
-
env[::ActionDispatch::Routing::RouteSet::PARAMETERS_KEY] = (old_params || {}).merge(params)
-
dispatcher = route.app
-
while dispatcher.is_a?(Mapper::Constraints) && dispatcher.matches?(env) do
-
dispatcher = dispatcher.app
-
end
-
-
if dispatcher.is_a?(Dispatcher)
-
if dispatcher.controller(params, false)
-
dispatcher.prepare_params!(params)
-
return params
-
else
-
raise ActionController::RoutingError, "A route matches #{path.inspect}, but references missing controller: #{params[:controller].camelize}Controller"
-
end
-
end
-
end
-
-
raise ActionController::RoutingError, "No route matches #{path.inspect}"
-
end
-
-
2
private
-
-
2
def extract_authentication(options)
-
23
if options[:user] && options[:password]
-
[options.delete(:user), options.delete(:password)]
-
else
-
nil
-
end
-
end
-
-
end
-
end
-
end
-
2
require 'active_support/core_ext/array/extract_options'
-
-
2
module ActionDispatch
-
2
module Routing
-
2
class RoutesProxy #:nodoc:
-
2
include ActionDispatch::Routing::UrlFor
-
-
2
attr_accessor :scope, :routes
-
2
alias :_routes :routes
-
-
2
def initialize(routes, scope)
-
@routes, @scope = routes, scope
-
end
-
-
2
def url_options
-
scope.send(:_with_routes, routes) do
-
scope.url_options
-
end
-
end
-
-
2
def respond_to?(method, include_private = false)
-
super || routes.url_helpers.respond_to?(method)
-
end
-
-
2
def method_missing(method, *args)
-
if routes.url_helpers.respond_to?(method)
-
self.class.class_eval <<-RUBY, __FILE__, __LINE__ + 1
-
def #{method}(*args)
-
options = args.extract_options!
-
args << url_options.merge((options || {}).symbolize_keys)
-
routes.url_helpers.#{method}(*args)
-
end
-
RUBY
-
send(method, *args)
-
else
-
super
-
end
-
end
-
end
-
end
-
end
-
2
module ActionDispatch
-
2
module Routing
-
# In <tt>config/routes.rb</tt> you define URL-to-controller mappings, but the reverse
-
# is also possible: an URL can be generated from one of your routing definitions.
-
# URL generation functionality is centralized in this module.
-
#
-
# See ActionDispatch::Routing for general information about routing and routes.rb.
-
#
-
# <b>Tip:</b> If you need to generate URLs from your models or some other place,
-
# then ActionController::UrlFor is what you're looking for. Read on for
-
# an introduction. In general, this module should not be included on its own,
-
# as it is usually included by url_helpers (as in Rails.application.routes.url_helpers).
-
#
-
# == URL generation from parameters
-
#
-
# As you may know, some functions, such as ActionController::Base#url_for
-
# and ActionView::Helpers::UrlHelper#link_to, can generate URLs given a set
-
# of parameters. For example, you've probably had the chance to write code
-
# like this in one of your views:
-
#
-
# <%= link_to('Click here', controller: 'users',
-
# action: 'new', message: 'Welcome!') %>
-
# # => <a href="/users/new?message=Welcome%21">Click here</a>
-
#
-
# link_to, and all other functions that require URL generation functionality,
-
# actually use ActionController::UrlFor under the hood. And in particular,
-
# they use the ActionController::UrlFor#url_for method. One can generate
-
# the same path as the above example by using the following code:
-
#
-
# include UrlFor
-
# url_for(controller: 'users',
-
# action: 'new',
-
# message: 'Welcome!',
-
# only_path: true)
-
# # => "/users/new?message=Welcome%21"
-
#
-
# Notice the <tt>only_path: true</tt> part. This is because UrlFor has no
-
# information about the website hostname that your Rails app is serving. So if you
-
# want to include the hostname as well, then you must also pass the <tt>:host</tt>
-
# argument:
-
#
-
# include UrlFor
-
# url_for(controller: 'users',
-
# action: 'new',
-
# message: 'Welcome!',
-
# host: 'www.example.com')
-
# # => "http://www.example.com/users/new?message=Welcome%21"
-
#
-
# By default, all controllers and views have access to a special version of url_for,
-
# that already knows what the current hostname is. So if you use url_for in your
-
# controllers or your views, then you don't need to explicitly pass the <tt>:host</tt>
-
# argument.
-
#
-
# For convenience reasons, mailers provide a shortcut for ActionController::UrlFor#url_for.
-
# So within mailers, you only have to type 'url_for' instead of 'ActionController::UrlFor#url_for'
-
# in full. However, mailers don't have hostname information, and that's why you'll still
-
# have to specify the <tt>:host</tt> argument when generating URLs in mailers.
-
#
-
#
-
# == URL generation for named routes
-
#
-
# UrlFor also allows one to access methods that have been auto-generated from
-
# named routes. For example, suppose that you have a 'users' resource in your
-
# <tt>config/routes.rb</tt>:
-
#
-
# resources :users
-
#
-
# This generates, among other things, the method <tt>users_path</tt>. By default,
-
# this method is accessible from your controllers, views and mailers. If you need
-
# to access this auto-generated method from other places (such as a model), then
-
# you can do that by including Rails.application.routes.url_helpers in your class:
-
#
-
# class User < ActiveRecord::Base
-
# include Rails.application.routes.url_helpers
-
#
-
# def base_uri
-
# user_path(self)
-
# end
-
# end
-
#
-
# User.find(1).base_uri # => "/users/1"
-
#
-
2
module UrlFor
-
2
extend ActiveSupport::Concern
-
2
include PolymorphicRoutes
-
-
2
included do
-
20
unless method_defined?(:default_url_options)
-
# Including in a class uses an inheritable hash. Modules get a plain hash.
-
18
if respond_to?(:class_attribute)
-
16
class_attribute :default_url_options
-
else
-
2
mattr_writer :default_url_options
-
end
-
-
18
self.default_url_options = {}
-
end
-
-
20
include(*_url_for_modules) if respond_to?(:_url_for_modules)
-
end
-
-
2
def initialize(*)
-
58
@_routes = nil
-
58
super
-
end
-
-
# Hook overridden in controller to add request information
-
# with `default_url_options`. Application logic should not
-
# go into url_options.
-
2
def url_options
-
24
default_url_options
-
end
-
-
# Generate a url based on the options provided, default_url_options and the
-
# routes defined in routes.rb. The following options are supported:
-
#
-
# * <tt>:only_path</tt> - If true, the relative url is returned. Defaults to +false+.
-
# * <tt>:protocol</tt> - The protocol to connect to. Defaults to 'http'.
-
# * <tt>:host</tt> - Specifies the host the link should be targeted at.
-
# If <tt>:only_path</tt> is false, this option must be
-
# provided either explicitly, or via +default_url_options+.
-
# * <tt>:subdomain</tt> - Specifies the subdomain of the link, using the +tld_length+
-
# to split the subdomain from the host.
-
# If false, removes all subdomains from the host part of the link.
-
# * <tt>:domain</tt> - Specifies the domain of the link, using the +tld_length+
-
# to split the domain from the host.
-
# * <tt>:tld_length</tt> - Number of labels the TLD id composed of, only used if
-
# <tt>:subdomain</tt> or <tt>:domain</tt> are supplied. Defaults to
-
# <tt>ActionDispatch::Http::URL.tld_length</tt>, which in turn defaults to 1.
-
# * <tt>:port</tt> - Optionally specify the port to connect to.
-
# * <tt>:anchor</tt> - An anchor name to be appended to the path.
-
# * <tt>:trailing_slash</tt> - If true, adds a trailing slash, as in "/archive/2009/"
-
# * <tt>:script_name</tt> - Specifies application path relative to domain root. If provided, prepends application path.
-
#
-
# Any other key (<tt>:controller</tt>, <tt>:action</tt>, etc.) given to
-
# +url_for+ is forwarded to the Routes module.
-
#
-
# url_for controller: 'tasks', action: 'testing', host: 'somehost.org', port: '8080'
-
# # => 'http://somehost.org:8080/tasks/testing'
-
# url_for controller: 'tasks', action: 'testing', host: 'somehost.org', anchor: 'ok', only_path: true
-
# # => '/tasks/testing#ok'
-
# url_for controller: 'tasks', action: 'testing', trailing_slash: true
-
# # => 'http://somehost.org/tasks/testing/'
-
# url_for controller: 'tasks', action: 'testing', host: 'somehost.org', number: '33'
-
# # => 'http://somehost.org/tasks/testing?number=33'
-
# url_for controller: 'tasks', action: 'testing', host: 'somehost.org', script_name: "/myapp"
-
# # => 'http://somehost.org/myapp/tasks/testing'
-
# url_for controller: 'tasks', action: 'testing', host: 'somehost.org', script_name: "/myapp", only_path: true
-
# # => '/myapp/tasks/testing'
-
2
def url_for(options = nil)
-
12
case options
-
when nil
-
_routes.url_for(url_options.symbolize_keys)
-
when Hash
-
12
_routes.url_for(options.symbolize_keys.reverse_merge!(url_options))
-
when String
-
options
-
when Array
-
polymorphic_url(options, options.extract_options!)
-
else
-
polymorphic_url(options)
-
end
-
end
-
-
2
protected
-
-
2
def optimize_routes_generation?
-
55
return @_optimized_routes if defined?(@_optimized_routes)
-
19
@_optimized_routes = _routes.optimize_routes_generation? && default_url_options.empty?
-
end
-
-
2
def _with_routes(routes)
-
old_routes, @_routes = @_routes, routes
-
yield
-
ensure
-
@_routes = old_routes
-
end
-
-
2
def _routes_context
-
self
-
end
-
end
-
end
-
end
-
2
module ActionDispatch
-
2
module Assertions
-
2
autoload :DomAssertions, 'action_dispatch/testing/assertions/dom'
-
2
autoload :ResponseAssertions, 'action_dispatch/testing/assertions/response'
-
2
autoload :RoutingAssertions, 'action_dispatch/testing/assertions/routing'
-
2
autoload :SelectorAssertions, 'action_dispatch/testing/assertions/selector'
-
2
autoload :TagAssertions, 'action_dispatch/testing/assertions/tag'
-
-
2
extend ActiveSupport::Concern
-
-
2
include DomAssertions
-
2
include ResponseAssertions
-
2
include RoutingAssertions
-
2
include SelectorAssertions
-
2
include TagAssertions
-
end
-
end
-
-
2
require 'action_view/vendor/html-scanner'
-
-
2
module ActionDispatch
-
2
module Assertions
-
2
module DomAssertions
-
# \Test two HTML strings for equivalency (e.g., identical up to reordering of attributes)
-
#
-
# # assert that the referenced method generates the appropriate HTML string
-
# assert_dom_equal '<a href="http://www.example.com">Apples</a>', link_to("Apples", "http://www.example.com")
-
2
def assert_dom_equal(expected, actual, message = nil)
-
expected_dom = HTML::Document.new(expected).root
-
actual_dom = HTML::Document.new(actual).root
-
assert_equal expected_dom, actual_dom, message
-
end
-
-
# The negated form of +assert_dom_equivalent+.
-
#
-
# # assert that the referenced method does not generate the specified HTML string
-
# assert_dom_not_equal '<a href="http://www.example.com">Apples</a>', link_to("Oranges", "http://www.example.com")
-
2
def assert_dom_not_equal(expected, actual, message = nil)
-
expected_dom = HTML::Document.new(expected).root
-
actual_dom = HTML::Document.new(actual).root
-
assert_not_equal expected_dom, actual_dom, message
-
end
-
end
-
end
-
end
-
-
2
module ActionDispatch
-
2
module Assertions
-
# A small suite of assertions that test responses from \Rails applications.
-
2
module ResponseAssertions
-
# Asserts that the response is one of the following types:
-
#
-
# * <tt>:success</tt> - Status code was in the 200-299 range
-
# * <tt>:redirect</tt> - Status code was in the 300-399 range
-
# * <tt>:missing</tt> - Status code was 404
-
# * <tt>:error</tt> - Status code was in the 500-599 range
-
#
-
# You can also pass an explicit status number like <tt>assert_response(501)</tt>
-
# or its symbolic equivalent <tt>assert_response(:not_implemented)</tt>.
-
# See Rack::Utils::SYMBOL_TO_STATUS_CODE for a full list.
-
#
-
# # assert that the response was a redirection
-
# assert_response :redirect
-
#
-
# # assert that the response code was status code 401 (unauthorized)
-
# assert_response 401
-
2
def assert_response(type, message = nil)
-
message ||= "Expected response to be a <#{type}>, but was <#{@response.response_code}>"
-
-
if Symbol === type
-
if [:success, :missing, :redirect, :error].include?(type)
-
assert @response.send("#{type}?"), message
-
else
-
code = Rack::Utils::SYMBOL_TO_STATUS_CODE[type]
-
if code.nil?
-
raise ArgumentError, "Invalid response type :#{type}"
-
end
-
assert_equal code, @response.response_code, message
-
end
-
else
-
assert_equal type, @response.response_code, message
-
end
-
end
-
-
# Assert that the redirection options passed in match those of the redirect called in the latest action.
-
# This match can be partial, such that <tt>assert_redirected_to(controller: "weblog")</tt> will also
-
# match the redirection of <tt>redirect_to(controller: "weblog", action: "show")</tt> and so on.
-
#
-
# # assert that the redirection was to the "index" action on the WeblogController
-
# assert_redirected_to controller: "weblog", action: "index"
-
#
-
# # assert that the redirection was to the named route login_url
-
# assert_redirected_to login_url
-
#
-
# # assert that the redirection was to the url for @customer
-
# assert_redirected_to @customer
-
#
-
# # asserts that the redirection matches the regular expression
-
# assert_redirected_to %r(\Ahttp://example.org)
-
2
def assert_redirected_to(options = {}, message=nil)
-
assert_response(:redirect, message)
-
return true if options === @response.location
-
-
redirect_is = normalize_argument_to_redirection(@response.location)
-
redirect_expected = normalize_argument_to_redirection(options)
-
-
message ||= "Expected response to be a redirect to <#{redirect_expected}> but was a redirect to <#{redirect_is}>"
-
assert_operator redirect_expected, :===, redirect_is, message
-
end
-
-
2
private
-
# Proxy to to_param if the object will respond to it.
-
2
def parameterize(value)
-
value.respond_to?(:to_param) ? value.to_param : value
-
end
-
-
2
def normalize_argument_to_redirection(fragment)
-
if Regexp === fragment
-
fragment
-
else
-
handle = @controller || Class.new(ActionController::Metal) do
-
include ActionController::Redirecting
-
def initialize(request)
-
@_request = request
-
end
-
end.new(@request)
-
handle._compute_redirect_to_location(fragment)
-
end
-
end
-
end
-
end
-
end
-
2
require 'uri'
-
2
require 'active_support/core_ext/hash/indifferent_access'
-
2
require 'active_support/core_ext/string/access'
-
2
require 'action_controller/metal/exceptions'
-
-
2
module ActionDispatch
-
2
module Assertions
-
# Suite of assertions to test routes generated by \Rails and the handling of requests made to them.
-
2
module RoutingAssertions
-
# Asserts that the routing of the given +path+ was handled correctly and that the parsed options (given in the +expected_options+ hash)
-
# match +path+. Basically, it asserts that \Rails recognizes the route given by +expected_options+.
-
#
-
# Pass a hash in the second argument (+path+) to specify the request method. This is useful for routes
-
# requiring a specific HTTP method. The hash should contain a :path with the incoming request path
-
# and a :method containing the required HTTP verb.
-
#
-
# # assert that POSTing to /items will call the create action on ItemsController
-
# assert_recognizes({controller: 'items', action: 'create'}, {path: 'items', method: :post})
-
#
-
# You can also pass in +extras+ with a hash containing URL parameters that would normally be in the query string. This can be used
-
# to assert that values in the query string string will end up in the params hash correctly. To test query strings you must use the
-
# extras argument, appending the query string on the path directly will not work. For example:
-
#
-
# # assert that a path of '/items/list/1?view=print' returns the correct options
-
# assert_recognizes({controller: 'items', action: 'list', id: '1', view: 'print'}, 'items/list/1', { view: "print" })
-
#
-
# The +message+ parameter allows you to pass in an error message that is displayed upon failure.
-
#
-
# # Check the default route (i.e., the index action)
-
# assert_recognizes({controller: 'items', action: 'index'}, 'items')
-
#
-
# # Test a specific action
-
# assert_recognizes({controller: 'items', action: 'list'}, 'items/list')
-
#
-
# # Test an action with a parameter
-
# assert_recognizes({controller: 'items', action: 'destroy', id: '1'}, 'items/destroy/1')
-
#
-
# # Test a custom route
-
# assert_recognizes({controller: 'items', action: 'show', id: '1'}, 'view/item1')
-
2
def assert_recognizes(expected_options, path, extras={}, msg=nil)
-
request = recognized_request_for(path, extras, msg)
-
-
expected_options = expected_options.clone
-
-
expected_options.stringify_keys!
-
-
msg = message(msg, "") {
-
sprintf("The recognized options <%s> did not match <%s>, difference:",
-
request.path_parameters, expected_options)
-
}
-
-
assert_equal(expected_options, request.path_parameters, msg)
-
end
-
-
# Asserts that the provided options can be used to generate the provided path. This is the inverse of +assert_recognizes+.
-
# The +extras+ parameter is used to tell the request the names and values of additional request parameters that would be in
-
# a query string. The +message+ parameter allows you to specify a custom error message for assertion failures.
-
#
-
# The +defaults+ parameter is unused.
-
#
-
# # Asserts that the default action is generated for a route with no action
-
# assert_generates "/items", controller: "items", action: "index"
-
#
-
# # Tests that the list action is properly routed
-
# assert_generates "/items/list", controller: "items", action: "list"
-
#
-
# # Tests the generation of a route with a parameter
-
# assert_generates "/items/list/1", { controller: "items", action: "list", id: "1" }
-
#
-
# # Asserts that the generated route gives us our custom route
-
# assert_generates "changesets/12", { controller: 'scm', action: 'show_diff', revision: "12" }
-
2
def assert_generates(expected_path, options, defaults={}, extras={}, message=nil)
-
if expected_path =~ %r{://}
-
fail_on(URI::InvalidURIError, message) do
-
uri = URI.parse(expected_path)
-
expected_path = uri.path.to_s.empty? ? "/" : uri.path
-
end
-
else
-
expected_path = "/#{expected_path}" unless expected_path.first == '/'
-
end
-
# Load routes.rb if it hasn't been loaded.
-
-
generated_path, extra_keys = @routes.generate_extras(options, defaults)
-
found_extras = options.reject { |k, _| ! extra_keys.include? k }
-
-
msg = message || sprintf("found extras <%s>, not <%s>", found_extras, extras)
-
assert_equal(extras, found_extras, msg)
-
-
msg = message || sprintf("The generated path <%s> did not match <%s>", generated_path,
-
expected_path)
-
assert_equal(expected_path, generated_path, msg)
-
end
-
-
# Asserts that path and options match both ways; in other words, it verifies that <tt>path</tt> generates
-
# <tt>options</tt> and then that <tt>options</tt> generates <tt>path</tt>. This essentially combines +assert_recognizes+
-
# and +assert_generates+ into one step.
-
#
-
# The +extras+ hash allows you to specify options that would normally be provided as a query string to the action. The
-
# +message+ parameter allows you to specify a custom error message to display upon failure.
-
#
-
# # Assert a basic route: a controller with the default action (index)
-
# assert_routing '/home', controller: 'home', action: 'index'
-
#
-
# # Test a route generated with a specific controller, action, and parameter (id)
-
# assert_routing '/entries/show/23', controller: 'entries', action: 'show', id: 23
-
#
-
# # Assert a basic route (controller + default action), with an error message if it fails
-
# assert_routing '/store', { controller: 'store', action: 'index' }, {}, {}, 'Route for store index not generated properly'
-
#
-
# # Tests a route, providing a defaults hash
-
# assert_routing 'controller/action/9', {id: "9", item: "square"}, {controller: "controller", action: "action"}, {}, {item: "square"}
-
#
-
# # Tests a route with a HTTP method
-
# assert_routing({ method: 'put', path: '/product/321' }, { controller: "product", action: "update", id: "321" })
-
2
def assert_routing(path, options, defaults={}, extras={}, message=nil)
-
assert_recognizes(options, path, extras, message)
-
-
controller, default_controller = options[:controller], defaults[:controller]
-
if controller && controller.include?(?/) && default_controller && default_controller.include?(?/)
-
options[:controller] = "/#{controller}"
-
end
-
-
generate_options = options.dup.delete_if{ |k, _| defaults.key?(k) }
-
assert_generates(path.is_a?(Hash) ? path[:path] : path, generate_options, defaults, extras, message)
-
end
-
-
# A helper to make it easier to test different route configurations.
-
# This method temporarily replaces @routes
-
# with a new RouteSet instance.
-
#
-
# The new instance is yielded to the passed block. Typically the block
-
# will create some routes using <tt>set.draw { match ... }</tt>:
-
#
-
# with_routing do |set|
-
# set.draw do
-
# resources :users
-
# end
-
# assert_equal "/users", users_path
-
# end
-
#
-
2
def with_routing
-
old_routes, @routes = @routes, ActionDispatch::Routing::RouteSet.new
-
if defined?(@controller) && @controller
-
old_controller, @controller = @controller, @controller.clone
-
_routes = @routes
-
-
# Unfortunately, there is currently an abstraction leak between AC::Base
-
# and AV::Base which requires having the URL helpers in both AC and AV.
-
# To do this safely at runtime for tests, we need to bump up the helper serial
-
# to that the old AV subclass isn't cached.
-
#
-
# TODO: Make this unnecessary
-
@controller.singleton_class.send(:include, _routes.url_helpers)
-
@controller.view_context_class = Class.new(@controller.view_context_class) do
-
include _routes.url_helpers
-
end
-
end
-
yield @routes
-
ensure
-
@routes = old_routes
-
if defined?(@controller) && @controller
-
@controller = old_controller
-
end
-
end
-
-
# ROUTES TODO: These assertions should really work in an integration context
-
2
def method_missing(selector, *args, &block)
-
11
if defined?(@controller) && @controller && @routes && @routes.named_routes.helpers.include?(selector)
-
@controller.send(selector, *args, &block)
-
else
-
11
super
-
end
-
end
-
-
2
private
-
# Recognizes the route for a given path.
-
2
def recognized_request_for(path, extras = {}, msg)
-
if path.is_a?(Hash)
-
method = path[:method]
-
path = path[:path]
-
else
-
method = :get
-
end
-
-
# Assume given controller
-
request = ActionController::TestRequest.new
-
-
if path =~ %r{://}
-
fail_on(URI::InvalidURIError, msg) do
-
uri = URI.parse(path)
-
request.env["rack.url_scheme"] = uri.scheme || "http"
-
request.host = uri.host if uri.host
-
request.port = uri.port if uri.port
-
request.path = uri.path.to_s.empty? ? "/" : uri.path
-
end
-
else
-
path = "/#{path}" unless path.first == "/"
-
request.path = path
-
end
-
-
request.request_method = method if method
-
-
params = fail_on(ActionController::RoutingError, msg) do
-
@routes.recognize_path(path, { :method => method, :extras => extras })
-
end
-
request.path_parameters = params.with_indifferent_access
-
-
request
-
end
-
-
2
def fail_on(exception_class, message)
-
yield
-
rescue exception_class => e
-
raise Minitest::Assertion, message || e.message
-
end
-
end
-
end
-
end
-
2
require 'action_view/vendor/html-scanner'
-
2
require 'active_support/core_ext/object/inclusion'
-
-
#--
-
# Copyright (c) 2006 Assaf Arkin (http://labnotes.org)
-
# Under MIT and/or CC By license.
-
#++
-
-
2
module ActionDispatch
-
2
module Assertions
-
2
NO_STRIP = %w{pre script style textarea}
-
-
# Adds the +assert_select+ method for use in Rails functional
-
# test cases, which can be used to make assertions on the response HTML of a controller
-
# action. You can also call +assert_select+ within another +assert_select+ to
-
# make assertions on elements selected by the enclosing assertion.
-
#
-
# Use +css_select+ to select elements without making an assertions, either
-
# from the response HTML or elements selected by the enclosing assertion.
-
#
-
# In addition to HTML responses, you can make the following assertions:
-
#
-
# * +assert_select_encoded+ - Assertions on HTML encoded inside XML, for example for dealing with feed item descriptions.
-
# * +assert_select_email+ - Assertions on the HTML body of an e-mail.
-
#
-
# Also see HTML::Selector to learn how to use selectors.
-
2
module SelectorAssertions
-
# Select and return all matching elements.
-
#
-
# If called with a single argument, uses that argument as a selector
-
# to match all elements of the current page. Returns an empty array
-
# if no match is found.
-
#
-
# If called with two arguments, uses the first argument as the base
-
# element and the second argument as the selector. Attempts to match the
-
# base element and any of its children. Returns an empty array if no
-
# match is found.
-
#
-
# The selector may be a CSS selector expression (String), an expression
-
# with substitution values (Array) or an HTML::Selector object.
-
#
-
# # Selects all div tags
-
# divs = css_select("div")
-
#
-
# # Selects all paragraph tags and does something interesting
-
# pars = css_select("p")
-
# pars.each do |par|
-
# # Do something fun with paragraphs here...
-
# end
-
#
-
# # Selects all list items in unordered lists
-
# items = css_select("ul>li")
-
#
-
# # Selects all form tags and then all inputs inside the form
-
# forms = css_select("form")
-
# forms.each do |form|
-
# inputs = css_select(form, "input")
-
# ...
-
# end
-
2
def css_select(*args)
-
# See assert_select to understand what's going on here.
-
arg = args.shift
-
-
if arg.is_a?(HTML::Node)
-
root = arg
-
arg = args.shift
-
elsif arg == nil
-
raise ArgumentError, "First argument is either selector or element to select, but nil found. Perhaps you called assert_select with an element that does not exist?"
-
elsif defined?(@selected) && @selected
-
matches = []
-
-
@selected.each do |selected|
-
subset = css_select(selected, HTML::Selector.new(arg.dup, args.dup))
-
subset.each do |match|
-
matches << match unless matches.any? { |m| m.equal?(match) }
-
end
-
end
-
-
return matches
-
else
-
root = response_from_page
-
end
-
-
case arg
-
when String
-
selector = HTML::Selector.new(arg, args)
-
when Array
-
selector = HTML::Selector.new(*arg)
-
when HTML::Selector
-
selector = arg
-
else raise ArgumentError, "Expecting a selector as the first argument"
-
end
-
-
selector.select(root)
-
end
-
-
# An assertion that selects elements and makes one or more equality tests.
-
#
-
# If the first argument is an element, selects all matching elements
-
# starting from (and including) that element and all its children in
-
# depth-first order.
-
#
-
# If no element if specified, calling +assert_select+ selects from the
-
# response HTML unless +assert_select+ is called from within an +assert_select+ block.
-
#
-
# When called with a block +assert_select+ passes an array of selected elements
-
# to the block. Calling +assert_select+ from the block, with no element specified,
-
# runs the assertion on the complete set of elements selected by the enclosing assertion.
-
# Alternatively the array may be iterated through so that +assert_select+ can be called
-
# separately for each element.
-
#
-
#
-
# ==== Example
-
# If the response contains two ordered lists, each with four list elements then:
-
# assert_select "ol" do |elements|
-
# elements.each do |element|
-
# assert_select element, "li", 4
-
# end
-
# end
-
#
-
# will pass, as will:
-
# assert_select "ol" do
-
# assert_select "li", 8
-
# end
-
#
-
# The selector may be a CSS selector expression (String), an expression
-
# with substitution values, or an HTML::Selector object.
-
#
-
# === Equality Tests
-
#
-
# The equality test may be one of the following:
-
# * <tt>true</tt> - Assertion is true if at least one element selected.
-
# * <tt>false</tt> - Assertion is true if no element selected.
-
# * <tt>String/Regexp</tt> - Assertion is true if the text value of at least
-
# one element matches the string or regular expression.
-
# * <tt>Integer</tt> - Assertion is true if exactly that number of
-
# elements are selected.
-
# * <tt>Range</tt> - Assertion is true if the number of selected
-
# elements fit the range.
-
# If no equality test specified, the assertion is true if at least one
-
# element selected.
-
#
-
# To perform more than one equality tests, use a hash with the following keys:
-
# * <tt>:text</tt> - Narrow the selection to elements that have this text
-
# value (string or regexp).
-
# * <tt>:html</tt> - Narrow the selection to elements that have this HTML
-
# content (string or regexp).
-
# * <tt>:count</tt> - Assertion is true if the number of selected elements
-
# is equal to this value.
-
# * <tt>:minimum</tt> - Assertion is true if the number of selected
-
# elements is at least this value.
-
# * <tt>:maximum</tt> - Assertion is true if the number of selected
-
# elements is at most this value.
-
#
-
# If the method is called with a block, once all equality tests are
-
# evaluated the block is called with an array of all matched elements.
-
#
-
# # At least one form element
-
# assert_select "form"
-
#
-
# # Form element includes four input fields
-
# assert_select "form input", 4
-
#
-
# # Page title is "Welcome"
-
# assert_select "title", "Welcome"
-
#
-
# # Page title is "Welcome" and there is only one title element
-
# assert_select "title", {count: 1, text: "Welcome"},
-
# "Wrong title or more than one title element"
-
#
-
# # Page contains no forms
-
# assert_select "form", false, "This page must contain no forms"
-
#
-
# # Test the content and style
-
# assert_select "body div.header ul.menu"
-
#
-
# # Use substitution values
-
# assert_select "ol>li#?", /item-\d+/
-
#
-
# # All input fields in the form have a name
-
# assert_select "form input" do
-
# assert_select "[name=?]", /.+/ # Not empty
-
# end
-
2
def assert_select(*args, &block)
-
# Start with optional element followed by mandatory selector.
-
arg = args.shift
-
@selected ||= nil
-
-
if arg.is_a?(HTML::Node)
-
# First argument is a node (tag or text, but also HTML root),
-
# so we know what we're selecting from.
-
root = arg
-
arg = args.shift
-
elsif arg == nil
-
# This usually happens when passing a node/element that
-
# happens to be nil.
-
raise ArgumentError, "First argument is either selector or element to select, but nil found. Perhaps you called assert_select with an element that does not exist?"
-
elsif @selected
-
root = HTML::Node.new(nil)
-
root.children.concat @selected
-
else
-
# Otherwise just operate on the response document.
-
root = response_from_page
-
end
-
-
# First or second argument is the selector: string and we pass
-
# all remaining arguments. Array and we pass the argument. Also
-
# accepts selector itself.
-
case arg
-
when String
-
selector = HTML::Selector.new(arg, args)
-
when Array
-
selector = HTML::Selector.new(*arg)
-
when HTML::Selector
-
selector = arg
-
else raise ArgumentError, "Expecting a selector as the first argument"
-
end
-
-
# Next argument is used for equality tests.
-
equals = {}
-
case arg = args.shift
-
when Hash
-
equals = arg
-
when String, Regexp
-
equals[:text] = arg
-
when Integer
-
equals[:count] = arg
-
when Range
-
equals[:minimum] = arg.begin
-
equals[:maximum] = arg.end
-
when FalseClass
-
equals[:count] = 0
-
when NilClass, TrueClass
-
equals[:minimum] = 1
-
else raise ArgumentError, "I don't understand what you're trying to match"
-
end
-
-
# By default we're looking for at least one match.
-
if equals[:count]
-
equals[:minimum] = equals[:maximum] = equals[:count]
-
else
-
equals[:minimum] = 1 unless equals[:minimum]
-
end
-
-
# Last argument is the message we use if the assertion fails.
-
message = args.shift
-
#- message = "No match made with selector #{selector.inspect}" unless message
-
if args.shift
-
raise ArgumentError, "Not expecting that last argument, you either have too many arguments, or they're the wrong type"
-
end
-
-
matches = selector.select(root)
-
# If text/html, narrow down to those elements that match it.
-
content_mismatch = nil
-
if match_with = equals[:text]
-
matches.delete_if do |match|
-
text = ""
-
stack = match.children.reverse
-
while node = stack.pop
-
if node.tag?
-
stack.concat node.children.reverse
-
else
-
content = node.content
-
text << content
-
end
-
end
-
text.strip! unless NO_STRIP.include?(match.name)
-
text.sub!(/\A\n/, '') if match.name == "textarea"
-
unless match_with.is_a?(Regexp) ? (text =~ match_with) : (text == match_with.to_s)
-
content_mismatch ||= sprintf("<%s> expected but was\n<%s>", match_with, text)
-
true
-
end
-
end
-
elsif match_with = equals[:html]
-
matches.delete_if do |match|
-
html = match.children.map(&:to_s).join
-
html.strip! unless NO_STRIP.include?(match.name)
-
unless match_with.is_a?(Regexp) ? (html =~ match_with) : (html == match_with.to_s)
-
content_mismatch ||= sprintf("<%s> expected but was\n<%s>", match_with, html)
-
true
-
end
-
end
-
end
-
# Expecting foo found bar element only if found zero, not if
-
# found one but expecting two.
-
message ||= content_mismatch if matches.empty?
-
# Test minimum/maximum occurrence.
-
min, max, count = equals[:minimum], equals[:maximum], equals[:count]
-
-
# FIXME: minitest provides messaging when we use assert_operator,
-
# so is this custom message really needed?
-
message = message || %(Expected #{count_description(min, max, count)} matching "#{selector.to_s}", found #{matches.size})
-
if count
-
assert_equal count, matches.size, message
-
else
-
assert_operator matches.size, :>=, min, message if min
-
assert_operator matches.size, :<=, max, message if max
-
end
-
-
# If a block is given call that block. Set @selected to allow
-
# nested assert_select, which can be nested several levels deep.
-
if block_given? && !matches.empty?
-
begin
-
in_scope, @selected = @selected, matches
-
yield matches
-
ensure
-
@selected = in_scope
-
end
-
end
-
-
# Returns all matches elements.
-
matches
-
end
-
-
2
def count_description(min, max, count) #:nodoc:
-
pluralize = lambda {|word, quantity| word << (quantity == 1 ? '' : 's')}
-
-
if min && max && (max != min)
-
"between #{min} and #{max} elements"
-
elsif min && max && max == min && count
-
"exactly #{count} #{pluralize['element', min]}"
-
elsif min && !(min == 1 && max == 1)
-
"at least #{min} #{pluralize['element', min]}"
-
elsif max
-
"at most #{max} #{pluralize['element', max]}"
-
end
-
end
-
-
# Extracts the content of an element, treats it as encoded HTML and runs
-
# nested assertion on it.
-
#
-
# You typically call this method within another assertion to operate on
-
# all currently selected elements. You can also pass an element or array
-
# of elements.
-
#
-
# The content of each element is un-encoded, and wrapped in the root
-
# element +encoded+. It then calls the block with all un-encoded elements.
-
#
-
# # Selects all bold tags from within the title of an Atom feed's entries (perhaps to nab a section name prefix)
-
# assert_select "feed[xmlns='http://www.w3.org/2005/Atom']" do
-
# # Select each entry item and then the title item
-
# assert_select "entry>title" do
-
# # Run assertions on the encoded title elements
-
# assert_select_encoded do
-
# assert_select "b"
-
# end
-
# end
-
# end
-
#
-
#
-
# # Selects all paragraph tags from within the description of an RSS feed
-
# assert_select "rss[version=2.0]" do
-
# # Select description element of each feed item.
-
# assert_select "channel>item>description" do
-
# # Run assertions on the encoded elements.
-
# assert_select_encoded do
-
# assert_select "p"
-
# end
-
# end
-
# end
-
2
def assert_select_encoded(element = nil, &block)
-
case element
-
when Array
-
elements = element
-
when HTML::Node
-
elements = [element]
-
when nil
-
unless elements = @selected
-
raise ArgumentError, "First argument is optional, but must be called from a nested assert_select"
-
end
-
else
-
raise ArgumentError, "Argument is optional, and may be node or array of nodes"
-
end
-
-
fix_content = lambda do |node|
-
# Gets around a bug in the Rails 1.1 HTML parser.
-
node.content.gsub(/<!\[CDATA\[(.*)(\]\]>)?/m) { Rack::Utils.escapeHTML($1) }
-
end
-
-
selected = elements.map do |elem|
-
text = elem.children.select{ |c| not c.tag? }.map{ |c| fix_content[c] }.join
-
root = HTML::Document.new(CGI.unescapeHTML("<encoded>#{text}</encoded>")).root
-
css_select(root, "encoded:root", &block)[0]
-
end
-
-
begin
-
old_selected, @selected = @selected, selected
-
assert_select ":root", &block
-
ensure
-
@selected = old_selected
-
end
-
end
-
-
# Extracts the body of an email and runs nested assertions on it.
-
#
-
# You must enable deliveries for this assertion to work, use:
-
# ActionMailer::Base.perform_deliveries = true
-
#
-
# assert_select_email do
-
# assert_select "h1", "Email alert"
-
# end
-
#
-
# assert_select_email do
-
# items = assert_select "ol>li"
-
# items.each do
-
# # Work with items here...
-
# end
-
# end
-
2
def assert_select_email(&block)
-
deliveries = ActionMailer::Base.deliveries
-
assert !deliveries.empty?, "No e-mail in delivery list"
-
-
deliveries.each do |delivery|
-
(delivery.parts.empty? ? [delivery] : delivery.parts).each do |part|
-
if part["Content-Type"].to_s =~ /^text\/html\W/
-
root = HTML::Document.new(part.body.to_s).root
-
assert_select root, ":root", &block
-
end
-
end
-
end
-
end
-
-
2
protected
-
# +assert_select+ and +css_select+ call this to obtain the content in the HTML page.
-
2
def response_from_page
-
html_document.root
-
end
-
end
-
end
-
end
-
2
require 'action_view/vendor/html-scanner'
-
-
2
module ActionDispatch
-
2
module Assertions
-
# Pair of assertions to testing elements in the HTML output of the response.
-
2
module TagAssertions
-
# Asserts that there is a tag/node/element in the body of the response
-
# that meets all of the given conditions. The +conditions+ parameter must
-
# be a hash of any of the following keys (all are optional):
-
#
-
# * <tt>:tag</tt>: the node type must match the corresponding value
-
# * <tt>:attributes</tt>: a hash. The node's attributes must match the
-
# corresponding values in the hash.
-
# * <tt>:parent</tt>: a hash. The node's parent must match the
-
# corresponding hash.
-
# * <tt>:child</tt>: a hash. At least one of the node's immediate children
-
# must meet the criteria described by the hash.
-
# * <tt>:ancestor</tt>: a hash. At least one of the node's ancestors must
-
# meet the criteria described by the hash.
-
# * <tt>:descendant</tt>: a hash. At least one of the node's descendants
-
# must meet the criteria described by the hash.
-
# * <tt>:sibling</tt>: a hash. At least one of the node's siblings must
-
# meet the criteria described by the hash.
-
# * <tt>:after</tt>: a hash. The node must be after any sibling meeting
-
# the criteria described by the hash, and at least one sibling must match.
-
# * <tt>:before</tt>: a hash. The node must be before any sibling meeting
-
# the criteria described by the hash, and at least one sibling must match.
-
# * <tt>:children</tt>: a hash, for counting children of a node. Accepts
-
# the keys:
-
# * <tt>:count</tt>: either a number or a range which must equal (or
-
# include) the number of children that match.
-
# * <tt>:less_than</tt>: the number of matching children must be less
-
# than this number.
-
# * <tt>:greater_than</tt>: the number of matching children must be
-
# greater than this number.
-
# * <tt>:only</tt>: another hash consisting of the keys to use
-
# to match on the children, and only matching children will be
-
# counted.
-
# * <tt>:content</tt>: the textual content of the node must match the
-
# given value. This will not match HTML tags in the body of a
-
# tag--only text.
-
#
-
# Conditions are matched using the following algorithm:
-
#
-
# * if the condition is a string, it must be a substring of the value.
-
# * if the condition is a regexp, it must match the value.
-
# * if the condition is a number, the value must match number.to_s.
-
# * if the condition is +true+, the value must not be +nil+.
-
# * if the condition is +false+ or +nil+, the value must be +nil+.
-
#
-
# # Assert that there is a "span" tag
-
# assert_tag tag: "span"
-
#
-
# # Assert that there is a "span" tag with id="x"
-
# assert_tag tag: "span", attributes: { id: "x" }
-
#
-
# # Assert that there is a "span" tag using the short-hand
-
# assert_tag :span
-
#
-
# # Assert that there is a "span" tag with id="x" using the short-hand
-
# assert_tag :span, attributes: { id: "x" }
-
#
-
# # Assert that there is a "span" inside of a "div"
-
# assert_tag tag: "span", parent: { tag: "div" }
-
#
-
# # Assert that there is a "span" somewhere inside a table
-
# assert_tag tag: "span", ancestor: { tag: "table" }
-
#
-
# # Assert that there is a "span" with at least one "em" child
-
# assert_tag tag: "span", child: { tag: "em" }
-
#
-
# # Assert that there is a "span" containing a (possibly nested)
-
# # "strong" tag.
-
# assert_tag tag: "span", descendant: { tag: "strong" }
-
#
-
# # Assert that there is a "span" containing between 2 and 4 "em" tags
-
# # as immediate children
-
# assert_tag tag: "span",
-
# children: { count: 2..4, only: { tag: "em" } }
-
#
-
# # Get funky: assert that there is a "div", with an "ul" ancestor
-
# # and an "li" parent (with "class" = "enum"), and containing a
-
# # "span" descendant that contains text matching /hello world/
-
# assert_tag tag: "div",
-
# ancestor: { tag: "ul" },
-
# parent: { tag: "li",
-
# attributes: { class: "enum" } },
-
# descendant: { tag: "span",
-
# child: /hello world/ }
-
#
-
# <b>Please note</b>: +assert_tag+ and +assert_no_tag+ only work
-
# with well-formed XHTML. They recognize a few tags as implicitly self-closing
-
# (like br and hr and such) but will not work correctly with tags
-
# that allow optional closing tags (p, li, td). <em>You must explicitly
-
# close all of your tags to use these assertions.</em>
-
2
def assert_tag(*opts)
-
opts = opts.size > 1 ? opts.last.merge({ :tag => opts.first.to_s }) : opts.first
-
tag = find_tag(opts)
-
assert tag, "expected tag, but no tag found matching #{opts.inspect} in:\n#{@response.body.inspect}"
-
end
-
-
# Identical to +assert_tag+, but asserts that a matching tag does _not_
-
# exist. (See +assert_tag+ for a full discussion of the syntax.)
-
#
-
# # Assert that there is not a "div" containing a "p"
-
# assert_no_tag tag: "div", descendant: { tag: "p" }
-
#
-
# # Assert that an unordered list is empty
-
# assert_no_tag tag: "ul", descendant: { tag: "li" }
-
#
-
# # Assert that there is not a "p" tag with between 1 to 3 "img" tags
-
# # as immediate children
-
# assert_no_tag tag: "p",
-
# children: { count: 1..3, only: { tag: "img" } }
-
2
def assert_no_tag(*opts)
-
opts = opts.size > 1 ? opts.last.merge({ :tag => opts.first.to_s }) : opts.first
-
tag = find_tag(opts)
-
assert !tag, "expected no tag, but found tag matching #{opts.inspect} in:\n#{@response.body.inspect}"
-
end
-
-
2
def find_tag(conditions)
-
html_document.find(conditions)
-
end
-
-
2
def find_all_tag(conditions)
-
html_document.find_all(conditions)
-
end
-
-
2
def html_document
-
xml = @response.content_type =~ /xml$/
-
@html_document ||= HTML::Document.new(@response.body, false, xml)
-
end
-
end
-
end
-
end
-
2
require 'stringio'
-
2
require 'uri'
-
2
require 'active_support/core_ext/kernel/singleton_class'
-
2
require 'active_support/core_ext/object/try'
-
2
require 'rack/test'
-
2
require 'minitest'
-
-
2
module ActionDispatch
-
2
module Integration #:nodoc:
-
2
module RequestHelpers
-
# Performs a GET request with the given parameters.
-
#
-
# - +path+: The URI (as a String) on which you want to perform a GET
-
# request.
-
# - +parameters+: The HTTP parameters that you want to pass. This may
-
# be +nil+,
-
# a Hash, or a String that is appropriately encoded
-
# (<tt>application/x-www-form-urlencoded</tt> or
-
# <tt>multipart/form-data</tt>).
-
# - +headers_or_env+: Additional headers to pass, as a Hash. The headers will be
-
# merged into the Rack env hash.
-
#
-
# This method returns a Response object, which one can use to
-
# inspect the details of the response. Furthermore, if this method was
-
# called from an ActionDispatch::IntegrationTest object, then that
-
# object's <tt>@response</tt> instance variable will point to the same
-
# response object.
-
#
-
# You can also perform POST, PATCH, PUT, DELETE, and HEAD requests with
-
# +#post+, +#patch+, +#put+, +#delete+, and +#head+.
-
2
def get(path, parameters = nil, headers_or_env = nil)
-
process :get, path, parameters, headers_or_env
-
end
-
-
# Performs a POST request with the given parameters. See +#get+ for more
-
# details.
-
2
def post(path, parameters = nil, headers_or_env = nil)
-
process :post, path, parameters, headers_or_env
-
end
-
-
# Performs a PATCH request with the given parameters. See +#get+ for more
-
# details.
-
2
def patch(path, parameters = nil, headers_or_env = nil)
-
process :patch, path, parameters, headers_or_env
-
end
-
-
# Performs a PUT request with the given parameters. See +#get+ for more
-
# details.
-
2
def put(path, parameters = nil, headers_or_env = nil)
-
process :put, path, parameters, headers_or_env
-
end
-
-
# Performs a DELETE request with the given parameters. See +#get+ for
-
# more details.
-
2
def delete(path, parameters = nil, headers_or_env = nil)
-
process :delete, path, parameters, headers_or_env
-
end
-
-
# Performs a HEAD request with the given parameters. See +#get+ for more
-
# details.
-
2
def head(path, parameters = nil, headers_or_env = nil)
-
process :head, path, parameters, headers_or_env
-
end
-
-
# Performs an XMLHttpRequest request with the given parameters, mirroring
-
# a request from the Prototype library.
-
#
-
# The request_method is +:get+, +:post+, +:patch+, +:put+, +:delete+ or
-
# +:head+; the parameters are +nil+, a hash, or a url-encoded or multipart
-
# string; the headers are a hash.
-
2
def xml_http_request(request_method, path, parameters = nil, headers_or_env = nil)
-
headers_or_env ||= {}
-
headers_or_env['HTTP_X_REQUESTED_WITH'] = 'XMLHttpRequest'
-
headers_or_env['HTTP_ACCEPT'] ||= [Mime::JS, Mime::HTML, Mime::XML, 'text/xml', Mime::ALL].join(', ')
-
process(request_method, path, parameters, headers_or_env)
-
end
-
2
alias xhr :xml_http_request
-
-
# Follow a single redirect response. If the last response was not a
-
# redirect, an exception will be raised. Otherwise, the redirect is
-
# performed on the location header.
-
2
def follow_redirect!
-
raise "not a redirect! #{status} #{status_message}" unless redirect?
-
get(response.location)
-
status
-
end
-
-
# Performs a request using the specified method, following any subsequent
-
# redirect. Note that the redirects are followed until the response is
-
# not a redirect--this means you may run into an infinite loop if your
-
# redirect loops back to itself.
-
2
def request_via_redirect(http_method, path, parameters = nil, headers_or_env = nil)
-
process(http_method, path, parameters, headers_or_env)
-
follow_redirect! while redirect?
-
status
-
end
-
-
# Performs a GET request, following any subsequent redirect.
-
# See +request_via_redirect+ for more information.
-
2
def get_via_redirect(path, parameters = nil, headers_or_env = nil)
-
request_via_redirect(:get, path, parameters, headers_or_env)
-
end
-
-
# Performs a POST request, following any subsequent redirect.
-
# See +request_via_redirect+ for more information.
-
2
def post_via_redirect(path, parameters = nil, headers_or_env = nil)
-
request_via_redirect(:post, path, parameters, headers_or_env)
-
end
-
-
# Performs a PATCH request, following any subsequent redirect.
-
# See +request_via_redirect+ for more information.
-
2
def patch_via_redirect(path, parameters = nil, headers_or_env = nil)
-
request_via_redirect(:patch, path, parameters, headers_or_env)
-
end
-
-
# Performs a PUT request, following any subsequent redirect.
-
# See +request_via_redirect+ for more information.
-
2
def put_via_redirect(path, parameters = nil, headers_or_env = nil)
-
request_via_redirect(:put, path, parameters, headers_or_env)
-
end
-
-
# Performs a DELETE request, following any subsequent redirect.
-
# See +request_via_redirect+ for more information.
-
2
def delete_via_redirect(path, parameters = nil, headers_or_env = nil)
-
request_via_redirect(:delete, path, parameters, headers_or_env)
-
end
-
end
-
-
# An instance of this class represents a set of requests and responses
-
# performed sequentially by a test process. Because you can instantiate
-
# multiple sessions and run them side-by-side, you can also mimic (to some
-
# limited extent) multiple simultaneous users interacting with your system.
-
#
-
# Typically, you will instantiate a new session using
-
# IntegrationTest#open_session, rather than instantiating
-
# Integration::Session directly.
-
2
class Session
-
2
DEFAULT_HOST = "www.example.com"
-
-
2
include Minitest::Assertions
-
2
include TestProcess, RequestHelpers, Assertions
-
-
2
%w( status status_message headers body redirect? ).each do |method|
-
10
delegate method, :to => :response, :allow_nil => true
-
end
-
-
2
%w( path ).each do |method|
-
2
delegate method, :to => :request, :allow_nil => true
-
end
-
-
# The hostname used in the last request.
-
2
def host
-
6
@host || DEFAULT_HOST
-
end
-
2
attr_writer :host
-
-
# The remote_addr used in the last request.
-
2
attr_accessor :remote_addr
-
-
# The Accept header to send.
-
2
attr_accessor :accept
-
-
# A map of the cookies returned by the last response, and which will be
-
# sent with the next request.
-
2
def cookies
-
_mock_session.cookie_jar
-
end
-
-
# A reference to the controller instance used by the last request.
-
2
attr_reader :controller
-
-
# A reference to the request instance used by the last request.
-
2
attr_reader :request
-
-
# A reference to the response instance used by the last request.
-
2
attr_reader :response
-
-
# A running counter of the number of requests processed.
-
2
attr_accessor :request_count
-
-
2
include ActionDispatch::Routing::UrlFor
-
-
# Create and initialize a new Session instance.
-
2
def initialize(app)
-
6
super()
-
6
@app = app
-
-
# If the app is a Rails app, make url_helpers available on the session
-
# This makes app.url_for and app.foo_path available in the console
-
6
if app.respond_to?(:routes)
-
6
singleton_class.class_eval do
-
6
include app.routes.url_helpers if app.routes.respond_to?(:url_helpers)
-
6
include app.routes.mounted_helpers if app.routes.respond_to?(:mounted_helpers)
-
end
-
end
-
-
6
reset!
-
end
-
-
2
def url_options
-
@url_options ||= default_url_options.dup.tap do |url_options|
-
6
url_options.reverse_merge!(controller.url_options) if controller
-
-
6
if @app.respond_to?(:routes) && @app.routes.respond_to?(:default_url_options)
-
6
url_options.reverse_merge!(@app.routes.default_url_options)
-
end
-
-
6
url_options.reverse_merge!(:host => host, :protocol => https? ? "https" : "http")
-
6
end
-
end
-
-
# Resets the instance. This can be used to reset the state information
-
# in an existing session instance, so it can be used from a clean-slate
-
# condition.
-
#
-
# session.reset!
-
2
def reset!
-
6
@https = false
-
6
@controller = @request = @response = nil
-
6
@_mock_session = nil
-
6
@request_count = 0
-
6
@url_options = nil
-
-
6
self.host = DEFAULT_HOST
-
6
self.remote_addr = "127.0.0.1"
-
6
self.accept = "text/xml,application/xml,application/xhtml+xml," +
-
"text/html;q=0.9,text/plain;q=0.8,image/png," +
-
"*/*;q=0.5"
-
-
6
unless defined? @named_routes_configured
-
# the helpers are made protected by default--we make them public for
-
# easier access during testing and troubleshooting.
-
6
@named_routes_configured = true
-
end
-
end
-
-
# Specify whether or not the session should mimic a secure HTTPS request.
-
#
-
# session.https!
-
# session.https!(false)
-
2
def https!(flag = true)
-
@https = flag
-
end
-
-
# Returns +true+ if the session is mimicking a secure HTTPS request.
-
#
-
# if session.https?
-
# ...
-
# end
-
2
def https?
-
6
@https
-
end
-
-
# Set the host name to use in the next request.
-
#
-
# session.host! "www.example.com"
-
2
alias :host! :host=
-
-
2
private
-
2
def _mock_session
-
@_mock_session ||= Rack::MockSession.new(@app, host)
-
end
-
-
# Performs the actual request.
-
2
def process(method, path, parameters = nil, headers_or_env = nil)
-
if path =~ %r{://}
-
location = URI.parse(path)
-
https! URI::HTTPS === location if location.scheme
-
host! "#{location.host}:#{location.port}" if location.host
-
path = location.query ? "#{location.path}?#{location.query}" : location.path
-
end
-
-
unless ActionController::Base < ActionController::Testing
-
ActionController::Base.class_eval do
-
include ActionController::Testing
-
end
-
end
-
-
hostname, port = host.split(':')
-
-
env = {
-
:method => method,
-
:params => parameters,
-
-
"SERVER_NAME" => hostname,
-
"SERVER_PORT" => port || (https? ? "443" : "80"),
-
"HTTPS" => https? ? "on" : "off",
-
"rack.url_scheme" => https? ? "https" : "http",
-
-
"REQUEST_URI" => path,
-
"HTTP_HOST" => host,
-
"REMOTE_ADDR" => remote_addr,
-
"CONTENT_TYPE" => "application/x-www-form-urlencoded",
-
"HTTP_ACCEPT" => accept
-
}
-
# this modifies the passed env directly
-
Http::Headers.new(env).merge!(headers_or_env || {})
-
-
session = Rack::Test::Session.new(_mock_session)
-
-
# NOTE: rack-test v0.5 doesn't build a default uri correctly
-
# Make sure requested path is always a full uri
-
uri = URI.parse('/')
-
uri.scheme ||= env['rack.url_scheme']
-
uri.host ||= env['SERVER_NAME']
-
uri.port ||= env['SERVER_PORT'].try(:to_i)
-
uri += path
-
-
session.request(uri.to_s, env)
-
-
@request_count += 1
-
@request = ActionDispatch::Request.new(session.last_request.env)
-
response = _mock_session.last_response
-
@response = ActionDispatch::TestResponse.new(response.status, response.headers, response.body)
-
@html_document = nil
-
@url_options = nil
-
-
@controller = session.last_request.env['action_controller.instance']
-
-
return response.status
-
end
-
end
-
-
2
module Runner
-
2
include ActionDispatch::Assertions
-
-
2
def app
-
6
@app ||= nil
-
end
-
-
# Reset the current session. This is useful for testing multiple sessions
-
# in a single test case.
-
2
def reset!
-
6
@integration_session = Integration::Session.new(app)
-
end
-
-
%w(get post patch put head delete cookies assigns
-
2
xml_http_request xhr get_via_redirect post_via_redirect).each do |method|
-
24
define_method(method) do |*args|
-
reset! unless integration_session
-
# reset the html_document variable, but only for new get/post calls
-
@html_document = nil unless method == 'cookies' || method == 'assigns'
-
integration_session.__send__(method, *args).tap do
-
copy_session_variables!
-
end
-
end
-
end
-
-
# Open a new session instance. If a block is given, the new session is
-
# yielded to the block before being returned.
-
#
-
# session = open_session do |sess|
-
# sess.extend(CustomAssertions)
-
# end
-
#
-
# By default, a single session is automatically created for you, but you
-
# can use this method to open multiple sessions that ought to be tested
-
# simultaneously.
-
2
def open_session(app = nil)
-
dup.tap do |session|
-
yield session if block_given?
-
end
-
end
-
-
# Copy the instance variables from the current session instance into the
-
# test instance.
-
2
def copy_session_variables! #:nodoc:
-
6
return unless integration_session
-
6
%w(controller response request).each do |var|
-
18
instance_variable_set("@#{var}", @integration_session.__send__(var))
-
end
-
end
-
-
2
def default_url_options
-
reset! unless integration_session
-
integration_session.default_url_options
-
end
-
-
2
def default_url_options=(options)
-
reset! unless integration_session
-
integration_session.default_url_options = options
-
end
-
-
2
def respond_to?(method, include_private = false)
-
integration_session.respond_to?(method, include_private) || super
-
end
-
-
# Delegate unhandled messages to the current session instance.
-
2
def method_missing(sym, *args, &block)
-
6
reset! unless integration_session
-
6
if integration_session.respond_to?(sym)
-
6
integration_session.__send__(sym, *args, &block).tap do
-
6
copy_session_variables!
-
end
-
else
-
super
-
end
-
end
-
-
2
private
-
2
def integration_session
-
24
@integration_session ||= nil
-
end
-
end
-
end
-
-
# An integration test spans multiple controllers and actions,
-
# tying them all together to ensure they work together as expected. It tests
-
# more completely than either unit or functional tests do, exercising the
-
# entire stack, from the dispatcher to the database.
-
#
-
# At its simplest, you simply extend <tt>IntegrationTest</tt> and write your tests
-
# using the get/post methods:
-
#
-
# require "test_helper"
-
#
-
# class ExampleTest < ActionDispatch::IntegrationTest
-
# fixtures :people
-
#
-
# def test_login
-
# # get the login page
-
# get "/login"
-
# assert_equal 200, status
-
#
-
# # post the login and follow through to the home page
-
# post "/login", username: people(:jamis).username,
-
# password: people(:jamis).password
-
# follow_redirect!
-
# assert_equal 200, status
-
# assert_equal "/home", path
-
# end
-
# end
-
#
-
# However, you can also have multiple session instances open per test, and
-
# even extend those instances with assertions and methods to create a very
-
# powerful testing DSL that is specific for your application. You can even
-
# reference any named routes you happen to have defined.
-
#
-
# require "test_helper"
-
#
-
# class AdvancedTest < ActionDispatch::IntegrationTest
-
# fixtures :people, :rooms
-
#
-
# def test_login_and_speak
-
# jamis, david = login(:jamis), login(:david)
-
# room = rooms(:office)
-
#
-
# jamis.enter(room)
-
# jamis.speak(room, "anybody home?")
-
#
-
# david.enter(room)
-
# david.speak(room, "hello!")
-
# end
-
#
-
# private
-
#
-
# module CustomAssertions
-
# def enter(room)
-
# # reference a named route, for maximum internal consistency!
-
# get(room_url(id: room.id))
-
# assert(...)
-
# ...
-
# end
-
#
-
# def speak(room, message)
-
# xml_http_request "/say/#{room.id}", message: message
-
# assert(...)
-
# ...
-
# end
-
# end
-
#
-
# def login(who)
-
# open_session do |sess|
-
# sess.extend(CustomAssertions)
-
# who = people(who)
-
# sess.post "/login", username: who.username,
-
# password: who.password
-
# assert(...)
-
# end
-
# end
-
# end
-
2
class IntegrationTest < ActiveSupport::TestCase
-
2
include Integration::Runner
-
2
include ActionController::TemplateAssertions
-
2
include ActionDispatch::Routing::UrlFor
-
-
2
@@app = nil
-
-
2
def self.app
-
6
@@app || ActionDispatch.test_app
-
end
-
-
2
def self.app=(app)
-
@@app = app
-
end
-
-
2
def app
-
6
super || self.class.app
-
end
-
-
2
def url_options
-
reset! unless integration_session
-
integration_session.url_options
-
end
-
end
-
end
-
2
require 'action_dispatch/middleware/cookies'
-
2
require 'action_dispatch/middleware/flash'
-
2
require 'active_support/core_ext/hash/indifferent_access'
-
-
2
module ActionDispatch
-
2
module TestProcess
-
2
def assigns(key = nil)
-
assigns = {}.with_indifferent_access
-
@controller.view_assigns.each { |k, v| assigns.regular_writer(k, v) }
-
key.nil? ? assigns : assigns[key]
-
end
-
-
2
def session
-
@request.session
-
end
-
-
2
def flash
-
@request.flash
-
end
-
-
2
def cookies
-
@request.cookie_jar
-
end
-
-
2
def redirect_to_url
-
@response.redirect_url
-
end
-
-
# Shortcut for <tt>Rack::Test::UploadedFile.new(File.join(ActionController::TestCase.fixture_path, path), type)</tt>:
-
#
-
# post :change_avatar, avatar: fixture_file_upload('files/spongebob.png', 'image/png')
-
#
-
# To upload binary files on Windows, pass <tt>:binary</tt> as the last parameter.
-
# This will not affect other platforms:
-
#
-
# post :change_avatar, avatar: fixture_file_upload('files/spongebob.png', 'image/png', :binary)
-
2
def fixture_file_upload(path, mime_type = nil, binary = false)
-
if self.class.respond_to?(:fixture_path) && self.class.fixture_path
-
path = File.join(self.class.fixture_path, path)
-
end
-
Rack::Test::UploadedFile.new(path, mime_type, binary)
-
end
-
end
-
end
-
2
require 'active_support/core_ext/hash/indifferent_access'
-
2
require 'rack/utils'
-
-
2
module ActionDispatch
-
2
class TestRequest < Request
-
2
DEFAULT_ENV = Rack::MockRequest.env_for('/',
-
'HTTP_HOST' => 'test.host',
-
'REMOTE_ADDR' => '0.0.0.0',
-
'HTTP_USER_AGENT' => 'Rails Testing'
-
)
-
-
2
def self.new(env = {})
-
15
super
-
end
-
-
2
def initialize(env = {})
-
15
env = Rails.application.env_config.merge(env) if defined?(Rails.application) && Rails.application
-
15
super(default_env.merge(env))
-
end
-
-
2
def request_method=(method)
-
@env['REQUEST_METHOD'] = method.to_s.upcase
-
end
-
-
2
def host=(host)
-
@env['HTTP_HOST'] = host
-
end
-
-
2
def port=(number)
-
@env['SERVER_PORT'] = number.to_i
-
end
-
-
2
def request_uri=(uri)
-
@env['REQUEST_URI'] = uri
-
end
-
-
2
def path=(path)
-
@env['PATH_INFO'] = path
-
end
-
-
2
def action=(action_name)
-
path_parameters["action"] = action_name.to_s
-
end
-
-
2
def if_modified_since=(last_modified)
-
@env['HTTP_IF_MODIFIED_SINCE'] = last_modified
-
end
-
-
2
def if_none_match=(etag)
-
@env['HTTP_IF_NONE_MATCH'] = etag
-
end
-
-
2
def remote_addr=(addr)
-
@env['REMOTE_ADDR'] = addr
-
end
-
-
2
def user_agent=(user_agent)
-
@env['HTTP_USER_AGENT'] = user_agent
-
end
-
-
2
def accept=(mime_types)
-
@env.delete('action_dispatch.request.accepts')
-
@env['HTTP_ACCEPT'] = Array(mime_types).collect { |mime_type| mime_type.to_s }.join(",")
-
end
-
-
2
alias :rack_cookies :cookies
-
-
2
def cookies
-
22
@cookies ||= {}.with_indifferent_access
-
end
-
-
2
private
-
-
2
def default_env
-
DEFAULT_ENV
-
end
-
end
-
end
-
2
module ActionDispatch
-
# Integration test methods such as ActionDispatch::Integration::Session#get
-
# and ActionDispatch::Integration::Session#post return objects of class
-
# TestResponse, which represent the HTTP response results of the requested
-
# controller actions.
-
#
-
# See Response for more information on controller response objects.
-
2
class TestResponse < Response
-
2
def self.from_response(response)
-
new.tap do |resp|
-
resp.status = response.status
-
resp.headers = response.headers
-
resp.body = response.body
-
end
-
end
-
-
# Was the response successful?
-
2
alias_method :success?, :successful?
-
-
# Was the URL not found?
-
2
alias_method :missing?, :not_found?
-
-
# Were we redirected?
-
2
alias_method :redirect?, :redirection?
-
-
# Was there a server-side error?
-
2
alias_method :error?, :server_error?
-
end
-
end
-
#--
-
# Copyright (c) 2004-2014 David Heinemeier Hansson
-
#
-
# Permission is hereby granted, free of charge, to any person obtaining
-
# a copy of this software and associated documentation files (the
-
# "Software"), to deal in the Software without restriction, including
-
# without limitation the rights to use, copy, modify, merge, publish,
-
# distribute, sublicense, and/or sell copies of the Software, and to
-
# permit persons to whom the Software is furnished to do so, subject to
-
# the following conditions:
-
#
-
# The above copyright notice and this permission notice shall be
-
# included in all copies or substantial portions of the Software.
-
#
-
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
-
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
-
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
-
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-
#++
-
-
2
require 'action_pack/version'
-
2
module ActionPack
-
# Returns the version of the currently loaded ActionPack as a <tt>Gem::Version</tt>
-
2
def self.gem_version
-
Gem::Version.new VERSION::STRING
-
end
-
-
2
module VERSION
-
2
MAJOR = 4
-
2
MINOR = 1
-
2
TINY = 8
-
2
PRE = nil
-
-
2
STRING = [MAJOR, MINOR, TINY, PRE].compact.join(".")
-
end
-
end
-
2
require_relative 'gem_version'
-
-
2
module ActionPack
-
# Returns the version of the currently loaded ActionPack as a <tt>Gem::Version</tt>
-
2
def self.version
-
gem_version
-
end
-
end
-
#--
-
# Copyright (c) 2004-2014 David Heinemeier Hansson
-
#
-
# Permission is hereby granted, free of charge, to any person obtaining
-
# a copy of this software and associated documentation files (the
-
# "Software"), to deal in the Software without restriction, including
-
# without limitation the rights to use, copy, modify, merge, publish,
-
# distribute, sublicense, and/or sell copies of the Software, and to
-
# permit persons to whom the Software is furnished to do so, subject to
-
# the following conditions:
-
#
-
# The above copyright notice and this permission notice shall be
-
# included in all copies or substantial portions of the Software.
-
#
-
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
-
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
-
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
-
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-
#++
-
-
2
require 'active_support'
-
2
require 'active_support/rails'
-
2
require 'action_view/version'
-
-
2
module ActionView
-
2
extend ActiveSupport::Autoload
-
-
2
ENCODING_FLAG = '#.*coding[:=]\s*(\S+)[ \t]*'
-
-
2
eager_autoload do
-
2
autoload :Base
-
2
autoload :Context
-
2
autoload :CompiledTemplates, "action_view/context"
-
2
autoload :Digestor
-
2
autoload :Helpers
-
2
autoload :LookupContext
-
2
autoload :Layouts
-
2
autoload :PathSet
-
2
autoload :RecordIdentifier
-
2
autoload :Rendering
-
2
autoload :RoutingUrlFor
-
2
autoload :Template
-
2
autoload :ViewPaths
-
-
2
autoload_under "renderer" do
-
2
autoload :Renderer
-
2
autoload :AbstractRenderer
-
2
autoload :PartialRenderer
-
2
autoload :TemplateRenderer
-
2
autoload :StreamingTemplateRenderer
-
end
-
-
2
autoload_at "action_view/template/resolver" do
-
2
autoload :Resolver
-
2
autoload :PathResolver
-
2
autoload :OptimizedFileSystemResolver
-
2
autoload :FallbackFileSystemResolver
-
end
-
-
2
autoload_at "action_view/buffers" do
-
2
autoload :OutputBuffer
-
2
autoload :StreamingBuffer
-
end
-
-
2
autoload_at "action_view/flows" do
-
2
autoload :OutputFlow
-
2
autoload :StreamingFlow
-
end
-
-
2
autoload_at "action_view/template/error" do
-
2
autoload :MissingTemplate
-
2
autoload :ActionViewError
-
2
autoload :EncodingError
-
2
autoload :MissingRequestError
-
2
autoload :TemplateError
-
2
autoload :WrongEncodingError
-
end
-
end
-
-
2
autoload :TestCase
-
-
2
def self.eager_load!
-
super
-
ActionView::Helpers.eager_load!
-
ActionView::Template.eager_load!
-
HTML.eager_load!
-
end
-
end
-
-
2
require 'active_support/core_ext/string/output_safety'
-
-
2
ActiveSupport.on_load(:i18n) do
-
2
I18n.load_path << "#{File.dirname(__FILE__)}/action_view/locale/en.yml"
-
end
-
2
require 'active_support/core_ext/module/attr_internal'
-
2
require 'active_support/core_ext/module/attribute_accessors'
-
2
require 'active_support/ordered_options'
-
2
require 'action_view/log_subscriber'
-
2
require 'action_view/helpers'
-
2
require 'action_view/context'
-
2
require 'action_view/template'
-
2
require 'action_view/lookup_context'
-
-
2
module ActionView #:nodoc:
-
# = Action View Base
-
#
-
# Action View templates can be written in several ways. If the template file has a <tt>.erb</tt> extension then it uses a mixture of ERB
-
# (included in Ruby) and HTML. If the template file has a <tt>.builder</tt> extension then Jim Weirich's Builder::XmlMarkup library is used.
-
#
-
# == ERB
-
#
-
# You trigger ERB by using embeddings such as <% %>, <% -%>, and <%= %>. The <%= %> tag set is used when you want output. Consider the
-
# following loop for names:
-
#
-
# <b>Names of all the people</b>
-
# <% @people.each do |person| %>
-
# Name: <%= person.name %><br/>
-
# <% end %>
-
#
-
# The loop is setup in regular embedding tags <% %> and the name is written using the output embedding tag <%= %>. Note that this
-
# is not just a usage suggestion. Regular output functions like print or puts won't work with ERB templates. So this would be wrong:
-
#
-
# <%# WRONG %>
-
# Hi, Mr. <% puts "Frodo" %>
-
#
-
# If you absolutely must write from within a function use +concat+.
-
#
-
# <%- and -%> suppress leading and trailing whitespace, including the trailing newline, and can be used interchangeably with <% and %>.
-
#
-
# === Using sub templates
-
#
-
# Using sub templates allows you to sidestep tedious replication and extract common display structures in shared templates. The
-
# classic example is the use of a header and footer (even though the Action Pack-way would be to use Layouts):
-
#
-
# <%= render "shared/header" %>
-
# Something really specific and terrific
-
# <%= render "shared/footer" %>
-
#
-
# As you see, we use the output embeddings for the render methods. The render call itself will just return a string holding the
-
# result of the rendering. The output embedding writes it to the current template.
-
#
-
# But you don't have to restrict yourself to static includes. Templates can share variables amongst themselves by using instance
-
# variables defined using the regular embedding tags. Like this:
-
#
-
# <% @page_title = "A Wonderful Hello" %>
-
# <%= render "shared/header" %>
-
#
-
# Now the header can pick up on the <tt>@page_title</tt> variable and use it for outputting a title tag:
-
#
-
# <title><%= @page_title %></title>
-
#
-
# === Passing local variables to sub templates
-
#
-
# You can pass local variables to sub templates by using a hash with the variable names as keys and the objects as values:
-
#
-
# <%= render "shared/header", { headline: "Welcome", person: person } %>
-
#
-
# These can now be accessed in <tt>shared/header</tt> with:
-
#
-
# Headline: <%= headline %>
-
# First name: <%= person.first_name %>
-
#
-
# If you need to find out whether a certain local variable has been assigned a value in a particular render call,
-
# you need to use the following pattern:
-
#
-
# <% if local_assigns.has_key? :headline %>
-
# Headline: <%= headline %>
-
# <% end %>
-
#
-
# Testing using <tt>defined? headline</tt> will not work. This is an implementation restriction.
-
#
-
# === Template caching
-
#
-
# By default, Rails will compile each template to a method in order to render it. When you alter a template,
-
# Rails will check the file's modification time and recompile it in development mode.
-
#
-
# == Builder
-
#
-
# Builder templates are a more programmatic alternative to ERB. They are especially useful for generating XML content. An XmlMarkup object
-
# named +xml+ is automatically made available to templates with a <tt>.builder</tt> extension.
-
#
-
# Here are some basic examples:
-
#
-
# xml.em("emphasized") # => <em>emphasized</em>
-
# xml.em { xml.b("emph & bold") } # => <em><b>emph & bold</b></em>
-
# xml.a("A Link", "href" => "http://onestepback.org") # => <a href="http://onestepback.org">A Link</a>
-
# xml.target("name" => "compile", "option" => "fast") # => <target option="fast" name="compile"\>
-
# # NOTE: order of attributes is not specified.
-
#
-
# Any method with a block will be treated as an XML markup tag with nested markup in the block. For example, the following:
-
#
-
# xml.div do
-
# xml.h1(@person.name)
-
# xml.p(@person.bio)
-
# end
-
#
-
# would produce something like:
-
#
-
# <div>
-
# <h1>David Heinemeier Hansson</h1>
-
# <p>A product of Danish Design during the Winter of '79...</p>
-
# </div>
-
#
-
# A full-length RSS example actually used on Basecamp:
-
#
-
# xml.rss("version" => "2.0", "xmlns:dc" => "http://purl.org/dc/elements/1.1/") do
-
# xml.channel do
-
# xml.title(@feed_title)
-
# xml.link(@url)
-
# xml.description "Basecamp: Recent items"
-
# xml.language "en-us"
-
# xml.ttl "40"
-
#
-
# @recent_items.each do |item|
-
# xml.item do
-
# xml.title(item_title(item))
-
# xml.description(item_description(item)) if item_description(item)
-
# xml.pubDate(item_pubDate(item))
-
# xml.guid(@person.firm.account.url + @recent_items.url(item))
-
# xml.link(@person.firm.account.url + @recent_items.url(item))
-
#
-
# xml.tag!("dc:creator", item.author_name) if item_has_creator?(item)
-
# end
-
# end
-
# end
-
# end
-
#
-
# More builder documentation can be found at http://builder.rubyforge.org.
-
2
class Base
-
2
include Helpers, ::ERB::Util, Context
-
-
# Specify the proc used to decorate input tags that refer to attributes with errors.
-
2
cattr_accessor :field_error_proc
-
8
@@field_error_proc = Proc.new{ |html_tag, instance| "<div class=\"field_with_errors\">#{html_tag}</div>".html_safe }
-
-
# How to complete the streaming when an exception occurs.
-
# This is our best guess: first try to close the attribute, then the tag.
-
2
cattr_accessor :streaming_completion_on_exception
-
2
@@streaming_completion_on_exception = %("><script>window.location = "/500.html"</script></html>)
-
-
# Specify whether rendering within namespaced controllers should prefix
-
# the partial paths for ActiveModel objects with the namespace.
-
# (e.g., an Admin::PostsController would render @post using /admin/posts/_post.erb)
-
2
cattr_accessor :prefix_partial_path_with_controller_namespace
-
2
@@prefix_partial_path_with_controller_namespace = true
-
-
# Specify default_formats that can be rendered.
-
2
cattr_accessor :default_formats
-
-
# Specify whether an error should be raised for missing translations
-
2
cattr_accessor :raise_on_missing_translations
-
2
@@raise_on_missing_translations = false
-
-
2
class_attribute :_routes
-
2
class_attribute :logger
-
-
2
class << self
-
2
delegate :erb_trim_mode=, :to => 'ActionView::Template::Handlers::ERB'
-
-
2
def cache_template_loading
-
ActionView::Resolver.caching?
-
end
-
-
2
def cache_template_loading=(value)
-
ActionView::Resolver.caching = value
-
end
-
-
2
def xss_safe? #:nodoc:
-
true
-
end
-
end
-
-
2
attr_accessor :view_renderer
-
2
attr_internal :config, :assigns
-
-
2
delegate :lookup_context, :to => :view_renderer
-
2
delegate :formats, :formats=, :locale, :locale=, :view_paths, :view_paths=, :to => :lookup_context
-
-
2
def assign(new_assigns) # :nodoc:
-
54
@_assigns = new_assigns.each { |key, value| instance_variable_set("@#{key}", value) }
-
end
-
-
2
def initialize(context = nil, assigns = {}, controller = nil, formats = nil) #:nodoc:
-
24
@_config = ActiveSupport::InheritableOptions.new
-
-
24
if context.is_a?(ActionView::Renderer)
-
24
@view_renderer = context
-
else
-
lookup_context = context.is_a?(ActionView::LookupContext) ?
-
context : ActionView::LookupContext.new(context)
-
lookup_context.formats = formats if formats
-
lookup_context.prefixes = controller._prefixes if controller
-
@view_renderer = ActionView::Renderer.new(lookup_context)
-
end
-
-
24
assign(assigns)
-
24
assign_controller(controller)
-
24
_prepare_context
-
end
-
-
2
ActiveSupport.run_load_hooks(:action_view, self)
-
end
-
end
-
1
require 'active_support/core_ext/string/output_safety'
-
-
1
module ActionView
-
1
class OutputBuffer < ActiveSupport::SafeBuffer #:nodoc:
-
1
def initialize(*)
-
57
super
-
57
encode!
-
end
-
-
1
def <<(value)
-
209
return self if value.nil?
-
183
super(value.to_s)
-
end
-
1
alias :append= :<<
-
-
1
def safe_concat(value)
-
379
return self if value.nil?
-
379
super(value.to_s)
-
end
-
1
alias :safe_append= :safe_concat
-
end
-
-
1
class StreamingBuffer #:nodoc:
-
1
def initialize(block)
-
@block = block
-
end
-
-
1
def <<(value)
-
value = value.to_s
-
value = ERB::Util.h(value) unless value.html_safe?
-
@block.call(value)
-
end
-
1
alias :concat :<<
-
1
alias :append= :<<
-
-
1
def safe_concat(value)
-
@block.call(value.to_s)
-
end
-
1
alias :safe_append= :safe_concat
-
-
1
def html_safe?
-
true
-
end
-
-
1
def html_safe
-
self
-
end
-
end
-
end
-
2
module ActionView
-
2
module CompiledTemplates #:nodoc:
-
# holds compiled template code
-
end
-
-
# = Action View Context
-
#
-
# Action View contexts are supplied to Action Controller to render a template.
-
# The default Action View context is ActionView::Base.
-
#
-
# In order to work with ActionController, a Context must just include this module.
-
# The initialization of the variables used by the context (@output_buffer, @view_flow,
-
# and @virtual_path) is responsibility of the object that includes this module
-
# (although you can call _prepare_context defined below).
-
2
module Context
-
2
include CompiledTemplates
-
2
attr_accessor :output_buffer, :view_flow
-
-
# Prepares the context by setting the appropriate instance variables.
-
# :api: plugin
-
2
def _prepare_context
-
24
@view_flow = OutputFlow.new
-
24
@output_buffer = nil
-
24
@virtual_path = nil
-
end
-
-
# Encapsulates the interaction with the view flow so it
-
# returns the correct buffer on +yield+. This is usually
-
# overwritten by helpers to add more behavior.
-
# :api: plugin
-
2
def _layout_for(name=nil)
-
13
name ||= :layout
-
13
view_flow.get(name).html_safe
-
end
-
end
-
end
-
2
require 'thread_safe'
-
-
2
module ActionView
-
2
class DependencyTracker # :nodoc:
-
2
@trackers = ThreadSafe::Cache.new
-
-
2
def self.find_dependencies(name, template)
-
tracker = @trackers[template.handler]
-
-
if tracker.present?
-
tracker.call(name, template)
-
else
-
[]
-
end
-
end
-
-
2
def self.register_tracker(extension, tracker)
-
4
handler = Template.handler_for_extension(extension)
-
4
@trackers[handler] = tracker
-
end
-
-
2
def self.remove_tracker(handler)
-
@trackers.delete(handler)
-
end
-
-
2
class ERBTracker # :nodoc:
-
2
EXPLICIT_DEPENDENCY = /# Template Dependency: (\S+)/
-
-
# A valid ruby identifier - suitable for class, method and specially variable names
-
2
IDENTIFIER = /
-
[[:alpha:]_] # at least one uppercase letter, lowercase letter or underscore
-
[[:word:]]* # followed by optional letters, numbers or underscores
-
/x
-
-
# Any kind of variable name. e.g. @instance, @@class, $global or local.
-
# Possibly following a method call chain
-
2
VARIABLE_OR_METHOD_CHAIN = /
-
(?:\$|@{1,2})? # optional global, instance or class variable indicator
-
(?:#{IDENTIFIER}\.)* # followed by an optional chain of zero-argument method calls
-
(?<dynamic>#{IDENTIFIER}) # and a final valid identifier, captured as DYNAMIC
-
/x
-
-
# A simple string literal. e.g. "School's out!"
-
2
STRING = /
-
(?<quote>['"]) # an opening quote
-
(?<static>.*?) # with anything inside, captured as STATIC
-
\k<quote> # and a matching closing quote
-
/x
-
-
# Part of any hash containing the :partial key
-
2
PARTIAL_HASH_KEY = /
-
(?:\bpartial:|:partial\s*=>) # partial key in either old or new style hash syntax
-
\s* # followed by optional spaces
-
/x
-
-
# Part of any hash containing the :layout key
-
2
LAYOUT_HASH_KEY = /
-
(?:\blayout:|:layout\s*=>) # layout key in either old or new style hash syntax
-
\s* # followed by optional spaces
-
/x
-
-
# Matches:
-
# partial: "comments/comment", collection: @all_comments => "comments/comment"
-
# (object: @single_comment, partial: "comments/comment") => "comments/comment"
-
#
-
# "comments/comments"
-
# 'comments/comments'
-
# ('comments/comments')
-
#
-
# (@topic) => "topics/topic"
-
# topics => "topics/topic"
-
# (message.topics) => "topics/topic"
-
2
RENDER_ARGUMENTS = /\A
-
(?:\s*\(?\s*) # optional opening paren surrounded by spaces
-
(?:.*?#{PARTIAL_HASH_KEY}|#{LAYOUT_HASH_KEY})? # optional hash, up to the partial or layout key declaration
-
(?:#{STRING}|#{VARIABLE_OR_METHOD_CHAIN}) # finally, the dependency name of interest
-
/xm
-
-
2
def self.call(name, template)
-
new(name, template).dependencies
-
end
-
-
2
def initialize(name, template)
-
@name, @template = name, template
-
end
-
-
2
def dependencies
-
render_dependencies + explicit_dependencies
-
end
-
-
2
attr_reader :name, :template
-
2
private :name, :template
-
-
-
2
private
-
2
def source
-
template.source
-
end
-
-
2
def directory
-
name.split("/")[0..-2].join("/")
-
end
-
-
2
def render_dependencies
-
render_dependencies = []
-
render_calls = source.split(/\brender\b/).drop(1)
-
-
render_calls.each do |arguments|
-
arguments.scan(RENDER_ARGUMENTS) do
-
add_dynamic_dependency(render_dependencies, Regexp.last_match[:dynamic])
-
add_static_dependency(render_dependencies, Regexp.last_match[:static])
-
end
-
end
-
-
render_dependencies.uniq
-
end
-
-
2
def add_dynamic_dependency(dependencies, dependency)
-
if dependency
-
dependencies << "#{dependency.pluralize}/#{dependency.singularize}"
-
end
-
end
-
-
2
def add_static_dependency(dependencies, dependency)
-
if dependency
-
if dependency.include?('/')
-
dependencies << dependency
-
else
-
dependencies << "#{directory}/#{dependency}"
-
end
-
end
-
end
-
-
2
def explicit_dependencies
-
source.scan(EXPLICIT_DEPENDENCY).flatten.uniq
-
end
-
end
-
-
2
register_tracker :erb, ERBTracker
-
end
-
end
-
2
require 'active_support/core_ext/string/output_safety'
-
-
2
module ActionView
-
2
class OutputFlow #:nodoc:
-
2
attr_reader :content
-
-
2
def initialize
-
24
@content = Hash.new { |h,k| h[k] = ActiveSupport::SafeBuffer.new }
-
end
-
-
# Called by _layout_for to read stored values.
-
2
def get(key)
-
13
@content[key]
-
end
-
-
# Called by each renderer object to set the layout contents.
-
2
def set(key, value)
-
24
@content[key] = value
-
end
-
-
# Called by content_for
-
2
def append(key, value)
-
@content[key] << value
-
end
-
2
alias_method :append!, :append
-
-
end
-
-
2
class StreamingFlow < OutputFlow #:nodoc:
-
2
def initialize(view, fiber)
-
@view = view
-
@parent = nil
-
@child = view.output_buffer
-
@content = view.view_flow.content
-
@fiber = fiber
-
@root = Fiber.current.object_id
-
end
-
-
# Try to get stored content. If the content
-
# is not available and we are inside the layout
-
# fiber, we set that we are waiting for the given
-
# key and yield.
-
2
def get(key)
-
return super if @content.key?(key)
-
-
if inside_fiber?
-
view = @view
-
-
begin
-
@waiting_for = key
-
view.output_buffer, @parent = @child, view.output_buffer
-
Fiber.yield
-
ensure
-
@waiting_for = nil
-
view.output_buffer, @child = @parent, view.output_buffer
-
end
-
end
-
-
super
-
end
-
-
# Appends the contents for the given key. This is called
-
# by provides and resumes back to the fiber if it is
-
# the key it is waiting for.
-
2
def append!(key, value)
-
super
-
@fiber.resume if @waiting_for == key
-
end
-
-
2
private
-
-
2
def inside_fiber?
-
Fiber.current.object_id != @root
-
end
-
end
-
end
-
2
module ActionView
-
# Returns the version of the currently loaded ActionView as a <tt>Gem::Version</tt>
-
2
def self.gem_version
-
Gem::Version.new VERSION::STRING
-
end
-
-
2
module VERSION
-
2
MAJOR = 4
-
2
MINOR = 1
-
2
TINY = 8
-
2
PRE = nil
-
-
2
STRING = [MAJOR, MINOR, TINY, PRE].compact.join(".")
-
end
-
end
-
2
require 'active_support/benchmarkable'
-
-
2
module ActionView #:nodoc:
-
2
module Helpers #:nodoc:
-
2
extend ActiveSupport::Autoload
-
-
2
autoload :ActiveModelHelper
-
2
autoload :AssetTagHelper
-
2
autoload :AssetUrlHelper
-
2
autoload :AtomFeedHelper
-
2
autoload :CacheHelper
-
2
autoload :CaptureHelper
-
2
autoload :ControllerHelper
-
2
autoload :CsrfHelper
-
2
autoload :DateHelper
-
2
autoload :DebugHelper
-
2
autoload :FormHelper
-
2
autoload :FormOptionsHelper
-
2
autoload :FormTagHelper
-
2
autoload :JavaScriptHelper, "action_view/helpers/javascript_helper"
-
2
autoload :NumberHelper
-
2
autoload :OutputSafetyHelper
-
2
autoload :RecordTagHelper
-
2
autoload :RenderingHelper
-
2
autoload :SanitizeHelper
-
2
autoload :TagHelper
-
2
autoload :TextHelper
-
2
autoload :TranslationHelper
-
2
autoload :UrlHelper
-
2
autoload :Tags
-
-
2
def self.eager_load!
-
super
-
Tags.eager_load!
-
end
-
-
2
extend ActiveSupport::Concern
-
-
2
include ActiveSupport::Benchmarkable
-
2
include ActiveModelHelper
-
2
include AssetTagHelper
-
2
include AssetUrlHelper
-
2
include AtomFeedHelper
-
2
include CacheHelper
-
2
include CaptureHelper
-
2
include ControllerHelper
-
2
include CsrfHelper
-
2
include DateHelper
-
2
include DebugHelper
-
2
include FormHelper
-
2
include FormOptionsHelper
-
2
include FormTagHelper
-
2
include JavaScriptHelper
-
2
include NumberHelper
-
2
include OutputSafetyHelper
-
2
include RecordTagHelper
-
2
include RenderingHelper
-
2
include SanitizeHelper
-
2
include TagHelper
-
2
include TextHelper
-
2
include TranslationHelper
-
2
include UrlHelper
-
end
-
end
-
2
require 'active_support/core_ext/module/attribute_accessors'
-
2
require 'active_support/core_ext/enumerable'
-
-
2
module ActionView
-
# = Active Model Helpers
-
2
module Helpers
-
2
module ActiveModelHelper
-
end
-
-
2
module ActiveModelInstanceTag
-
2
def object
-
@active_model_object ||= begin
-
object = super
-
object.respond_to?(:to_model) ? object.to_model : object
-
end
-
end
-
-
2
def content_tag(*)
-
14
error_wrapping(super)
-
end
-
-
2
def tag(type, options, *)
-
34
tag_generate_errors?(options) ? error_wrapping(super) : super
-
end
-
-
2
def error_wrapping(html_tag)
-
48
if object_has_errors?
-
6
Base.field_error_proc.call(html_tag, self)
-
else
-
42
html_tag
-
end
-
end
-
-
2
def error_message
-
28
object.errors[@method_name]
-
end
-
-
2
private
-
-
2
def object_has_errors?
-
48
object.respond_to?(:errors) && object.errors.respond_to?(:[]) && error_message.present?
-
end
-
-
2
def tag_generate_errors?(options)
-
34
options['type'] != 'hidden'
-
end
-
end
-
end
-
end
-
2
require 'active_support/core_ext/array/extract_options'
-
2
require 'active_support/core_ext/hash/keys'
-
2
require 'action_view/helpers/asset_url_helper'
-
2
require 'action_view/helpers/tag_helper'
-
-
2
module ActionView
-
# = Action View Asset Tag Helpers
-
2
module Helpers #:nodoc:
-
# This module provides methods for generating HTML that links views to assets such
-
# as images, javascripts, stylesheets, and feeds. These methods do not verify
-
# the assets exist before linking to them:
-
#
-
# image_tag("rails.png")
-
# # => <img alt="Rails" src="/assets/rails.png" />
-
# stylesheet_link_tag("application")
-
# # => <link href="/assets/application.css?body=1" media="screen" rel="stylesheet" />
-
2
module AssetTagHelper
-
2
extend ActiveSupport::Concern
-
-
2
include AssetUrlHelper
-
2
include TagHelper
-
-
# Returns an HTML script tag for each of the +sources+ provided.
-
#
-
# Sources may be paths to JavaScript files. Relative paths are assumed to be relative
-
# to <tt>assets/javascripts</tt>, full paths are assumed to be relative to the document
-
# root. Relative paths are idiomatic, use absolute paths only when needed.
-
#
-
# When passing paths, the ".js" extension is optional. If you do not want ".js"
-
# appended to the path <tt>extname: false</tt> can be set on the options.
-
#
-
# You can modify the HTML attributes of the script tag by passing a hash as the
-
# last argument.
-
#
-
# When the Asset Pipeline is enabled, you can pass the name of your manifest as
-
# source, and include other JavaScript or CoffeeScript files inside the manifest.
-
#
-
# javascript_include_tag "xmlhr"
-
# # => <script src="/assets/xmlhr.js?1284139606"></script>
-
#
-
# javascript_include_tag "template.jst", extname: false
-
# # => <script src="/assets/template.jst?1284139606"></script>
-
#
-
# javascript_include_tag "xmlhr.js"
-
# # => <script src="/assets/xmlhr.js?1284139606"></script>
-
#
-
# javascript_include_tag "common.javascript", "/elsewhere/cools"
-
# # => <script src="/assets/common.javascript?1284139606"></script>
-
# # <script src="/elsewhere/cools.js?1423139606"></script>
-
#
-
# javascript_include_tag "http://www.example.com/xmlhr"
-
# # => <script src="http://www.example.com/xmlhr"></script>
-
#
-
# javascript_include_tag "http://www.example.com/xmlhr.js"
-
# # => <script src="http://www.example.com/xmlhr.js"></script>
-
2
def javascript_include_tag(*sources)
-
13
options = sources.extract_options!.stringify_keys
-
13
path_options = options.extract!('protocol', 'extname').symbolize_keys
-
sources.uniq.map { |source|
-
13
tag_options = {
-
"src" => path_to_javascript(source, path_options)
-
}.merge!(options)
-
13
content_tag(:script, "", tag_options)
-
13
}.join("\n").html_safe
-
end
-
-
# Returns a stylesheet link tag for the sources specified as arguments. If
-
# you don't specify an extension, <tt>.css</tt> will be appended automatically.
-
# You can modify the link attributes by passing a hash as the last argument.
-
# For historical reasons, the 'media' attribute will always be present and defaults
-
# to "screen", so you must explicitly set it to "all" for the stylesheet(s) to
-
# apply to all media types.
-
#
-
# stylesheet_link_tag "style"
-
# # => <link href="/assets/style.css" media="screen" rel="stylesheet" />
-
#
-
# stylesheet_link_tag "style.css"
-
# # => <link href="/assets/style.css" media="screen" rel="stylesheet" />
-
#
-
# stylesheet_link_tag "http://www.example.com/style.css"
-
# # => <link href="http://www.example.com/style.css" media="screen" rel="stylesheet" />
-
#
-
# stylesheet_link_tag "style", media: "all"
-
# # => <link href="/assets/style.css" media="all" rel="stylesheet" />
-
#
-
# stylesheet_link_tag "style", media: "print"
-
# # => <link href="/assets/style.css" media="print" rel="stylesheet" />
-
#
-
# stylesheet_link_tag "random.styles", "/css/stylish"
-
# # => <link href="/assets/random.styles" media="screen" rel="stylesheet" />
-
# # <link href="/css/stylish.css" media="screen" rel="stylesheet" />
-
2
def stylesheet_link_tag(*sources)
-
13
options = sources.extract_options!.stringify_keys
-
13
path_options = options.extract!('protocol').symbolize_keys
-
-
sources.uniq.map { |source|
-
13
tag_options = {
-
"rel" => "stylesheet",
-
"media" => "screen",
-
"href" => path_to_stylesheet(source, path_options)
-
}.merge!(options)
-
13
tag(:link, tag_options)
-
13
}.join("\n").html_safe
-
end
-
-
# Returns a link tag that browsers and feed readers can use to auto-detect
-
# an RSS or Atom feed. The +type+ can either be <tt>:rss</tt> (default) or
-
# <tt>:atom</tt>. Control the link options in url_for format using the
-
# +url_options+. You can modify the LINK tag itself in +tag_options+.
-
#
-
# ==== Options
-
#
-
# * <tt>:rel</tt> - Specify the relation of this link, defaults to "alternate"
-
# * <tt>:type</tt> - Override the auto-generated mime type
-
# * <tt>:title</tt> - Specify the title of the link, defaults to the +type+
-
#
-
# ==== Examples
-
#
-
# auto_discovery_link_tag
-
# # => <link rel="alternate" type="application/rss+xml" title="RSS" href="http://www.currenthost.com/controller/action" />
-
# auto_discovery_link_tag(:atom)
-
# # => <link rel="alternate" type="application/atom+xml" title="ATOM" href="http://www.currenthost.com/controller/action" />
-
# auto_discovery_link_tag(:rss, {action: "feed"})
-
# # => <link rel="alternate" type="application/rss+xml" title="RSS" href="http://www.currenthost.com/controller/feed" />
-
# auto_discovery_link_tag(:rss, {action: "feed"}, {title: "My RSS"})
-
# # => <link rel="alternate" type="application/rss+xml" title="My RSS" href="http://www.currenthost.com/controller/feed" />
-
# auto_discovery_link_tag(:rss, {controller: "news", action: "feed"})
-
# # => <link rel="alternate" type="application/rss+xml" title="RSS" href="http://www.currenthost.com/news/feed" />
-
# auto_discovery_link_tag(:rss, "http://www.example.com/feed.rss", {title: "Example RSS"})
-
# # => <link rel="alternate" type="application/rss+xml" title="Example RSS" href="http://www.example.com/feed" />
-
2
def auto_discovery_link_tag(type = :rss, url_options = {}, tag_options = {})
-
if !(type == :rss || type == :atom) && tag_options[:type].blank?
-
raise ArgumentError.new("You should pass :type tag_option key explicitly, because you have passed #{type} type other than :rss or :atom.")
-
end
-
-
tag(
-
"link",
-
"rel" => tag_options[:rel] || "alternate",
-
"type" => tag_options[:type] || Mime::Type.lookup_by_extension(type.to_s).to_s,
-
"title" => tag_options[:title] || type.to_s.upcase,
-
"href" => url_options.is_a?(Hash) ? url_for(url_options.merge(:only_path => false)) : url_options
-
)
-
end
-
-
# Returns a link loading a favicon file. You may specify a different file
-
# in the first argument. The helper accepts an additional options hash where
-
# you can override "rel" and "type".
-
#
-
# ==== Options
-
#
-
# * <tt>:rel</tt> - Specify the relation of this link, defaults to 'shortcut icon'
-
# * <tt>:type</tt> - Override the auto-generated mime type, defaults to 'image/vnd.microsoft.icon'
-
#
-
# ==== Examples
-
#
-
# favicon_link_tag 'myicon.ico'
-
# # => <link href="/assets/myicon.ico" rel="shortcut icon" type="image/vnd.microsoft.icon" />
-
#
-
# Mobile Safari looks for a different <link> tag, pointing to an image that
-
# will be used if you add the page to the home screen of an iPod Touch, iPhone, or iPad.
-
# The following call would generate such a tag:
-
#
-
# favicon_link_tag 'mb-icon.png', rel: 'apple-touch-icon', type: 'image/png'
-
# # => <link href="/assets/mb-icon.png" rel="apple-touch-icon" type="image/png" />
-
2
def favicon_link_tag(source='favicon.ico', options={})
-
tag('link', {
-
:rel => 'shortcut icon',
-
:type => 'image/vnd.microsoft.icon',
-
:href => path_to_image(source)
-
}.merge!(options.symbolize_keys))
-
end
-
-
# Returns an HTML image tag for the +source+. The +source+ can be a full
-
# path or a file.
-
#
-
# ==== Options
-
#
-
# You can add HTML attributes using the +options+. The +options+ supports
-
# two additional keys for convenience and conformance:
-
#
-
# * <tt>:alt</tt> - If no alt text is given, the file name part of the
-
# +source+ is used (capitalized and without the extension)
-
# * <tt>:size</tt> - Supplied as "{Width}x{Height}" or "{Number}", so "30x45" becomes
-
# width="30" and height="45", and "50" becomes width="50" and height="50".
-
# <tt>:size</tt> will be ignored if the value is not in the correct format.
-
#
-
# ==== Examples
-
#
-
# image_tag("icon")
-
# # => <img alt="Icon" src="/assets/icon" />
-
# image_tag("icon.png")
-
# # => <img alt="Icon" src="/assets/icon.png" />
-
# image_tag("icon.png", size: "16x10", alt: "Edit Entry")
-
# # => <img src="/assets/icon.png" width="16" height="10" alt="Edit Entry" />
-
# image_tag("/icons/icon.gif", size: "16")
-
# # => <img src="/icons/icon.gif" width="16" height="16" alt="Icon" />
-
# image_tag("/icons/icon.gif", height: '32', width: '32')
-
# # => <img alt="Icon" height="32" src="/icons/icon.gif" width="32" />
-
# image_tag("/icons/icon.gif", class: "menu_icon")
-
# # => <img alt="Icon" class="menu_icon" src="/icons/icon.gif" />
-
2
def image_tag(source, options={})
-
13
options = options.symbolize_keys
-
-
13
src = options[:src] = path_to_image(source)
-
-
13
unless src =~ /^(?:cid|data):/ || src.blank?
-
26
options[:alt] = options.fetch(:alt){ image_alt(src) }
-
end
-
-
13
options[:width], options[:height] = extract_dimensions(options.delete(:size)) if options[:size]
-
13
tag("img", options)
-
end
-
-
# Returns a string suitable for an html image tag alt attribute.
-
# The +src+ argument is meant to be an image file path.
-
# The method removes the basename of the file path and the digest,
-
# if any. It also removes hyphens and underscores from file names and
-
# replaces them with spaces, returning a space-separated, titleized
-
# string.
-
#
-
# ==== Examples
-
#
-
# image_alt('rails.png')
-
# # => Rails
-
#
-
# image_alt('hyphenated-file-name.png')
-
# # => Hyphenated file name
-
#
-
# image_alt('underscored_file_name.png')
-
# # => Underscored file name
-
2
def image_alt(src)
-
13
File.basename(src, '.*').sub(/-[[:xdigit:]]{32}\z/, '').tr('-_', ' ').capitalize
-
end
-
-
# Returns an html video tag for the +sources+. If +sources+ is a string,
-
# a single video tag will be returned. If +sources+ is an array, a video
-
# tag with nested source tags for each source will be returned. The
-
# +sources+ can be full paths or files that exists in your public videos
-
# directory.
-
#
-
# ==== Options
-
# You can add HTML attributes using the +options+. The +options+ supports
-
# two additional keys for convenience and conformance:
-
#
-
# * <tt>:poster</tt> - Set an image (like a screenshot) to be shown
-
# before the video loads. The path is calculated like the +src+ of +image_tag+.
-
# * <tt>:size</tt> - Supplied as "{Width}x{Height}" or "{Number}", so "30x45" becomes
-
# width="30" and height="45", and "50" becomes width="50" and height="50".
-
# <tt>:size</tt> will be ignored if the value is not in the correct format.
-
#
-
# ==== Examples
-
#
-
# video_tag("trailer")
-
# # => <video src="/videos/trailer" />
-
# video_tag("trailer.ogg")
-
# # => <video src="/videos/trailer.ogg" />
-
# video_tag("trailer.ogg", controls: true, autobuffer: true)
-
# # => <video autobuffer="autobuffer" controls="controls" src="/videos/trailer.ogg" />
-
# video_tag("trailer.m4v", size: "16x10", poster: "screenshot.png")
-
# # => <video src="/videos/trailer.m4v" width="16" height="10" poster="/assets/screenshot.png" />
-
# video_tag("/trailers/hd.avi", size: "16x16")
-
# # => <video src="/trailers/hd.avi" width="16" height="16" />
-
# video_tag("/trailers/hd.avi", size: "16")
-
# # => <video height="16" src="/trailers/hd.avi" width="16" />
-
# video_tag("/trailers/hd.avi", height: '32', width: '32')
-
# # => <video height="32" src="/trailers/hd.avi" width="32" />
-
# video_tag("trailer.ogg", "trailer.flv")
-
# # => <video><source src="/videos/trailer.ogg" /><source src="/videos/trailer.flv" /></video>
-
# video_tag(["trailer.ogg", "trailer.flv"])
-
# # => <video><source src="/videos/trailer.ogg" /><source src="/videos/trailer.flv" /></video>
-
# video_tag(["trailer.ogg", "trailer.flv"], size: "160x120")
-
# # => <video height="120" width="160"><source src="/videos/trailer.ogg" /><source src="/videos/trailer.flv" /></video>
-
2
def video_tag(*sources)
-
multiple_sources_tag('video', sources) do |options|
-
options[:poster] = path_to_image(options[:poster]) if options[:poster]
-
options[:width], options[:height] = extract_dimensions(options.delete(:size)) if options[:size]
-
end
-
end
-
-
# Returns an HTML audio tag for the +source+.
-
# The +source+ can be full path or file that exists in
-
# your public audios directory.
-
#
-
# audio_tag("sound")
-
# # => <audio src="/audios/sound" />
-
# audio_tag("sound.wav")
-
# # => <audio src="/audios/sound.wav" />
-
# audio_tag("sound.wav", autoplay: true, controls: true)
-
# # => <audio autoplay="autoplay" controls="controls" src="/audios/sound.wav" />
-
# audio_tag("sound.wav", "sound.mid")
-
# # => <audio><source src="/audios/sound.wav" /><source src="/audios/sound.mid" /></audio>
-
2
def audio_tag(*sources)
-
multiple_sources_tag('audio', sources)
-
end
-
-
2
private
-
2
def multiple_sources_tag(type, sources)
-
options = sources.extract_options!.symbolize_keys
-
sources.flatten!
-
-
yield options if block_given?
-
-
if sources.size > 1
-
content_tag(type, options) do
-
safe_join sources.map { |source| tag("source", :src => send("path_to_#{type}", source)) }
-
end
-
else
-
options[:src] = send("path_to_#{type}", sources.first)
-
content_tag(type, nil, options)
-
end
-
end
-
-
2
def extract_dimensions(size)
-
if size =~ %r{\A\d+x\d+\z}
-
size.split('x')
-
elsif size =~ %r{\A\d+\z}
-
[size, size]
-
end
-
end
-
end
-
end
-
end
-
2
require 'zlib'
-
-
2
module ActionView
-
# = Action View Asset URL Helpers
-
2
module Helpers
-
# This module provides methods for generating asset paths and
-
# urls.
-
#
-
# image_path("rails.png")
-
# # => "/assets/rails.png"
-
#
-
# image_url("rails.png")
-
# # => "http://www.example.com/assets/rails.png"
-
#
-
# === Using asset hosts
-
#
-
# By default, Rails links to these assets on the current host in the public
-
# folder, but you can direct Rails to link to assets from a dedicated asset
-
# server by setting <tt>ActionController::Base.asset_host</tt> in the application
-
# configuration, typically in <tt>config/environments/production.rb</tt>.
-
# For example, you'd define <tt>assets.example.com</tt> to be your asset
-
# host this way, inside the <tt>configure</tt> block of your environment-specific
-
# configuration files or <tt>config/application.rb</tt>:
-
#
-
# config.action_controller.asset_host = "assets.example.com"
-
#
-
# Helpers take that into account:
-
#
-
# image_tag("rails.png")
-
# # => <img alt="Rails" src="http://assets.example.com/assets/rails.png" />
-
# stylesheet_link_tag("application")
-
# # => <link href="http://assets.example.com/assets/application.css" media="screen" rel="stylesheet" />
-
#
-
# Browsers typically open at most two simultaneous connections to a single
-
# host, which means your assets often have to wait for other assets to finish
-
# downloading. You can alleviate this by using a <tt>%d</tt> wildcard in the
-
# +asset_host+. For example, "assets%d.example.com". If that wildcard is
-
# present Rails distributes asset requests among the corresponding four hosts
-
# "assets0.example.com", ..., "assets3.example.com". With this trick browsers
-
# will open eight simultaneous connections rather than two.
-
#
-
# image_tag("rails.png")
-
# # => <img alt="Rails" src="http://assets0.example.com/assets/rails.png" />
-
# stylesheet_link_tag("application")
-
# # => <link href="http://assets2.example.com/assets/application.css" media="screen" rel="stylesheet" />
-
#
-
# To do this, you can either setup four actual hosts, or you can use wildcard
-
# DNS to CNAME the wildcard to a single asset host. You can read more about
-
# setting up your DNS CNAME records from your ISP.
-
#
-
# Note: This is purely a browser performance optimization and is not meant
-
# for server load balancing. See http://www.die.net/musings/page_load_time/
-
# for background.
-
#
-
# Alternatively, you can exert more control over the asset host by setting
-
# +asset_host+ to a proc like this:
-
#
-
# ActionController::Base.asset_host = Proc.new { |source|
-
# "http://assets#{Digest::MD5.hexdigest(source).to_i(16) % 2 + 1}.example.com"
-
# }
-
# image_tag("rails.png")
-
# # => <img alt="Rails" src="http://assets1.example.com/assets/rails.png" />
-
# stylesheet_link_tag("application")
-
# # => <link href="http://assets2.example.com/assets/application.css" media="screen" rel="stylesheet" />
-
#
-
# The example above generates "http://assets1.example.com" and
-
# "http://assets2.example.com". This option is useful for example if
-
# you need fewer/more than four hosts, custom host names, etc.
-
#
-
# As you see the proc takes a +source+ parameter. That's a string with the
-
# absolute path of the asset, for example "/assets/rails.png".
-
#
-
# ActionController::Base.asset_host = Proc.new { |source|
-
# if source.ends_with?('.css')
-
# "http://stylesheets.example.com"
-
# else
-
# "http://assets.example.com"
-
# end
-
# }
-
# image_tag("rails.png")
-
# # => <img alt="Rails" src="http://assets.example.com/assets/rails.png" />
-
# stylesheet_link_tag("application")
-
# # => <link href="http://stylesheets.example.com/assets/application.css" media="screen" rel="stylesheet" />
-
#
-
# Alternatively you may ask for a second parameter +request+. That one is
-
# particularly useful for serving assets from an SSL-protected page. The
-
# example proc below disables asset hosting for HTTPS connections, while
-
# still sending assets for plain HTTP requests from asset hosts. If you don't
-
# have SSL certificates for each of the asset hosts this technique allows you
-
# to avoid warnings in the client about mixed media.
-
#
-
# config.action_controller.asset_host = Proc.new { |source, request|
-
# if request.ssl?
-
# "#{request.protocol}#{request.host_with_port}"
-
# else
-
# "#{request.protocol}assets.example.com"
-
# end
-
# }
-
#
-
# You can also implement a custom asset host object that responds to +call+
-
# and takes either one or two parameters just like the proc.
-
#
-
# config.action_controller.asset_host = AssetHostingWithMinimumSsl.new(
-
# "http://asset%d.example.com", "https://asset1.example.com"
-
# )
-
#
-
2
module AssetUrlHelper
-
2
URI_REGEXP = %r{^[-a-z]+://|^(?:cid|data):|^//}i
-
-
# Computes the path to asset in public directory. If :type
-
# options is set, a file extension will be appended and scoped
-
# to the corresponding public directory.
-
#
-
# All other asset *_path helpers delegate through this method.
-
#
-
# asset_path "application.js" # => /application.js
-
# asset_path "application", type: :javascript # => /javascripts/application.js
-
# asset_path "application", type: :stylesheet # => /stylesheets/application.css
-
# asset_path "http://www.example.com/js/xmlhr.js" # => http://www.example.com/js/xmlhr.js
-
2
def asset_path(source, options = {})
-
39
source = source.to_s
-
39
return "" unless source.present?
-
39
return source if source =~ URI_REGEXP
-
-
39
tail, source = source[/([\?#].+)$/], source.sub(/([\?#].+)$/, '')
-
-
39
if extname = compute_asset_extname(source, options)
-
26
source = "#{source}#{extname}"
-
end
-
-
39
if source[0] != ?/
-
39
source = compute_asset_path(source, options)
-
end
-
-
39
relative_url_root = defined?(config.relative_url_root) && config.relative_url_root
-
39
if relative_url_root
-
source = File.join(relative_url_root, source) unless source.starts_with?("#{relative_url_root}/")
-
end
-
-
39
if host = compute_asset_host(source, options)
-
source = File.join(host, source)
-
end
-
-
39
"#{source}#{tail}"
-
end
-
2
alias_method :path_to_asset, :asset_path # aliased to avoid conflicts with an asset_path named route
-
-
# Computes the full URL to an asset in the public directory. This
-
# will use +asset_path+ internally, so most of their behaviors
-
# will be the same.
-
2
def asset_url(source, options = {})
-
path_to_asset(source, options.merge(:protocol => :request))
-
end
-
2
alias_method :url_to_asset, :asset_url # aliased to avoid conflicts with an asset_url named route
-
-
2
ASSET_EXTENSIONS = {
-
javascript: '.js',
-
stylesheet: '.css'
-
}
-
-
# Compute extname to append to asset path. Returns nil if
-
# nothing should be added.
-
2
def compute_asset_extname(source, options = {})
-
39
return if options[:extname] == false
-
39
extname = options[:extname] || ASSET_EXTENSIONS[options[:type]]
-
39
extname if extname && File.extname(source) != extname
-
end
-
-
# Maps asset types to public directory.
-
2
ASSET_PUBLIC_DIRECTORIES = {
-
audio: '/audios',
-
font: '/fonts',
-
image: '/images',
-
javascript: '/javascripts',
-
stylesheet: '/stylesheets',
-
video: '/videos'
-
}
-
-
# Computes asset path to public directory. Plugins and
-
# extensions can override this method to point to custom assets
-
# or generate digested paths or query strings.
-
2
def compute_asset_path(source, options = {})
-
dir = ASSET_PUBLIC_DIRECTORIES[options[:type]] || ""
-
File.join(dir, source)
-
end
-
-
# Pick an asset host for this source. Returns +nil+ if no host is set,
-
# the host if no wildcard is set, the host interpolated with the
-
# numbers 0-3 if it contains <tt>%d</tt> (the number is the source hash mod 4),
-
# or the value returned from invoking call on an object responding to call
-
# (proc or otherwise).
-
2
def compute_asset_host(source = "", options = {})
-
39
request = self.request if respond_to?(:request)
-
39
host = config.asset_host if defined? config.asset_host
-
-
39
if host.respond_to?(:call)
-
arity = host.respond_to?(:arity) ? host.arity : host.method(:call).arity
-
args = [source]
-
args << request if request && (arity > 1 || arity < 0)
-
host = host.call(*args)
-
elsif host =~ /%d/
-
host = host % (Zlib.crc32(source) % 4)
-
end
-
-
39
host ||= request.base_url if request && options[:protocol] == :request
-
39
return unless host
-
-
if host =~ URI_REGEXP
-
host
-
else
-
protocol = options[:protocol] || config.default_asset_host_protocol || (request ? :request : :relative)
-
case protocol
-
when :relative
-
"//#{host}"
-
when :request
-
"#{request.protocol}#{host}"
-
else
-
"#{protocol}://#{host}"
-
end
-
end
-
end
-
-
# Computes the path to a javascript asset in the public javascripts directory.
-
# If the +source+ filename has no extension, .js will be appended (except for explicit URIs)
-
# Full paths from the document root will be passed through.
-
# Used internally by javascript_include_tag to build the script path.
-
#
-
# javascript_path "xmlhr" # => /javascripts/xmlhr.js
-
# javascript_path "dir/xmlhr.js" # => /javascripts/dir/xmlhr.js
-
# javascript_path "/dir/xmlhr" # => /dir/xmlhr.js
-
# javascript_path "http://www.example.com/js/xmlhr" # => http://www.example.com/js/xmlhr
-
# javascript_path "http://www.example.com/js/xmlhr.js" # => http://www.example.com/js/xmlhr.js
-
2
def javascript_path(source, options = {})
-
13
path_to_asset(source, {type: :javascript}.merge!(options))
-
end
-
2
alias_method :path_to_javascript, :javascript_path # aliased to avoid conflicts with a javascript_path named route
-
-
# Computes the full URL to a javascript asset in the public javascripts directory.
-
# This will use +javascript_path+ internally, so most of their behaviors will be the same.
-
2
def javascript_url(source, options = {})
-
url_to_asset(source, {type: :javascript}.merge!(options))
-
end
-
2
alias_method :url_to_javascript, :javascript_url # aliased to avoid conflicts with a javascript_url named route
-
-
# Computes the path to a stylesheet asset in the public stylesheets directory.
-
# If the +source+ filename has no extension, <tt>.css</tt> will be appended (except for explicit URIs).
-
# Full paths from the document root will be passed through.
-
# Used internally by +stylesheet_link_tag+ to build the stylesheet path.
-
#
-
# stylesheet_path "style" # => /stylesheets/style.css
-
# stylesheet_path "dir/style.css" # => /stylesheets/dir/style.css
-
# stylesheet_path "/dir/style.css" # => /dir/style.css
-
# stylesheet_path "http://www.example.com/css/style" # => http://www.example.com/css/style
-
# stylesheet_path "http://www.example.com/css/style.css" # => http://www.example.com/css/style.css
-
2
def stylesheet_path(source, options = {})
-
13
path_to_asset(source, {type: :stylesheet}.merge!(options))
-
end
-
2
alias_method :path_to_stylesheet, :stylesheet_path # aliased to avoid conflicts with a stylesheet_path named route
-
-
# Computes the full URL to a stylesheet asset in the public stylesheets directory.
-
# This will use +stylesheet_path+ internally, so most of their behaviors will be the same.
-
2
def stylesheet_url(source, options = {})
-
url_to_asset(source, {type: :stylesheet}.merge!(options))
-
end
-
2
alias_method :url_to_stylesheet, :stylesheet_url # aliased to avoid conflicts with a stylesheet_url named route
-
-
# Computes the path to an image asset.
-
# Full paths from the document root will be passed through.
-
# Used internally by +image_tag+ to build the image path:
-
#
-
# image_path("edit") # => "/assets/edit"
-
# image_path("edit.png") # => "/assets/edit.png"
-
# image_path("icons/edit.png") # => "/assets/icons/edit.png"
-
# image_path("/icons/edit.png") # => "/icons/edit.png"
-
# image_path("http://www.example.com/img/edit.png") # => "http://www.example.com/img/edit.png"
-
#
-
# If you have images as application resources this method may conflict with their named routes.
-
# The alias +path_to_image+ is provided to avoid that. Rails uses the alias internally, and
-
# plugin authors are encouraged to do so.
-
2
def image_path(source, options = {})
-
13
path_to_asset(source, {type: :image}.merge!(options))
-
end
-
2
alias_method :path_to_image, :image_path # aliased to avoid conflicts with an image_path named route
-
-
# Computes the full URL to an image asset.
-
# This will use +image_path+ internally, so most of their behaviors will be the same.
-
2
def image_url(source, options = {})
-
url_to_asset(source, {type: :image}.merge!(options))
-
end
-
2
alias_method :url_to_image, :image_url # aliased to avoid conflicts with an image_url named route
-
-
# Computes the path to a video asset in the public videos directory.
-
# Full paths from the document root will be passed through.
-
# Used internally by +video_tag+ to build the video path.
-
#
-
# video_path("hd") # => /videos/hd
-
# video_path("hd.avi") # => /videos/hd.avi
-
# video_path("trailers/hd.avi") # => /videos/trailers/hd.avi
-
# video_path("/trailers/hd.avi") # => /trailers/hd.avi
-
# video_path("http://www.example.com/vid/hd.avi") # => http://www.example.com/vid/hd.avi
-
2
def video_path(source, options = {})
-
path_to_asset(source, {type: :video}.merge!(options))
-
end
-
2
alias_method :path_to_video, :video_path # aliased to avoid conflicts with a video_path named route
-
-
# Computes the full URL to a video asset in the public videos directory.
-
# This will use +video_path+ internally, so most of their behaviors will be the same.
-
2
def video_url(source, options = {})
-
url_to_asset(source, {type: :video}.merge!(options))
-
end
-
2
alias_method :url_to_video, :video_url # aliased to avoid conflicts with an video_url named route
-
-
# Computes the path to an audio asset in the public audios directory.
-
# Full paths from the document root will be passed through.
-
# Used internally by +audio_tag+ to build the audio path.
-
#
-
# audio_path("horse") # => /audios/horse
-
# audio_path("horse.wav") # => /audios/horse.wav
-
# audio_path("sounds/horse.wav") # => /audios/sounds/horse.wav
-
# audio_path("/sounds/horse.wav") # => /sounds/horse.wav
-
# audio_path("http://www.example.com/sounds/horse.wav") # => http://www.example.com/sounds/horse.wav
-
2
def audio_path(source, options = {})
-
path_to_asset(source, {type: :audio}.merge!(options))
-
end
-
2
alias_method :path_to_audio, :audio_path # aliased to avoid conflicts with an audio_path named route
-
-
# Computes the full URL to an audio asset in the public audios directory.
-
# This will use +audio_path+ internally, so most of their behaviors will be the same.
-
2
def audio_url(source, options = {})
-
url_to_asset(source, {type: :audio}.merge!(options))
-
end
-
2
alias_method :url_to_audio, :audio_url # aliased to avoid conflicts with an audio_url named route
-
-
# Computes the path to a font asset.
-
# Full paths from the document root will be passed through.
-
#
-
# font_path("font") # => /assets/font
-
# font_path("font.ttf") # => /assets/font.ttf
-
# font_path("dir/font.ttf") # => /assets/dir/font.ttf
-
# font_path("/dir/font.ttf") # => /dir/font.ttf
-
# font_path("http://www.example.com/dir/font.ttf") # => http://www.example.com/dir/font.ttf
-
2
def font_path(source, options = {})
-
path_to_asset(source, {type: :font}.merge!(options))
-
end
-
2
alias_method :path_to_font, :font_path # aliased to avoid conflicts with an font_path named route
-
-
# Computes the full URL to a font asset.
-
# This will use +font_path+ internally, so most of their behaviors will be the same.
-
2
def font_url(source, options = {})
-
url_to_asset(source, {type: :font}.merge!(options))
-
end
-
2
alias_method :url_to_font, :font_url # aliased to avoid conflicts with an font_url named route
-
end
-
end
-
end
-
2
require 'set'
-
-
2
module ActionView
-
# = Action View Atom Feed Helpers
-
2
module Helpers
-
2
module AtomFeedHelper
-
# Adds easy defaults to writing Atom feeds with the Builder template engine (this does not work on ERB or any other
-
# template languages).
-
#
-
# Full usage example:
-
#
-
# config/routes.rb:
-
# Rails.application.routes.draw do
-
# resources :posts
-
# root to: "posts#index"
-
# end
-
#
-
# app/controllers/posts_controller.rb:
-
# class PostsController < ApplicationController::Base
-
# # GET /posts.html
-
# # GET /posts.atom
-
# def index
-
# @posts = Post.all
-
#
-
# respond_to do |format|
-
# format.html
-
# format.atom
-
# end
-
# end
-
# end
-
#
-
# app/views/posts/index.atom.builder:
-
# atom_feed do |feed|
-
# feed.title("My great blog!")
-
# feed.updated(@posts[0].created_at) if @posts.length > 0
-
#
-
# @posts.each do |post|
-
# feed.entry(post) do |entry|
-
# entry.title(post.title)
-
# entry.content(post.body, type: 'html')
-
#
-
# entry.author do |author|
-
# author.name("DHH")
-
# end
-
# end
-
# end
-
# end
-
#
-
# The options for atom_feed are:
-
#
-
# * <tt>:language</tt>: Defaults to "en-US".
-
# * <tt>:root_url</tt>: The HTML alternative that this feed is doubling for. Defaults to / on the current host.
-
# * <tt>:url</tt>: The URL for this feed. Defaults to the current URL.
-
# * <tt>:id</tt>: The id for this feed. Defaults to "tag:#{request.host},#{options[:schema_date]}:#{request.fullpath.split(".")[0]}"
-
# * <tt>:schema_date</tt>: The date at which the tag scheme for the feed was first used. A good default is the year you
-
# created the feed. See http://feedvalidator.org/docs/error/InvalidTAG.html for more information. If not specified,
-
# 2005 is used (as an "I don't care" value).
-
# * <tt>:instruct</tt>: Hash of XML processing instructions in the form {target => {attribute => value, }} or {target => [{attribute => value, }, ]}
-
#
-
# Other namespaces can be added to the root element:
-
#
-
# app/views/posts/index.atom.builder:
-
# atom_feed({'xmlns:app' => 'http://www.w3.org/2007/app',
-
# 'xmlns:openSearch' => 'http://a9.com/-/spec/opensearch/1.1/'}) do |feed|
-
# feed.title("My great blog!")
-
# feed.updated((@posts.first.created_at))
-
# feed.tag!('openSearch:totalResults', 10)
-
#
-
# @posts.each do |post|
-
# feed.entry(post) do |entry|
-
# entry.title(post.title)
-
# entry.content(post.body, type: 'html')
-
# entry.tag!('app:edited', Time.now)
-
#
-
# entry.author do |author|
-
# author.name("DHH")
-
# end
-
# end
-
# end
-
# end
-
#
-
# The Atom spec defines five elements (content rights title subtitle
-
# summary) which may directly contain xhtml content if type: 'xhtml'
-
# is specified as an attribute. If so, this helper will take care of
-
# the enclosing div and xhtml namespace declaration. Example usage:
-
#
-
# entry.summary type: 'xhtml' do |xhtml|
-
# xhtml.p pluralize(order.line_items.count, "line item")
-
# xhtml.p "Shipped to #{order.address}"
-
# xhtml.p "Paid by #{order.pay_type}"
-
# end
-
#
-
#
-
# <tt>atom_feed</tt> yields an +AtomFeedBuilder+ instance. Nested elements yield
-
# an +AtomBuilder+ instance.
-
2
def atom_feed(options = {}, &block)
-
if options[:schema_date]
-
options[:schema_date] = options[:schema_date].strftime("%Y-%m-%d") if options[:schema_date].respond_to?(:strftime)
-
else
-
options[:schema_date] = "2005" # The Atom spec copyright date
-
end
-
-
xml = options.delete(:xml) || eval("xml", block.binding)
-
xml.instruct!
-
if options[:instruct]
-
options[:instruct].each do |target,attrs|
-
if attrs.respond_to?(:keys)
-
xml.instruct!(target, attrs)
-
elsif attrs.respond_to?(:each)
-
attrs.each { |attr_group| xml.instruct!(target, attr_group) }
-
end
-
end
-
end
-
-
feed_opts = {"xml:lang" => options[:language] || "en-US", "xmlns" => 'http://www.w3.org/2005/Atom'}
-
feed_opts.merge!(options).reject!{|k,v| !k.to_s.match(/^xml/)}
-
-
xml.feed(feed_opts) do
-
xml.id(options[:id] || "tag:#{request.host},#{options[:schema_date]}:#{request.fullpath.split(".")[0]}")
-
xml.link(:rel => 'alternate', :type => 'text/html', :href => options[:root_url] || (request.protocol + request.host_with_port))
-
xml.link(:rel => 'self', :type => 'application/atom+xml', :href => options[:url] || request.url)
-
-
yield AtomFeedBuilder.new(xml, self, options)
-
end
-
end
-
-
2
class AtomBuilder #:nodoc:
-
2
XHTML_TAG_NAMES = %w(content rights title subtitle summary).to_set
-
-
2
def initialize(xml)
-
@xml = xml
-
end
-
-
2
private
-
# Delegate to xml builder, first wrapping the element in a xhtml
-
# namespaced div element if the method and arguments indicate
-
# that an xhtml_block? is desired.
-
2
def method_missing(method, *arguments, &block)
-
if xhtml_block?(method, arguments)
-
@xml.__send__(method, *arguments) do
-
@xml.div(:xmlns => 'http://www.w3.org/1999/xhtml') do |xhtml|
-
block.call(xhtml)
-
end
-
end
-
else
-
@xml.__send__(method, *arguments, &block)
-
end
-
end
-
-
# True if the method name matches one of the five elements defined
-
# in the Atom spec as potentially containing XHTML content and
-
# if type: 'xhtml' is, in fact, specified.
-
2
def xhtml_block?(method, arguments)
-
if XHTML_TAG_NAMES.include?(method.to_s)
-
last = arguments.last
-
last.is_a?(Hash) && last[:type].to_s == 'xhtml'
-
end
-
end
-
end
-
-
2
class AtomFeedBuilder < AtomBuilder #:nodoc:
-
2
def initialize(xml, view, feed_options = {})
-
@xml, @view, @feed_options = xml, view, feed_options
-
end
-
-
# Accepts a Date or Time object and inserts it in the proper format. If nil is passed, current time in UTC is used.
-
2
def updated(date_or_time = nil)
-
@xml.updated((date_or_time || Time.now.utc).xmlschema)
-
end
-
-
# Creates an entry tag for a specific record and prefills the id using class and id.
-
#
-
# Options:
-
#
-
# * <tt>:published</tt>: Time first published. Defaults to the created_at attribute on the record if one such exists.
-
# * <tt>:updated</tt>: Time of update. Defaults to the updated_at attribute on the record if one such exists.
-
# * <tt>:url</tt>: The URL for this entry. Defaults to the polymorphic_url for the record.
-
# * <tt>:id</tt>: The ID for this entry. Defaults to "tag:#{@view.request.host},#{@feed_options[:schema_date]}:#{record.class}/#{record.id}"
-
# * <tt>:type</tt>: The TYPE for this entry. Defaults to "text/html".
-
2
def entry(record, options = {})
-
@xml.entry do
-
@xml.id(options[:id] || "tag:#{@view.request.host},#{@feed_options[:schema_date]}:#{record.class}/#{record.id}")
-
-
if options[:published] || (record.respond_to?(:created_at) && record.created_at)
-
@xml.published((options[:published] || record.created_at).xmlschema)
-
end
-
-
if options[:updated] || (record.respond_to?(:updated_at) && record.updated_at)
-
@xml.updated((options[:updated] || record.updated_at).xmlschema)
-
end
-
-
type = options.fetch(:type, 'text/html')
-
-
@xml.link(:rel => 'alternate', :type => type, :href => options[:url] || @view.polymorphic_url(record))
-
-
yield AtomBuilder.new(@xml)
-
end
-
end
-
end
-
-
end
-
end
-
end
-
2
module ActionView
-
# = Action View Cache Helper
-
2
module Helpers
-
2
module CacheHelper
-
# This helper exposes a method for caching fragments of a view
-
# rather than an entire action or page. This technique is useful
-
# caching pieces like menus, lists of new topics, static HTML
-
# fragments, and so on. This method takes a block that contains
-
# the content you wish to cache.
-
#
-
# The best way to use this is by doing key-based cache expiration
-
# on top of a cache store like Memcached that'll automatically
-
# kick out old entries. For more on key-based expiration, see:
-
# http://37signals.com/svn/posts/3113-how-key-based-cache-expiration-works
-
#
-
# When using this method, you list the cache dependency as the name of the cache, like so:
-
#
-
# <% cache project do %>
-
# <b>All the topics on this project</b>
-
# <%= render project.topics %>
-
# <% end %>
-
#
-
# This approach will assume that when a new topic is added, you'll touch
-
# the project. The cache key generated from this call will be something like:
-
#
-
# views/projects/123-20120806214154/7a1156131a6928cb0026877f8b749ac9
-
# ^class ^id ^updated_at ^template tree digest
-
#
-
# The cache is thus automatically bumped whenever the project updated_at is touched.
-
#
-
# If your template cache depends on multiple sources (try to avoid this to keep things simple),
-
# you can name all these dependencies as part of an array:
-
#
-
# <% cache [ project, current_user ] do %>
-
# <b>All the topics on this project</b>
-
# <%= render project.topics %>
-
# <% end %>
-
#
-
# This will include both records as part of the cache key and updating either of them will
-
# expire the cache.
-
#
-
# ==== Template digest
-
#
-
# The template digest that's added to the cache key is computed by taking an md5 of the
-
# contents of the entire template file. This ensures that your caches will automatically
-
# expire when you change the template file.
-
#
-
# Note that the md5 is taken of the entire template file, not just what's within the
-
# cache do/end call. So it's possible that changing something outside of that call will
-
# still expire the cache.
-
#
-
# Additionally, the digestor will automatically look through your template file for
-
# explicit and implicit dependencies, and include those as part of the digest.
-
#
-
# The digestor can be bypassed by passing skip_digest: true as an option to the cache call:
-
#
-
# <% cache project, skip_digest: true do %>
-
# <b>All the topics on this project</b>
-
# <%= render project.topics %>
-
# <% end %>
-
#
-
# ==== Implicit dependencies
-
#
-
# Most template dependencies can be derived from calls to render in the template itself.
-
# Here are some examples of render calls that Cache Digests knows how to decode:
-
#
-
# render partial: "comments/comment", collection: commentable.comments
-
# render "comments/comments"
-
# render 'comments/comments'
-
# render('comments/comments')
-
#
-
# render "header" => render("comments/header")
-
#
-
# render(@topic) => render("topics/topic")
-
# render(topics) => render("topics/topic")
-
# render(message.topics) => render("topics/topic")
-
#
-
# It's not possible to derive all render calls like that, though. Here are a few examples of things that can't be derived:
-
#
-
# render group_of_attachments
-
# render @project.documents.where(published: true).order('created_at')
-
#
-
# You will have to rewrite those to the explicit form:
-
#
-
# render partial: 'attachments/attachment', collection: group_of_attachments
-
# render partial: 'documents/document', collection: @project.documents.where(published: true).order('created_at')
-
#
-
# === Explicit dependencies
-
#
-
# Some times you'll have template dependencies that can't be derived at all. This is typically
-
# the case when you have template rendering that happens in helpers. Here's an example:
-
#
-
# <%= render_sortable_todolists @project.todolists %>
-
#
-
# You'll need to use a special comment format to call those out:
-
#
-
# <%# Template Dependency: todolists/todolist %>
-
# <%= render_sortable_todolists @project.todolists %>
-
#
-
# The pattern used to match these is /# Template Dependency: ([^ ]+)/, so it's important that you type it out just so.
-
# You can only declare one template dependency per line.
-
#
-
# === External dependencies
-
#
-
# If you use a helper method, for example, inside of a cached block and you then update that helper,
-
# you'll have to bump the cache as well. It doesn't really matter how you do it, but the md5 of the template file
-
# must change. One recommendation is to simply be explicit in a comment, like:
-
#
-
# <%# Helper Dependency Updated: May 6, 2012 at 6pm %>
-
# <%= some_helper_method(person) %>
-
#
-
# Now all you'll have to do is change that timestamp when the helper method changes.
-
2
def cache(name = {}, options = nil, &block)
-
if controller.perform_caching
-
safe_concat(fragment_for(cache_fragment_name(name, options), options, &block))
-
else
-
yield
-
end
-
-
nil
-
end
-
-
# Cache fragments of a view if +condition+ is true
-
#
-
# <%= cache_if admin?, project do %>
-
# <b>All the topics on this project</b>
-
# <%= render project.topics %>
-
# <% end %>
-
2
def cache_if(condition, name = {}, options = nil, &block)
-
if condition
-
cache(name, options, &block)
-
else
-
yield
-
end
-
-
nil
-
end
-
-
# Cache fragments of a view unless +condition+ is true
-
#
-
# <%= cache_unless admin?, project do %>
-
# <b>All the topics on this project</b>
-
# <%= render project.topics %>
-
# <% end %>
-
2
def cache_unless(condition, name = {}, options = nil, &block)
-
cache_if !condition, name, options, &block
-
end
-
-
# This helper returns the name of a cache key for a given fragment cache
-
# call. By supplying skip_digest: true to cache, the digestion of cache
-
# fragments can be manually bypassed. This is useful when cache fragments
-
# cannot be manually expired unless you know the exact key which is the
-
# case when using memcached.
-
2
def cache_fragment_name(name = {}, options = nil)
-
skip_digest = options && options[:skip_digest]
-
-
if skip_digest
-
name
-
else
-
fragment_name_with_digest(name)
-
end
-
end
-
-
2
private
-
-
2
def fragment_name_with_digest(name) #:nodoc:
-
if @virtual_path
-
names = Array(name.is_a?(Hash) ? controller.url_for(name).split("://").last : name)
-
digest = Digestor.digest name: @virtual_path, finder: lookup_context, dependencies: view_cache_dependencies
-
-
[ *names, digest ]
-
else
-
name
-
end
-
end
-
-
# TODO: Create an object that has caching read/write on it
-
2
def fragment_for(name = {}, options = nil, &block) #:nodoc:
-
read_fragment_for(name, options) || write_fragment_for(name, options, &block)
-
end
-
-
2
def read_fragment_for(name, options) #:nodoc:
-
controller.read_fragment(name, options)
-
end
-
-
2
def write_fragment_for(name, options) #:nodoc:
-
# VIEW TODO: Make #capture usable outside of ERB
-
# This dance is needed because Builder can't use capture
-
pos = output_buffer.length
-
yield
-
output_safe = output_buffer.html_safe?
-
fragment = output_buffer.slice!(pos..-1)
-
if output_safe
-
self.output_buffer = output_buffer.class.new(output_buffer)
-
end
-
controller.write_fragment(name, fragment, options)
-
end
-
end
-
end
-
end
-
2
require 'active_support/core_ext/string/output_safety'
-
-
2
module ActionView
-
# = Action View Capture Helper
-
2
module Helpers
-
# CaptureHelper exposes methods to let you extract generated markup which
-
# can be used in other parts of a template or layout file.
-
#
-
# It provides a method to capture blocks into variables through capture and
-
# a way to capture a block of markup for use in a layout through content_for.
-
2
module CaptureHelper
-
# The capture method allows you to extract part of a template into a
-
# variable. You can then use this variable anywhere in your templates or layout.
-
#
-
# The capture method can be used in ERB templates...
-
#
-
# <% @greeting = capture do %>
-
# Welcome to my shiny new web page! The date and time is
-
# <%= Time.now %>
-
# <% end %>
-
#
-
# ...and Builder (RXML) templates.
-
#
-
# @timestamp = capture do
-
# "The current timestamp is #{Time.now}."
-
# end
-
#
-
# You can then use that variable anywhere else. For example:
-
#
-
# <html>
-
# <head><title><%= @greeting %></title></head>
-
# <body>
-
# <b><%= @greeting %></b>
-
# </body></html>
-
#
-
2
def capture(*args)
-
18
value = nil
-
36
buffer = with_output_buffer { value = yield(*args) }
-
18
if string = buffer.presence || value and string.is_a?(String)
-
18
ERB::Util.html_escape string
-
end
-
end
-
-
# Calling content_for stores a block of markup in an identifier for later use.
-
# In order to access this stored content in other templates, helper modules
-
# or the layout, you would pass the identifier as an argument to <tt>content_for</tt>.
-
#
-
# Note: <tt>yield</tt> can still be used to retrieve the stored content, but calling
-
# <tt>yield</tt> doesn't work in helper modules, while <tt>content_for</tt> does.
-
#
-
# <% content_for :not_authorized do %>
-
# alert('You are not authorized to do that!')
-
# <% end %>
-
#
-
# You can then use <tt>content_for :not_authorized</tt> anywhere in your templates.
-
#
-
# <%= content_for :not_authorized if current_user.nil? %>
-
#
-
# This is equivalent to:
-
#
-
# <%= yield :not_authorized if current_user.nil? %>
-
#
-
# <tt>content_for</tt>, however, can also be used in helper modules.
-
#
-
# module StorageHelper
-
# def stored_content
-
# content_for(:storage) || "Your storage is empty"
-
# end
-
# end
-
#
-
# This helper works just like normal helpers.
-
#
-
# <%= stored_content %>
-
#
-
# You can also use the <tt>yield</tt> syntax alongside an existing call to
-
# <tt>yield</tt> in a layout. For example:
-
#
-
# <%# This is the layout %>
-
# <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
-
# <head>
-
# <title>My Website</title>
-
# <%= yield :script %>
-
# </head>
-
# <body>
-
# <%= yield %>
-
# </body>
-
# </html>
-
#
-
# And now, we'll create a view that has a <tt>content_for</tt> call that
-
# creates the <tt>script</tt> identifier.
-
#
-
# <%# This is our view %>
-
# Please login!
-
#
-
# <% content_for :script do %>
-
# <script>alert('You are not authorized to view this page!')</script>
-
# <% end %>
-
#
-
# Then, in another view, you could to do something like this:
-
#
-
# <%= link_to 'Logout', action: 'logout', remote: true %>
-
#
-
# <% content_for :script do %>
-
# <%= javascript_include_tag :defaults %>
-
# <% end %>
-
#
-
# That will place +script+ tags for your default set of JavaScript files on the page;
-
# this technique is useful if you'll only be using these scripts in a few views.
-
#
-
# Note that content_for concatenates (default) the blocks it is given for a particular
-
# identifier in order. For example:
-
#
-
# <% content_for :navigation do %>
-
# <li><%= link_to 'Home', action: 'index' %></li>
-
# <% end %>
-
#
-
# And in other place:
-
#
-
# <% content_for :navigation do %>
-
# <li><%= link_to 'Login', action: 'login' %></li>
-
# <% end %>
-
#
-
# Then, in another template or layout, this code would render both links in order:
-
#
-
# <ul><%= content_for :navigation %></ul>
-
#
-
# If the flush parameter is true content_for replaces the blocks it is given. For example:
-
#
-
# <% content_for :navigation do %>
-
# <li><%= link_to 'Home', action: 'index' %></li>
-
# <% end %>
-
#
-
# <%# Add some other content, or use a different template: %>
-
#
-
# <% content_for :navigation, flush: true do %>
-
# <li><%= link_to 'Login', action: 'login' %></li>
-
# <% end %>
-
#
-
# Then, in another template or layout, this code would render only the last link:
-
#
-
# <ul><%= content_for :navigation %></ul>
-
#
-
# Lastly, simple content can be passed as a parameter:
-
#
-
# <% content_for :script, javascript_include_tag(:defaults) %>
-
#
-
# WARNING: content_for is ignored in caches. So you shouldn't use it for elements that will be fragment cached.
-
2
def content_for(name, content = nil, options = {}, &block)
-
if content || block_given?
-
if block_given?
-
options = content if content
-
content = capture(&block)
-
end
-
if content
-
options[:flush] ? @view_flow.set(name, content) : @view_flow.append(name, content)
-
end
-
nil
-
else
-
@view_flow.get(name).presence
-
end
-
end
-
-
# The same as +content_for+ but when used with streaming flushes
-
# straight back to the layout. In other words, if you want to
-
# concatenate several times to the same buffer when rendering a given
-
# template, you should use +content_for+, if not, use +provide+ to tell
-
# the layout to stop looking for more contents.
-
2
def provide(name, content = nil, &block)
-
content = capture(&block) if block_given?
-
result = @view_flow.append!(name, content) if content
-
result unless content
-
end
-
-
# content_for? checks whether any content has been captured yet using `content_for`.
-
# Useful to render parts of your layout differently based on what is in your views.
-
#
-
# <%# This is the layout %>
-
# <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
-
# <head>
-
# <title>My Website</title>
-
# <%= yield :script %>
-
# </head>
-
# <body class="<%= content_for?(:right_col) ? 'two-column' : 'one-column' %>">
-
# <%= yield %>
-
# <%= yield :right_col %>
-
# </body>
-
# </html>
-
2
def content_for?(name)
-
@view_flow.get(name).present?
-
end
-
-
# Use an alternate output buffer for the duration of the block.
-
# Defaults to a new empty string.
-
2
def with_output_buffer(buf = nil) #:nodoc:
-
18
unless buf
-
18
buf = ActionView::OutputBuffer.new
-
18
buf.force_encoding(output_buffer.encoding) if output_buffer
-
end
-
18
self.output_buffer, old_buffer = buf, output_buffer
-
18
yield
-
18
output_buffer
-
ensure
-
18
self.output_buffer = old_buffer
-
end
-
-
# Add the output buffer to the response body and start a new one.
-
2
def flush_output_buffer #:nodoc:
-
if output_buffer && !output_buffer.empty?
-
response.stream.write output_buffer
-
self.output_buffer = output_buffer.respond_to?(:clone_empty) ? output_buffer.clone_empty : output_buffer[0, 0]
-
nil
-
end
-
end
-
end
-
end
-
end
-
2
require 'active_support/core_ext/module/attr_internal'
-
-
2
module ActionView
-
2
module Helpers
-
# This module keeps all methods and behavior in ActionView
-
# that simply delegates to the controller.
-
2
module ControllerHelper #:nodoc:
-
2
attr_internal :controller, :request
-
-
2
delegate :request_forgery_protection_token, :params, :session, :cookies, :response, :headers,
-
:flash, :action_name, :controller_name, :controller_path, :to => :controller
-
-
2
def assign_controller(controller)
-
24
if @_controller = controller
-
24
@_request = controller.request if controller.respond_to?(:request)
-
24
@_config = controller.config.inheritable_copy if controller.respond_to?(:config)
-
end
-
end
-
-
2
def logger
-
controller.logger if controller.respond_to?(:logger)
-
end
-
end
-
end
-
end
-
2
module ActionView
-
# = Action View CSRF Helper
-
2
module Helpers
-
2
module CsrfHelper
-
# Returns meta tags "csrf-param" and "csrf-token" with the name of the cross-site
-
# request forgery protection parameter and token, respectively.
-
#
-
# <head>
-
# <%= csrf_meta_tags %>
-
# </head>
-
#
-
# These are used to generate the dynamic forms that implement non-remote links with
-
# <tt>:method</tt>.
-
#
-
# You don't need to use these tags for regular forms as they generate their own hidden fields.
-
#
-
# For AJAX requests other than GETs, extract the "csrf-token" from the meta-tag and send as the
-
# "X-CSRF-Token" HTTP header. If you are using jQuery with jquery-rails this happens automatically.
-
#
-
2
def csrf_meta_tags
-
26
if protect_against_forgery?
-
[
-
tag('meta', :name => 'csrf-param', :content => request_forgery_protection_token),
-
tag('meta', :name => 'csrf-token', :content => form_authenticity_token)
-
].join("\n").html_safe
-
end
-
end
-
-
# For backwards compatibility.
-
2
alias csrf_meta_tag csrf_meta_tags
-
end
-
end
-
end
-
2
require 'date'
-
2
require 'action_view/helpers/tag_helper'
-
2
require 'active_support/core_ext/array/extract_options'
-
2
require 'active_support/core_ext/date/conversions'
-
2
require 'active_support/core_ext/hash/slice'
-
2
require 'active_support/core_ext/object/with_options'
-
-
2
module ActionView
-
2
module Helpers
-
# = Action View Date Helpers
-
#
-
# The Date Helper primarily creates select/option tags for different kinds of dates and times or date and time
-
# elements. All of the select-type methods share a number of common options that are as follows:
-
#
-
# * <tt>:prefix</tt> - overwrites the default prefix of "date" used for the select names. So specifying "birthday"
-
# would give \birthday[month] instead of \date[month] if passed to the <tt>select_month</tt> method.
-
# * <tt>:include_blank</tt> - set to true if it should be possible to set an empty date.
-
# * <tt>:discard_type</tt> - set to true if you want to discard the type part of the select name. If set to true,
-
# the <tt>select_month</tt> method would use simply "date" (which can be overwritten using <tt>:prefix</tt>) instead
-
# of \date[month].
-
2
module DateHelper
-
# Reports the approximate distance in time between two Time, Date or DateTime objects or integers as seconds.
-
# Pass <tt>include_seconds: true</tt> if you want more detailed approximations when distance < 1 min, 29 secs.
-
# Distances are reported based on the following table:
-
#
-
# 0 <-> 29 secs # => less than a minute
-
# 30 secs <-> 1 min, 29 secs # => 1 minute
-
# 1 min, 30 secs <-> 44 mins, 29 secs # => [2..44] minutes
-
# 44 mins, 30 secs <-> 89 mins, 29 secs # => about 1 hour
-
# 89 mins, 30 secs <-> 23 hrs, 59 mins, 29 secs # => about [2..24] hours
-
# 23 hrs, 59 mins, 30 secs <-> 41 hrs, 59 mins, 29 secs # => 1 day
-
# 41 hrs, 59 mins, 30 secs <-> 29 days, 23 hrs, 59 mins, 29 secs # => [2..29] days
-
# 29 days, 23 hrs, 59 mins, 30 secs <-> 44 days, 23 hrs, 59 mins, 29 secs # => about 1 month
-
# 44 days, 23 hrs, 59 mins, 30 secs <-> 59 days, 23 hrs, 59 mins, 29 secs # => about 2 months
-
# 59 days, 23 hrs, 59 mins, 30 secs <-> 1 yr minus 1 sec # => [2..12] months
-
# 1 yr <-> 1 yr, 3 months # => about 1 year
-
# 1 yr, 3 months <-> 1 yr, 9 months # => over 1 year
-
# 1 yr, 9 months <-> 2 yr minus 1 sec # => almost 2 years
-
# 2 yrs <-> max time or date # => (same rules as 1 yr)
-
#
-
# With <tt>include_seconds: true</tt> and the difference < 1 minute 29 seconds:
-
# 0-4 secs # => less than 5 seconds
-
# 5-9 secs # => less than 10 seconds
-
# 10-19 secs # => less than 20 seconds
-
# 20-39 secs # => half a minute
-
# 40-59 secs # => less than a minute
-
# 60-89 secs # => 1 minute
-
#
-
# from_time = Time.now
-
# distance_of_time_in_words(from_time, from_time + 50.minutes) # => about 1 hour
-
# distance_of_time_in_words(from_time, 50.minutes.from_now) # => about 1 hour
-
# distance_of_time_in_words(from_time, from_time + 15.seconds) # => less than a minute
-
# distance_of_time_in_words(from_time, from_time + 15.seconds, include_seconds: true) # => less than 20 seconds
-
# distance_of_time_in_words(from_time, 3.years.from_now) # => about 3 years
-
# distance_of_time_in_words(from_time, from_time + 60.hours) # => 3 days
-
# distance_of_time_in_words(from_time, from_time + 45.seconds, include_seconds: true) # => less than a minute
-
# distance_of_time_in_words(from_time, from_time - 45.seconds, include_seconds: true) # => less than a minute
-
# distance_of_time_in_words(from_time, 76.seconds.from_now) # => 1 minute
-
# distance_of_time_in_words(from_time, from_time + 1.year + 3.days) # => about 1 year
-
# distance_of_time_in_words(from_time, from_time + 3.years + 6.months) # => over 3 years
-
# distance_of_time_in_words(from_time, from_time + 4.years + 9.days + 30.minutes + 5.seconds) # => about 4 years
-
#
-
# to_time = Time.now + 6.years + 19.days
-
# distance_of_time_in_words(from_time, to_time, include_seconds: true) # => about 6 years
-
# distance_of_time_in_words(to_time, from_time, include_seconds: true) # => about 6 years
-
# distance_of_time_in_words(Time.now, Time.now) # => less than a minute
-
2
def distance_of_time_in_words(from_time, to_time = 0, options = {})
-
options = {
-
scope: :'datetime.distance_in_words'
-
}.merge!(options)
-
-
from_time = from_time.to_time if from_time.respond_to?(:to_time)
-
to_time = to_time.to_time if to_time.respond_to?(:to_time)
-
from_time, to_time = to_time, from_time if from_time > to_time
-
distance_in_minutes = ((to_time - from_time)/60.0).round
-
distance_in_seconds = (to_time - from_time).round
-
-
I18n.with_options :locale => options[:locale], :scope => options[:scope] do |locale|
-
case distance_in_minutes
-
when 0..1
-
return distance_in_minutes == 0 ?
-
locale.t(:less_than_x_minutes, :count => 1) :
-
locale.t(:x_minutes, :count => distance_in_minutes) unless options[:include_seconds]
-
-
case distance_in_seconds
-
when 0..4 then locale.t :less_than_x_seconds, :count => 5
-
when 5..9 then locale.t :less_than_x_seconds, :count => 10
-
when 10..19 then locale.t :less_than_x_seconds, :count => 20
-
when 20..39 then locale.t :half_a_minute
-
when 40..59 then locale.t :less_than_x_minutes, :count => 1
-
else locale.t :x_minutes, :count => 1
-
end
-
-
when 2...45 then locale.t :x_minutes, :count => distance_in_minutes
-
when 45...90 then locale.t :about_x_hours, :count => 1
-
# 90 mins up to 24 hours
-
when 90...1440 then locale.t :about_x_hours, :count => (distance_in_minutes.to_f / 60.0).round
-
# 24 hours up to 42 hours
-
when 1440...2520 then locale.t :x_days, :count => 1
-
# 42 hours up to 30 days
-
when 2520...43200 then locale.t :x_days, :count => (distance_in_minutes.to_f / 1440.0).round
-
# 30 days up to 60 days
-
when 43200...86400 then locale.t :about_x_months, :count => (distance_in_minutes.to_f / 43200.0).round
-
# 60 days up to 365 days
-
when 86400...525600 then locale.t :x_months, :count => (distance_in_minutes.to_f / 43200.0).round
-
else
-
if from_time.acts_like?(:time) && to_time.acts_like?(:time)
-
fyear = from_time.year
-
fyear += 1 if from_time.month >= 3
-
tyear = to_time.year
-
tyear -= 1 if to_time.month < 3
-
leap_years = (fyear > tyear) ? 0 : (fyear..tyear).count{|x| Date.leap?(x)}
-
minute_offset_for_leap_year = leap_years * 1440
-
# Discount the leap year days when calculating year distance.
-
# e.g. if there are 20 leap year days between 2 dates having the same day
-
# and month then the based on 365 days calculation
-
# the distance in years will come out to over 80 years when in written
-
# English it would read better as about 80 years.
-
minutes_with_offset = distance_in_minutes - minute_offset_for_leap_year
-
else
-
minutes_with_offset = distance_in_minutes
-
end
-
remainder = (minutes_with_offset % 525600)
-
distance_in_years = (minutes_with_offset.div 525600)
-
if remainder < 131400
-
locale.t(:about_x_years, :count => distance_in_years)
-
elsif remainder < 394200
-
locale.t(:over_x_years, :count => distance_in_years)
-
else
-
locale.t(:almost_x_years, :count => distance_in_years + 1)
-
end
-
end
-
end
-
end
-
-
# Like <tt>distance_of_time_in_words</tt>, but where <tt>to_time</tt> is fixed to <tt>Time.now</tt>.
-
#
-
# time_ago_in_words(3.minutes.from_now) # => 3 minutes
-
# time_ago_in_words(3.minutes.ago) # => 3 minutes
-
# time_ago_in_words(Time.now - 15.hours) # => about 15 hours
-
# time_ago_in_words(Time.now) # => less than a minute
-
# time_ago_in_words(Time.now, include_seconds: true) # => less than 5 seconds
-
#
-
# from_time = Time.now - 3.days - 14.minutes - 25.seconds
-
# time_ago_in_words(from_time) # => 3 days
-
#
-
# from_time = (3.days + 14.minutes + 25.seconds).ago
-
# time_ago_in_words(from_time) # => 3 days
-
#
-
# Note that you cannot pass a <tt>Numeric</tt> value to <tt>time_ago_in_words</tt>.
-
#
-
2
def time_ago_in_words(from_time, include_seconds_or_options = {})
-
distance_of_time_in_words(from_time, Time.now, include_seconds_or_options)
-
end
-
-
2
alias_method :distance_of_time_in_words_to_now, :time_ago_in_words
-
-
# Returns a set of select tags (one for year, month, and day) pre-selected for accessing a specified date-based
-
# attribute (identified by +method+) on an object assigned to the template (identified by +object+).
-
#
-
# ==== Options
-
# * <tt>:use_month_numbers</tt> - Set to true if you want to use month numbers rather than month names (e.g.
-
# "2" instead of "February").
-
# * <tt>:use_two_digit_numbers</tt> - Set to true if you want to display two digit month and day numbers (e.g.
-
# "02" instead of "February" and "08" instead of "8").
-
# * <tt>:use_short_month</tt> - Set to true if you want to use abbreviated month names instead of full
-
# month names (e.g. "Feb" instead of "February").
-
# * <tt>:add_month_numbers</tt> - Set to true if you want to use both month numbers and month names (e.g.
-
# "2 - February" instead of "February").
-
# * <tt>:use_month_names</tt> - Set to an array with 12 month names if you want to customize month names.
-
# Note: You can also use Rails' i18n functionality for this.
-
# * <tt>:month_format_string</tt> - Set to a format string. The string gets passed keys +:number+ (integer)
-
# and +:name+ (string). A format string would be something like "%{name} (%<number>02d)" for example.
-
# See <tt>Kernel.sprintf</tt> for documentation on format sequences.
-
# * <tt>:date_separator</tt> - Specifies a string to separate the date fields. Default is "" (i.e. nothing).
-
# * <tt>:start_year</tt> - Set the start year for the year select. Default is <tt>Date.today.year - 5</tt>if
-
# you are creating new record. While editing existing record, <tt>:start_year</tt> defaults to
-
# the current selected year minus 5.
-
# * <tt>:end_year</tt> - Set the end year for the year select. Default is <tt>Date.today.year + 5</tt> if
-
# you are creating new record. While editing existing record, <tt>:end_year</tt> defaults to
-
# the current selected year plus 5.
-
# * <tt>:discard_day</tt> - Set to true if you don't want to show a day select. This includes the day
-
# as a hidden field instead of showing a select field. Also note that this implicitly sets the day to be the
-
# first of the given month in order to not create invalid dates like 31 February.
-
# * <tt>:discard_month</tt> - Set to true if you don't want to show a month select. This includes the month
-
# as a hidden field instead of showing a select field. Also note that this implicitly sets :discard_day to true.
-
# * <tt>:discard_year</tt> - Set to true if you don't want to show a year select. This includes the year
-
# as a hidden field instead of showing a select field.
-
# * <tt>:order</tt> - Set to an array containing <tt>:day</tt>, <tt>:month</tt> and <tt>:year</tt> to
-
# customize the order in which the select fields are shown. If you leave out any of the symbols, the respective
-
# select will not be shown (like when you set <tt>discard_xxx: true</tt>. Defaults to the order defined in
-
# the respective locale (e.g. [:year, :month, :day] in the en locale that ships with Rails).
-
# * <tt>:include_blank</tt> - Include a blank option in every select field so it's possible to set empty
-
# dates.
-
# * <tt>:default</tt> - Set a default date if the affected date isn't set or is nil.
-
# * <tt>:selected</tt> - Set a date that overrides the actual value.
-
# * <tt>:disabled</tt> - Set to true if you want show the select fields as disabled.
-
# * <tt>:prompt</tt> - Set to true (for a generic prompt), a prompt string or a hash of prompt strings
-
# for <tt>:year</tt>, <tt>:month</tt>, <tt>:day</tt>, <tt>:hour</tt>, <tt>:minute</tt> and <tt>:second</tt>.
-
# Setting this option prepends a select option with a generic prompt (Day, Month, Year, Hour, Minute, Seconds)
-
# or the given prompt string.
-
# * <tt>:with_css_classes</tt> - Set to true if you want assign different styles for 'select' tags. This option
-
# automatically set classes 'year', 'month', 'day', 'hour', 'minute' and 'second' for your 'select' tags.
-
#
-
# If anything is passed in the +html_options+ hash it will be applied to every select tag in the set.
-
#
-
# NOTE: Discarded selects will default to 1. So if no month select is available, January will be assumed.
-
#
-
# # Generates a date select that when POSTed is stored in the article variable, in the written_on attribute.
-
# date_select("article", "written_on")
-
#
-
# # Generates a date select that when POSTed is stored in the article variable, in the written_on attribute,
-
# # with the year in the year drop down box starting at 1995.
-
# date_select("article", "written_on", start_year: 1995)
-
#
-
# # Generates a date select that when POSTed is stored in the article variable, in the written_on attribute,
-
# # with the year in the year drop down box starting at 1995, numbers used for months instead of words,
-
# # and without a day select box.
-
# date_select("article", "written_on", start_year: 1995, use_month_numbers: true,
-
# discard_day: true, include_blank: true)
-
#
-
# # Generates a date select that when POSTed is stored in the article variable, in the written_on attribute,
-
# # with two digit numbers used for months and days.
-
# date_select("article", "written_on", use_two_digit_numbers: true)
-
#
-
# # Generates a date select that when POSTed is stored in the article variable, in the written_on attribute
-
# # with the fields ordered as day, month, year rather than month, day, year.
-
# date_select("article", "written_on", order: [:day, :month, :year])
-
#
-
# # Generates a date select that when POSTed is stored in the user variable, in the birthday attribute
-
# # lacking a year field.
-
# date_select("user", "birthday", order: [:month, :day])
-
#
-
# # Generates a date select that when POSTed is stored in the article variable, in the written_on attribute
-
# # which is initially set to the date 3 days from the current date
-
# date_select("article", "written_on", default: 3.days.from_now)
-
#
-
# # Generates a date select that when POSTed is stored in the article variable, in the written_on attribute
-
# # which is set in the form with todays date, regardless of the value in the Active Record object.
-
# date_select("article", "written_on", selected: Date.today)
-
#
-
# # Generates a date select that when POSTed is stored in the credit_card variable, in the bill_due attribute
-
# # that will have a default day of 20.
-
# date_select("credit_card", "bill_due", default: { day: 20 })
-
#
-
# # Generates a date select with custom prompts.
-
# date_select("article", "written_on", prompt: { day: 'Select day', month: 'Select month', year: 'Select year' })
-
#
-
# The selects are prepared for multi-parameter assignment to an Active Record object.
-
#
-
# Note: If the day is not included as an option but the month is, the day will be set to the 1st to ensure that
-
# all month choices are valid.
-
2
def date_select(object_name, method, options = {}, html_options = {})
-
Tags::DateSelect.new(object_name, method, self, options, html_options).render
-
end
-
-
# Returns a set of select tags (one for hour, minute and optionally second) pre-selected for accessing a
-
# specified time-based attribute (identified by +method+) on an object assigned to the template (identified by
-
# +object+). You can include the seconds with <tt>:include_seconds</tt>. You can get hours in the AM/PM format
-
# with <tt>:ampm</tt> option.
-
#
-
# This method will also generate 3 input hidden tags, for the actual year, month and day unless the option
-
# <tt>:ignore_date</tt> is set to +true+. If you set the <tt>:ignore_date</tt> to +true+, you must have a
-
# +date_select+ on the same method within the form otherwise an exception will be raised.
-
#
-
# If anything is passed in the html_options hash it will be applied to every select tag in the set.
-
#
-
# # Creates a time select tag that, when POSTed, will be stored in the article variable in the sunrise attribute.
-
# time_select("article", "sunrise")
-
#
-
# # Creates a time select tag with a seconds field that, when POSTed, will be stored in the article variables in
-
# # the sunrise attribute.
-
# time_select("article", "start_time", include_seconds: true)
-
#
-
# # You can set the <tt>:minute_step</tt> to 15 which will give you: 00, 15, 30 and 45.
-
# time_select 'game', 'game_time', {minute_step: 15}
-
#
-
# # Creates a time select tag with a custom prompt. Use <tt>prompt: true</tt> for generic prompts.
-
# time_select("article", "written_on", prompt: {hour: 'Choose hour', minute: 'Choose minute', second: 'Choose seconds'})
-
# time_select("article", "written_on", prompt: {hour: true}) # generic prompt for hours
-
# time_select("article", "written_on", prompt: true) # generic prompts for all
-
#
-
# # You can set :ampm option to true which will show the hours as: 12 PM, 01 AM .. 11 PM.
-
# time_select 'game', 'game_time', {ampm: true}
-
#
-
# The selects are prepared for multi-parameter assignment to an Active Record object.
-
#
-
# Note: If the day is not included as an option but the month is, the day will be set to the 1st to ensure that
-
# all month choices are valid.
-
2
def time_select(object_name, method, options = {}, html_options = {})
-
Tags::TimeSelect.new(object_name, method, self, options, html_options).render
-
end
-
-
# Returns a set of select tags (one for year, month, day, hour, and minute) pre-selected for accessing a
-
# specified datetime-based attribute (identified by +method+) on an object assigned to the template (identified
-
# by +object+).
-
#
-
# If anything is passed in the html_options hash it will be applied to every select tag in the set.
-
#
-
# # Generates a datetime select that, when POSTed, will be stored in the article variable in the written_on
-
# # attribute.
-
# datetime_select("article", "written_on")
-
#
-
# # Generates a datetime select with a year select that starts at 1995 that, when POSTed, will be stored in the
-
# # article variable in the written_on attribute.
-
# datetime_select("article", "written_on", start_year: 1995)
-
#
-
# # Generates a datetime select with a default value of 3 days from the current time that, when POSTed, will
-
# # be stored in the trip variable in the departing attribute.
-
# datetime_select("trip", "departing", default: 3.days.from_now)
-
#
-
# # Generate a datetime select with hours in the AM/PM format
-
# datetime_select("article", "written_on", ampm: true)
-
#
-
# # Generates a datetime select that discards the type that, when POSTed, will be stored in the article variable
-
# # as the written_on attribute.
-
# datetime_select("article", "written_on", discard_type: true)
-
#
-
# # Generates a datetime select with a custom prompt. Use <tt>prompt: true</tt> for generic prompts.
-
# datetime_select("article", "written_on", prompt: {day: 'Choose day', month: 'Choose month', year: 'Choose year'})
-
# datetime_select("article", "written_on", prompt: {hour: true}) # generic prompt for hours
-
# datetime_select("article", "written_on", prompt: true) # generic prompts for all
-
#
-
# The selects are prepared for multi-parameter assignment to an Active Record object.
-
2
def datetime_select(object_name, method, options = {}, html_options = {})
-
Tags::DatetimeSelect.new(object_name, method, self, options, html_options).render
-
end
-
-
# Returns a set of html select-tags (one for year, month, day, hour, minute, and second) pre-selected with the
-
# +datetime+. It's also possible to explicitly set the order of the tags using the <tt>:order</tt> option with
-
# an array of symbols <tt>:year</tt>, <tt>:month</tt> and <tt>:day</tt> in the desired order. If you do not
-
# supply a Symbol, it will be appended onto the <tt>:order</tt> passed in. You can also add
-
# <tt>:date_separator</tt>, <tt>:datetime_separator</tt> and <tt>:time_separator</tt> keys to the +options+ to
-
# control visual display of the elements.
-
#
-
# If anything is passed in the html_options hash it will be applied to every select tag in the set.
-
#
-
# my_date_time = Time.now + 4.days
-
#
-
# # Generates a datetime select that defaults to the datetime in my_date_time (four days after today).
-
# select_datetime(my_date_time)
-
#
-
# # Generates a datetime select that defaults to today (no specified datetime)
-
# select_datetime()
-
#
-
# # Generates a datetime select that defaults to the datetime in my_date_time (four days after today)
-
# # with the fields ordered year, month, day rather than month, day, year.
-
# select_datetime(my_date_time, order: [:year, :month, :day])
-
#
-
# # Generates a datetime select that defaults to the datetime in my_date_time (four days after today)
-
# # with a '/' between each date field.
-
# select_datetime(my_date_time, date_separator: '/')
-
#
-
# # Generates a datetime select that defaults to the datetime in my_date_time (four days after today)
-
# # with a date fields separated by '/', time fields separated by '' and the date and time fields
-
# # separated by a comma (',').
-
# select_datetime(my_date_time, date_separator: '/', time_separator: '', datetime_separator: ',')
-
#
-
# # Generates a datetime select that discards the type of the field and defaults to the datetime in
-
# # my_date_time (four days after today)
-
# select_datetime(my_date_time, discard_type: true)
-
#
-
# # Generate a datetime field with hours in the AM/PM format
-
# select_datetime(my_date_time, ampm: true)
-
#
-
# # Generates a datetime select that defaults to the datetime in my_date_time (four days after today)
-
# # prefixed with 'payday' rather than 'date'
-
# select_datetime(my_date_time, prefix: 'payday')
-
#
-
# # Generates a datetime select with a custom prompt. Use <tt>prompt: true</tt> for generic prompts.
-
# select_datetime(my_date_time, prompt: {day: 'Choose day', month: 'Choose month', year: 'Choose year'})
-
# select_datetime(my_date_time, prompt: {hour: true}) # generic prompt for hours
-
# select_datetime(my_date_time, prompt: true) # generic prompts for all
-
2
def select_datetime(datetime = Time.current, options = {}, html_options = {})
-
DateTimeSelector.new(datetime, options, html_options).select_datetime
-
end
-
-
# Returns a set of html select-tags (one for year, month, and day) pre-selected with the +date+.
-
# It's possible to explicitly set the order of the tags using the <tt>:order</tt> option with an array of
-
# symbols <tt>:year</tt>, <tt>:month</tt> and <tt>:day</tt> in the desired order.
-
# If the array passed to the <tt>:order</tt> option does not contain all the three symbols, all tags will be hidden.
-
#
-
# If anything is passed in the html_options hash it will be applied to every select tag in the set.
-
#
-
# my_date = Time.now + 6.days
-
#
-
# # Generates a date select that defaults to the date in my_date (six days after today).
-
# select_date(my_date)
-
#
-
# # Generates a date select that defaults to today (no specified date).
-
# select_date()
-
#
-
# # Generates a date select that defaults to the date in my_date (six days after today)
-
# # with the fields ordered year, month, day rather than month, day, year.
-
# select_date(my_date, order: [:year, :month, :day])
-
#
-
# # Generates a date select that discards the type of the field and defaults to the date in
-
# # my_date (six days after today).
-
# select_date(my_date, discard_type: true)
-
#
-
# # Generates a date select that defaults to the date in my_date,
-
# # which has fields separated by '/'.
-
# select_date(my_date, date_separator: '/')
-
#
-
# # Generates a date select that defaults to the datetime in my_date (six days after today)
-
# # prefixed with 'payday' rather than 'date'.
-
# select_date(my_date, prefix: 'payday')
-
#
-
# # Generates a date select with a custom prompt. Use <tt>prompt: true</tt> for generic prompts.
-
# select_date(my_date, prompt: {day: 'Choose day', month: 'Choose month', year: 'Choose year'})
-
# select_date(my_date, prompt: {hour: true}) # generic prompt for hours
-
# select_date(my_date, prompt: true) # generic prompts for all
-
2
def select_date(date = Date.current, options = {}, html_options = {})
-
DateTimeSelector.new(date, options, html_options).select_date
-
end
-
-
# Returns a set of html select-tags (one for hour and minute).
-
# You can set <tt>:time_separator</tt> key to format the output, and
-
# the <tt>:include_seconds</tt> option to include an input for seconds.
-
#
-
# If anything is passed in the html_options hash it will be applied to every select tag in the set.
-
#
-
# my_time = Time.now + 5.days + 7.hours + 3.minutes + 14.seconds
-
#
-
# # Generates a time select that defaults to the time in my_time.
-
# select_time(my_time)
-
#
-
# # Generates a time select that defaults to the current time (no specified time).
-
# select_time()
-
#
-
# # Generates a time select that defaults to the time in my_time,
-
# # which has fields separated by ':'.
-
# select_time(my_time, time_separator: ':')
-
#
-
# # Generates a time select that defaults to the time in my_time,
-
# # that also includes an input for seconds.
-
# select_time(my_time, include_seconds: true)
-
#
-
# # Generates a time select that defaults to the time in my_time, that has fields
-
# # separated by ':' and includes an input for seconds.
-
# select_time(my_time, time_separator: ':', include_seconds: true)
-
#
-
# # Generate a time select field with hours in the AM/PM format
-
# select_time(my_time, ampm: true)
-
#
-
# # Generates a time select field with hours that range from 2 to 14
-
# select_time(my_time, start_hour: 2, end_hour: 14)
-
#
-
# # Generates a time select with a custom prompt. Use <tt>:prompt</tt> to true for generic prompts.
-
# select_time(my_time, prompt: {day: 'Choose day', month: 'Choose month', year: 'Choose year'})
-
# select_time(my_time, prompt: {hour: true}) # generic prompt for hours
-
# select_time(my_time, prompt: true) # generic prompts for all
-
2
def select_time(datetime = Time.current, options = {}, html_options = {})
-
DateTimeSelector.new(datetime, options, html_options).select_time
-
end
-
-
# Returns a select tag with options for each of the seconds 0 through 59 with the current second selected.
-
# The <tt>datetime</tt> can be either a +Time+ or +DateTime+ object or an integer.
-
# Override the field name using the <tt>:field_name</tt> option, 'second' by default.
-
#
-
# my_time = Time.now + 16.minutes
-
#
-
# # Generates a select field for seconds that defaults to the seconds for the time in my_time.
-
# select_second(my_time)
-
#
-
# # Generates a select field for seconds that defaults to the number given.
-
# select_second(33)
-
#
-
# # Generates a select field for seconds that defaults to the seconds for the time in my_time
-
# # that is named 'interval' rather than 'second'.
-
# select_second(my_time, field_name: 'interval')
-
#
-
# # Generates a select field for seconds with a custom prompt. Use <tt>prompt: true</tt> for a
-
# # generic prompt.
-
# select_second(14, prompt: 'Choose seconds')
-
2
def select_second(datetime, options = {}, html_options = {})
-
DateTimeSelector.new(datetime, options, html_options).select_second
-
end
-
-
# Returns a select tag with options for each of the minutes 0 through 59 with the current minute selected.
-
# Also can return a select tag with options by <tt>minute_step</tt> from 0 through 59 with the 00 minute
-
# selected. The <tt>datetime</tt> can be either a +Time+ or +DateTime+ object or an integer.
-
# Override the field name using the <tt>:field_name</tt> option, 'minute' by default.
-
#
-
# my_time = Time.now + 6.hours
-
#
-
# # Generates a select field for minutes that defaults to the minutes for the time in my_time.
-
# select_minute(my_time)
-
#
-
# # Generates a select field for minutes that defaults to the number given.
-
# select_minute(14)
-
#
-
# # Generates a select field for minutes that defaults to the minutes for the time in my_time
-
# # that is named 'moment' rather than 'minute'.
-
# select_minute(my_time, field_name: 'moment')
-
#
-
# # Generates a select field for minutes with a custom prompt. Use <tt>prompt: true</tt> for a
-
# # generic prompt.
-
# select_minute(14, prompt: 'Choose minutes')
-
2
def select_minute(datetime, options = {}, html_options = {})
-
DateTimeSelector.new(datetime, options, html_options).select_minute
-
end
-
-
# Returns a select tag with options for each of the hours 0 through 23 with the current hour selected.
-
# The <tt>datetime</tt> can be either a +Time+ or +DateTime+ object or an integer.
-
# Override the field name using the <tt>:field_name</tt> option, 'hour' by default.
-
#
-
# my_time = Time.now + 6.hours
-
#
-
# # Generates a select field for hours that defaults to the hour for the time in my_time.
-
# select_hour(my_time)
-
#
-
# # Generates a select field for hours that defaults to the number given.
-
# select_hour(13)
-
#
-
# # Generates a select field for hours that defaults to the hour for the time in my_time
-
# # that is named 'stride' rather than 'hour'.
-
# select_hour(my_time, field_name: 'stride')
-
#
-
# # Generates a select field for hours with a custom prompt. Use <tt>prompt: true</tt> for a
-
# # generic prompt.
-
# select_hour(13, prompt: 'Choose hour')
-
#
-
# # Generate a select field for hours in the AM/PM format
-
# select_hour(my_time, ampm: true)
-
#
-
# # Generates a select field that includes options for hours from 2 to 14.
-
# select_hour(my_time, start_hour: 2, end_hour: 14)
-
2
def select_hour(datetime, options = {}, html_options = {})
-
DateTimeSelector.new(datetime, options, html_options).select_hour
-
end
-
-
# Returns a select tag with options for each of the days 1 through 31 with the current day selected.
-
# The <tt>date</tt> can also be substituted for a day number.
-
# If you want to display days with a leading zero set the <tt>:use_two_digit_numbers</tt> key in +options+ to true.
-
# Override the field name using the <tt>:field_name</tt> option, 'day' by default.
-
#
-
# my_date = Time.now + 2.days
-
#
-
# # Generates a select field for days that defaults to the day for the date in my_date.
-
# select_day(my_date)
-
#
-
# # Generates a select field for days that defaults to the number given.
-
# select_day(5)
-
#
-
# # Generates a select field for days that defaults to the number given, but displays it with two digits.
-
# select_day(5, use_two_digit_numbers: true)
-
#
-
# # Generates a select field for days that defaults to the day for the date in my_date
-
# # that is named 'due' rather than 'day'.
-
# select_day(my_date, field_name: 'due')
-
#
-
# # Generates a select field for days with a custom prompt. Use <tt>prompt: true</tt> for a
-
# # generic prompt.
-
# select_day(5, prompt: 'Choose day')
-
2
def select_day(date, options = {}, html_options = {})
-
DateTimeSelector.new(date, options, html_options).select_day
-
end
-
-
# Returns a select tag with options for each of the months January through December with the current month
-
# selected. The month names are presented as keys (what's shown to the user) and the month numbers (1-12) are
-
# used as values (what's submitted to the server). It's also possible to use month numbers for the presentation
-
# instead of names -- set the <tt>:use_month_numbers</tt> key in +options+ to true for this to happen. If you
-
# want both numbers and names, set the <tt>:add_month_numbers</tt> key in +options+ to true. If you would prefer
-
# to show month names as abbreviations, set the <tt>:use_short_month</tt> key in +options+ to true. If you want
-
# to use your own month names, set the <tt>:use_month_names</tt> key in +options+ to an array of 12 month names.
-
# If you want to display months with a leading zero set the <tt>:use_two_digit_numbers</tt> key in +options+ to true.
-
# Override the field name using the <tt>:field_name</tt> option, 'month' by default.
-
#
-
# # Generates a select field for months that defaults to the current month that
-
# # will use keys like "January", "March".
-
# select_month(Date.today)
-
#
-
# # Generates a select field for months that defaults to the current month that
-
# # is named "start" rather than "month".
-
# select_month(Date.today, field_name: 'start')
-
#
-
# # Generates a select field for months that defaults to the current month that
-
# # will use keys like "1", "3".
-
# select_month(Date.today, use_month_numbers: true)
-
#
-
# # Generates a select field for months that defaults to the current month that
-
# # will use keys like "1 - January", "3 - March".
-
# select_month(Date.today, add_month_numbers: true)
-
#
-
# # Generates a select field for months that defaults to the current month that
-
# # will use keys like "Jan", "Mar".
-
# select_month(Date.today, use_short_month: true)
-
#
-
# # Generates a select field for months that defaults to the current month that
-
# # will use keys like "Januar", "Marts."
-
# select_month(Date.today, use_month_names: %w(Januar Februar Marts ...))
-
#
-
# # Generates a select field for months that defaults to the current month that
-
# # will use keys with two digit numbers like "01", "03".
-
# select_month(Date.today, use_two_digit_numbers: true)
-
#
-
# # Generates a select field for months with a custom prompt. Use <tt>prompt: true</tt> for a
-
# # generic prompt.
-
# select_month(14, prompt: 'Choose month')
-
2
def select_month(date, options = {}, html_options = {})
-
DateTimeSelector.new(date, options, html_options).select_month
-
end
-
-
# Returns a select tag with options for each of the five years on each side of the current, which is selected.
-
# The five year radius can be changed using the <tt>:start_year</tt> and <tt>:end_year</tt> keys in the
-
# +options+. Both ascending and descending year lists are supported by making <tt>:start_year</tt> less than or
-
# greater than <tt>:end_year</tt>. The <tt>date</tt> can also be substituted for a year given as a number.
-
# Override the field name using the <tt>:field_name</tt> option, 'year' by default.
-
#
-
# # Generates a select field for years that defaults to the current year that
-
# # has ascending year values.
-
# select_year(Date.today, start_year: 1992, end_year: 2007)
-
#
-
# # Generates a select field for years that defaults to the current year that
-
# # is named 'birth' rather than 'year'.
-
# select_year(Date.today, field_name: 'birth')
-
#
-
# # Generates a select field for years that defaults to the current year that
-
# # has descending year values.
-
# select_year(Date.today, start_year: 2005, end_year: 1900)
-
#
-
# # Generates a select field for years that defaults to the year 2006 that
-
# # has ascending year values.
-
# select_year(2006, start_year: 2000, end_year: 2010)
-
#
-
# # Generates a select field for years with a custom prompt. Use <tt>prompt: true</tt> for a
-
# # generic prompt.
-
# select_year(14, prompt: 'Choose year')
-
2
def select_year(date, options = {}, html_options = {})
-
DateTimeSelector.new(date, options, html_options).select_year
-
end
-
-
# Returns an html time tag for the given date or time.
-
#
-
# time_tag Date.today # =>
-
# <time datetime="2010-11-04">November 04, 2010</time>
-
# time_tag Time.now # =>
-
# <time datetime="2010-11-04T17:55:45+01:00">November 04, 2010 17:55</time>
-
# time_tag Date.yesterday, 'Yesterday' # =>
-
# <time datetime="2010-11-03">Yesterday</time>
-
# time_tag Date.today, pubdate: true # =>
-
# <time datetime="2010-11-04" pubdate="pubdate">November 04, 2010</time>
-
# time_tag Date.today, datetime: Date.today.strftime('%G-W%V') # =>
-
# <time datetime="2010-W44">November 04, 2010</time>
-
#
-
# <%= time_tag Time.now do %>
-
# <span>Right now</span>
-
# <% end %>
-
# # => <time datetime="2010-11-04T17:55:45+01:00"><span>Right now</span></time>
-
2
def time_tag(date_or_time, *args, &block)
-
options = args.extract_options!
-
format = options.delete(:format) || :long
-
content = args.first || I18n.l(date_or_time, :format => format)
-
datetime = date_or_time.acts_like?(:time) ? date_or_time.xmlschema : date_or_time.iso8601
-
-
content_tag(:time, content, options.reverse_merge(:datetime => datetime), &block)
-
end
-
end
-
-
2
class DateTimeSelector #:nodoc:
-
2
include ActionView::Helpers::TagHelper
-
-
2
DEFAULT_PREFIX = 'date'.freeze
-
2
POSITION = {
-
:year => 1, :month => 2, :day => 3, :hour => 4, :minute => 5, :second => 6
-
}.freeze
-
-
2
AMPM_TRANSLATION = Hash[
-
[[0, "12 AM"], [1, "01 AM"], [2, "02 AM"], [3, "03 AM"],
-
[4, "04 AM"], [5, "05 AM"], [6, "06 AM"], [7, "07 AM"],
-
[8, "08 AM"], [9, "09 AM"], [10, "10 AM"], [11, "11 AM"],
-
[12, "12 PM"], [13, "01 PM"], [14, "02 PM"], [15, "03 PM"],
-
[16, "04 PM"], [17, "05 PM"], [18, "06 PM"], [19, "07 PM"],
-
[20, "08 PM"], [21, "09 PM"], [22, "10 PM"], [23, "11 PM"]]
-
].freeze
-
-
2
def initialize(datetime, options = {}, html_options = {})
-
@options = options.dup
-
@html_options = html_options.dup
-
@datetime = datetime
-
@options[:datetime_separator] ||= ' — '
-
@options[:time_separator] ||= ' : '
-
end
-
-
2
def select_datetime
-
order = date_order.dup
-
order -= [:hour, :minute, :second]
-
@options[:discard_year] ||= true unless order.include?(:year)
-
@options[:discard_month] ||= true unless order.include?(:month)
-
@options[:discard_day] ||= true if @options[:discard_month] || !order.include?(:day)
-
@options[:discard_minute] ||= true if @options[:discard_hour]
-
@options[:discard_second] ||= true unless @options[:include_seconds] && !@options[:discard_minute]
-
-
set_day_if_discarded
-
-
if @options[:tag] && @options[:ignore_date]
-
select_time
-
else
-
[:day, :month, :year].each { |o| order.unshift(o) unless order.include?(o) }
-
order += [:hour, :minute, :second] unless @options[:discard_hour]
-
-
build_selects_from_types(order)
-
end
-
end
-
-
2
def select_date
-
order = date_order.dup
-
-
@options[:discard_hour] = true
-
@options[:discard_minute] = true
-
@options[:discard_second] = true
-
-
@options[:discard_year] ||= true unless order.include?(:year)
-
@options[:discard_month] ||= true unless order.include?(:month)
-
@options[:discard_day] ||= true if @options[:discard_month] || !order.include?(:day)
-
-
set_day_if_discarded
-
-
[:day, :month, :year].each { |o| order.unshift(o) unless order.include?(o) }
-
-
build_selects_from_types(order)
-
end
-
-
2
def select_time
-
order = []
-
-
@options[:discard_month] = true
-
@options[:discard_year] = true
-
@options[:discard_day] = true
-
@options[:discard_second] ||= true unless @options[:include_seconds]
-
-
order += [:year, :month, :day] unless @options[:ignore_date]
-
-
order += [:hour, :minute]
-
order << :second if @options[:include_seconds]
-
-
build_selects_from_types(order)
-
end
-
-
2
def select_second
-
if @options[:use_hidden] || @options[:discard_second]
-
build_hidden(:second, sec) if @options[:include_seconds]
-
else
-
build_options_and_select(:second, sec)
-
end
-
end
-
-
2
def select_minute
-
if @options[:use_hidden] || @options[:discard_minute]
-
build_hidden(:minute, min)
-
else
-
build_options_and_select(:minute, min, :step => @options[:minute_step])
-
end
-
end
-
-
2
def select_hour
-
if @options[:use_hidden] || @options[:discard_hour]
-
build_hidden(:hour, hour)
-
else
-
options = {}
-
options[:ampm] = @options[:ampm] || false
-
options[:start] = @options[:start_hour] || 0
-
options[:end] = @options[:end_hour] || 23
-
build_options_and_select(:hour, hour, options)
-
end
-
end
-
-
2
def select_day
-
if @options[:use_hidden] || @options[:discard_day]
-
build_hidden(:day, day || 1)
-
else
-
build_options_and_select(:day, day, :start => 1, :end => 31, :leading_zeros => false, :use_two_digit_numbers => @options[:use_two_digit_numbers])
-
end
-
end
-
-
2
def select_month
-
if @options[:use_hidden] || @options[:discard_month]
-
build_hidden(:month, month || 1)
-
else
-
month_options = []
-
1.upto(12) do |month_number|
-
options = { :value => month_number }
-
options[:selected] = "selected" if month == month_number
-
month_options << content_tag(:option, month_name(month_number), options) + "\n"
-
end
-
build_select(:month, month_options.join)
-
end
-
end
-
-
2
def select_year
-
if !@datetime || @datetime == 0
-
val = '1'
-
middle_year = Date.today.year
-
else
-
val = middle_year = year
-
end
-
-
if @options[:use_hidden] || @options[:discard_year]
-
build_hidden(:year, val)
-
else
-
options = {}
-
options[:start] = @options[:start_year] || middle_year - 5
-
options[:end] = @options[:end_year] || middle_year + 5
-
options[:step] = options[:start] < options[:end] ? 1 : -1
-
options[:leading_zeros] = false
-
options[:max_years_allowed] = @options[:max_years_allowed] || 1000
-
-
if (options[:end] - options[:start]).abs > options[:max_years_allowed]
-
raise ArgumentError, "There are too many years options to be built. Are you sure you haven't mistyped something? You can provide the :max_years_allowed parameter."
-
end
-
-
build_options_and_select(:year, val, options)
-
end
-
end
-
-
2
private
-
2
%w( sec min hour day month year ).each do |method|
-
12
define_method(method) do
-
@datetime.kind_of?(Numeric) ? @datetime : @datetime.send(method) if @datetime
-
end
-
end
-
-
# If the day is hidden, the day should be set to the 1st so all month and year choices are
-
# valid. Otherwise, February 31st or February 29th, 2011 can be selected, which are invalid.
-
2
def set_day_if_discarded
-
if @datetime && @options[:discard_day]
-
@datetime = @datetime.change(:day => 1)
-
end
-
end
-
-
# Returns translated month names, but also ensures that a custom month
-
# name array has a leading nil element.
-
2
def month_names
-
@month_names ||= begin
-
month_names = @options[:use_month_names] || translated_month_names
-
month_names.unshift(nil) if month_names.size < 13
-
month_names
-
end
-
end
-
-
# Returns translated month names.
-
# => [nil, "January", "February", "March",
-
# "April", "May", "June", "July",
-
# "August", "September", "October",
-
# "November", "December"]
-
#
-
# If <tt>:use_short_month</tt> option is set
-
# => [nil, "Jan", "Feb", "Mar", "Apr", "May", "Jun",
-
# "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
-
2
def translated_month_names
-
key = @options[:use_short_month] ? :'date.abbr_month_names' : :'date.month_names'
-
I18n.translate(key, :locale => @options[:locale])
-
end
-
-
# Looks up month names by number (1-based):
-
#
-
# month_name(1) # => "January"
-
#
-
# If the <tt>:use_month_numbers</tt> option is passed:
-
#
-
# month_name(1) # => 1
-
#
-
# If the <tt>:use_two_month_numbers</tt> option is passed:
-
#
-
# month_name(1) # => '01'
-
#
-
# If the <tt>:add_month_numbers</tt> option is passed:
-
#
-
# month_name(1) # => "1 - January"
-
#
-
# If the <tt>:month_format_string</tt> option is passed:
-
#
-
# month_name(1) # => "January (01)"
-
#
-
# depending on the format string.
-
2
def month_name(number)
-
if @options[:use_month_numbers]
-
number
-
elsif @options[:use_two_digit_numbers]
-
'%02d' % number
-
elsif @options[:add_month_numbers]
-
"#{number} - #{month_names[number]}"
-
elsif format_string = @options[:month_format_string]
-
format_string % {number: number, name: month_names[number]}
-
else
-
month_names[number]
-
end
-
end
-
-
2
def date_order
-
@date_order ||= @options[:order] || translated_date_order
-
end
-
-
2
def translated_date_order
-
date_order = I18n.translate(:'date.order', :locale => @options[:locale], :default => [])
-
date_order = date_order.map { |element| element.to_sym }
-
-
forbidden_elements = date_order - [:year, :month, :day]
-
if forbidden_elements.any?
-
raise StandardError,
-
"#{@options[:locale]}.date.order only accepts :year, :month and :day"
-
end
-
-
date_order
-
end
-
-
# Build full select tag from date type and options.
-
2
def build_options_and_select(type, selected, options = {})
-
build_select(type, build_options(selected, options))
-
end
-
-
# Build select option html from date value and options.
-
# build_options(15, start: 1, end: 31)
-
# => "<option value="1">1</option>
-
# <option value="2">2</option>
-
# <option value="3">3</option>..."
-
#
-
# If <tt>use_two_digit_numbers: true</tt> option is passed
-
# build_options(15, start: 1, end: 31, use_two_digit_numbers: true)
-
# => "<option value="1">01</option>
-
# <option value="2">02</option>
-
# <option value="3">03</option>..."
-
#
-
# If <tt>:step</tt> options is passed
-
# build_options(15, start: 1, end: 31, step: 2)
-
# => "<option value="1">1</option>
-
# <option value="3">3</option>
-
# <option value="5">5</option>..."
-
2
def build_options(selected, options = {})
-
options = {
-
leading_zeros: true, ampm: false, use_two_digit_numbers: false
-
}.merge!(options)
-
-
start = options.delete(:start) || 0
-
stop = options.delete(:end) || 59
-
step = options.delete(:step) || 1
-
leading_zeros = options.delete(:leading_zeros)
-
-
select_options = []
-
start.step(stop, step) do |i|
-
value = leading_zeros ? sprintf("%02d", i) : i
-
tag_options = { :value => value }
-
tag_options[:selected] = "selected" if selected == i
-
text = options[:use_two_digit_numbers] ? sprintf("%02d", i) : value
-
text = options[:ampm] ? AMPM_TRANSLATION[i] : text
-
select_options << content_tag(:option, text, tag_options)
-
end
-
-
(select_options.join("\n") + "\n").html_safe
-
end
-
-
# Builds select tag from date type and html select options.
-
# build_select(:month, "<option value="1">January</option>...")
-
# => "<select id="post_written_on_2i" name="post[written_on(2i)]">
-
# <option value="1">January</option>...
-
# </select>"
-
2
def build_select(type, select_options_as_html)
-
select_options = {
-
:id => input_id_from_type(type),
-
:name => input_name_from_type(type)
-
}.merge!(@html_options)
-
select_options[:disabled] = 'disabled' if @options[:disabled]
-
select_options[:class] = [select_options[:class], type].compact.join(' ') if @options[:with_css_classes]
-
-
select_html = "\n"
-
select_html << content_tag(:option, '', :value => '') + "\n" if @options[:include_blank]
-
select_html << prompt_option_tag(type, @options[:prompt]) + "\n" if @options[:prompt]
-
select_html << select_options_as_html
-
-
(content_tag(:select, select_html.html_safe, select_options) + "\n").html_safe
-
end
-
-
# Builds a prompt option tag with supplied options or from default options.
-
# prompt_option_tag(:month, prompt: 'Select month')
-
# => "<option value="">Select month</option>"
-
2
def prompt_option_tag(type, options)
-
prompt = case options
-
when Hash
-
default_options = {:year => false, :month => false, :day => false, :hour => false, :minute => false, :second => false}
-
default_options.merge!(options)[type.to_sym]
-
when String
-
options
-
else
-
I18n.translate(:"datetime.prompts.#{type}", :locale => @options[:locale])
-
end
-
-
prompt ? content_tag(:option, prompt, :value => '') : ''
-
end
-
-
# Builds hidden input tag for date part and value.
-
# build_hidden(:year, 2008)
-
# => "<input id="post_written_on_1i" name="post[written_on(1i)]" type="hidden" value="2008" />"
-
2
def build_hidden(type, value)
-
select_options = {
-
:type => "hidden",
-
:id => input_id_from_type(type),
-
:name => input_name_from_type(type),
-
:value => value
-
}.merge!(@html_options.slice(:disabled))
-
select_options[:disabled] = 'disabled' if @options[:disabled]
-
-
tag(:input, select_options) + "\n".html_safe
-
end
-
-
# Returns the name attribute for the input tag.
-
# => post[written_on(1i)]
-
2
def input_name_from_type(type)
-
prefix = @options[:prefix] || ActionView::Helpers::DateTimeSelector::DEFAULT_PREFIX
-
prefix += "[#{@options[:index]}]" if @options.has_key?(:index)
-
-
field_name = @options[:field_name] || type
-
if @options[:include_position]
-
field_name += "(#{ActionView::Helpers::DateTimeSelector::POSITION[type]}i)"
-
end
-
-
@options[:discard_type] ? prefix : "#{prefix}[#{field_name}]"
-
end
-
-
# Returns the id attribute for the input tag.
-
# => "post_written_on_1i"
-
2
def input_id_from_type(type)
-
id = input_name_from_type(type).gsub(/([\[\(])|(\]\[)/, '_').gsub(/[\]\)]/, '')
-
id = @options[:namespace] + '_' + id if @options[:namespace]
-
-
id
-
end
-
-
# Given an ordering of datetime components, create the selection HTML
-
# and join them with their appropriate separators.
-
2
def build_selects_from_types(order)
-
select = ''
-
first_visible = order.find { |type| !@options[:"discard_#{type}"] }
-
order.reverse.each do |type|
-
separator = separator(type) unless type == first_visible # don't add before first visible field
-
select.insert(0, separator.to_s + send("select_#{type}").to_s)
-
end
-
select.html_safe
-
end
-
-
# Returns the separator for a given datetime component.
-
2
def separator(type)
-
return "" if @options[:use_hidden]
-
-
case type
-
when :year, :month, :day
-
@options[:"discard_#{type}"] ? "" : @options[:date_separator]
-
when :hour
-
(@options[:discard_year] && @options[:discard_day]) ? "" : @options[:datetime_separator]
-
when :minute, :second
-
@options[:"discard_#{type}"] ? "" : @options[:time_separator]
-
end
-
end
-
end
-
-
2
class FormBuilder
-
# Wraps ActionView::Helpers::DateHelper#date_select for form builders:
-
#
-
# <%= form_for @person do |f| %>
-
# <%= f.date_select :birth_date %>
-
# <%= f.submit %>
-
# <% end %>
-
#
-
# Please refer to the documentation of the base helper for details.
-
2
def date_select(method, options = {}, html_options = {})
-
@template.date_select(@object_name, method, objectify_options(options), html_options)
-
end
-
-
# Wraps ActionView::Helpers::DateHelper#time_select for form builders:
-
#
-
# <%= form_for @race do |f| %>
-
# <%= f.time_select :average_lap %>
-
# <%= f.submit %>
-
# <% end %>
-
#
-
# Please refer to the documentation of the base helper for details.
-
2
def time_select(method, options = {}, html_options = {})
-
@template.time_select(@object_name, method, objectify_options(options), html_options)
-
end
-
-
# Wraps ActionView::Helpers::DateHelper#datetime_select for form builders:
-
#
-
# <%= form_for @person do |f| %>
-
# <%= f.datetime_select :last_request_at %>
-
# <%= f.submit %>
-
# <% end %>
-
#
-
# Please refer to the documentation of the base helper for details.
-
2
def datetime_select(method, options = {}, html_options = {})
-
@template.datetime_select(@object_name, method, objectify_options(options), html_options)
-
end
-
end
-
end
-
end
-
2
module ActionView
-
# = Action View Debug Helper
-
#
-
# Provides a set of methods for making it easier to debug Rails objects.
-
2
module Helpers
-
2
module DebugHelper
-
-
2
include TagHelper
-
-
# Returns a YAML representation of +object+ wrapped with <pre> and </pre>.
-
# If the object cannot be converted to YAML using +to_yaml+, +inspect+ will be called instead.
-
# Useful for inspecting an object at the time of rendering.
-
#
-
# @user = User.new({ username: 'testing', password: 'xyz', age: 42}) %>
-
# debug(@user)
-
# # =>
-
# <pre class='debug_dump'>--- !ruby/object:User
-
# attributes:
-
# updated_at:
-
# username: testing
-
#
-
# age: 42
-
# password: xyz
-
# created_at:
-
# attributes_cache: {}
-
#
-
# new_record: true
-
# </pre>
-
2
def debug(object)
-
Marshal::dump(object)
-
object = ERB::Util.html_escape(object.to_yaml).gsub(" ", " ").html_safe
-
content_tag(:pre, object, :class => "debug_dump")
-
rescue Exception # errors from Marshal or YAML
-
# Object couldn't be dumped, perhaps because of singleton methods -- this is the fallback
-
content_tag(:code, object.inspect, :class => "debug_dump")
-
end
-
end
-
end
-
end
-
2
require 'cgi'
-
2
require 'action_view/helpers/date_helper'
-
2
require 'action_view/helpers/tag_helper'
-
2
require 'action_view/helpers/form_tag_helper'
-
2
require 'action_view/helpers/active_model_helper'
-
2
require 'action_view/model_naming'
-
2
require 'active_support/core_ext/module/attribute_accessors'
-
2
require 'active_support/core_ext/hash/slice'
-
2
require 'active_support/core_ext/string/output_safety'
-
2
require 'active_support/core_ext/string/inflections'
-
-
2
module ActionView
-
# = Action View Form Helpers
-
2
module Helpers
-
# Form helpers are designed to make working with resources much easier
-
# compared to using vanilla HTML.
-
#
-
# Typically, a form designed to create or update a resource reflects the
-
# identity of the resource in several ways: (i) the url that the form is
-
# sent to (the form element's +action+ attribute) should result in a request
-
# being routed to the appropriate controller action (with the appropriate <tt>:id</tt>
-
# parameter in the case of an existing resource), (ii) input fields should
-
# be named in such a way that in the controller their values appear in the
-
# appropriate places within the +params+ hash, and (iii) for an existing record,
-
# when the form is initially displayed, input fields corresponding to attributes
-
# of the resource should show the current values of those attributes.
-
#
-
# In Rails, this is usually achieved by creating the form using +form_for+ and
-
# a number of related helper methods. +form_for+ generates an appropriate <tt>form</tt>
-
# tag and yields a form builder object that knows the model the form is about.
-
# Input fields are created by calling methods defined on the form builder, which
-
# means they are able to generate the appropriate names and default values
-
# corresponding to the model attributes, as well as convenient IDs, etc.
-
# Conventions in the generated field names allow controllers to receive form data
-
# nicely structured in +params+ with no effort on your side.
-
#
-
# For example, to create a new person you typically set up a new instance of
-
# +Person+ in the <tt>PeopleController#new</tt> action, <tt>@person</tt>, and
-
# in the view template pass that object to +form_for+:
-
#
-
# <%= form_for @person do |f| %>
-
# <%= f.label :first_name %>:
-
# <%= f.text_field :first_name %><br />
-
#
-
# <%= f.label :last_name %>:
-
# <%= f.text_field :last_name %><br />
-
#
-
# <%= f.submit %>
-
# <% end %>
-
#
-
# The HTML generated for this would be (modulus formatting):
-
#
-
# <form action="/people" class="new_person" id="new_person" method="post">
-
# <div style="display:none">
-
# <input name="authenticity_token" type="hidden" value="NrOp5bsjoLRuK8IW5+dQEYjKGUJDe7TQoZVvq95Wteg=" />
-
# </div>
-
# <label for="person_first_name">First name</label>:
-
# <input id="person_first_name" name="person[first_name]" type="text" /><br />
-
#
-
# <label for="person_last_name">Last name</label>:
-
# <input id="person_last_name" name="person[last_name]" type="text" /><br />
-
#
-
# <input name="commit" type="submit" value="Create Person" />
-
# </form>
-
#
-
# As you see, the HTML reflects knowledge about the resource in several spots,
-
# like the path the form should be submitted to, or the names of the input fields.
-
#
-
# In particular, thanks to the conventions followed in the generated field names, the
-
# controller gets a nested hash <tt>params[:person]</tt> with the person attributes
-
# set in the form. That hash is ready to be passed to <tt>Person.create</tt>:
-
#
-
# if @person = Person.create(params[:person])
-
# # success
-
# else
-
# # error handling
-
# end
-
#
-
# Interestingly, the exact same view code in the previous example can be used to edit
-
# a person. If <tt>@person</tt> is an existing record with name "John Smith" and ID 256,
-
# the code above as is would yield instead:
-
#
-
# <form action="/people/256" class="edit_person" id="edit_person_256" method="post">
-
# <div style="display:none">
-
# <input name="_method" type="hidden" value="patch" />
-
# <input name="authenticity_token" type="hidden" value="NrOp5bsjoLRuK8IW5+dQEYjKGUJDe7TQoZVvq95Wteg=" />
-
# </div>
-
# <label for="person_first_name">First name</label>:
-
# <input id="person_first_name" name="person[first_name]" type="text" value="John" /><br />
-
#
-
# <label for="person_last_name">Last name</label>:
-
# <input id="person_last_name" name="person[last_name]" type="text" value="Smith" /><br />
-
#
-
# <input name="commit" type="submit" value="Update Person" />
-
# </form>
-
#
-
# Note that the endpoint, default values, and submit button label are tailored for <tt>@person</tt>.
-
# That works that way because the involved helpers know whether the resource is a new record or not,
-
# and generate HTML accordingly.
-
#
-
# The controller would receive the form data again in <tt>params[:person]</tt>, ready to be
-
# passed to <tt>Person#update</tt>:
-
#
-
# if @person.update(params[:person])
-
# # success
-
# else
-
# # error handling
-
# end
-
#
-
# That's how you typically work with resources.
-
2
module FormHelper
-
2
extend ActiveSupport::Concern
-
-
2
include FormTagHelper
-
2
include UrlHelper
-
2
include ModelNaming
-
-
# Creates a form that allows the user to create or update the attributes
-
# of a specific model object.
-
#
-
# The method can be used in several slightly different ways, depending on
-
# how much you wish to rely on Rails to infer automatically from the model
-
# how the form should be constructed. For a generic model object, a form
-
# can be created by passing +form_for+ a string or symbol representing
-
# the object we are concerned with:
-
#
-
# <%= form_for :person do |f| %>
-
# First name: <%= f.text_field :first_name %><br />
-
# Last name : <%= f.text_field :last_name %><br />
-
# Biography : <%= f.text_area :biography %><br />
-
# Admin? : <%= f.check_box :admin %><br />
-
# <%= f.submit %>
-
# <% end %>
-
#
-
# The variable +f+ yielded to the block is a FormBuilder object that
-
# incorporates the knowledge about the model object represented by
-
# <tt>:person</tt> passed to +form_for+. Methods defined on the FormBuilder
-
# are used to generate fields bound to this model. Thus, for example,
-
#
-
# <%= f.text_field :first_name %>
-
#
-
# will get expanded to
-
#
-
# <%= text_field :person, :first_name %>
-
# which results in an html <tt><input></tt> tag whose +name+ attribute is
-
# <tt>person[first_name]</tt>. This means that when the form is submitted,
-
# the value entered by the user will be available in the controller as
-
# <tt>params[:person][:first_name]</tt>.
-
#
-
# For fields generated in this way using the FormBuilder,
-
# if <tt>:person</tt> also happens to be the name of an instance variable
-
# <tt>@person</tt>, the default value of the field shown when the form is
-
# initially displayed (e.g. in the situation where you are editing an
-
# existing record) will be the value of the corresponding attribute of
-
# <tt>@person</tt>.
-
#
-
# The rightmost argument to +form_for+ is an
-
# optional hash of options -
-
#
-
# * <tt>:url</tt> - The URL the form is to be submitted to. This may be
-
# represented in the same way as values passed to +url_for+ or +link_to+.
-
# So for example you may use a named route directly. When the model is
-
# represented by a string or symbol, as in the example above, if the
-
# <tt>:url</tt> option is not specified, by default the form will be
-
# sent back to the current url (We will describe below an alternative
-
# resource-oriented usage of +form_for+ in which the URL does not need
-
# to be specified explicitly).
-
# * <tt>:namespace</tt> - A namespace for your form to ensure uniqueness of
-
# id attributes on form elements. The namespace attribute will be prefixed
-
# with underscore on the generated HTML id.
-
# * <tt>:html</tt> - Optional HTML attributes for the form tag.
-
#
-
# Also note that +form_for+ doesn't create an exclusive scope. It's still
-
# possible to use both the stand-alone FormHelper methods and methods
-
# from FormTagHelper. For example:
-
#
-
# <%= form_for :person do |f| %>
-
# First name: <%= f.text_field :first_name %>
-
# Last name : <%= f.text_field :last_name %>
-
# Biography : <%= text_area :person, :biography %>
-
# Admin? : <%= check_box_tag "person[admin]", "1", @person.company.admin? %>
-
# <%= f.submit %>
-
# <% end %>
-
#
-
# This also works for the methods in FormOptionHelper and DateHelper that
-
# are designed to work with an object as base, like
-
# FormOptionHelper#collection_select and DateHelper#datetime_select.
-
#
-
# === #form_for with a model object
-
#
-
# In the examples above, the object to be created or edited was
-
# represented by a symbol passed to +form_for+, and we noted that
-
# a string can also be used equivalently. It is also possible, however,
-
# to pass a model object itself to +form_for+. For example, if <tt>@post</tt>
-
# is an existing record you wish to edit, you can create the form using
-
#
-
# <%= form_for @post do |f| %>
-
# ...
-
# <% end %>
-
#
-
# This behaves in almost the same way as outlined previously, with a
-
# couple of small exceptions. First, the prefix used to name the input
-
# elements within the form (hence the key that denotes them in the +params+
-
# hash) is actually derived from the object's _class_, e.g. <tt>params[:post]</tt>
-
# if the object's class is +Post+. However, this can be overwritten using
-
# the <tt>:as</tt> option, e.g. -
-
#
-
# <%= form_for(@person, as: :client) do |f| %>
-
# ...
-
# <% end %>
-
#
-
# would result in <tt>params[:client]</tt>.
-
#
-
# Secondly, the field values shown when the form is initially displayed
-
# are taken from the attributes of the object passed to +form_for+,
-
# regardless of whether the object is an instance
-
# variable. So, for example, if we had a _local_ variable +post+
-
# representing an existing record,
-
#
-
# <%= form_for post do |f| %>
-
# ...
-
# <% end %>
-
#
-
# would produce a form with fields whose initial state reflect the current
-
# values of the attributes of +post+.
-
#
-
# === Resource-oriented style
-
#
-
# In the examples just shown, although not indicated explicitly, we still
-
# need to use the <tt>:url</tt> option in order to specify where the
-
# form is going to be sent. However, further simplification is possible
-
# if the record passed to +form_for+ is a _resource_, i.e. it corresponds
-
# to a set of RESTful routes, e.g. defined using the +resources+ method
-
# in <tt>config/routes.rb</tt>. In this case Rails will simply infer the
-
# appropriate URL from the record itself. For example,
-
#
-
# <%= form_for @post do |f| %>
-
# ...
-
# <% end %>
-
#
-
# is then equivalent to something like:
-
#
-
# <%= form_for @post, as: :post, url: post_path(@post), method: :patch, html: { class: "edit_post", id: "edit_post_45" } do |f| %>
-
# ...
-
# <% end %>
-
#
-
# And for a new record
-
#
-
# <%= form_for(Post.new) do |f| %>
-
# ...
-
# <% end %>
-
#
-
# is equivalent to something like:
-
#
-
# <%= form_for @post, as: :post, url: posts_path, html: { class: "new_post", id: "new_post" } do |f| %>
-
# ...
-
# <% end %>
-
#
-
# However you can still overwrite individual conventions, such as:
-
#
-
# <%= form_for(@post, url: super_posts_path) do |f| %>
-
# ...
-
# <% end %>
-
#
-
# You can also set the answer format, like this:
-
#
-
# <%= form_for(@post, format: :json) do |f| %>
-
# ...
-
# <% end %>
-
#
-
# For namespaced routes, like +admin_post_url+:
-
#
-
# <%= form_for([:admin, @post]) do |f| %>
-
# ...
-
# <% end %>
-
#
-
# If your resource has associations defined, for example, you want to add comments
-
# to the document given that the routes are set correctly:
-
#
-
# <%= form_for([@document, @comment]) do |f| %>
-
# ...
-
# <% end %>
-
#
-
# Where <tt>@document = Document.find(params[:id])</tt> and
-
# <tt>@comment = Comment.new</tt>.
-
#
-
# === Setting the method
-
#
-
# You can force the form to use the full array of HTTP verbs by setting
-
#
-
# method: (:get|:post|:patch|:put|:delete)
-
#
-
# in the options hash. If the verb is not GET or POST, which are natively
-
# supported by HTML forms, the form will be set to POST and a hidden input
-
# called _method will carry the intended verb for the server to interpret.
-
#
-
# === Unobtrusive JavaScript
-
#
-
# Specifying:
-
#
-
# remote: true
-
#
-
# in the options hash creates a form that will allow the unobtrusive JavaScript drivers to modify its
-
# behavior. The expected default behavior is an XMLHttpRequest in the background instead of the regular
-
# POST arrangement, but ultimately the behavior is the choice of the JavaScript driver implementor.
-
# Even though it's using JavaScript to serialize the form elements, the form submission will work just like
-
# a regular submission as viewed by the receiving side (all elements available in <tt>params</tt>).
-
#
-
# Example:
-
#
-
# <%= form_for(@post, remote: true) do |f| %>
-
# ...
-
# <% end %>
-
#
-
# The HTML generated for this would be:
-
#
-
# <form action='http://www.example.com' method='post' data-remote='true'>
-
# <div style='display:none'>
-
# <input name='_method' type='hidden' value='patch' />
-
# </div>
-
# ...
-
# </form>
-
#
-
# === Setting HTML options
-
#
-
# You can set data attributes directly by passing in a data hash, but all other HTML options must be wrapped in
-
# the HTML key. Example:
-
#
-
# <%= form_for(@post, data: { behavior: "autosave" }, html: { name: "go" }) do |f| %>
-
# ...
-
# <% end %>
-
#
-
# The HTML generated for this would be:
-
#
-
# <form action='http://www.example.com' method='post' data-behavior='autosave' name='go'>
-
# <div style='display:none'>
-
# <input name='_method' type='hidden' value='patch' />
-
# </div>
-
# ...
-
# </form>
-
#
-
# === Removing hidden model id's
-
#
-
# The form_for method automatically includes the model id as a hidden field in the form.
-
# This is used to maintain the correlation between the form data and its associated model.
-
# Some ORM systems do not use IDs on nested models so in this case you want to be able
-
# to disable the hidden id.
-
#
-
# In the following example the Post model has many Comments stored within it in a NoSQL database,
-
# thus there is no primary key for comments.
-
#
-
# Example:
-
#
-
# <%= form_for(@post) do |f| %>
-
# <%= f.fields_for(:comments, include_id: false) do |cf| %>
-
# ...
-
# <% end %>
-
# <% end %>
-
#
-
# === Customized form builders
-
#
-
# You can also build forms using a customized FormBuilder class. Subclass
-
# FormBuilder and override or define some more helpers, then use your
-
# custom builder. For example, let's say you made a helper to
-
# automatically add labels to form inputs.
-
#
-
# <%= form_for @person, url: { action: "create" }, builder: LabellingFormBuilder do |f| %>
-
# <%= f.text_field :first_name %>
-
# <%= f.text_field :last_name %>
-
# <%= f.text_area :biography %>
-
# <%= f.check_box :admin %>
-
# <%= f.submit %>
-
# <% end %>
-
#
-
# In this case, if you use this:
-
#
-
# <%= render f %>
-
#
-
# The rendered template is <tt>people/_labelling_form</tt> and the local
-
# variable referencing the form builder is called
-
# <tt>labelling_form</tt>.
-
#
-
# The custom FormBuilder class is automatically merged with the options
-
# of a nested fields_for call, unless it's explicitly set.
-
#
-
# In many cases you will want to wrap the above in another helper, so you
-
# could do something like the following:
-
#
-
# def labelled_form_for(record_or_name_or_array, *args, &block)
-
# options = args.extract_options!
-
# form_for(record_or_name_or_array, *(args << options.merge(builder: LabellingFormBuilder)), &block)
-
# end
-
#
-
# If you don't need to attach a form to a model instance, then check out
-
# FormTagHelper#form_tag.
-
#
-
# === Form to external resources
-
#
-
# When you build forms to external resources sometimes you need to set an authenticity token or just render a form
-
# without it, for example when you submit data to a payment gateway number and types of fields could be limited.
-
#
-
# To set an authenticity token you need to pass an <tt>:authenticity_token</tt> parameter
-
#
-
# <%= form_for @invoice, url: external_url, authenticity_token: 'external_token' do |f|
-
# ...
-
# <% end %>
-
#
-
# If you don't want to an authenticity token field be rendered at all just pass <tt>false</tt>:
-
#
-
# <%= form_for @invoice, url: external_url, authenticity_token: false do |f|
-
# ...
-
# <% end %>
-
2
def form_for(record, options = {}, &block)
-
9
raise ArgumentError, "Missing block" unless block_given?
-
9
html_options = options[:html] ||= {}
-
-
9
case record
-
when String, Symbol
-
5
object_name = record
-
5
object = nil
-
else
-
4
object = record.is_a?(Array) ? record.last : record
-
4
raise ArgumentError, "First argument in form cannot contain nil or be empty" unless object
-
4
object_name = options[:as] || model_name_from_record_or_class(object).param_key
-
4
apply_form_for_options!(record, object, options)
-
end
-
-
9
html_options[:data] = options.delete(:data) if options.has_key?(:data)
-
9
html_options[:remote] = options.delete(:remote) if options.has_key?(:remote)
-
9
html_options[:method] = options.delete(:method) if options.has_key?(:method)
-
9
html_options[:authenticity_token] = options.delete(:authenticity_token)
-
-
9
builder = instantiate_builder(object_name, object, options)
-
9
output = capture(builder, &block)
-
9
html_options[:multipart] ||= builder.multipart?
-
-
18
form_tag(options[:url] || {}, html_options) { output }
-
end
-
-
2
def apply_form_for_options!(record, object, options) #:nodoc:
-
4
object = convert_to_model(object)
-
-
4
as = options[:as]
-
4
namespace = options[:namespace]
-
4
action, method = object.respond_to?(:persisted?) && object.persisted? ? [:edit, :patch] : [:new, :post]
-
4
options[:html].reverse_merge!(
-
class: as ? "#{action}_#{as}" : dom_class(object, action),
-
4
id: (as ? [namespace, action, as] : [namespace, dom_id(object, action)]).compact.join("_").presence,
-
method: method
-
)
-
-
4
options[:url] ||= polymorphic_path(record, format: options.delete(:format))
-
end
-
2
private :apply_form_for_options!
-
-
# Creates a scope around a specific model object like form_for, but
-
# doesn't create the form tags themselves. This makes fields_for suitable
-
# for specifying additional model objects in the same form.
-
#
-
# Although the usage and purpose of +field_for+ is similar to +form_for+'s,
-
# its method signature is slightly different. Like +form_for+, it yields
-
# a FormBuilder object associated with a particular model object to a block,
-
# and within the block allows methods to be called on the builder to
-
# generate fields associated with the model object. Fields may reflect
-
# a model object in two ways - how they are named (hence how submitted
-
# values appear within the +params+ hash in the controller) and what
-
# default values are shown when the form the fields appear in is first
-
# displayed. In order for both of these features to be specified independently,
-
# both an object name (represented by either a symbol or string) and the
-
# object itself can be passed to the method separately -
-
#
-
# <%= form_for @person do |person_form| %>
-
# First name: <%= person_form.text_field :first_name %>
-
# Last name : <%= person_form.text_field :last_name %>
-
#
-
# <%= fields_for :permission, @person.permission do |permission_fields| %>
-
# Admin? : <%= permission_fields.check_box :admin %>
-
# <% end %>
-
#
-
# <%= f.submit %>
-
# <% end %>
-
#
-
# In this case, the checkbox field will be represented by an HTML +input+
-
# tag with the +name+ attribute <tt>permission[admin]</tt>, and the submitted
-
# value will appear in the controller as <tt>params[:permission][:admin]</tt>.
-
# If <tt>@person.permission</tt> is an existing record with an attribute
-
# +admin+, the initial state of the checkbox when first displayed will
-
# reflect the value of <tt>@person.permission.admin</tt>.
-
#
-
# Often this can be simplified by passing just the name of the model
-
# object to +fields_for+ -
-
#
-
# <%= fields_for :permission do |permission_fields| %>
-
# Admin?: <%= permission_fields.check_box :admin %>
-
# <% end %>
-
#
-
# ...in which case, if <tt>:permission</tt> also happens to be the name of an
-
# instance variable <tt>@permission</tt>, the initial state of the input
-
# field will reflect the value of that variable's attribute <tt>@permission.admin</tt>.
-
#
-
# Alternatively, you can pass just the model object itself (if the first
-
# argument isn't a string or symbol +fields_for+ will realize that the
-
# name has been omitted) -
-
#
-
# <%= fields_for @person.permission do |permission_fields| %>
-
# Admin?: <%= permission_fields.check_box :admin %>
-
# <% end %>
-
#
-
# and +fields_for+ will derive the required name of the field from the
-
# _class_ of the model object, e.g. if <tt>@person.permission</tt>, is
-
# of class +Permission+, the field will still be named <tt>permission[admin]</tt>.
-
#
-
# Note: This also works for the methods in FormOptionHelper and
-
# DateHelper that are designed to work with an object as base, like
-
# FormOptionHelper#collection_select and DateHelper#datetime_select.
-
#
-
# === Nested Attributes Examples
-
#
-
# When the object belonging to the current scope has a nested attribute
-
# writer for a certain attribute, fields_for will yield a new scope
-
# for that attribute. This allows you to create forms that set or change
-
# the attributes of a parent object and its associations in one go.
-
#
-
# Nested attribute writers are normal setter methods named after an
-
# association. The most common way of defining these writers is either
-
# with +accepts_nested_attributes_for+ in a model definition or by
-
# defining a method with the proper name. For example: the attribute
-
# writer for the association <tt>:address</tt> is called
-
# <tt>address_attributes=</tt>.
-
#
-
# Whether a one-to-one or one-to-many style form builder will be yielded
-
# depends on whether the normal reader method returns a _single_ object
-
# or an _array_ of objects.
-
#
-
# ==== One-to-one
-
#
-
# Consider a Person class which returns a _single_ Address from the
-
# <tt>address</tt> reader method and responds to the
-
# <tt>address_attributes=</tt> writer method:
-
#
-
# class Person
-
# def address
-
# @address
-
# end
-
#
-
# def address_attributes=(attributes)
-
# # Process the attributes hash
-
# end
-
# end
-
#
-
# This model can now be used with a nested fields_for, like so:
-
#
-
# <%= form_for @person do |person_form| %>
-
# ...
-
# <%= person_form.fields_for :address do |address_fields| %>
-
# Street : <%= address_fields.text_field :street %>
-
# Zip code: <%= address_fields.text_field :zip_code %>
-
# <% end %>
-
# ...
-
# <% end %>
-
#
-
# When address is already an association on a Person you can use
-
# +accepts_nested_attributes_for+ to define the writer method for you:
-
#
-
# class Person < ActiveRecord::Base
-
# has_one :address
-
# accepts_nested_attributes_for :address
-
# end
-
#
-
# If you want to destroy the associated model through the form, you have
-
# to enable it first using the <tt>:allow_destroy</tt> option for
-
# +accepts_nested_attributes_for+:
-
#
-
# class Person < ActiveRecord::Base
-
# has_one :address
-
# accepts_nested_attributes_for :address, allow_destroy: true
-
# end
-
#
-
# Now, when you use a form element with the <tt>_destroy</tt> parameter,
-
# with a value that evaluates to +true+, you will destroy the associated
-
# model (eg. 1, '1', true, or 'true'):
-
#
-
# <%= form_for @person do |person_form| %>
-
# ...
-
# <%= person_form.fields_for :address do |address_fields| %>
-
# ...
-
# Delete: <%= address_fields.check_box :_destroy %>
-
# <% end %>
-
# ...
-
# <% end %>
-
#
-
# ==== One-to-many
-
#
-
# Consider a Person class which returns an _array_ of Project instances
-
# from the <tt>projects</tt> reader method and responds to the
-
# <tt>projects_attributes=</tt> writer method:
-
#
-
# class Person
-
# def projects
-
# [@project1, @project2]
-
# end
-
#
-
# def projects_attributes=(attributes)
-
# # Process the attributes hash
-
# end
-
# end
-
#
-
# Note that the <tt>projects_attributes=</tt> writer method is in fact
-
# required for fields_for to correctly identify <tt>:projects</tt> as a
-
# collection, and the correct indices to be set in the form markup.
-
#
-
# When projects is already an association on Person you can use
-
# +accepts_nested_attributes_for+ to define the writer method for you:
-
#
-
# class Person < ActiveRecord::Base
-
# has_many :projects
-
# accepts_nested_attributes_for :projects
-
# end
-
#
-
# This model can now be used with a nested fields_for. The block given to
-
# the nested fields_for call will be repeated for each instance in the
-
# collection:
-
#
-
# <%= form_for @person do |person_form| %>
-
# ...
-
# <%= person_form.fields_for :projects do |project_fields| %>
-
# <% if project_fields.object.active? %>
-
# Name: <%= project_fields.text_field :name %>
-
# <% end %>
-
# <% end %>
-
# ...
-
# <% end %>
-
#
-
# It's also possible to specify the instance to be used:
-
#
-
# <%= form_for @person do |person_form| %>
-
# ...
-
# <% @person.projects.each do |project| %>
-
# <% if project.active? %>
-
# <%= person_form.fields_for :projects, project do |project_fields| %>
-
# Name: <%= project_fields.text_field :name %>
-
# <% end %>
-
# <% end %>
-
# <% end %>
-
# ...
-
# <% end %>
-
#
-
# Or a collection to be used:
-
#
-
# <%= form_for @person do |person_form| %>
-
# ...
-
# <%= person_form.fields_for :projects, @active_projects do |project_fields| %>
-
# Name: <%= project_fields.text_field :name %>
-
# <% end %>
-
# ...
-
# <% end %>
-
#
-
# If you want to destroy any of the associated models through the
-
# form, you have to enable it first using the <tt>:allow_destroy</tt>
-
# option for +accepts_nested_attributes_for+:
-
#
-
# class Person < ActiveRecord::Base
-
# has_many :projects
-
# accepts_nested_attributes_for :projects, allow_destroy: true
-
# end
-
#
-
# This will allow you to specify which models to destroy in the
-
# attributes hash by adding a form element for the <tt>_destroy</tt>
-
# parameter with a value that evaluates to +true+
-
# (eg. 1, '1', true, or 'true'):
-
#
-
# <%= form_for @person do |person_form| %>
-
# ...
-
# <%= person_form.fields_for :projects do |project_fields| %>
-
# Delete: <%= project_fields.check_box :_destroy %>
-
# <% end %>
-
# ...
-
# <% end %>
-
#
-
# When a collection is used you might want to know the index of each
-
# object into the array. For this purpose, the <tt>index</tt> method
-
# is available in the FormBuilder object.
-
#
-
# <%= form_for @person do |person_form| %>
-
# ...
-
# <%= person_form.fields_for :projects do |project_fields| %>
-
# Project #<%= project_fields.index %>
-
# ...
-
# <% end %>
-
# ...
-
# <% end %>
-
#
-
# Note that fields_for will automatically generate a hidden field
-
# to store the ID of the record. There are circumstances where this
-
# hidden field is not needed and you can pass <tt>include_id: false</tt>
-
# to prevent fields_for from rendering it automatically.
-
2
def fields_for(record_name, record_object = nil, options = {}, &block)
-
builder = instantiate_builder(record_name, record_object, options)
-
capture(builder, &block)
-
end
-
-
# Returns a label tag tailored for labelling an input field for a specified attribute (identified by +method+) on an object
-
# assigned to the template (identified by +object+). The text of label will default to the attribute name unless a translation
-
# is found in the current I18n locale (through helpers.label.<modelname>.<attribute>) or you specify it explicitly.
-
# Additional options on the label tag can be passed as a hash with +options+. These options will be tagged
-
# onto the HTML as an HTML element attribute as in the example shown, except for the <tt>:value</tt> option, which is designed to
-
# target labels for radio_button tags (where the value is used in the ID of the input tag).
-
#
-
# ==== Examples
-
# label(:post, :title)
-
# # => <label for="post_title">Title</label>
-
#
-
# You can localize your labels based on model and attribute names.
-
# For example you can define the following in your locale (e.g. en.yml)
-
#
-
# helpers:
-
# label:
-
# post:
-
# body: "Write your entire text here"
-
#
-
# Which then will result in
-
#
-
# label(:post, :body)
-
# # => <label for="post_body">Write your entire text here</label>
-
#
-
# Localization can also be based purely on the translation of the attribute-name
-
# (if you are using ActiveRecord):
-
#
-
# activerecord:
-
# attributes:
-
# post:
-
# cost: "Total cost"
-
#
-
# label(:post, :cost)
-
# # => <label for="post_cost">Total cost</label>
-
#
-
# label(:post, :title, "A short title")
-
# # => <label for="post_title">A short title</label>
-
#
-
# label(:post, :title, "A short title", class: "title_label")
-
# # => <label for="post_title" class="title_label">A short title</label>
-
#
-
# label(:post, :privacy, "Public Post", value: "public")
-
# # => <label for="post_privacy_public">Public Post</label>
-
#
-
# label(:post, :terms) do
-
# 'Accept <a href="/terms">Terms</a>.'.html_safe
-
# end
-
2
def label(object_name, method, content_or_options = nil, options = nil, &block)
-
10
Tags::Label.new(object_name, method, self, content_or_options, options).render(&block)
-
end
-
-
# Returns an input tag of the "text" type tailored for accessing a specified attribute (identified by +method+) on an object
-
# assigned to the template (identified by +object+). Additional options on the input tag can be passed as a
-
# hash with +options+. These options will be tagged onto the HTML as an HTML element attribute as in the example
-
# shown.
-
#
-
# ==== Examples
-
# text_field(:post, :title, size: 20)
-
# # => <input type="text" id="post_title" name="post[title]" size="20" value="#{@post.title}" />
-
#
-
# text_field(:post, :title, class: "create_input")
-
# # => <input type="text" id="post_title" name="post[title]" value="#{@post.title}" class="create_input" />
-
#
-
# text_field(:session, :user, onchange: "if ($('#session_user').val() === 'admin') { alert('Your login cannot be admin!'); }")
-
# # => <input type="text" id="session_user" name="session[user]" value="#{@session.user}" onchange="if ($('#session_user').val() === 'admin') { alert('Your login cannot be admin!'); }"/>
-
#
-
# text_field(:snippet, :code, size: 20, class: 'code_input')
-
# # => <input type="text" id="snippet_code" name="snippet[code]" size="20" value="#{@snippet.code}" class="code_input" />
-
2
def text_field(object_name, method, options = {})
-
17
Tags::TextField.new(object_name, method, self, options).render
-
end
-
-
# Returns an input tag of the "password" type tailored for accessing a specified attribute (identified by +method+) on an object
-
# assigned to the template (identified by +object+). Additional options on the input tag can be passed as a
-
# hash with +options+. These options will be tagged onto the HTML as an HTML element attribute as in the example
-
# shown. For security reasons this field is blank by default; pass in a value via +options+ if this is not desired.
-
#
-
# ==== Examples
-
# password_field(:login, :pass, size: 20)
-
# # => <input type="password" id="login_pass" name="login[pass]" size="20" />
-
#
-
# password_field(:account, :secret, class: "form_input", value: @account.secret)
-
# # => <input type="password" id="account_secret" name="account[secret]" value="#{@account.secret}" class="form_input" />
-
#
-
# password_field(:user, :password, onchange: "if ($('#user_password').val().length > 30) { alert('Your password needs to be shorter!'); }")
-
# # => <input type="password" id="user_password" name="user[password]" onchange="if ($('#user_password').val().length > 30) { alert('Your password needs to be shorter!'); }"/>
-
#
-
# password_field(:account, :pin, size: 20, class: 'form_input')
-
# # => <input type="password" id="account_pin" name="account[pin]" size="20" class="form_input" />
-
2
def password_field(object_name, method, options = {})
-
13
Tags::PasswordField.new(object_name, method, self, options).render
-
end
-
-
# Returns a hidden input tag tailored for accessing a specified attribute (identified by +method+) on an object
-
# assigned to the template (identified by +object+). Additional options on the input tag can be passed as a
-
# hash with +options+. These options will be tagged onto the HTML as an HTML element attribute as in the example
-
# shown.
-
#
-
# ==== Examples
-
# hidden_field(:signup, :pass_confirm)
-
# # => <input type="hidden" id="signup_pass_confirm" name="signup[pass_confirm]" value="#{@signup.pass_confirm}" />
-
#
-
# hidden_field(:post, :tag_list)
-
# # => <input type="hidden" id="post_tag_list" name="post[tag_list]" value="#{@post.tag_list}" />
-
#
-
# hidden_field(:user, :token)
-
# # => <input type="hidden" id="user_token" name="user[token]" value="#{@user.token}" />
-
2
def hidden_field(object_name, method, options = {})
-
Tags::HiddenField.new(object_name, method, self, options).render
-
end
-
-
# Returns a file upload input tag tailored for accessing a specified attribute (identified by +method+) on an object
-
# assigned to the template (identified by +object+). Additional options on the input tag can be passed as a
-
# hash with +options+. These options will be tagged onto the HTML as an HTML element attribute as in the example
-
# shown.
-
#
-
# Using this method inside a +form_for+ block will set the enclosing form's encoding to <tt>multipart/form-data</tt>.
-
#
-
# ==== Options
-
# * Creates standard HTML attributes for the tag.
-
# * <tt>:disabled</tt> - If set to true, the user will not be able to use this input.
-
# * <tt>:multiple</tt> - If set to true, *in most updated browsers* the user will be allowed to select multiple files.
-
# * <tt>:accept</tt> - If set to one or multiple mime-types, the user will be suggested a filter when choosing a file. You still need to set up model validations.
-
#
-
# ==== Examples
-
# file_field(:user, :avatar)
-
# # => <input type="file" id="user_avatar" name="user[avatar]" />
-
#
-
# file_field(:post, :image, :multiple => true)
-
# # => <input type="file" id="post_image" name="post[image]" multiple="true" />
-
#
-
# file_field(:post, :attached, accept: 'text/html')
-
# # => <input accept="text/html" type="file" id="post_attached" name="post[attached]" />
-
#
-
# file_field(:post, :image, accept: 'image/png,image/gif,image/jpeg')
-
# # => <input type="file" id="post_image" name="post[image]" accept="image/png,image/gif,image/jpeg" />
-
#
-
# file_field(:attachment, :file, class: 'file_input')
-
# # => <input type="file" id="attachment_file" name="attachment[file]" class="file_input" />
-
2
def file_field(object_name, method, options = {})
-
4
Tags::FileField.new(object_name, method, self, options).render
-
end
-
-
# Returns a textarea opening and closing tag set tailored for accessing a specified attribute (identified by +method+)
-
# on an object assigned to the template (identified by +object+). Additional options on the input tag can be passed as a
-
# hash with +options+.
-
#
-
# ==== Examples
-
# text_area(:post, :body, cols: 20, rows: 40)
-
# # => <textarea cols="20" rows="40" id="post_body" name="post[body]">
-
# # #{@post.body}
-
# # </textarea>
-
#
-
# text_area(:comment, :text, size: "20x30")
-
# # => <textarea cols="20" rows="30" id="comment_text" name="comment[text]">
-
# # #{@comment.text}
-
# # </textarea>
-
#
-
# text_area(:application, :notes, cols: 40, rows: 15, class: 'app_input')
-
# # => <textarea cols="40" rows="15" id="application_notes" name="application[notes]" class="app_input">
-
# # #{@application.notes}
-
# # </textarea>
-
#
-
# text_area(:entry, :body, size: "20x20", disabled: 'disabled')
-
# # => <textarea cols="20" rows="20" id="entry_body" name="entry[body]" disabled="disabled">
-
# # #{@entry.body}
-
# # </textarea>
-
2
def text_area(object_name, method, options = {})
-
Tags::TextArea.new(object_name, method, self, options).render
-
end
-
-
# Returns a checkbox tag tailored for accessing a specified attribute (identified by +method+) on an object
-
# assigned to the template (identified by +object+). This object must be an instance object (@object) and not a local object.
-
# It's intended that +method+ returns an integer and if that integer is above zero, then the checkbox is checked.
-
# Additional options on the input tag can be passed as a hash with +options+. The +checked_value+ defaults to 1
-
# while the default +unchecked_value+ is set to 0 which is convenient for boolean values.
-
#
-
# ==== Gotcha
-
#
-
# The HTML specification says unchecked check boxes are not successful, and
-
# thus web browsers do not send them. Unfortunately this introduces a gotcha:
-
# if an +Invoice+ model has a +paid+ flag, and in the form that edits a paid
-
# invoice the user unchecks its check box, no +paid+ parameter is sent. So,
-
# any mass-assignment idiom like
-
#
-
# @invoice.update(params[:invoice])
-
#
-
# wouldn't update the flag.
-
#
-
# To prevent this the helper generates an auxiliary hidden field before
-
# the very check box. The hidden field has the same name and its
-
# attributes mimic an unchecked check box.
-
#
-
# This way, the client either sends only the hidden field (representing
-
# the check box is unchecked), or both fields. Since the HTML specification
-
# says key/value pairs have to be sent in the same order they appear in the
-
# form, and parameters extraction gets the last occurrence of any repeated
-
# key in the query string, that works for ordinary forms.
-
#
-
# Unfortunately that workaround does not work when the check box goes
-
# within an array-like parameter, as in
-
#
-
# <%= fields_for "project[invoice_attributes][]", invoice, index: nil do |form| %>
-
# <%= form.check_box :paid %>
-
# ...
-
# <% end %>
-
#
-
# because parameter name repetition is precisely what Rails seeks to distinguish
-
# the elements of the array. For each item with a checked check box you
-
# get an extra ghost item with only that attribute, assigned to "0".
-
#
-
# In that case it is preferable to either use +check_box_tag+ or to use
-
# hashes instead of arrays.
-
#
-
# # Let's say that @post.validated? is 1:
-
# check_box("post", "validated")
-
# # => <input name="post[validated]" type="hidden" value="0" />
-
# # <input checked="checked" type="checkbox" id="post_validated" name="post[validated]" value="1" />
-
#
-
# # Let's say that @puppy.gooddog is "no":
-
# check_box("puppy", "gooddog", {}, "yes", "no")
-
# # => <input name="puppy[gooddog]" type="hidden" value="no" />
-
# # <input type="checkbox" id="puppy_gooddog" name="puppy[gooddog]" value="yes" />
-
#
-
# check_box("eula", "accepted", { class: 'eula_check' }, "yes", "no")
-
# # => <input name="eula[accepted]" type="hidden" value="no" />
-
# # <input type="checkbox" class="eula_check" id="eula_accepted" name="eula[accepted]" value="yes" />
-
2
def check_box(object_name, method, options = {}, checked_value = "1", unchecked_value = "0")
-
Tags::CheckBox.new(object_name, method, self, checked_value, unchecked_value, options).render
-
end
-
-
# Returns a radio button tag for accessing a specified attribute (identified by +method+) on an object
-
# assigned to the template (identified by +object+). If the current value of +method+ is +tag_value+ the
-
# radio button will be checked.
-
#
-
# To force the radio button to be checked pass <tt>checked: true</tt> in the
-
# +options+ hash. You may pass HTML options there as well.
-
#
-
# # Let's say that @post.category returns "rails":
-
# radio_button("post", "category", "rails")
-
# radio_button("post", "category", "java")
-
# # => <input type="radio" id="post_category_rails" name="post[category]" value="rails" checked="checked" />
-
# # <input type="radio" id="post_category_java" name="post[category]" value="java" />
-
#
-
# radio_button("user", "receive_newsletter", "yes")
-
# radio_button("user", "receive_newsletter", "no")
-
# # => <input type="radio" id="user_receive_newsletter_yes" name="user[receive_newsletter]" value="yes" />
-
# # <input type="radio" id="user_receive_newsletter_no" name="user[receive_newsletter]" value="no" checked="checked" />
-
2
def radio_button(object_name, method, tag_value, options = {})
-
Tags::RadioButton.new(object_name, method, self, tag_value, options).render
-
end
-
-
# Returns a text_field of type "color".
-
#
-
# color_field("car", "color")
-
# # => <input id="car_color" name="car[color]" type="color" value="#000000" />
-
2
def color_field(object_name, method, options = {})
-
Tags::ColorField.new(object_name, method, self, options).render
-
end
-
-
# Returns an input of type "search" for accessing a specified attribute (identified by +method+) on an object
-
# assigned to the template (identified by +object_name+). Inputs of type "search" may be styled differently by
-
# some browsers.
-
#
-
# search_field(:user, :name)
-
# # => <input id="user_name" name="user[name]" type="search" />
-
# search_field(:user, :name, autosave: false)
-
# # => <input autosave="false" id="user_name" name="user[name]" type="search" />
-
# search_field(:user, :name, results: 3)
-
# # => <input id="user_name" name="user[name]" results="3" type="search" />
-
# # Assume request.host returns "www.example.com"
-
# search_field(:user, :name, autosave: true)
-
# # => <input autosave="com.example.www" id="user_name" name="user[name]" results="10" type="search" />
-
# search_field(:user, :name, onsearch: true)
-
# # => <input id="user_name" incremental="true" name="user[name]" onsearch="true" type="search" />
-
# search_field(:user, :name, autosave: false, onsearch: true)
-
# # => <input autosave="false" id="user_name" incremental="true" name="user[name]" onsearch="true" type="search" />
-
# search_field(:user, :name, autosave: true, onsearch: true)
-
# # => <input autosave="com.example.www" id="user_name" incremental="true" name="user[name]" onsearch="true" results="10" type="search" />
-
2
def search_field(object_name, method, options = {})
-
Tags::SearchField.new(object_name, method, self, options).render
-
end
-
-
# Returns a text_field of type "tel".
-
#
-
# telephone_field("user", "phone")
-
# # => <input id="user_phone" name="user[phone]" type="tel" />
-
#
-
2
def telephone_field(object_name, method, options = {})
-
Tags::TelField.new(object_name, method, self, options).render
-
end
-
# aliases telephone_field
-
2
alias phone_field telephone_field
-
-
# Returns a text_field of type "date".
-
#
-
# date_field("user", "born_on")
-
# # => <input id="user_born_on" name="user[born_on]" type="date" />
-
#
-
# The default value is generated by trying to call "to_date"
-
# on the object's value, which makes it behave as expected for instances
-
# of DateTime and ActiveSupport::TimeWithZone. You can still override that
-
# by passing the "value" option explicitly, e.g.
-
#
-
# @user.born_on = Date.new(1984, 1, 27)
-
# date_field("user", "born_on", value: "1984-05-12")
-
# # => <input id="user_born_on" name="user[born_on]" type="date" value="1984-05-12" />
-
#
-
2
def date_field(object_name, method, options = {})
-
Tags::DateField.new(object_name, method, self, options).render
-
end
-
-
# Returns a text_field of type "time".
-
#
-
# The default value is generated by trying to call +strftime+ with "%T.%L"
-
# on the objects's value. It is still possible to override that
-
# by passing the "value" option.
-
#
-
# === Options
-
# * Accepts same options as time_field_tag
-
#
-
# === Example
-
# time_field("task", "started_at")
-
# # => <input id="task_started_at" name="task[started_at]" type="time" />
-
#
-
2
def time_field(object_name, method, options = {})
-
Tags::TimeField.new(object_name, method, self, options).render
-
end
-
-
# Returns a text_field of type "datetime".
-
#
-
# datetime_field("user", "born_on")
-
# # => <input id="user_born_on" name="user[born_on]" type="datetime" />
-
#
-
# The default value is generated by trying to call +strftime+ with "%Y-%m-%dT%T.%L%z"
-
# on the object's value, which makes it behave as expected for instances
-
# of DateTime and ActiveSupport::TimeWithZone.
-
#
-
# @user.born_on = Date.new(1984, 1, 12)
-
# datetime_field("user", "born_on")
-
# # => <input id="user_born_on" name="user[born_on]" type="datetime" value="1984-01-12T00:00:00.000+0000" />
-
#
-
2
def datetime_field(object_name, method, options = {})
-
Tags::DatetimeField.new(object_name, method, self, options).render
-
end
-
-
# Returns a text_field of type "datetime-local".
-
#
-
# datetime_local_field("user", "born_on")
-
# # => <input id="user_born_on" name="user[born_on]" type="datetime-local" />
-
#
-
# The default value is generated by trying to call +strftime+ with "%Y-%m-%dT%T"
-
# on the object's value, which makes it behave as expected for instances
-
# of DateTime and ActiveSupport::TimeWithZone.
-
#
-
# @user.born_on = Date.new(1984, 1, 12)
-
# datetime_local_field("user", "born_on")
-
# # => <input id="user_born_on" name="user[born_on]" type="datetime-local" value="1984-01-12T00:00:00" />
-
#
-
2
def datetime_local_field(object_name, method, options = {})
-
Tags::DatetimeLocalField.new(object_name, method, self, options).render
-
end
-
-
# Returns a text_field of type "month".
-
#
-
# month_field("user", "born_on")
-
# # => <input id="user_born_on" name="user[born_on]" type="month" />
-
#
-
# The default value is generated by trying to call +strftime+ with "%Y-%m"
-
# on the object's value, which makes it behave as expected for instances
-
# of DateTime and ActiveSupport::TimeWithZone.
-
#
-
# @user.born_on = Date.new(1984, 1, 27)
-
# month_field("user", "born_on")
-
# # => <input id="user_born_on" name="user[born_on]" type="date" value="1984-01" />
-
#
-
2
def month_field(object_name, method, options = {})
-
Tags::MonthField.new(object_name, method, self, options).render
-
end
-
-
# Returns a text_field of type "week".
-
#
-
# week_field("user", "born_on")
-
# # => <input id="user_born_on" name="user[born_on]" type="week" />
-
#
-
# The default value is generated by trying to call +strftime+ with "%Y-W%W"
-
# on the object's value, which makes it behave as expected for instances
-
# of DateTime and ActiveSupport::TimeWithZone.
-
#
-
# @user.born_on = Date.new(1984, 5, 12)
-
# week_field("user", "born_on")
-
# # => <input id="user_born_on" name="user[born_on]" type="date" value="1984-W19" />
-
#
-
2
def week_field(object_name, method, options = {})
-
Tags::WeekField.new(object_name, method, self, options).render
-
end
-
-
# Returns a text_field of type "url".
-
#
-
# url_field("user", "homepage")
-
# # => <input id="user_homepage" name="user[homepage]" type="url" />
-
#
-
2
def url_field(object_name, method, options = {})
-
Tags::UrlField.new(object_name, method, self, options).render
-
end
-
-
# Returns a text_field of type "email".
-
#
-
# email_field("user", "address")
-
# # => <input id="user_address" name="user[address]" type="email" />
-
#
-
2
def email_field(object_name, method, options = {})
-
Tags::EmailField.new(object_name, method, self, options).render
-
end
-
-
# Returns an input tag of type "number".
-
#
-
# ==== Options
-
# * Accepts same options as number_field_tag
-
2
def number_field(object_name, method, options = {})
-
Tags::NumberField.new(object_name, method, self, options).render
-
end
-
-
# Returns an input tag of type "range".
-
#
-
# ==== Options
-
# * Accepts same options as range_field_tag
-
2
def range_field(object_name, method, options = {})
-
Tags::RangeField.new(object_name, method, self, options).render
-
end
-
-
2
private
-
-
2
def instantiate_builder(record_name, record_object, options)
-
9
case record_name
-
when String, Symbol
-
9
object = record_object
-
9
object_name = record_name
-
else
-
object = record_name
-
object_name = model_name_from_record_or_class(object).param_key
-
end
-
-
9
builder = options[:builder] || default_form_builder
-
9
builder.new(object_name, object, self, options)
-
end
-
-
2
def default_form_builder
-
builder = ActionView::Base.default_form_builder
-
builder.respond_to?(:constantize) ? builder.constantize : builder
-
end
-
end
-
-
# A +FormBuilder+ object is associated with a particular model object and
-
# allows you to generate fields associated with the model object. The
-
# +FormBuilder+ object is yielded when using +form_for+ or +fields_for+.
-
# For example:
-
#
-
# <%= form_for @person do |person_form| %>
-
# Name: <%= person_form.text_field :name %>
-
# Admin: <%= person_form.check_box :admin %>
-
# <% end %>
-
#
-
# In the above block, the a +FormBuilder+ object is yielded as the
-
# +person_form+ variable. This allows you to generate the +text_field+
-
# and +check_box+ fields by specifying their eponymous methods, which
-
# modify the underlying template and associates the +@person+ model object
-
# with the form.
-
#
-
# The +FormBuilder+ object can be thought of as serving as a proxy for the
-
# methods in the +FormHelper+ module. This class, however, allows you to
-
# call methods with the model object you are building the form for.
-
#
-
# You can create your own custom FormBuilder templates by subclassing this
-
# class. For example:
-
#
-
# class MyFormBuilder < ActionView::Helpers::FormBuilder
-
# def div_radio_button(method, tag_value, options = {})
-
# @template.content_tag(:div,
-
# @template.radio_button(
-
# @object_name, method, tag_value, objectify_options(options)
-
# )
-
# )
-
# end
-
#
-
# The above code creates a new method +div_radio_button+ which wraps a div
-
# around the a new radio button. Note that when options are passed in, you
-
# must called +objectify_options+ in order for the model object to get
-
# correctly passed to the method. If +objectify_options+ is not called,
-
# then the newly created helper will not be linked back to the model.
-
#
-
# The +div_radio_button+ code from above can now be used as follows:
-
#
-
# <%= form_for @person, :builder => MyFormBuilder do |f| %>
-
# I am a child: <%= f.div_radio_button(:admin, "child") %>
-
# I am an adult: <%= f.div_radio_button(:admin, "adult") %>
-
# <% end -%>
-
#
-
# The standard set of helper methods for form building are located in the
-
# +field_helpers+ class attribute.
-
2
class FormBuilder
-
2
include ModelNaming
-
-
# The methods which wrap a form helper call.
-
2
class_attribute :field_helpers
-
2
self.field_helpers = [:fields_for, :label, :text_field, :password_field,
-
:hidden_field, :file_field, :text_area, :check_box,
-
:radio_button, :color_field, :search_field,
-
:telephone_field, :phone_field, :date_field,
-
:time_field, :datetime_field, :datetime_local_field,
-
:month_field, :week_field, :url_field, :email_field,
-
:number_field, :range_field]
-
-
2
attr_accessor :object_name, :object, :options
-
-
2
attr_reader :multipart, :index
-
2
alias :multipart? :multipart
-
-
2
def multipart=(multipart)
-
4
@multipart = multipart
-
-
4
if parent_builder = @options[:parent_builder]
-
parent_builder.multipart = multipart
-
end
-
end
-
-
2
def self._to_partial_path
-
@_to_partial_path ||= name.demodulize.underscore.sub!(/_builder$/, '')
-
end
-
-
2
def to_partial_path
-
self.class._to_partial_path
-
end
-
-
2
def to_model
-
self
-
end
-
-
2
def initialize(object_name, object, template, options)
-
9
@nested_child_index = {}
-
9
@object_name, @object, @template, @options = object_name, object, template, options
-
9
@default_options = @options ? @options.slice(:index, :namespace) : {}
-
9
if @object_name.to_s.match(/\[\]$/)
-
if object ||= @template.instance_variable_get("@#{Regexp.last_match.pre_match}") and object.respond_to?(:to_param)
-
@auto_index = object.to_param
-
else
-
raise ArgumentError, "object[] naming but object param and @object var don't exist or don't respond to to_param: #{object.inspect}"
-
end
-
end
-
9
@multipart = nil
-
9
@index = options[:index] || options[:child_index]
-
end
-
-
2
(field_helpers - [:label, :check_box, :radio_button, :fields_for, :hidden_field, :file_field]).each do |selector|
-
34
class_eval <<-RUBY_EVAL, __FILE__, __LINE__ + 1
-
def #{selector}(method, options = {}) # def text_field(method, options = {})
-
@template.send( # @template.send(
-
#{selector.inspect}, # "text_field",
-
@object_name, # @object_name,
-
method, # method,
-
objectify_options(options)) # objectify_options(options))
-
end # end
-
RUBY_EVAL
-
end
-
-
# Creates a scope around a specific model object like form_for, but
-
# doesn't create the form tags themselves. This makes fields_for suitable
-
# for specifying additional model objects in the same form.
-
#
-
# Although the usage and purpose of +field_for+ is similar to +form_for+'s,
-
# its method signature is slightly different. Like +form_for+, it yields
-
# a FormBuilder object associated with a particular model object to a block,
-
# and within the block allows methods to be called on the builder to
-
# generate fields associated with the model object. Fields may reflect
-
# a model object in two ways - how they are named (hence how submitted
-
# values appear within the +params+ hash in the controller) and what
-
# default values are shown when the form the fields appear in is first
-
# displayed. In order for both of these features to be specified independently,
-
# both an object name (represented by either a symbol or string) and the
-
# object itself can be passed to the method separately -
-
#
-
# <%= form_for @person do |person_form| %>
-
# First name: <%= person_form.text_field :first_name %>
-
# Last name : <%= person_form.text_field :last_name %>
-
#
-
# <%= fields_for :permission, @person.permission do |permission_fields| %>
-
# Admin? : <%= permission_fields.check_box :admin %>
-
# <% end %>
-
#
-
# <%= person_form.submit %>
-
# <% end %>
-
#
-
# In this case, the checkbox field will be represented by an HTML +input+
-
# tag with the +name+ attribute <tt>permission[admin]</tt>, and the submitted
-
# value will appear in the controller as <tt>params[:permission][:admin]</tt>.
-
# If <tt>@person.permission</tt> is an existing record with an attribute
-
# +admin+, the initial state of the checkbox when first displayed will
-
# reflect the value of <tt>@person.permission.admin</tt>.
-
#
-
# Often this can be simplified by passing just the name of the model
-
# object to +fields_for+ -
-
#
-
# <%= fields_for :permission do |permission_fields| %>
-
# Admin?: <%= permission_fields.check_box :admin %>
-
# <% end %>
-
#
-
# ...in which case, if <tt>:permission</tt> also happens to be the name of an
-
# instance variable <tt>@permission</tt>, the initial state of the input
-
# field will reflect the value of that variable's attribute <tt>@permission.admin</tt>.
-
#
-
# Alternatively, you can pass just the model object itself (if the first
-
# argument isn't a string or symbol +fields_for+ will realize that the
-
# name has been omitted) -
-
#
-
# <%= fields_for @person.permission do |permission_fields| %>
-
# Admin?: <%= permission_fields.check_box :admin %>
-
# <% end %>
-
#
-
# and +fields_for+ will derive the required name of the field from the
-
# _class_ of the model object, e.g. if <tt>@person.permission</tt>, is
-
# of class +Permission+, the field will still be named <tt>permission[admin]</tt>.
-
#
-
# Note: This also works for the methods in FormOptionHelper and
-
# DateHelper that are designed to work with an object as base, like
-
# FormOptionHelper#collection_select and DateHelper#datetime_select.
-
#
-
# === Nested Attributes Examples
-
#
-
# When the object belonging to the current scope has a nested attribute
-
# writer for a certain attribute, fields_for will yield a new scope
-
# for that attribute. This allows you to create forms that set or change
-
# the attributes of a parent object and its associations in one go.
-
#
-
# Nested attribute writers are normal setter methods named after an
-
# association. The most common way of defining these writers is either
-
# with +accepts_nested_attributes_for+ in a model definition or by
-
# defining a method with the proper name. For example: the attribute
-
# writer for the association <tt>:address</tt> is called
-
# <tt>address_attributes=</tt>.
-
#
-
# Whether a one-to-one or one-to-many style form builder will be yielded
-
# depends on whether the normal reader method returns a _single_ object
-
# or an _array_ of objects.
-
#
-
# ==== One-to-one
-
#
-
# Consider a Person class which returns a _single_ Address from the
-
# <tt>address</tt> reader method and responds to the
-
# <tt>address_attributes=</tt> writer method:
-
#
-
# class Person
-
# def address
-
# @address
-
# end
-
#
-
# def address_attributes=(attributes)
-
# # Process the attributes hash
-
# end
-
# end
-
#
-
# This model can now be used with a nested fields_for, like so:
-
#
-
# <%= form_for @person do |person_form| %>
-
# ...
-
# <%= person_form.fields_for :address do |address_fields| %>
-
# Street : <%= address_fields.text_field :street %>
-
# Zip code: <%= address_fields.text_field :zip_code %>
-
# <% end %>
-
# ...
-
# <% end %>
-
#
-
# When address is already an association on a Person you can use
-
# +accepts_nested_attributes_for+ to define the writer method for you:
-
#
-
# class Person < ActiveRecord::Base
-
# has_one :address
-
# accepts_nested_attributes_for :address
-
# end
-
#
-
# If you want to destroy the associated model through the form, you have
-
# to enable it first using the <tt>:allow_destroy</tt> option for
-
# +accepts_nested_attributes_for+:
-
#
-
# class Person < ActiveRecord::Base
-
# has_one :address
-
# accepts_nested_attributes_for :address, allow_destroy: true
-
# end
-
#
-
# Now, when you use a form element with the <tt>_destroy</tt> parameter,
-
# with a value that evaluates to +true+, you will destroy the associated
-
# model (eg. 1, '1', true, or 'true'):
-
#
-
# <%= form_for @person do |person_form| %>
-
# ...
-
# <%= person_form.fields_for :address do |address_fields| %>
-
# ...
-
# Delete: <%= address_fields.check_box :_destroy %>
-
# <% end %>
-
# ...
-
# <% end %>
-
#
-
# ==== One-to-many
-
#
-
# Consider a Person class which returns an _array_ of Project instances
-
# from the <tt>projects</tt> reader method and responds to the
-
# <tt>projects_attributes=</tt> writer method:
-
#
-
# class Person
-
# def projects
-
# [@project1, @project2]
-
# end
-
#
-
# def projects_attributes=(attributes)
-
# # Process the attributes hash
-
# end
-
# end
-
#
-
# Note that the <tt>projects_attributes=</tt> writer method is in fact
-
# required for fields_for to correctly identify <tt>:projects</tt> as a
-
# collection, and the correct indices to be set in the form markup.
-
#
-
# When projects is already an association on Person you can use
-
# +accepts_nested_attributes_for+ to define the writer method for you:
-
#
-
# class Person < ActiveRecord::Base
-
# has_many :projects
-
# accepts_nested_attributes_for :projects
-
# end
-
#
-
# This model can now be used with a nested fields_for. The block given to
-
# the nested fields_for call will be repeated for each instance in the
-
# collection:
-
#
-
# <%= form_for @person do |person_form| %>
-
# ...
-
# <%= person_form.fields_for :projects do |project_fields| %>
-
# <% if project_fields.object.active? %>
-
# Name: <%= project_fields.text_field :name %>
-
# <% end %>
-
# <% end %>
-
# ...
-
# <% end %>
-
#
-
# It's also possible to specify the instance to be used:
-
#
-
# <%= form_for @person do |person_form| %>
-
# ...
-
# <% @person.projects.each do |project| %>
-
# <% if project.active? %>
-
# <%= person_form.fields_for :projects, project do |project_fields| %>
-
# Name: <%= project_fields.text_field :name %>
-
# <% end %>
-
# <% end %>
-
# <% end %>
-
# ...
-
# <% end %>
-
#
-
# Or a collection to be used:
-
#
-
# <%= form_for @person do |person_form| %>
-
# ...
-
# <%= person_form.fields_for :projects, @active_projects do |project_fields| %>
-
# Name: <%= project_fields.text_field :name %>
-
# <% end %>
-
# ...
-
# <% end %>
-
#
-
# If you want to destroy any of the associated models through the
-
# form, you have to enable it first using the <tt>:allow_destroy</tt>
-
# option for +accepts_nested_attributes_for+:
-
#
-
# class Person < ActiveRecord::Base
-
# has_many :projects
-
# accepts_nested_attributes_for :projects, allow_destroy: true
-
# end
-
#
-
# This will allow you to specify which models to destroy in the
-
# attributes hash by adding a form element for the <tt>_destroy</tt>
-
# parameter with a value that evaluates to +true+
-
# (eg. 1, '1', true, or 'true'):
-
#
-
# <%= form_for @person do |person_form| %>
-
# ...
-
# <%= person_form.fields_for :projects do |project_fields| %>
-
# Delete: <%= project_fields.check_box :_destroy %>
-
# <% end %>
-
# ...
-
# <% end %>
-
#
-
# When a collection is used you might want to know the index of each
-
# object into the array. For this purpose, the <tt>index</tt> method
-
# is available in the FormBuilder object.
-
#
-
# <%= form_for @person do |person_form| %>
-
# ...
-
# <%= person_form.fields_for :projects do |project_fields| %>
-
# Project #<%= project_fields.index %>
-
# ...
-
# <% end %>
-
# ...
-
# <% end %>
-
#
-
# Note that fields_for will automatically generate a hidden field
-
# to store the ID of the record. There are circumstances where this
-
# hidden field is not needed and you can pass <tt>include_id: false</tt>
-
# to prevent fields_for from rendering it automatically.
-
2
def fields_for(record_name, record_object = nil, fields_options = {}, &block)
-
fields_options, record_object = record_object, nil if record_object.is_a?(Hash) && record_object.extractable_options?
-
fields_options[:builder] ||= options[:builder]
-
fields_options[:namespace] = options[:namespace]
-
fields_options[:parent_builder] = self
-
-
case record_name
-
when String, Symbol
-
if nested_attributes_association?(record_name)
-
return fields_for_with_nested_attributes(record_name, record_object, fields_options, block)
-
end
-
else
-
record_object = record_name.is_a?(Array) ? record_name.last : record_name
-
record_name = model_name_from_record_or_class(record_object).param_key
-
end
-
-
index = if options.has_key?(:index)
-
options[:index]
-
elsif defined?(@auto_index)
-
self.object_name = @object_name.to_s.sub(/\[\]$/,"")
-
@auto_index
-
end
-
-
record_name = index ? "#{object_name}[#{index}][#{record_name}]" : "#{object_name}[#{record_name}]"
-
fields_options[:child_index] = index
-
-
@template.fields_for(record_name, record_object, fields_options, &block)
-
end
-
-
# Returns a label tag tailored for labelling an input field for a specified attribute (identified by +method+) on an object
-
# assigned to the template (identified by +object+). The text of label will default to the attribute name unless a translation
-
# is found in the current I18n locale (through helpers.label.<modelname>.<attribute>) or you specify it explicitly.
-
# Additional options on the label tag can be passed as a hash with +options+. These options will be tagged
-
# onto the HTML as an HTML element attribute as in the example shown, except for the <tt>:value</tt> option, which is designed to
-
# target labels for radio_button tags (where the value is used in the ID of the input tag).
-
#
-
# ==== Examples
-
# label(:post, :title)
-
# # => <label for="post_title">Title</label>
-
#
-
# You can localize your labels based on model and attribute names.
-
# For example you can define the following in your locale (e.g. en.yml)
-
#
-
# helpers:
-
# label:
-
# post:
-
# body: "Write your entire text here"
-
#
-
# Which then will result in
-
#
-
# label(:post, :body)
-
# # => <label for="post_body">Write your entire text here</label>
-
#
-
# Localization can also be based purely on the translation of the attribute-name
-
# (if you are using ActiveRecord):
-
#
-
# activerecord:
-
# attributes:
-
# post:
-
# cost: "Total cost"
-
#
-
# label(:post, :cost)
-
# # => <label for="post_cost">Total cost</label>
-
#
-
# label(:post, :title, "A short title")
-
# # => <label for="post_title">A short title</label>
-
#
-
# label(:post, :title, "A short title", class: "title_label")
-
# # => <label for="post_title" class="title_label">A short title</label>
-
#
-
# label(:post, :privacy, "Public Post", value: "public")
-
# # => <label for="post_privacy_public">Public Post</label>
-
#
-
# label(:post, :terms) do
-
# 'Accept <a href="/terms">Terms</a>.'.html_safe
-
# end
-
2
def label(method, text = nil, options = {}, &block)
-
10
@template.label(@object_name, method, text, objectify_options(options), &block)
-
end
-
-
# Returns a checkbox tag tailored for accessing a specified attribute (identified by +method+) on an object
-
# assigned to the template (identified by +object+). This object must be an instance object (@object) and not a local object.
-
# It's intended that +method+ returns an integer and if that integer is above zero, then the checkbox is checked.
-
# Additional options on the input tag can be passed as a hash with +options+. The +checked_value+ defaults to 1
-
# while the default +unchecked_value+ is set to 0 which is convenient for boolean values.
-
#
-
# ==== Gotcha
-
#
-
# The HTML specification says unchecked check boxes are not successful, and
-
# thus web browsers do not send them. Unfortunately this introduces a gotcha:
-
# if an +Invoice+ model has a +paid+ flag, and in the form that edits a paid
-
# invoice the user unchecks its check box, no +paid+ parameter is sent. So,
-
# any mass-assignment idiom like
-
#
-
# @invoice.update(params[:invoice])
-
#
-
# wouldn't update the flag.
-
#
-
# To prevent this the helper generates an auxiliary hidden field before
-
# the very check box. The hidden field has the same name and its
-
# attributes mimic an unchecked check box.
-
#
-
# This way, the client either sends only the hidden field (representing
-
# the check box is unchecked), or both fields. Since the HTML specification
-
# says key/value pairs have to be sent in the same order they appear in the
-
# form, and parameters extraction gets the last occurrence of any repeated
-
# key in the query string, that works for ordinary forms.
-
#
-
# Unfortunately that workaround does not work when the check box goes
-
# within an array-like parameter, as in
-
#
-
# <%= fields_for "project[invoice_attributes][]", invoice, index: nil do |form| %>
-
# <%= form.check_box :paid %>
-
# ...
-
# <% end %>
-
#
-
# because parameter name repetition is precisely what Rails seeks to distinguish
-
# the elements of the array. For each item with a checked check box you
-
# get an extra ghost item with only that attribute, assigned to "0".
-
#
-
# In that case it is preferable to either use +check_box_tag+ or to use
-
# hashes instead of arrays.
-
#
-
# # Let's say that @post.validated? is 1:
-
# check_box("post", "validated")
-
# # => <input name="post[validated]" type="hidden" value="0" />
-
# # <input checked="checked" type="checkbox" id="post_validated" name="post[validated]" value="1" />
-
#
-
# # Let's say that @puppy.gooddog is "no":
-
# check_box("puppy", "gooddog", {}, "yes", "no")
-
# # => <input name="puppy[gooddog]" type="hidden" value="no" />
-
# # <input type="checkbox" id="puppy_gooddog" name="puppy[gooddog]" value="yes" />
-
#
-
# check_box("eula", "accepted", { class: 'eula_check' }, "yes", "no")
-
# # => <input name="eula[accepted]" type="hidden" value="no" />
-
# # <input type="checkbox" class="eula_check" id="eula_accepted" name="eula[accepted]" value="yes" />
-
2
def check_box(method, options = {}, checked_value = "1", unchecked_value = "0")
-
@template.check_box(@object_name, method, objectify_options(options), checked_value, unchecked_value)
-
end
-
-
# Returns a radio button tag for accessing a specified attribute (identified by +method+) on an object
-
# assigned to the template (identified by +object+). If the current value of +method+ is +tag_value+ the
-
# radio button will be checked.
-
#
-
# To force the radio button to be checked pass <tt>checked: true</tt> in the
-
# +options+ hash. You may pass HTML options there as well.
-
#
-
# # Let's say that @post.category returns "rails":
-
# radio_button("post", "category", "rails")
-
# radio_button("post", "category", "java")
-
# # => <input type="radio" id="post_category_rails" name="post[category]" value="rails" checked="checked" />
-
# # <input type="radio" id="post_category_java" name="post[category]" value="java" />
-
#
-
# radio_button("user", "receive_newsletter", "yes")
-
# radio_button("user", "receive_newsletter", "no")
-
# # => <input type="radio" id="user_receive_newsletter_yes" name="user[receive_newsletter]" value="yes" />
-
# # <input type="radio" id="user_receive_newsletter_no" name="user[receive_newsletter]" value="no" checked="checked" />
-
2
def radio_button(method, tag_value, options = {})
-
@template.radio_button(@object_name, method, tag_value, objectify_options(options))
-
end
-
-
# Returns a hidden input tag tailored for accessing a specified attribute (identified by +method+) on an object
-
# assigned to the template (identified by +object+). Additional options on the input tag can be passed as a
-
# hash with +options+. These options will be tagged onto the HTML as an HTML element attribute as in the example
-
# shown.
-
#
-
# ==== Examples
-
# hidden_field(:signup, :pass_confirm)
-
# # => <input type="hidden" id="signup_pass_confirm" name="signup[pass_confirm]" value="#{@signup.pass_confirm}" />
-
#
-
# hidden_field(:post, :tag_list)
-
# # => <input type="hidden" id="post_tag_list" name="post[tag_list]" value="#{@post.tag_list}" />
-
#
-
# hidden_field(:user, :token)
-
# # => <input type="hidden" id="user_token" name="user[token]" value="#{@user.token}" />
-
#
-
2
def hidden_field(method, options = {})
-
@emitted_hidden_id = true if method == :id
-
@template.hidden_field(@object_name, method, objectify_options(options))
-
end
-
-
# Returns a file upload input tag tailored for accessing a specified attribute (identified by +method+) on an object
-
# assigned to the template (identified by +object+). Additional options on the input tag can be passed as a
-
# hash with +options+. These options will be tagged onto the HTML as an HTML element attribute as in the example
-
# shown.
-
#
-
# Using this method inside a +form_for+ block will set the enclosing form's encoding to <tt>multipart/form-data</tt>.
-
#
-
# ==== Options
-
# * Creates standard HTML attributes for the tag.
-
# * <tt>:disabled</tt> - If set to true, the user will not be able to use this input.
-
# * <tt>:multiple</tt> - If set to true, *in most updated browsers* the user will be allowed to select multiple files.
-
# * <tt>:accept</tt> - If set to one or multiple mime-types, the user will be suggested a filter when choosing a file. You still need to set up model validations.
-
#
-
# ==== Examples
-
# file_field(:user, :avatar)
-
# # => <input type="file" id="user_avatar" name="user[avatar]" />
-
#
-
# file_field(:post, :image, :multiple => true)
-
# # => <input type="file" id="post_image" name="post[image]" multiple="true" />
-
#
-
# file_field(:post, :attached, accept: 'text/html')
-
# # => <input accept="text/html" type="file" id="post_attached" name="post[attached]" />
-
#
-
# file_field(:post, :image, accept: 'image/png,image/gif,image/jpeg')
-
# # => <input type="file" id="post_image" name="post[image]" accept="image/png,image/gif,image/jpeg" />
-
#
-
# file_field(:attachment, :file, class: 'file_input')
-
# # => <input type="file" id="attachment_file" name="attachment[file]" class="file_input" />
-
2
def file_field(method, options = {})
-
4
self.multipart = true
-
4
@template.file_field(@object_name, method, objectify_options(options))
-
end
-
-
# Add the submit button for the given form. When no value is given, it checks
-
# if the object is a new resource or not to create the proper label:
-
#
-
# <%= form_for @post do |f| %>
-
# <%= f.submit %>
-
# <% end %>
-
#
-
# In the example above, if @post is a new record, it will use "Create Post" as
-
# submit button label, otherwise, it uses "Update Post".
-
#
-
# Those labels can be customized using I18n, under the helpers.submit key and accept
-
# the %{model} as translation interpolation:
-
#
-
# en:
-
# helpers:
-
# submit:
-
# create: "Create a %{model}"
-
# update: "Confirm changes to %{model}"
-
#
-
# It also searches for a key specific for the given object:
-
#
-
# en:
-
# helpers:
-
# submit:
-
# post:
-
# create: "Add %{model}"
-
#
-
2
def submit(value=nil, options={})
-
9
value, options = nil, value if value.is_a?(Hash)
-
9
value ||= submit_default_value
-
9
@template.submit_tag(value, options)
-
end
-
-
# Add the submit button for the given form. When no value is given, it checks
-
# if the object is a new resource or not to create the proper label:
-
#
-
# <%= form_for @post do |f| %>
-
# <%= f.button %>
-
# <% end %>
-
#
-
# In the example above, if @post is a new record, it will use "Create Post" as
-
# button label, otherwise, it uses "Update Post".
-
#
-
# Those labels can be customized using I18n, under the helpers.submit key
-
# (the same as submit helper) and accept the %{model} as translation interpolation:
-
#
-
# en:
-
# helpers:
-
# submit:
-
# create: "Create a %{model}"
-
# update: "Confirm changes to %{model}"
-
#
-
# It also searches for a key specific for the given object:
-
#
-
# en:
-
# helpers:
-
# submit:
-
# post:
-
# create: "Add %{model}"
-
#
-
# ==== Examples
-
# button("Create a post")
-
# # => <button name='button' type='submit'>Create post</button>
-
#
-
# button do
-
# content_tag(:strong, 'Ask me!')
-
# end
-
# # => <button name='button' type='submit'>
-
# # <strong>Ask me!</strong>
-
# # </button>
-
#
-
2
def button(value = nil, options = {}, &block)
-
value, options = nil, value if value.is_a?(Hash)
-
value ||= submit_default_value
-
@template.button_tag(value, options, &block)
-
end
-
-
2
def emitted_hidden_id?
-
@emitted_hidden_id ||= nil
-
end
-
-
2
private
-
2
def objectify_options(options)
-
48
@default_options.merge(options.merge(object: @object))
-
end
-
-
2
def submit_default_value
-
object = convert_to_model(@object)
-
key = object ? (object.persisted? ? :update : :create) : :submit
-
-
model = if object.class.respond_to?(:model_name)
-
object.class.model_name.human
-
else
-
@object_name.to_s.humanize
-
end
-
-
defaults = []
-
defaults << :"helpers.submit.#{object_name}.#{key}"
-
defaults << :"helpers.submit.#{key}"
-
defaults << "#{key.to_s.humanize} #{model}"
-
-
I18n.t(defaults.shift, model: model, default: defaults)
-
end
-
-
2
def nested_attributes_association?(association_name)
-
@object.respond_to?("#{association_name}_attributes=")
-
end
-
-
2
def fields_for_with_nested_attributes(association_name, association, options, block)
-
name = "#{object_name}[#{association_name}_attributes]"
-
association = convert_to_model(association)
-
-
if association.respond_to?(:persisted?)
-
association = [association] if @object.send(association_name).respond_to?(:to_ary)
-
elsif !association.respond_to?(:to_ary)
-
association = @object.send(association_name)
-
end
-
-
if association.respond_to?(:to_ary)
-
explicit_child_index = options[:child_index]
-
output = ActiveSupport::SafeBuffer.new
-
association.each do |child|
-
options[:child_index] = nested_child_index(name) unless explicit_child_index
-
output << fields_for_nested_model("#{name}[#{options[:child_index]}]", child, options, block)
-
end
-
output
-
elsif association
-
fields_for_nested_model(name, association, options, block)
-
end
-
end
-
-
2
def fields_for_nested_model(name, object, fields_options, block)
-
object = convert_to_model(object)
-
emit_hidden_id = object.persisted? && fields_options.fetch(:include_id) {
-
options.fetch(:include_id, true)
-
}
-
-
@template.fields_for(name, object, fields_options) do |f|
-
output = @template.capture(f, &block)
-
output.concat f.hidden_field(:id) if output && emit_hidden_id && !f.emitted_hidden_id?
-
output
-
end
-
end
-
-
2
def nested_child_index(name)
-
@nested_child_index[name] ||= -1
-
@nested_child_index[name] += 1
-
end
-
end
-
end
-
-
2
ActiveSupport.on_load(:action_view) do
-
6
cattr_accessor(:default_form_builder) { ::ActionView::Helpers::FormBuilder }
-
end
-
end
-
2
require 'cgi'
-
2
require 'erb'
-
2
require 'action_view/helpers/form_helper'
-
2
require 'active_support/core_ext/string/output_safety'
-
2
require 'active_support/core_ext/array/extract_options'
-
2
require 'active_support/core_ext/array/wrap'
-
-
2
module ActionView
-
# = Action View Form Option Helpers
-
2
module Helpers
-
# Provides a number of methods for turning different kinds of containers into a set of option tags.
-
#
-
# The <tt>collection_select</tt>, <tt>select</tt> and <tt>time_zone_select</tt> methods take an <tt>options</tt> parameter, a hash:
-
#
-
# * <tt>:include_blank</tt> - set to true or a prompt string if the first option element of the select element is a blank. Useful if there is not a default value required for the select element.
-
#
-
# select("post", "category", Post::CATEGORIES, {include_blank: true})
-
#
-
# could become:
-
#
-
# <select name="post[category]">
-
# <option></option>
-
# <option>joke</option>
-
# <option>poem</option>
-
# </select>
-
#
-
# Another common case is a select tag for a <tt>belongs_to</tt>-associated object.
-
#
-
# Example with <tt>@post.person_id => 2</tt>:
-
#
-
# select("post", "person_id", Person.all.collect {|p| [ p.name, p.id ] }, {include_blank: 'None'})
-
#
-
# could become:
-
#
-
# <select name="post[person_id]">
-
# <option value="">None</option>
-
# <option value="1">David</option>
-
# <option value="2" selected="selected">Sam</option>
-
# <option value="3">Tobias</option>
-
# </select>
-
#
-
# * <tt>:prompt</tt> - set to true or a prompt string. When the select element doesn't have a value yet, this prepends an option with a generic prompt -- "Please select" -- or the given prompt string.
-
#
-
# select("post", "person_id", Person.all.collect {|p| [ p.name, p.id ] }, {prompt: 'Select Person'})
-
#
-
# could become:
-
#
-
# <select name="post[person_id]">
-
# <option value="">Select Person</option>
-
# <option value="1">David</option>
-
# <option value="2">Sam</option>
-
# <option value="3">Tobias</option>
-
# </select>
-
#
-
# * <tt>:index</tt> - like the other form helpers, +select+ can accept an <tt>:index</tt> option to manually set the ID used in the resulting output. Unlike other helpers, +select+ expects this
-
# option to be in the +html_options+ parameter.
-
#
-
# select("album[]", "genre", %w[rap rock country], {}, { index: nil })
-
#
-
# becomes:
-
#
-
# <select name="album[][genre]" id="album__genre">
-
# <option value="rap">rap</option>
-
# <option value="rock">rock</option>
-
# <option value="country">country</option>
-
# </select>
-
#
-
# * <tt>:disabled</tt> - can be a single value or an array of values that will be disabled options in the final output.
-
#
-
# select("post", "category", Post::CATEGORIES, {disabled: 'restricted'})
-
#
-
# could become:
-
#
-
# <select name="post[category]">
-
# <option></option>
-
# <option>joke</option>
-
# <option>poem</option>
-
# <option disabled="disabled">restricted</option>
-
# </select>
-
#
-
# When used with the <tt>collection_select</tt> helper, <tt>:disabled</tt> can also be a Proc that identifies those options that should be disabled.
-
#
-
# collection_select(:post, :category_id, Category.all, :id, :name, {disabled: lambda{|category| category.archived? }})
-
#
-
# If the categories "2008 stuff" and "Christmas" return true when the method <tt>archived?</tt> is called, this would return:
-
# <select name="post[category_id]">
-
# <option value="1" disabled="disabled">2008 stuff</option>
-
# <option value="2" disabled="disabled">Christmas</option>
-
# <option value="3">Jokes</option>
-
# <option value="4">Poems</option>
-
# </select>
-
#
-
2
module FormOptionsHelper
-
# ERB::Util can mask some helpers like textilize. Make sure to include them.
-
2
include TextHelper
-
-
# Create a select tag and a series of contained option tags for the provided object and method.
-
# The option currently held by the object will be selected, provided that the object is available.
-
#
-
# There are two possible formats for the +choices+ parameter, corresponding to other helpers' output:
-
#
-
# * A flat collection (see +options_for_select+).
-
#
-
# * A nested collection (see +grouped_options_for_select+).
-
#
-
# For example:
-
#
-
# select("post", "person_id", Person.all.collect {|p| [ p.name, p.id ] }, { include_blank: true })
-
#
-
# would become:
-
#
-
# <select name="post[person_id]">
-
# <option value=""></option>
-
# <option value="1" selected="selected">David</option>
-
# <option value="2">Sam</option>
-
# <option value="3">Tobias</option>
-
# </select>
-
#
-
# assuming the associated person has ID 1.
-
#
-
# This can be used to provide a default set of options in the standard way: before rendering the create form, a
-
# new model instance is assigned the default options and bound to @model_name. Usually this model is not saved
-
# to the database. Instead, a second model object is created when the create request is received.
-
# This allows the user to submit a form page more than once with the expected results of creating multiple records.
-
# In addition, this allows a single partial to be used to generate form inputs for both edit and create forms.
-
#
-
# By default, <tt>post.person_id</tt> is the selected option. Specify <tt>selected: value</tt> to use a different selection
-
# or <tt>selected: nil</tt> to leave all options unselected. Similarly, you can specify values to be disabled in the option
-
# tags by specifying the <tt>:disabled</tt> option. This can either be a single value or an array of values to be disabled.
-
#
-
# A block can be passed to +select+ to customize how the options tags will be rendered. This
-
# is useful when the options tag has complex attributes.
-
#
-
# select(report, "campaign_ids") do
-
# available_campaigns.each do |c|
-
# content_tag(:option, c.name, value: c.id, data: { tags: c.tags.to_json })
-
# end
-
# end
-
#
-
# ==== Gotcha
-
#
-
# The HTML specification says when +multiple+ parameter passed to select and all options got deselected
-
# web browsers do not send any value to server. Unfortunately this introduces a gotcha:
-
# if an +User+ model has many +roles+ and have +role_ids+ accessor, and in the form that edits roles of the user
-
# the user deselects all roles from +role_ids+ multiple select box, no +role_ids+ parameter is sent. So,
-
# any mass-assignment idiom like
-
#
-
# @user.update(params[:user])
-
#
-
# wouldn't update roles.
-
#
-
# To prevent this the helper generates an auxiliary hidden field before
-
# every multiple select. The hidden field has the same name as multiple select and blank value.
-
#
-
# <b>Note:</b> The client either sends only the hidden field (representing
-
# the deselected multiple select box), or both fields. This means that the resulting array
-
# always contains a blank string.
-
#
-
# In case if you don't want the helper to generate this hidden field you can specify
-
# <tt>include_hidden: false</tt> option.
-
#
-
2
def select(object, method, choices = nil, options = {}, html_options = {}, &block)
-
4
Tags::Select.new(object, method, self, choices, options, html_options, &block).render
-
end
-
-
# Returns <tt><select></tt> and <tt><option></tt> tags for the collection of existing return values of
-
# +method+ for +object+'s class. The value returned from calling +method+ on the instance +object+ will
-
# be selected. If calling +method+ returns +nil+, no selection is made without including <tt>:prompt</tt>
-
# or <tt>:include_blank</tt> in the +options+ hash.
-
#
-
# The <tt>:value_method</tt> and <tt>:text_method</tt> parameters are methods to be called on each member
-
# of +collection+. The return values are used as the +value+ attribute and contents of each
-
# <tt><option></tt> tag, respectively. They can also be any object that responds to +call+, such
-
# as a +proc+, that will be called for each member of the +collection+ to
-
# retrieve the value/text.
-
#
-
# Example object structure for use with this method:
-
#
-
# class Post < ActiveRecord::Base
-
# belongs_to :author
-
# end
-
#
-
# class Author < ActiveRecord::Base
-
# has_many :posts
-
# def name_with_initial
-
# "#{first_name.first}. #{last_name}"
-
# end
-
# end
-
#
-
# Sample usage (selecting the associated Author for an instance of Post, <tt>@post</tt>):
-
#
-
# collection_select(:post, :author_id, Author.all, :id, :name_with_initial, prompt: true)
-
#
-
# If <tt>@post.author_id</tt> is already <tt>1</tt>, this would return:
-
# <select name="post[author_id]">
-
# <option value="">Please select</option>
-
# <option value="1" selected="selected">D. Heinemeier Hansson</option>
-
# <option value="2">D. Thomas</option>
-
# <option value="3">M. Clark</option>
-
# </select>
-
2
def collection_select(object, method, collection, value_method, text_method, options = {}, html_options = {})
-
Tags::CollectionSelect.new(object, method, self, collection, value_method, text_method, options, html_options).render
-
end
-
-
# Returns <tt><select></tt>, <tt><optgroup></tt> and <tt><option></tt> tags for the collection of existing return values of
-
# +method+ for +object+'s class. The value returned from calling +method+ on the instance +object+ will
-
# be selected. If calling +method+ returns +nil+, no selection is made without including <tt>:prompt</tt>
-
# or <tt>:include_blank</tt> in the +options+ hash.
-
#
-
# Parameters:
-
# * +object+ - The instance of the class to be used for the select tag
-
# * +method+ - The attribute of +object+ corresponding to the select tag
-
# * +collection+ - An array of objects representing the <tt><optgroup></tt> tags.
-
# * +group_method+ - The name of a method which, when called on a member of +collection+, returns an
-
# array of child objects representing the <tt><option></tt> tags.
-
# * +group_label_method+ - The name of a method which, when called on a member of +collection+, returns a
-
# string to be used as the +label+ attribute for its <tt><optgroup></tt> tag.
-
# * +option_key_method+ - The name of a method which, when called on a child object of a member of
-
# +collection+, returns a value to be used as the +value+ attribute for its <tt><option></tt> tag.
-
# * +option_value_method+ - The name of a method which, when called on a child object of a member of
-
# +collection+, returns a value to be used as the contents of its <tt><option></tt> tag.
-
#
-
# Example object structure for use with this method:
-
#
-
# class Continent < ActiveRecord::Base
-
# has_many :countries
-
# # attribs: id, name
-
# end
-
#
-
# class Country < ActiveRecord::Base
-
# belongs_to :continent
-
# # attribs: id, name, continent_id
-
# end
-
#
-
# class City < ActiveRecord::Base
-
# belongs_to :country
-
# # attribs: id, name, country_id
-
# end
-
#
-
# Sample usage:
-
#
-
# grouped_collection_select(:city, :country_id, @continents, :countries, :name, :id, :name)
-
#
-
# Possible output:
-
#
-
# <select name="city[country_id]">
-
# <optgroup label="Africa">
-
# <option value="1">South Africa</option>
-
# <option value="3">Somalia</option>
-
# </optgroup>
-
# <optgroup label="Europe">
-
# <option value="7" selected="selected">Denmark</option>
-
# <option value="2">Ireland</option>
-
# </optgroup>
-
# </select>
-
#
-
2
def grouped_collection_select(object, method, collection, group_method, group_label_method, option_key_method, option_value_method, options = {}, html_options = {})
-
Tags::GroupedCollectionSelect.new(object, method, self, collection, group_method, group_label_method, option_key_method, option_value_method, options, html_options).render
-
end
-
-
# Returns select and option tags for the given object and method, using
-
# #time_zone_options_for_select to generate the list of option tags.
-
#
-
# In addition to the <tt>:include_blank</tt> option documented above,
-
# this method also supports a <tt>:model</tt> option, which defaults
-
# to ActiveSupport::TimeZone. This may be used by users to specify a
-
# different time zone model object. (See +time_zone_options_for_select+
-
# for more information.)
-
#
-
# You can also supply an array of ActiveSupport::TimeZone objects
-
# as +priority_zones+, so that they will be listed above the rest of the
-
# (long) list. (You can use ActiveSupport::TimeZone.us_zones as a convenience
-
# for obtaining a list of the US time zones, or a Regexp to select the zones
-
# of your choice)
-
#
-
# Finally, this method supports a <tt>:default</tt> option, which selects
-
# a default ActiveSupport::TimeZone if the object's time zone is +nil+.
-
#
-
# time_zone_select( "user", "time_zone", nil, include_blank: true)
-
#
-
# time_zone_select( "user", "time_zone", nil, default: "Pacific Time (US & Canada)" )
-
#
-
# time_zone_select( "user", 'time_zone', ActiveSupport::TimeZone.us_zones, default: "Pacific Time (US & Canada)")
-
#
-
# time_zone_select( "user", 'time_zone', [ ActiveSupport::TimeZone['Alaska'], ActiveSupport::TimeZone['Hawaii'] ])
-
#
-
# time_zone_select( "user", 'time_zone', /Australia/)
-
#
-
# time_zone_select( "user", "time_zone", ActiveSupport::TimeZone.all.sort, model: ActiveSupport::TimeZone)
-
2
def time_zone_select(object, method, priority_zones = nil, options = {}, html_options = {})
-
Tags::TimeZoneSelect.new(object, method, self, priority_zones, options, html_options).render
-
end
-
-
# Accepts a container (hash, array, enumerable, your type) and returns a string of option tags. Given a container
-
# where the elements respond to first and last (such as a two-element array), the "lasts" serve as option values and
-
# the "firsts" as option text. Hashes are turned into this form automatically, so the keys become "firsts" and values
-
# become lasts. If +selected+ is specified, the matching "last" or element will get the selected option-tag. +selected+
-
# may also be an array of values to be selected when using a multiple select.
-
#
-
# options_for_select([["Dollar", "$"], ["Kroner", "DKK"]])
-
# # => <option value="$">Dollar</option>
-
# # => <option value="DKK">Kroner</option>
-
#
-
# options_for_select([ "VISA", "MasterCard" ], "MasterCard")
-
# # => <option>VISA</option>
-
# # => <option selected="selected">MasterCard</option>
-
#
-
# options_for_select({ "Basic" => "$20", "Plus" => "$40" }, "$40")
-
# # => <option value="$20">Basic</option>
-
# # => <option value="$40" selected="selected">Plus</option>
-
#
-
# options_for_select([ "VISA", "MasterCard", "Discover" ], ["VISA", "Discover"])
-
# # => <option selected="selected">VISA</option>
-
# # => <option>MasterCard</option>
-
# # => <option selected="selected">Discover</option>
-
#
-
# You can optionally provide html attributes as the last element of the array.
-
#
-
# options_for_select([ "Denmark", ["USA", {class: 'bold'}], "Sweden" ], ["USA", "Sweden"])
-
# # => <option value="Denmark">Denmark</option>
-
# # => <option value="USA" class="bold" selected="selected">USA</option>
-
# # => <option value="Sweden" selected="selected">Sweden</option>
-
#
-
# options_for_select([["Dollar", "$", {class: "bold"}], ["Kroner", "DKK", {onclick: "alert('HI');"}]])
-
# # => <option value="$" class="bold">Dollar</option>
-
# # => <option value="DKK" onclick="alert('HI');">Kroner</option>
-
#
-
# If you wish to specify disabled option tags, set +selected+ to be a hash, with <tt>:disabled</tt> being either a value
-
# or array of values to be disabled. In this case, you can use <tt>:selected</tt> to specify selected option tags.
-
#
-
# options_for_select(["Free", "Basic", "Advanced", "Super Platinum"], disabled: "Super Platinum")
-
# # => <option value="Free">Free</option>
-
# # => <option value="Basic">Basic</option>
-
# # => <option value="Advanced">Advanced</option>
-
# # => <option value="Super Platinum" disabled="disabled">Super Platinum</option>
-
#
-
# options_for_select(["Free", "Basic", "Advanced", "Super Platinum"], disabled: ["Advanced", "Super Platinum"])
-
# # => <option value="Free">Free</option>
-
# # => <option value="Basic">Basic</option>
-
# # => <option value="Advanced" disabled="disabled">Advanced</option>
-
# # => <option value="Super Platinum" disabled="disabled">Super Platinum</option>
-
#
-
# options_for_select(["Free", "Basic", "Advanced", "Super Platinum"], selected: "Free", disabled: "Super Platinum")
-
# # => <option value="Free" selected="selected">Free</option>
-
# # => <option value="Basic">Basic</option>
-
# # => <option value="Advanced">Advanced</option>
-
# # => <option value="Super Platinum" disabled="disabled">Super Platinum</option>
-
#
-
# NOTE: Only the option tags are returned, you have to wrap this call in a regular HTML select tag.
-
2
def options_for_select(container, selected = nil)
-
8
return container if String === container
-
-
4
selected, disabled = extract_selected_and_disabled(selected).map do |r|
-
8
Array(r).map { |item| item.to_s }
-
end
-
-
container.map do |element|
-
8
html_attributes = option_html_attributes(element)
-
24
text, value = option_text_and_value(element).map { |item| item.to_s }
-
-
8
html_attributes[:selected] ||= option_value_selected?(value, selected)
-
8
html_attributes[:disabled] ||= disabled && option_value_selected?(value, disabled)
-
8
html_attributes[:value] = value
-
-
8
content_tag_string(:option, text, html_attributes)
-
4
end.join("\n").html_safe
-
end
-
-
# Returns a string of option tags that have been compiled by iterating over the +collection+ and assigning
-
# the result of a call to the +value_method+ as the option value and the +text_method+ as the option text.
-
#
-
# options_from_collection_for_select(@people, 'id', 'name')
-
# # => <option value="#{person.id}">#{person.name}</option>
-
#
-
# This is more often than not used inside a #select_tag like this example:
-
#
-
# select_tag 'person', options_from_collection_for_select(@people, 'id', 'name')
-
#
-
# If +selected+ is specified as a value or array of values, the element(s) returning a match on +value_method+
-
# will be selected option tag(s).
-
#
-
# If +selected+ is specified as a Proc, those members of the collection that return true for the anonymous
-
# function are the selected values.
-
#
-
# +selected+ can also be a hash, specifying both <tt>:selected</tt> and/or <tt>:disabled</tt> values as required.
-
#
-
# Be sure to specify the same class as the +value_method+ when specifying selected or disabled options.
-
# Failure to do this will produce undesired results. Example:
-
# options_from_collection_for_select(@people, 'id', 'name', '1')
-
# Will not select a person with the id of 1 because 1 (an Integer) is not the same as '1' (a string)
-
# options_from_collection_for_select(@people, 'id', 'name', 1)
-
# should produce the desired results.
-
2
def options_from_collection_for_select(collection, value_method, text_method, selected = nil)
-
options = collection.map do |element|
-
[value_for_collection(element, text_method), value_for_collection(element, value_method), option_html_attributes(element)]
-
end
-
selected, disabled = extract_selected_and_disabled(selected)
-
select_deselect = {
-
selected: extract_values_from_collection(collection, value_method, selected),
-
disabled: extract_values_from_collection(collection, value_method, disabled)
-
}
-
-
options_for_select(options, select_deselect)
-
end
-
-
# Returns a string of <tt><option></tt> tags, like <tt>options_from_collection_for_select</tt>, but
-
# groups them by <tt><optgroup></tt> tags based on the object relationships of the arguments.
-
#
-
# Parameters:
-
# * +collection+ - An array of objects representing the <tt><optgroup></tt> tags.
-
# * +group_method+ - The name of a method which, when called on a member of +collection+, returns an
-
# array of child objects representing the <tt><option></tt> tags.
-
# * group_label_method+ - The name of a method which, when called on a member of +collection+, returns a
-
# string to be used as the +label+ attribute for its <tt><optgroup></tt> tag.
-
# * +option_key_method+ - The name of a method which, when called on a child object of a member of
-
# +collection+, returns a value to be used as the +value+ attribute for its <tt><option></tt> tag.
-
# * +option_value_method+ - The name of a method which, when called on a child object of a member of
-
# +collection+, returns a value to be used as the contents of its <tt><option></tt> tag.
-
# * +selected_key+ - A value equal to the +value+ attribute for one of the <tt><option></tt> tags,
-
# which will have the +selected+ attribute set. Corresponds to the return value of one of the calls
-
# to +option_key_method+. If +nil+, no selection is made. Can also be a hash if disabled values are
-
# to be specified.
-
#
-
# Example object structure for use with this method:
-
#
-
# class Continent < ActiveRecord::Base
-
# has_many :countries
-
# # attribs: id, name
-
# end
-
#
-
# class Country < ActiveRecord::Base
-
# belongs_to :continent
-
# # attribs: id, name, continent_id
-
# end
-
#
-
# Sample usage:
-
# option_groups_from_collection_for_select(@continents, :countries, :name, :id, :name, 3)
-
#
-
# Possible output:
-
# <optgroup label="Africa">
-
# <option value="1">Egypt</option>
-
# <option value="4">Rwanda</option>
-
# ...
-
# </optgroup>
-
# <optgroup label="Asia">
-
# <option value="3" selected="selected">China</option>
-
# <option value="12">India</option>
-
# <option value="5">Japan</option>
-
# ...
-
# </optgroup>
-
#
-
# <b>Note:</b> Only the <tt><optgroup></tt> and <tt><option></tt> tags are returned, so you still have to
-
# wrap the output in an appropriate <tt><select></tt> tag.
-
2
def option_groups_from_collection_for_select(collection, group_method, group_label_method, option_key_method, option_value_method, selected_key = nil)
-
collection.map do |group|
-
option_tags = options_from_collection_for_select(
-
group.send(group_method), option_key_method, option_value_method, selected_key)
-
-
content_tag(:optgroup, option_tags, label: group.send(group_label_method))
-
end.join.html_safe
-
end
-
-
# Returns a string of <tt><option></tt> tags, like <tt>options_for_select</tt>, but
-
# wraps them with <tt><optgroup></tt> tags:
-
#
-
# grouped_options = [
-
# ['North America',
-
# [['United States','US'],'Canada']],
-
# ['Europe',
-
# ['Denmark','Germany','France']]
-
# ]
-
# grouped_options_for_select(grouped_options)
-
#
-
# grouped_options = {
-
# 'North America' => [['United States','US'], 'Canada'],
-
# 'Europe' => ['Denmark','Germany','France']
-
# }
-
# grouped_options_for_select(grouped_options)
-
#
-
# Possible output:
-
# <optgroup label="North America">
-
# <option value="US">United States</option>
-
# <option value="Canada">Canada</option>
-
# </optgroup>
-
# <optgroup label="Europe">
-
# <option value="Denmark">Denmark</option>
-
# <option value="Germany">Germany</option>
-
# <option value="France">France</option>
-
# </optgroup>
-
#
-
# Parameters:
-
# * +grouped_options+ - Accepts a nested array or hash of strings. The first value serves as the
-
# <tt><optgroup></tt> label while the second value must be an array of options. The second value can be a
-
# nested array of text-value pairs. See <tt>options_for_select</tt> for more info.
-
# Ex. ["North America",[["United States","US"],["Canada","CA"]]]
-
# * +selected_key+ - A value equal to the +value+ attribute for one of the <tt><option></tt> tags,
-
# which will have the +selected+ attribute set. Note: It is possible for this value to match multiple options
-
# as you might have the same option in multiple groups. Each will then get <tt>selected="selected"</tt>.
-
#
-
# Options:
-
# * <tt>:prompt</tt> - set to true or a prompt string. When the select element doesn't have a value yet, this
-
# prepends an option with a generic prompt - "Please select" - or the given prompt string.
-
# * <tt>:divider</tt> - the divider for the options groups.
-
#
-
# grouped_options = [
-
# [['United States','US'], 'Canada'],
-
# ['Denmark','Germany','France']
-
# ]
-
# grouped_options_for_select(grouped_options, nil, divider: '---------')
-
#
-
# Possible output:
-
# <optgroup label="---------">
-
# <option value="US">United States</option>
-
# <option value="Canada">Canada</option>
-
# </optgroup>
-
# <optgroup label="---------">
-
# <option value="Denmark">Denmark</option>
-
# <option value="Germany">Germany</option>
-
# <option value="France">France</option>
-
# </optgroup>
-
#
-
# <b>Note:</b> Only the <tt><optgroup></tt> and <tt><option></tt> tags are returned, so you still have to
-
# wrap the output in an appropriate <tt><select></tt> tag.
-
2
def grouped_options_for_select(grouped_options, selected_key = nil, options = {})
-
prompt = options[:prompt]
-
divider = options[:divider]
-
-
body = "".html_safe
-
-
if prompt
-
body.safe_concat content_tag(:option, prompt_text(prompt), value: "")
-
end
-
-
grouped_options.each do |container|
-
html_attributes = option_html_attributes(container)
-
-
if divider
-
label = divider
-
else
-
label, container = container
-
end
-
-
html_attributes = { label: label }.merge!(html_attributes)
-
body.safe_concat content_tag(:optgroup, options_for_select(container, selected_key), html_attributes)
-
end
-
-
body
-
end
-
-
# Returns a string of option tags for pretty much any time zone in the
-
# world. Supply a ActiveSupport::TimeZone name as +selected+ to have it
-
# marked as the selected option tag. You can also supply an array of
-
# ActiveSupport::TimeZone objects as +priority_zones+, so that they will
-
# be listed above the rest of the (long) list. (You can use
-
# ActiveSupport::TimeZone.us_zones as a convenience for obtaining a list
-
# of the US time zones, or a Regexp to select the zones of your choice)
-
#
-
# The +selected+ parameter must be either +nil+, or a string that names
-
# a ActiveSupport::TimeZone.
-
#
-
# By default, +model+ is the ActiveSupport::TimeZone constant (which can
-
# be obtained in Active Record as a value object). The only requirement
-
# is that the +model+ parameter be an object that responds to +all+, and
-
# returns an array of objects that represent time zones.
-
#
-
# NOTE: Only the option tags are returned, you have to wrap this call in
-
# a regular HTML select tag.
-
2
def time_zone_options_for_select(selected = nil, priority_zones = nil, model = ::ActiveSupport::TimeZone)
-
zone_options = "".html_safe
-
-
zones = model.all
-
convert_zones = lambda { |list| list.map { |z| [ z.to_s, z.name ] } }
-
-
if priority_zones
-
if priority_zones.is_a?(Regexp)
-
priority_zones = zones.select { |z| z =~ priority_zones }
-
end
-
-
zone_options.safe_concat options_for_select(convert_zones[priority_zones], selected)
-
zone_options.safe_concat content_tag(:option, '-------------', value: '', disabled: true)
-
zone_options.safe_concat "\n"
-
-
zones = zones - priority_zones
-
end
-
-
zone_options.safe_concat options_for_select(convert_zones[zones], selected)
-
end
-
-
# Returns radio button tags for the collection of existing return values
-
# of +method+ for +object+'s class. The value returned from calling
-
# +method+ on the instance +object+ will be selected. If calling +method+
-
# returns +nil+, no selection is made.
-
#
-
# The <tt>:value_method</tt> and <tt>:text_method</tt> parameters are
-
# methods to be called on each member of +collection+. The return values
-
# are used as the +value+ attribute and contents of each radio button tag,
-
# respectively. They can also be any object that responds to +call+, such
-
# as a +proc+, that will be called for each member of the +collection+ to
-
# retrieve the value/text.
-
#
-
# Example object structure for use with this method:
-
# class Post < ActiveRecord::Base
-
# belongs_to :author
-
# end
-
# class Author < ActiveRecord::Base
-
# has_many :posts
-
# def name_with_initial
-
# "#{first_name.first}. #{last_name}"
-
# end
-
# end
-
#
-
# Sample usage (selecting the associated Author for an instance of Post, <tt>@post</tt>):
-
# collection_radio_buttons(:post, :author_id, Author.all, :id, :name_with_initial)
-
#
-
# If <tt>@post.author_id</tt> is already <tt>1</tt>, this would return:
-
# <input id="post_author_id_1" name="post[author_id]" type="radio" value="1" checked="checked" />
-
# <label for="post_author_id_1">D. Heinemeier Hansson</label>
-
# <input id="post_author_id_2" name="post[author_id]" type="radio" value="2" />
-
# <label for="post_author_id_2">D. Thomas</label>
-
# <input id="post_author_id_3" name="post[author_id]" type="radio" value="3" />
-
# <label for="post_author_id_3">M. Clark</label>
-
#
-
# It is also possible to customize the way the elements will be shown by
-
# giving a block to the method:
-
# collection_radio_buttons(:post, :author_id, Author.all, :id, :name_with_initial) do |b|
-
# b.label { b.radio_button }
-
# end
-
#
-
# The argument passed to the block is a special kind of builder for this
-
# collection, which has the ability to generate the label and radio button
-
# for the current item in the collection, with proper text and value.
-
# Using it, you can change the label and radio button display order or
-
# even use the label as wrapper, as in the example above.
-
#
-
# The builder methods <tt>label</tt> and <tt>radio_button</tt> also accept
-
# extra html options:
-
# collection_radio_buttons(:post, :author_id, Author.all, :id, :name_with_initial) do |b|
-
# b.label(class: "radio_button") { b.radio_button(class: "radio_button") }
-
# end
-
#
-
# There are also three special methods available: <tt>object</tt>, <tt>text</tt> and
-
# <tt>value</tt>, which are the current item being rendered, its text and value methods,
-
# respectively. You can use them like this:
-
# collection_radio_buttons(:post, :author_id, Author.all, :id, :name_with_initial) do |b|
-
# b.label(:"data-value" => b.value) { b.radio_button + b.text }
-
# end
-
2
def collection_radio_buttons(object, method, collection, value_method, text_method, options = {}, html_options = {}, &block)
-
Tags::CollectionRadioButtons.new(object, method, self, collection, value_method, text_method, options, html_options).render(&block)
-
end
-
-
# Returns check box tags for the collection of existing return values of
-
# +method+ for +object+'s class. The value returned from calling +method+
-
# on the instance +object+ will be selected. If calling +method+ returns
-
# +nil+, no selection is made.
-
#
-
# The <tt>:value_method</tt> and <tt>:text_method</tt> parameters are
-
# methods to be called on each member of +collection+. The return values
-
# are used as the +value+ attribute and contents of each check box tag,
-
# respectively. They can also be any object that responds to +call+, such
-
# as a +proc+, that will be called for each member of the +collection+ to
-
# retrieve the value/text.
-
#
-
# Example object structure for use with this method:
-
# class Post < ActiveRecord::Base
-
# has_and_belongs_to_many :authors
-
# end
-
# class Author < ActiveRecord::Base
-
# has_and_belongs_to_many :posts
-
# def name_with_initial
-
# "#{first_name.first}. #{last_name}"
-
# end
-
# end
-
#
-
# Sample usage (selecting the associated Author for an instance of Post, <tt>@post</tt>):
-
# collection_check_boxes(:post, :author_ids, Author.all, :id, :name_with_initial)
-
#
-
# If <tt>@post.author_ids</tt> is already <tt>[1]</tt>, this would return:
-
# <input id="post_author_ids_1" name="post[author_ids][]" type="checkbox" value="1" checked="checked" />
-
# <label for="post_author_ids_1">D. Heinemeier Hansson</label>
-
# <input id="post_author_ids_2" name="post[author_ids][]" type="checkbox" value="2" />
-
# <label for="post_author_ids_2">D. Thomas</label>
-
# <input id="post_author_ids_3" name="post[author_ids][]" type="checkbox" value="3" />
-
# <label for="post_author_ids_3">M. Clark</label>
-
# <input name="post[author_ids][]" type="hidden" value="" />
-
#
-
# It is also possible to customize the way the elements will be shown by
-
# giving a block to the method:
-
# collection_check_boxes(:post, :author_ids, Author.all, :id, :name_with_initial) do |b|
-
# b.label { b.check_box }
-
# end
-
#
-
# The argument passed to the block is a special kind of builder for this
-
# collection, which has the ability to generate the label and check box
-
# for the current item in the collection, with proper text and value.
-
# Using it, you can change the label and check box display order or even
-
# use the label as wrapper, as in the example above.
-
#
-
# The builder methods <tt>label</tt> and <tt>check_box</tt> also accept
-
# extra html options:
-
# collection_check_boxes(:post, :author_ids, Author.all, :id, :name_with_initial) do |b|
-
# b.label(class: "check_box") { b.check_box(class: "check_box") }
-
# end
-
#
-
# There are also three special methods available: <tt>object</tt>, <tt>text</tt> and
-
# <tt>value</tt>, which are the current item being rendered, its text and value methods,
-
# respectively. You can use them like this:
-
# collection_check_boxes(:post, :author_ids, Author.all, :id, :name_with_initial) do |b|
-
# b.label(:"data-value" => b.value) { b.check_box + b.text }
-
# end
-
2
def collection_check_boxes(object, method, collection, value_method, text_method, options = {}, html_options = {}, &block)
-
Tags::CollectionCheckBoxes.new(object, method, self, collection, value_method, text_method, options, html_options).render(&block)
-
end
-
-
2
private
-
2
def option_html_attributes(element)
-
8
if Array === element
-
24
element.select { |e| Hash === e }.reduce({}, :merge!)
-
else
-
{}
-
end
-
end
-
-
2
def option_text_and_value(option)
-
# Options are [text, value] pairs or strings used for both.
-
8
if !option.is_a?(String) && option.respond_to?(:first) && option.respond_to?(:last)
-
24
option = option.reject { |e| Hash === e } if Array === option
-
8
[option.first, option.last]
-
else
-
[option, option]
-
end
-
end
-
-
2
def option_value_selected?(value, selected)
-
16
Array(selected).include? value
-
end
-
-
2
def extract_selected_and_disabled(selected)
-
4
if selected.is_a?(Proc)
-
[selected, nil]
-
else
-
4
selected = Array.wrap(selected)
-
4
options = selected.extract_options!.symbolize_keys
-
4
selected_items = options.fetch(:selected, selected)
-
4
[selected_items, options[:disabled]]
-
end
-
end
-
-
2
def extract_values_from_collection(collection, value_method, selected)
-
if selected.is_a?(Proc)
-
collection.map do |element|
-
element.send(value_method) if selected.call(element)
-
end.compact
-
else
-
selected
-
end
-
end
-
-
2
def value_for_collection(item, value)
-
value.respond_to?(:call) ? value.call(item) : item.send(value)
-
end
-
-
2
def prompt_text(prompt)
-
prompt.kind_of?(String) ? prompt : I18n.translate('helpers.select.prompt', default: 'Please select')
-
end
-
end
-
-
2
class FormBuilder
-
# Wraps ActionView::Helpers::FormOptionsHelper#select for form builders:
-
#
-
# <%= form_for @post do |f| %>
-
# <%= f.select :person_id, Person.all.collect { |p| [ p.name, p.id ] }, include_blank: true %>
-
# <%= f.submit %>
-
# <% end %>
-
#
-
# Please refer to the documentation of the base helper for details.
-
2
def select(method, choices = nil, options = {}, html_options = {}, &block)
-
4
@template.select(@object_name, method, choices, objectify_options(options), @default_options.merge(html_options), &block)
-
end
-
-
# Wraps ActionView::Helpers::FormOptionsHelper#collection_select for form builders:
-
#
-
# <%= form_for @post do |f| %>
-
# <%= f.collection_select :person_id, Author.all, :id, :name_with_initial, prompt: true %>
-
# <%= f.submit %>
-
# <% end %>
-
#
-
# Please refer to the documentation of the base helper for details.
-
2
def collection_select(method, collection, value_method, text_method, options = {}, html_options = {})
-
@template.collection_select(@object_name, method, collection, value_method, text_method, objectify_options(options), @default_options.merge(html_options))
-
end
-
-
# Wraps ActionView::Helpers::FormOptionsHelper#grouped_collection_select for form builders:
-
#
-
# <%= form_for @city do |f| %>
-
# <%= f.grouped_collection_select :country_id, @continents, :countries, :name, :id, :name %>
-
# <%= f.submit %>
-
# <% end %>
-
#
-
# Please refer to the documentation of the base helper for details.
-
2
def grouped_collection_select(method, collection, group_method, group_label_method, option_key_method, option_value_method, options = {}, html_options = {})
-
@template.grouped_collection_select(@object_name, method, collection, group_method, group_label_method, option_key_method, option_value_method, objectify_options(options), @default_options.merge(html_options))
-
end
-
-
# Wraps ActionView::Helpers::FormOptionsHelper#time_zone_select for form builders:
-
#
-
# <%= form_for @user do |f| %>
-
# <%= f.time_zone_select :time_zone, nil, include_blank: true %>
-
# <%= f.submit %>
-
# <% end %>
-
#
-
# Please refer to the documentation of the base helper for details.
-
2
def time_zone_select(method, priority_zones = nil, options = {}, html_options = {})
-
@template.time_zone_select(@object_name, method, priority_zones, objectify_options(options), @default_options.merge(html_options))
-
end
-
-
# Wraps ActionView::Helpers::FormOptionsHelper#collection_check_boxes for form builders:
-
#
-
# <%= form_for @post do |f| %>
-
# <%= f.collection_check_boxes :author_ids, Author.all, :id, :name_with_initial %>
-
# <%= f.submit %>
-
# <% end %>
-
#
-
# Please refer to the documentation of the base helper for details.
-
2
def collection_check_boxes(method, collection, value_method, text_method, options = {}, html_options = {}, &block)
-
@template.collection_check_boxes(@object_name, method, collection, value_method, text_method, objectify_options(options), @default_options.merge(html_options), &block)
-
end
-
-
# Wraps ActionView::Helpers::FormOptionsHelper#collection_radio_buttons for form builders:
-
#
-
# <%= form_for @post do |f| %>
-
# <%= f.collection_radio_buttons :author_id, Author.all, :id, :name_with_initial %>
-
# <%= f.submit %>
-
# <% end %>
-
#
-
# Please refer to the documentation of the base helper for details.
-
2
def collection_radio_buttons(method, collection, value_method, text_method, options = {}, html_options = {}, &block)
-
@template.collection_radio_buttons(@object_name, method, collection, value_method, text_method, objectify_options(options), @default_options.merge(html_options), &block)
-
end
-
end
-
end
-
end
-
2
require 'cgi'
-
2
require 'action_view/helpers/tag_helper'
-
2
require 'active_support/core_ext/string/output_safety'
-
2
require 'active_support/core_ext/module/attribute_accessors'
-
-
2
module ActionView
-
# = Action View Form Tag Helpers
-
2
module Helpers
-
# Provides a number of methods for creating form tags that don't rely on an Active Record object assigned to the template like
-
# FormHelper does. Instead, you provide the names and values manually.
-
#
-
# NOTE: The HTML options <tt>disabled</tt>, <tt>readonly</tt>, and <tt>multiple</tt> can all be treated as booleans. So specifying
-
# <tt>disabled: true</tt> will give <tt>disabled="disabled"</tt>.
-
2
module FormTagHelper
-
2
extend ActiveSupport::Concern
-
-
2
include UrlHelper
-
2
include TextHelper
-
-
2
mattr_accessor :embed_authenticity_token_in_remote_forms
-
2
self.embed_authenticity_token_in_remote_forms = false
-
-
# Starts a form tag that points the action to an url configured with <tt>url_for_options</tt> just like
-
# ActionController::Base#url_for. The method for the form defaults to POST.
-
#
-
# ==== Options
-
# * <tt>:multipart</tt> - If set to true, the enctype is set to "multipart/form-data".
-
# * <tt>:method</tt> - The method to use when submitting the form, usually either "get" or "post".
-
# If "patch", "put", "delete", or another verb is used, a hidden input with name <tt>_method</tt>
-
# is added to simulate the verb over post.
-
# * <tt>:authenticity_token</tt> - Authenticity token to use in the form. Use only if you need to
-
# pass custom authenticity token string, or to not add authenticity_token field at all
-
# (by passing <tt>false</tt>). Remote forms may omit the embedded authenticity token
-
# by setting <tt>config.action_view.embed_authenticity_token_in_remote_forms = false</tt>.
-
# This is helpful when you're fragment-caching the form. Remote forms get the
-
# authenticity token from the <tt>meta</tt> tag, so embedding is unnecessary unless you
-
# support browsers without JavaScript.
-
# * <tt>:remote</tt> - If set to true, will allow the Unobtrusive JavaScript drivers to control the
-
# submit behavior. By default this behavior is an ajax submit.
-
# * <tt>:enforce_utf8</tt> - If set to false, a hidden input with name utf8 is not output.
-
# * Any other key creates standard HTML attributes for the tag.
-
#
-
# ==== Examples
-
# form_tag('/posts')
-
# # => <form action="/posts" method="post">
-
#
-
# form_tag('/posts/1', method: :put)
-
# # => <form action="/posts/1" method="post"> ... <input name="_method" type="hidden" value="put" /> ...
-
#
-
# form_tag('/upload', multipart: true)
-
# # => <form action="/upload" method="post" enctype="multipart/form-data">
-
#
-
# <%= form_tag('/posts') do -%>
-
# <div><%= submit_tag 'Save' %></div>
-
# <% end -%>
-
# # => <form action="/posts" method="post"><div><input type="submit" name="commit" value="Save" /></div></form>
-
#
-
# <%= form_tag('/posts', remote: true) %>
-
# # => <form action="/posts" method="post" data-remote="true">
-
#
-
# form_tag('http://far.away.com/form', authenticity_token: false)
-
# # form without authenticity token
-
#
-
# form_tag('http://far.away.com/form', authenticity_token: "cf50faa3fe97702ca1ae")
-
# # form with custom authenticity token
-
#
-
2
def form_tag(url_for_options = {}, options = {}, &block)
-
9
html_options = html_options_for_form(url_for_options, options)
-
9
if block_given?
-
9
form_tag_in_block(html_options, &block)
-
else
-
form_tag_html(html_options)
-
end
-
end
-
-
# Creates a dropdown selection box, or if the <tt>:multiple</tt> option is set to true, a multiple
-
# choice selection box.
-
#
-
# Helpers::FormOptions can be used to create common select boxes such as countries, time zones, or
-
# associated records. <tt>option_tags</tt> is a string containing the option tags for the select box.
-
#
-
# ==== Options
-
# * <tt>:multiple</tt> - If set to true the selection will allow multiple choices.
-
# * <tt>:disabled</tt> - If set to true, the user will not be able to use this input.
-
# * <tt>:include_blank</tt> - If set to true, an empty option will be created.
-
# * <tt>:prompt</tt> - Create a prompt option with blank value and the text asking user to select something
-
# * Any other key creates standard HTML attributes for the tag.
-
#
-
# ==== Examples
-
# select_tag "people", options_from_collection_for_select(@people, "id", "name")
-
# # <select id="people" name="people"><option value="1">David</option></select>
-
#
-
# select_tag "people", "<option>David</option>".html_safe
-
# # => <select id="people" name="people"><option>David</option></select>
-
#
-
# select_tag "count", "<option>1</option><option>2</option><option>3</option><option>4</option>".html_safe
-
# # => <select id="count" name="count"><option>1</option><option>2</option>
-
# # <option>3</option><option>4</option></select>
-
#
-
# select_tag "colors", "<option>Red</option><option>Green</option><option>Blue</option>".html_safe, multiple: true
-
# # => <select id="colors" multiple="multiple" name="colors[]"><option>Red</option>
-
# # <option>Green</option><option>Blue</option></select>
-
#
-
# select_tag "locations", "<option>Home</option><option selected='selected'>Work</option><option>Out</option>".html_safe
-
# # => <select id="locations" name="locations"><option>Home</option><option selected='selected'>Work</option>
-
# # <option>Out</option></select>
-
#
-
# select_tag "access", "<option>Read</option><option>Write</option>".html_safe, multiple: true, class: 'form_input'
-
# # => <select class="form_input" id="access" multiple="multiple" name="access[]"><option>Read</option>
-
# # <option>Write</option></select>
-
#
-
# select_tag "people", options_from_collection_for_select(@people, "id", "name"), include_blank: true
-
# # => <select id="people" name="people"><option value=""></option><option value="1">David</option></select>
-
#
-
# select_tag "people", options_from_collection_for_select(@people, "id", "name"), prompt: "Select something"
-
# # => <select id="people" name="people"><option value="">Select something</option><option value="1">David</option></select>
-
#
-
# select_tag "destination", "<option>NYC</option><option>Paris</option><option>Rome</option>".html_safe, disabled: true
-
# # => <select disabled="disabled" id="destination" name="destination"><option>NYC</option>
-
# # <option>Paris</option><option>Rome</option></select>
-
#
-
# select_tag "credit_card", options_for_select([ "VISA", "MasterCard" ], "MasterCard")
-
# # => <select id="credit_card" name="credit_card"><option>VISA</option>
-
# # <option selected="selected">MasterCard</option></select>
-
2
def select_tag(name, option_tags = nil, options = {})
-
option_tags ||= ""
-
html_name = (options[:multiple] == true && !name.to_s.ends_with?("[]")) ? "#{name}[]" : name
-
-
if options.include?(:include_blank)
-
include_blank = options.delete(:include_blank)
-
-
if include_blank == true
-
include_blank = ''
-
end
-
-
option_tags = content_tag(:option, include_blank, value: '').safe_concat(option_tags)
-
end
-
-
if prompt = options.delete(:prompt)
-
option_tags = content_tag(:option, prompt, value: '').safe_concat(option_tags)
-
end
-
-
content_tag :select, option_tags, { "name" => html_name, "id" => sanitize_to_id(name) }.update(options.stringify_keys)
-
end
-
-
# Creates a standard text field; use these text fields to input smaller chunks of text like a username
-
# or a search query.
-
#
-
# ==== Options
-
# * <tt>:disabled</tt> - If set to true, the user will not be able to use this input.
-
# * <tt>:size</tt> - The number of visible characters that will fit in the input.
-
# * <tt>:maxlength</tt> - The maximum number of characters that the browser will allow the user to enter.
-
# * <tt>:placeholder</tt> - The text contained in the field by default which is removed when the field receives focus.
-
# * Any other key creates standard HTML attributes for the tag.
-
#
-
# ==== Examples
-
# text_field_tag 'name'
-
# # => <input id="name" name="name" type="text" />
-
#
-
# text_field_tag 'query', 'Enter your search query here'
-
# # => <input id="query" name="query" type="text" value="Enter your search query here" />
-
#
-
# text_field_tag 'search', nil, placeholder: 'Enter search term...'
-
# # => <input id="search" name="search" placeholder="Enter search term..." type="text" />
-
#
-
# text_field_tag 'request', nil, class: 'special_input'
-
# # => <input class="special_input" id="request" name="request" type="text" />
-
#
-
# text_field_tag 'address', '', size: 75
-
# # => <input id="address" name="address" size="75" type="text" value="" />
-
#
-
# text_field_tag 'zip', nil, maxlength: 5
-
# # => <input id="zip" maxlength="5" name="zip" type="text" />
-
#
-
# text_field_tag 'payment_amount', '$0.00', disabled: true
-
# # => <input disabled="disabled" id="payment_amount" name="payment_amount" type="text" value="$0.00" />
-
#
-
# text_field_tag 'ip', '0.0.0.0', maxlength: 15, size: 20, class: "ip-input"
-
# # => <input class="ip-input" id="ip" maxlength="15" name="ip" size="20" type="text" value="0.0.0.0" />
-
2
def text_field_tag(name, value = nil, options = {})
-
tag :input, { "type" => "text", "name" => name, "id" => sanitize_to_id(name), "value" => value }.update(options.stringify_keys)
-
end
-
-
# Creates a label element. Accepts a block.
-
#
-
# ==== Options
-
# * Creates standard HTML attributes for the tag.
-
#
-
# ==== Examples
-
# label_tag 'name'
-
# # => <label for="name">Name</label>
-
#
-
# label_tag 'name', 'Your name'
-
# # => <label for="name">Your name</label>
-
#
-
# label_tag 'name', nil, class: 'small_label'
-
# # => <label for="name" class="small_label">Name</label>
-
2
def label_tag(name = nil, content_or_options = nil, options = nil, &block)
-
10
if block_given? && content_or_options.is_a?(Hash)
-
options = content_or_options = content_or_options.stringify_keys
-
else
-
10
options ||= {}
-
10
options = options.stringify_keys
-
end
-
10
options["for"] = sanitize_to_id(name) unless name.blank? || options.has_key?("for")
-
10
content_tag :label, content_or_options || name.to_s.humanize, options, &block
-
end
-
-
# Creates a hidden form input field used to transmit data that would be lost due to HTTP's statelessness or
-
# data that should be hidden from the user.
-
#
-
# ==== Options
-
# * Creates standard HTML attributes for the tag.
-
#
-
# ==== Examples
-
# hidden_field_tag 'tags_list'
-
# # => <input id="tags_list" name="tags_list" type="hidden" />
-
#
-
# hidden_field_tag 'token', 'VUBJKB23UIVI1UU1VOBVI@'
-
# # => <input id="token" name="token" type="hidden" value="VUBJKB23UIVI1UU1VOBVI@" />
-
#
-
# hidden_field_tag 'collected_input', '', onchange: "alert('Input collected!')"
-
# # => <input id="collected_input" name="collected_input" onchange="alert('Input collected!')"
-
# # type="hidden" value="" />
-
2
def hidden_field_tag(name, value = nil, options = {})
-
text_field_tag(name, value, options.stringify_keys.update("type" => "hidden"))
-
end
-
-
# Creates a file upload field. If you are using file uploads then you will also need
-
# to set the multipart option for the form tag:
-
#
-
# <%= form_tag '/upload', multipart: true do %>
-
# <label for="file">File to Upload</label> <%= file_field_tag "file" %>
-
# <%= submit_tag %>
-
# <% end %>
-
#
-
# The specified URL will then be passed a File object containing the selected file, or if the field
-
# was left blank, a StringIO object.
-
#
-
# ==== Options
-
# * Creates standard HTML attributes for the tag.
-
# * <tt>:disabled</tt> - If set to true, the user will not be able to use this input.
-
# * <tt>:multiple</tt> - If set to true, *in most updated browsers* the user will be allowed to select multiple files.
-
# * <tt>:accept</tt> - If set to one or multiple mime-types, the user will be suggested a filter when choosing a file. You still need to set up model validations.
-
#
-
# ==== Examples
-
# file_field_tag 'attachment'
-
# # => <input id="attachment" name="attachment" type="file" />
-
#
-
# file_field_tag 'avatar', class: 'profile_input'
-
# # => <input class="profile_input" id="avatar" name="avatar" type="file" />
-
#
-
# file_field_tag 'picture', disabled: true
-
# # => <input disabled="disabled" id="picture" name="picture" type="file" />
-
#
-
# file_field_tag 'resume', value: '~/resume.doc'
-
# # => <input id="resume" name="resume" type="file" value="~/resume.doc" />
-
#
-
# file_field_tag 'user_pic', accept: 'image/png,image/gif,image/jpeg'
-
# # => <input accept="image/png,image/gif,image/jpeg" id="user_pic" name="user_pic" type="file" />
-
#
-
# file_field_tag 'file', accept: 'text/html', class: 'upload', value: 'index.html'
-
# # => <input accept="text/html" class="upload" id="file" name="file" type="file" value="index.html" />
-
2
def file_field_tag(name, options = {})
-
text_field_tag(name, nil, options.update("type" => "file"))
-
end
-
-
# Creates a password field, a masked text field that will hide the users input behind a mask character.
-
#
-
# ==== Options
-
# * <tt>:disabled</tt> - If set to true, the user will not be able to use this input.
-
# * <tt>:size</tt> - The number of visible characters that will fit in the input.
-
# * <tt>:maxlength</tt> - The maximum number of characters that the browser will allow the user to enter.
-
# * Any other key creates standard HTML attributes for the tag.
-
#
-
# ==== Examples
-
# password_field_tag 'pass'
-
# # => <input id="pass" name="pass" type="password" />
-
#
-
# password_field_tag 'secret', 'Your secret here'
-
# # => <input id="secret" name="secret" type="password" value="Your secret here" />
-
#
-
# password_field_tag 'masked', nil, class: 'masked_input_field'
-
# # => <input class="masked_input_field" id="masked" name="masked" type="password" />
-
#
-
# password_field_tag 'token', '', size: 15
-
# # => <input id="token" name="token" size="15" type="password" value="" />
-
#
-
# password_field_tag 'key', nil, maxlength: 16
-
# # => <input id="key" maxlength="16" name="key" type="password" />
-
#
-
# password_field_tag 'confirm_pass', nil, disabled: true
-
# # => <input disabled="disabled" id="confirm_pass" name="confirm_pass" type="password" />
-
#
-
# password_field_tag 'pin', '1234', maxlength: 4, size: 6, class: "pin_input"
-
# # => <input class="pin_input" id="pin" maxlength="4" name="pin" size="6" type="password" value="1234" />
-
2
def password_field_tag(name = "password", value = nil, options = {})
-
text_field_tag(name, value, options.update("type" => "password"))
-
end
-
-
# Creates a text input area; use a textarea for longer text inputs such as blog posts or descriptions.
-
#
-
# ==== Options
-
# * <tt>:size</tt> - A string specifying the dimensions (columns by rows) of the textarea (e.g., "25x10").
-
# * <tt>:rows</tt> - Specify the number of rows in the textarea
-
# * <tt>:cols</tt> - Specify the number of columns in the textarea
-
# * <tt>:disabled</tt> - If set to true, the user will not be able to use this input.
-
# * <tt>:escape</tt> - By default, the contents of the text input are HTML escaped.
-
# If you need unescaped contents, set this to false.
-
# * Any other key creates standard HTML attributes for the tag.
-
#
-
# ==== Examples
-
# text_area_tag 'post'
-
# # => <textarea id="post" name="post"></textarea>
-
#
-
# text_area_tag 'bio', @user.bio
-
# # => <textarea id="bio" name="bio">This is my biography.</textarea>
-
#
-
# text_area_tag 'body', nil, rows: 10, cols: 25
-
# # => <textarea cols="25" id="body" name="body" rows="10"></textarea>
-
#
-
# text_area_tag 'body', nil, size: "25x10"
-
# # => <textarea name="body" id="body" cols="25" rows="10"></textarea>
-
#
-
# text_area_tag 'description', "Description goes here.", disabled: true
-
# # => <textarea disabled="disabled" id="description" name="description">Description goes here.</textarea>
-
#
-
# text_area_tag 'comment', nil, class: 'comment_input'
-
# # => <textarea class="comment_input" id="comment" name="comment"></textarea>
-
2
def text_area_tag(name, content = nil, options = {})
-
options = options.stringify_keys
-
-
if size = options.delete("size")
-
options["cols"], options["rows"] = size.split("x") if size.respond_to?(:split)
-
end
-
-
escape = options.delete("escape") { true }
-
content = ERB::Util.html_escape(content) if escape
-
-
content_tag :textarea, content.to_s.html_safe, { "name" => name, "id" => sanitize_to_id(name) }.update(options)
-
end
-
-
# Creates a check box form input tag.
-
#
-
# ==== Options
-
# * <tt>:disabled</tt> - If set to true, the user will not be able to use this input.
-
# * Any other key creates standard HTML options for the tag.
-
#
-
# ==== Examples
-
# check_box_tag 'accept'
-
# # => <input id="accept" name="accept" type="checkbox" value="1" />
-
#
-
# check_box_tag 'rock', 'rock music'
-
# # => <input id="rock" name="rock" type="checkbox" value="rock music" />
-
#
-
# check_box_tag 'receive_email', 'yes', true
-
# # => <input checked="checked" id="receive_email" name="receive_email" type="checkbox" value="yes" />
-
#
-
# check_box_tag 'tos', 'yes', false, class: 'accept_tos'
-
# # => <input class="accept_tos" id="tos" name="tos" type="checkbox" value="yes" />
-
#
-
# check_box_tag 'eula', 'accepted', false, disabled: true
-
# # => <input disabled="disabled" id="eula" name="eula" type="checkbox" value="accepted" />
-
2
def check_box_tag(name, value = "1", checked = false, options = {})
-
html_options = { "type" => "checkbox", "name" => name, "id" => sanitize_to_id(name), "value" => value }.update(options.stringify_keys)
-
html_options["checked"] = "checked" if checked
-
tag :input, html_options
-
end
-
-
# Creates a radio button; use groups of radio buttons named the same to allow users to
-
# select from a group of options.
-
#
-
# ==== Options
-
# * <tt>:disabled</tt> - If set to true, the user will not be able to use this input.
-
# * Any other key creates standard HTML options for the tag.
-
#
-
# ==== Examples
-
# radio_button_tag 'gender', 'male'
-
# # => <input id="gender_male" name="gender" type="radio" value="male" />
-
#
-
# radio_button_tag 'receive_updates', 'no', true
-
# # => <input checked="checked" id="receive_updates_no" name="receive_updates" type="radio" value="no" />
-
#
-
# radio_button_tag 'time_slot', "3:00 p.m.", false, disabled: true
-
# # => <input disabled="disabled" id="time_slot_300_pm" name="time_slot" type="radio" value="3:00 p.m." />
-
#
-
# radio_button_tag 'color', "green", true, class: "color_input"
-
# # => <input checked="checked" class="color_input" id="color_green" name="color" type="radio" value="green" />
-
2
def radio_button_tag(name, value, checked = false, options = {})
-
html_options = { "type" => "radio", "name" => name, "id" => "#{sanitize_to_id(name)}_#{sanitize_to_id(value)}", "value" => value }.update(options.stringify_keys)
-
html_options["checked"] = "checked" if checked
-
tag :input, html_options
-
end
-
-
# Creates a submit button with the text <tt>value</tt> as the caption.
-
#
-
# ==== Options
-
# * <tt>:data</tt> - This option can be used to add custom data attributes.
-
# * <tt>:disabled</tt> - If true, the user will not be able to use this input.
-
# * Any other key creates standard HTML options for the tag.
-
#
-
# ==== Data attributes
-
#
-
# * <tt>confirm: 'question?'</tt> - If present the unobtrusive JavaScript
-
# drivers will provide a prompt with the question specified. If the user accepts,
-
# the form is processed normally, otherwise no action is taken.
-
# * <tt>:disable_with</tt> - Value of this parameter will be used as the value for a
-
# disabled version of the submit button when the form is submitted. This feature is
-
# provided by the unobtrusive JavaScript driver.
-
#
-
# ==== Examples
-
# submit_tag
-
# # => <input name="commit" type="submit" value="Save changes" />
-
#
-
# submit_tag "Edit this article"
-
# # => <input name="commit" type="submit" value="Edit this article" />
-
#
-
# submit_tag "Save edits", disabled: true
-
# # => <input disabled="disabled" name="commit" type="submit" value="Save edits" />
-
#
-
# submit_tag "Complete sale", data: { disable_with: "Please wait..." }
-
# # => <input name="commit" data-disable-with="Please wait..." type="submit" value="Complete sale" />
-
#
-
# submit_tag nil, class: "form_submit"
-
# # => <input class="form_submit" name="commit" type="submit" />
-
#
-
# submit_tag "Edit", class: "edit_button"
-
# # => <input class="edit_button" name="commit" type="submit" value="Edit" />
-
#
-
# submit_tag "Save", data: { confirm: "Are you sure?" }
-
# # => <input name='commit' type='submit' value='Save' data-confirm="Are you sure?" />
-
#
-
2
def submit_tag(value = "Save changes", options = {})
-
9
options = options.stringify_keys
-
-
9
tag :input, { "type" => "submit", "name" => "commit", "value" => value }.update(options)
-
end
-
-
# Creates a button element that defines a <tt>submit</tt> button,
-
# <tt>reset</tt>button or a generic button which can be used in
-
# JavaScript, for example. You can use the button tag as a regular
-
# submit tag but it isn't supported in legacy browsers. However,
-
# the button tag allows richer labels such as images and emphasis,
-
# so this helper will also accept a block.
-
#
-
# ==== Options
-
# * <tt>:data</tt> - This option can be used to add custom data attributes.
-
# * <tt>:disabled</tt> - If true, the user will not be able to
-
# use this input.
-
# * Any other key creates standard HTML options for the tag.
-
#
-
# ==== Data attributes
-
#
-
# * <tt>confirm: 'question?'</tt> - If present, the
-
# unobtrusive JavaScript drivers will provide a prompt with
-
# the question specified. If the user accepts, the form is
-
# processed normally, otherwise no action is taken.
-
# * <tt>:disable_with</tt> - Value of this parameter will be
-
# used as the value for a disabled version of the submit
-
# button when the form is submitted. This feature is provided
-
# by the unobtrusive JavaScript driver.
-
#
-
# ==== Examples
-
# button_tag
-
# # => <button name="button" type="submit">Button</button>
-
#
-
# button_tag(type: 'button') do
-
# content_tag(:strong, 'Ask me!')
-
# end
-
# # => <button name="button" type="button">
-
# # <strong>Ask me!</strong>
-
# # </button>
-
#
-
# button_tag "Checkout", data: { disable_with: "Please wait..." }
-
# # => <button data-disable-with="Please wait..." name="button" type="submit">Checkout</button>
-
#
-
2
def button_tag(content_or_options = nil, options = nil, &block)
-
if content_or_options.is_a? Hash
-
options = content_or_options
-
else
-
options ||= {}
-
end
-
-
options = { 'name' => 'button', 'type' => 'submit' }.merge!(options.stringify_keys)
-
-
if block_given?
-
content_tag :button, options, &block
-
else
-
content_tag :button, content_or_options || 'Button', options
-
end
-
end
-
-
# Displays an image which when clicked will submit the form.
-
#
-
# <tt>source</tt> is passed to AssetTagHelper#path_to_image
-
#
-
# ==== Options
-
# * <tt>:data</tt> - This option can be used to add custom data attributes.
-
# * <tt>:disabled</tt> - If set to true, the user will not be able to use this input.
-
# * Any other key creates standard HTML options for the tag.
-
#
-
# ==== Data attributes
-
#
-
# * <tt>confirm: 'question?'</tt> - This will add a JavaScript confirm
-
# prompt with the question specified. If the user accepts, the form is
-
# processed normally, otherwise no action is taken.
-
#
-
# ==== Examples
-
# image_submit_tag("login.png")
-
# # => <input alt="Login" src="/images/login.png" type="image" />
-
#
-
# image_submit_tag("purchase.png", disabled: true)
-
# # => <input alt="Purchase" disabled="disabled" src="/images/purchase.png" type="image" />
-
#
-
# image_submit_tag("search.png", class: 'search_button', alt: 'Find')
-
# # => <input alt="Find" class="search_button" src="/images/search.png" type="image" />
-
#
-
# image_submit_tag("agree.png", disabled: true, class: "agree_disagree_button")
-
# # => <input alt="Agree" class="agree_disagree_button" disabled="disabled" src="/images/agree.png" type="image" />
-
#
-
# image_submit_tag("save.png", data: { confirm: "Are you sure?" })
-
# # => <input alt="Save" src="/images/save.png" data-confirm="Are you sure?" type="image" />
-
2
def image_submit_tag(source, options = {})
-
options = options.stringify_keys
-
tag :input, { "alt" => image_alt(source), "type" => "image", "src" => path_to_image(source) }.update(options)
-
end
-
-
# Creates a field set for grouping HTML form elements.
-
#
-
# <tt>legend</tt> will become the fieldset's title (optional as per W3C).
-
# <tt>options</tt> accept the same values as tag.
-
#
-
# ==== Examples
-
# <%= field_set_tag do %>
-
# <p><%= text_field_tag 'name' %></p>
-
# <% end %>
-
# # => <fieldset><p><input id="name" name="name" type="text" /></p></fieldset>
-
#
-
# <%= field_set_tag 'Your details' do %>
-
# <p><%= text_field_tag 'name' %></p>
-
# <% end %>
-
# # => <fieldset><legend>Your details</legend><p><input id="name" name="name" type="text" /></p></fieldset>
-
#
-
# <%= field_set_tag nil, class: 'format' do %>
-
# <p><%= text_field_tag 'name' %></p>
-
# <% end %>
-
# # => <fieldset class="format"><p><input id="name" name="name" type="text" /></p></fieldset>
-
2
def field_set_tag(legend = nil, options = nil, &block)
-
output = tag(:fieldset, options, true)
-
output.safe_concat(content_tag(:legend, legend)) unless legend.blank?
-
output.concat(capture(&block)) if block_given?
-
output.safe_concat("</fieldset>")
-
end
-
-
# Creates a text field of type "color".
-
#
-
# ==== Options
-
# * Accepts the same options as text_field_tag.
-
2
def color_field_tag(name, value = nil, options = {})
-
text_field_tag(name, value, options.stringify_keys.update("type" => "color"))
-
end
-
-
# Creates a text field of type "search".
-
#
-
# ==== Options
-
# * Accepts the same options as text_field_tag.
-
2
def search_field_tag(name, value = nil, options = {})
-
text_field_tag(name, value, options.stringify_keys.update("type" => "search"))
-
end
-
-
# Creates a text field of type "tel".
-
#
-
# ==== Options
-
# * Accepts the same options as text_field_tag.
-
2
def telephone_field_tag(name, value = nil, options = {})
-
text_field_tag(name, value, options.stringify_keys.update("type" => "tel"))
-
end
-
2
alias phone_field_tag telephone_field_tag
-
-
# Creates a text field of type "date".
-
#
-
# ==== Options
-
# * Accepts the same options as text_field_tag.
-
2
def date_field_tag(name, value = nil, options = {})
-
text_field_tag(name, value, options.stringify_keys.update("type" => "date"))
-
end
-
-
# Creates a text field of type "time".
-
#
-
# === Options
-
# * <tt>:min</tt> - The minimum acceptable value.
-
# * <tt>:max</tt> - The maximum acceptable value.
-
# * <tt>:step</tt> - The acceptable value granularity.
-
# * Otherwise accepts the same options as text_field_tag.
-
2
def time_field_tag(name, value = nil, options = {})
-
text_field_tag(name, value, options.stringify_keys.update("type" => "time"))
-
end
-
-
# Creates a text field of type "datetime".
-
#
-
# === Options
-
# * <tt>:min</tt> - The minimum acceptable value.
-
# * <tt>:max</tt> - The maximum acceptable value.
-
# * <tt>:step</tt> - The acceptable value granularity.
-
# * Otherwise accepts the same options as text_field_tag.
-
2
def datetime_field_tag(name, value = nil, options = {})
-
text_field_tag(name, value, options.stringify_keys.update("type" => "datetime"))
-
end
-
-
# Creates a text field of type "datetime-local".
-
#
-
# === Options
-
# * <tt>:min</tt> - The minimum acceptable value.
-
# * <tt>:max</tt> - The maximum acceptable value.
-
# * <tt>:step</tt> - The acceptable value granularity.
-
# * Otherwise accepts the same options as text_field_tag.
-
2
def datetime_local_field_tag(name, value = nil, options = {})
-
text_field_tag(name, value, options.stringify_keys.update("type" => "datetime-local"))
-
end
-
-
# Creates a text field of type "month".
-
#
-
# === Options
-
# * <tt>:min</tt> - The minimum acceptable value.
-
# * <tt>:max</tt> - The maximum acceptable value.
-
# * <tt>:step</tt> - The acceptable value granularity.
-
# * Otherwise accepts the same options as text_field_tag.
-
2
def month_field_tag(name, value = nil, options = {})
-
text_field_tag(name, value, options.stringify_keys.update("type" => "month"))
-
end
-
-
# Creates a text field of type "week".
-
#
-
# === Options
-
# * <tt>:min</tt> - The minimum acceptable value.
-
# * <tt>:max</tt> - The maximum acceptable value.
-
# * <tt>:step</tt> - The acceptable value granularity.
-
# * Otherwise accepts the same options as text_field_tag.
-
2
def week_field_tag(name, value = nil, options = {})
-
text_field_tag(name, value, options.stringify_keys.update("type" => "week"))
-
end
-
-
# Creates a text field of type "url".
-
#
-
# ==== Options
-
# * Accepts the same options as text_field_tag.
-
2
def url_field_tag(name, value = nil, options = {})
-
text_field_tag(name, value, options.stringify_keys.update("type" => "url"))
-
end
-
-
# Creates a text field of type "email".
-
#
-
# ==== Options
-
# * Accepts the same options as text_field_tag.
-
2
def email_field_tag(name, value = nil, options = {})
-
text_field_tag(name, value, options.stringify_keys.update("type" => "email"))
-
end
-
-
# Creates a number field.
-
#
-
# ==== Options
-
# * <tt>:min</tt> - The minimum acceptable value.
-
# * <tt>:max</tt> - The maximum acceptable value.
-
# * <tt>:in</tt> - A range specifying the <tt>:min</tt> and
-
# <tt>:max</tt> values.
-
# * <tt>:step</tt> - The acceptable value granularity.
-
# * Otherwise accepts the same options as text_field_tag.
-
#
-
# ==== Examples
-
# number_field_tag 'quantity', nil, in: 1...10
-
# # => <input id="quantity" name="quantity" min="1" max="9" type="number" />
-
2
def number_field_tag(name, value = nil, options = {})
-
options = options.stringify_keys
-
options["type"] ||= "number"
-
if range = options.delete("in") || options.delete("within")
-
options.update("min" => range.min, "max" => range.max)
-
end
-
text_field_tag(name, value, options)
-
end
-
-
# Creates a range form element.
-
#
-
# ==== Options
-
# * Accepts the same options as number_field_tag.
-
2
def range_field_tag(name, value = nil, options = {})
-
number_field_tag(name, value, options.stringify_keys.update("type" => "range"))
-
end
-
-
# Creates the hidden UTF8 enforcer tag. Override this method in a helper
-
# to customize the tag.
-
2
def utf8_enforcer_tag
-
9
tag(:input, :type => "hidden", :name => "utf8", :value => "✓".html_safe)
-
end
-
-
2
private
-
2
def html_options_for_form(url_for_options, options)
-
9
options.stringify_keys.tap do |html_options|
-
9
html_options["enctype"] = "multipart/form-data" if html_options.delete("multipart")
-
# The following URL is unescaped, this is just a hash of options, and it is the
-
# responsibility of the caller to escape all the values.
-
9
html_options["action"] = url_for(url_for_options)
-
9
html_options["accept-charset"] = "UTF-8"
-
-
9
html_options["data-remote"] = true if html_options.delete("remote")
-
-
if html_options["data-remote"] &&
-
9
!embed_authenticity_token_in_remote_forms &&
-
html_options["authenticity_token"].blank?
-
# The authenticity token is taken from the meta tag in this case
-
html_options["authenticity_token"] = false
-
elsif html_options["authenticity_token"] == true
-
# Include the default authenticity_token, which is only generated when its set to nil,
-
# but we needed the true value to override the default of no authenticity_token on data-remote.
-
html_options["authenticity_token"] = nil
-
end
-
end
-
end
-
-
2
def extra_tags_for_form(html_options)
-
9
authenticity_token = html_options.delete("authenticity_token")
-
9
method = html_options.delete("method").to_s
-
-
9
method_tag = case method
-
when /^get$/i # must be case-insensitive, but can't use downcase as might be nil
-
html_options["method"] = "get"
-
''
-
when /^post$/i, "", nil
-
9
html_options["method"] = "post"
-
9
token_tag(authenticity_token)
-
else
-
html_options["method"] = "post"
-
method_tag(method) + token_tag(authenticity_token)
-
end
-
-
18
enforce_utf8 = html_options.delete("enforce_utf8") { true }
-
9
tags = (enforce_utf8 ? utf8_enforcer_tag : ''.html_safe) << method_tag
-
9
content_tag(:div, tags, :style => 'display:none')
-
end
-
-
2
def form_tag_html(html_options)
-
9
extra_tags = extra_tags_for_form(html_options)
-
9
tag(:form, html_options, true) + extra_tags
-
end
-
-
2
def form_tag_in_block(html_options, &block)
-
9
content = capture(&block)
-
9
output = form_tag_html(html_options)
-
9
output << content
-
9
output.safe_concat("</form>")
-
end
-
-
# see http://www.w3.org/TR/html4/types.html#type-name
-
2
def sanitize_to_id(name)
-
name.to_s.delete(']').gsub(/[^-a-zA-Z0-9:.]/, "_")
-
end
-
end
-
end
-
end
-
2
require 'action_view/helpers/tag_helper'
-
-
2
module ActionView
-
2
module Helpers
-
2
module JavaScriptHelper
-
2
JS_ESCAPE_MAP = {
-
'\\' => '\\\\',
-
'</' => '<\/',
-
"\r\n" => '\n',
-
"\n" => '\n',
-
"\r" => '\n',
-
'"' => '\\"',
-
"'" => "\\'"
-
}
-
-
2
JS_ESCAPE_MAP["\342\200\250".force_encoding(Encoding::UTF_8).encode!] = '
'
-
2
JS_ESCAPE_MAP["\342\200\251".force_encoding(Encoding::UTF_8).encode!] = '
'
-
-
# Escapes carriage returns and single and double quotes for JavaScript segments.
-
#
-
# Also available through the alias j(). This is particularly helpful in JavaScript
-
# responses, like:
-
#
-
# $('some_element').replaceWith('<%=j render 'some/element_template' %>');
-
2
def escape_javascript(javascript)
-
if javascript
-
result = javascript.gsub(/(\\|<\/|\r\n|\342\200\250|\342\200\251|[\n\r"'])/u) {|match| JS_ESCAPE_MAP[match] }
-
javascript.html_safe? ? result.html_safe : result
-
else
-
''
-
end
-
end
-
-
2
alias_method :j, :escape_javascript
-
-
# Returns a JavaScript tag with the +content+ inside. Example:
-
# javascript_tag "alert('All is good')"
-
#
-
# Returns:
-
# <script>
-
# //<![CDATA[
-
# alert('All is good')
-
# //]]>
-
# </script>
-
#
-
# +html_options+ may be a hash of attributes for the <tt>\<script></tt>
-
# tag.
-
#
-
# javascript_tag "alert('All is good')", defer: 'defer'
-
# # => <script defer="defer">alert('All is good')</script>
-
#
-
# Instead of passing the content as an argument, you can also use a block
-
# in which case, you pass your +html_options+ as the first parameter.
-
#
-
# <%= javascript_tag defer: 'defer' do -%>
-
# alert('All is good')
-
# <% end -%>
-
2
def javascript_tag(content_or_options_with_block = nil, html_options = {}, &block)
-
content =
-
if block_given?
-
html_options = content_or_options_with_block if content_or_options_with_block.is_a?(Hash)
-
capture(&block)
-
else
-
content_or_options_with_block
-
end
-
-
content_tag(:script, javascript_cdata_section(content), html_options)
-
end
-
-
2
def javascript_cdata_section(content) #:nodoc:
-
"\n//#{cdata_section("\n#{content}\n//")}\n".html_safe
-
end
-
end
-
end
-
end
-
# encoding: utf-8
-
-
2
require 'active_support/core_ext/hash/keys'
-
2
require 'active_support/core_ext/string/output_safety'
-
2
require 'active_support/number_helper'
-
-
2
module ActionView
-
# = Action View Number Helpers
-
2
module Helpers #:nodoc:
-
-
# Provides methods for converting numbers into formatted strings.
-
# Methods are provided for phone numbers, currency, percentage,
-
# precision, positional notation, file size and pretty printing.
-
#
-
# Most methods expect a +number+ argument, and will return it
-
# unchanged if can't be converted into a valid number.
-
2
module NumberHelper
-
-
# Raised when argument +number+ param given to the helpers is invalid and
-
# the option :raise is set to +true+.
-
2
class InvalidNumberError < StandardError
-
2
attr_accessor :number
-
2
def initialize(number)
-
@number = number
-
end
-
end
-
-
# Formats a +number+ into a US phone number (e.g., (555)
-
# 123-9876). You can customize the format in the +options+ hash.
-
#
-
# ==== Options
-
#
-
# * <tt>:area_code</tt> - Adds parentheses around the area code.
-
# * <tt>:delimiter</tt> - Specifies the delimiter to use
-
# (defaults to "-").
-
# * <tt>:extension</tt> - Specifies an extension to add to the
-
# end of the generated number.
-
# * <tt>:country_code</tt> - Sets the country code for the phone
-
# number.
-
# * <tt>:raise</tt> - If true, raises +InvalidNumberError+ when
-
# the argument is invalid.
-
#
-
# ==== Examples
-
#
-
# number_to_phone(5551234) # => 555-1234
-
# number_to_phone("5551234") # => 555-1234
-
# number_to_phone(1235551234) # => 123-555-1234
-
# number_to_phone(1235551234, area_code: true) # => (123) 555-1234
-
# number_to_phone(1235551234, delimiter: " ") # => 123 555 1234
-
# number_to_phone(1235551234, area_code: true, extension: 555) # => (123) 555-1234 x 555
-
# number_to_phone(1235551234, country_code: 1) # => +1-123-555-1234
-
# number_to_phone("123a456") # => 123a456
-
# number_to_phone("1234a567", raise: true) # => InvalidNumberError
-
#
-
# number_to_phone(1235551234, country_code: 1, extension: 1343, delimiter: ".")
-
# # => +1.123.555.1234 x 1343
-
2
def number_to_phone(number, options = {})
-
return unless number
-
options = options.symbolize_keys
-
-
parse_float(number, true) if options.delete(:raise)
-
ERB::Util.html_escape(ActiveSupport::NumberHelper.number_to_phone(number, options))
-
end
-
-
# Formats a +number+ into a currency string (e.g., $13.65). You
-
# can customize the format in the +options+ hash.
-
#
-
# ==== Options
-
#
-
# * <tt>:locale</tt> - Sets the locale to be used for formatting
-
# (defaults to current locale).
-
# * <tt>:precision</tt> - Sets the level of precision (defaults
-
# to 2).
-
# * <tt>:unit</tt> - Sets the denomination of the currency
-
# (defaults to "$").
-
# * <tt>:separator</tt> - Sets the separator between the units
-
# (defaults to ".").
-
# * <tt>:delimiter</tt> - Sets the thousands delimiter (defaults
-
# to ",").
-
# * <tt>:format</tt> - Sets the format for non-negative numbers
-
# (defaults to "%u%n"). Fields are <tt>%u</tt> for the
-
# currency, and <tt>%n</tt> for the number.
-
# * <tt>:negative_format</tt> - Sets the format for negative
-
# numbers (defaults to prepending an hyphen to the formatted
-
# number given by <tt>:format</tt>). Accepts the same fields
-
# than <tt>:format</tt>, except <tt>%n</tt> is here the
-
# absolute value of the number.
-
# * <tt>:raise</tt> - If true, raises +InvalidNumberError+ when
-
# the argument is invalid.
-
#
-
# ==== Examples
-
#
-
# number_to_currency(1234567890.50) # => $1,234,567,890.50
-
# number_to_currency(1234567890.506) # => $1,234,567,890.51
-
# number_to_currency(1234567890.506, precision: 3) # => $1,234,567,890.506
-
# number_to_currency(1234567890.506, locale: :fr) # => 1 234 567 890,51 €
-
# number_to_currency("123a456") # => $123a456
-
#
-
# number_to_currency("123a456", raise: true) # => InvalidNumberError
-
#
-
# number_to_currency(-1234567890.50, negative_format: "(%u%n)")
-
# # => ($1,234,567,890.50)
-
# number_to_currency(1234567890.50, unit: "R$", separator: ",", delimiter: "")
-
# # => R$1234567890,50
-
# number_to_currency(1234567890.50, unit: "R$", separator: ",", delimiter: "", format: "%n %u")
-
# # => 1234567890,50 R$
-
2
def number_to_currency(number, options = {})
-
delegate_number_helper_method(:number_to_currency, number, options)
-
end
-
-
# Formats a +number+ as a percentage string (e.g., 65%). You can
-
# customize the format in the +options+ hash.
-
#
-
# ==== Options
-
#
-
# * <tt>:locale</tt> - Sets the locale to be used for formatting
-
# (defaults to current locale).
-
# * <tt>:precision</tt> - Sets the precision of the number
-
# (defaults to 3).
-
# * <tt>:significant</tt> - If +true+, precision will be the #
-
# of significant_digits. If +false+, the # of fractional
-
# digits (defaults to +false+).
-
# * <tt>:separator</tt> - Sets the separator between the
-
# fractional and integer digits (defaults to ".").
-
# * <tt>:delimiter</tt> - Sets the thousands delimiter (defaults
-
# to "").
-
# * <tt>:strip_insignificant_zeros</tt> - If +true+ removes
-
# insignificant zeros after the decimal separator (defaults to
-
# +false+).
-
# * <tt>:format</tt> - Specifies the format of the percentage
-
# string The number field is <tt>%n</tt> (defaults to "%n%").
-
# * <tt>:raise</tt> - If true, raises +InvalidNumberError+ when
-
# the argument is invalid.
-
#
-
# ==== Examples
-
#
-
# number_to_percentage(100) # => 100.000%
-
# number_to_percentage("98") # => 98.000%
-
# number_to_percentage(100, precision: 0) # => 100%
-
# number_to_percentage(1000, delimiter: '.', separator: ',') # => 1.000,000%
-
# number_to_percentage(302.24398923423, precision: 5) # => 302.24399%
-
# number_to_percentage(1000, locale: :fr) # => 1 000,000%
-
# number_to_percentage("98a") # => 98a%
-
# number_to_percentage(100, format: "%n %") # => 100 %
-
#
-
# number_to_percentage("98a", raise: true) # => InvalidNumberError
-
2
def number_to_percentage(number, options = {})
-
delegate_number_helper_method(:number_to_percentage, number, options)
-
end
-
-
# Formats a +number+ with grouped thousands using +delimiter+
-
# (e.g., 12,324). You can customize the format in the +options+
-
# hash.
-
#
-
# ==== Options
-
#
-
# * <tt>:locale</tt> - Sets the locale to be used for formatting
-
# (defaults to current locale).
-
# * <tt>:delimiter</tt> - Sets the thousands delimiter (defaults
-
# to ",").
-
# * <tt>:separator</tt> - Sets the separator between the
-
# fractional and integer digits (defaults to ".").
-
# * <tt>:raise</tt> - If true, raises +InvalidNumberError+ when
-
# the argument is invalid.
-
#
-
# ==== Examples
-
#
-
# number_with_delimiter(12345678) # => 12,345,678
-
# number_with_delimiter("123456") # => 123,456
-
# number_with_delimiter(12345678.05) # => 12,345,678.05
-
# number_with_delimiter(12345678, delimiter: ".") # => 12.345.678
-
# number_with_delimiter(12345678, delimiter: ",") # => 12,345,678
-
# number_with_delimiter(12345678.05, separator: " ") # => 12,345,678 05
-
# number_with_delimiter(12345678.05, locale: :fr) # => 12 345 678,05
-
# number_with_delimiter("112a") # => 112a
-
# number_with_delimiter(98765432.98, delimiter: " ", separator: ",")
-
# # => 98 765 432,98
-
#
-
# number_with_delimiter("112a", raise: true) # => raise InvalidNumberError
-
2
def number_with_delimiter(number, options = {})
-
delegate_number_helper_method(:number_to_delimited, number, options)
-
end
-
-
# Formats a +number+ with the specified level of
-
# <tt>:precision</tt> (e.g., 112.32 has a precision of 2 if
-
# +:significant+ is +false+, and 5 if +:significant+ is +true+).
-
# You can customize the format in the +options+ hash.
-
#
-
# ==== Options
-
#
-
# * <tt>:locale</tt> - Sets the locale to be used for formatting
-
# (defaults to current locale).
-
# * <tt>:precision</tt> - Sets the precision of the number
-
# (defaults to 3).
-
# * <tt>:significant</tt> - If +true+, precision will be the #
-
# of significant_digits. If +false+, the # of fractional
-
# digits (defaults to +false+).
-
# * <tt>:separator</tt> - Sets the separator between the
-
# fractional and integer digits (defaults to ".").
-
# * <tt>:delimiter</tt> - Sets the thousands delimiter (defaults
-
# to "").
-
# * <tt>:strip_insignificant_zeros</tt> - If +true+ removes
-
# insignificant zeros after the decimal separator (defaults to
-
# +false+).
-
# * <tt>:raise</tt> - If true, raises +InvalidNumberError+ when
-
# the argument is invalid.
-
#
-
# ==== Examples
-
#
-
# number_with_precision(111.2345) # => 111.235
-
# number_with_precision(111.2345, precision: 2) # => 111.23
-
# number_with_precision(13, precision: 5) # => 13.00000
-
# number_with_precision(389.32314, precision: 0) # => 389
-
# number_with_precision(111.2345, significant: true) # => 111
-
# number_with_precision(111.2345, precision: 1, significant: true) # => 100
-
# number_with_precision(13, precision: 5, significant: true) # => 13.000
-
# number_with_precision(111.234, locale: :fr) # => 111,234
-
#
-
# number_with_precision(13, precision: 5, significant: true, strip_insignificant_zeros: true)
-
# # => 13
-
#
-
# number_with_precision(389.32314, precision: 4, significant: true) # => 389.3
-
# number_with_precision(1111.2345, precision: 2, separator: ',', delimiter: '.')
-
# # => 1.111,23
-
2
def number_with_precision(number, options = {})
-
delegate_number_helper_method(:number_to_rounded, number, options)
-
end
-
-
# Formats the bytes in +number+ into a more understandable
-
# representation (e.g., giving it 1500 yields 1.5 KB). This
-
# method is useful for reporting file sizes to users. You can
-
# customize the format in the +options+ hash.
-
#
-
# See <tt>number_to_human</tt> if you want to pretty-print a
-
# generic number.
-
#
-
# ==== Options
-
#
-
# * <tt>:locale</tt> - Sets the locale to be used for formatting
-
# (defaults to current locale).
-
# * <tt>:precision</tt> - Sets the precision of the number
-
# (defaults to 3).
-
# * <tt>:significant</tt> - If +true+, precision will be the #
-
# of significant_digits. If +false+, the # of fractional
-
# digits (defaults to +true+)
-
# * <tt>:separator</tt> - Sets the separator between the
-
# fractional and integer digits (defaults to ".").
-
# * <tt>:delimiter</tt> - Sets the thousands delimiter (defaults
-
# to "").
-
# * <tt>:strip_insignificant_zeros</tt> - If +true+ removes
-
# insignificant zeros after the decimal separator (defaults to
-
# +true+)
-
# * <tt>:prefix</tt> - If +:si+ formats the number using the SI
-
# prefix (defaults to :binary)
-
# * <tt>:raise</tt> - If true, raises +InvalidNumberError+ when
-
# the argument is invalid.
-
#
-
# ==== Examples
-
#
-
# number_to_human_size(123) # => 123 Bytes
-
# number_to_human_size(1234) # => 1.21 KB
-
# number_to_human_size(12345) # => 12.1 KB
-
# number_to_human_size(1234567) # => 1.18 MB
-
# number_to_human_size(1234567890) # => 1.15 GB
-
# number_to_human_size(1234567890123) # => 1.12 TB
-
# number_to_human_size(1234567, precision: 2) # => 1.2 MB
-
# number_to_human_size(483989, precision: 2) # => 470 KB
-
# number_to_human_size(1234567, precision: 2, separator: ',') # => 1,2 MB
-
#
-
# Non-significant zeros after the fractional separator are
-
# stripped out by default (set
-
# <tt>:strip_insignificant_zeros</tt> to +false+ to change
-
# that):
-
#
-
# number_to_human_size(1234567890123, precision: 5) # => "1.1229 TB"
-
# number_to_human_size(524288000, precision: 5) # => "500 MB"
-
2
def number_to_human_size(number, options = {})
-
delegate_number_helper_method(:number_to_human_size, number, options)
-
end
-
-
# Pretty prints (formats and approximates) a number in a way it
-
# is more readable by humans (eg.: 1200000000 becomes "1.2
-
# Billion"). This is useful for numbers that can get very large
-
# (and too hard to read).
-
#
-
# See <tt>number_to_human_size</tt> if you want to print a file
-
# size.
-
#
-
# You can also define you own unit-quantifier names if you want
-
# to use other decimal units (eg.: 1500 becomes "1.5
-
# kilometers", 0.150 becomes "150 milliliters", etc). You may
-
# define a wide range of unit quantifiers, even fractional ones
-
# (centi, deci, mili, etc).
-
#
-
# ==== Options
-
#
-
# * <tt>:locale</tt> - Sets the locale to be used for formatting
-
# (defaults to current locale).
-
# * <tt>:precision</tt> - Sets the precision of the number
-
# (defaults to 3).
-
# * <tt>:significant</tt> - If +true+, precision will be the #
-
# of significant_digits. If +false+, the # of fractional
-
# digits (defaults to +true+)
-
# * <tt>:separator</tt> - Sets the separator between the
-
# fractional and integer digits (defaults to ".").
-
# * <tt>:delimiter</tt> - Sets the thousands delimiter (defaults
-
# to "").
-
# * <tt>:strip_insignificant_zeros</tt> - If +true+ removes
-
# insignificant zeros after the decimal separator (defaults to
-
# +true+)
-
# * <tt>:units</tt> - A Hash of unit quantifier names. Or a
-
# string containing an i18n scope where to find this hash. It
-
# might have the following keys:
-
# * *integers*: <tt>:unit</tt>, <tt>:ten</tt>,
-
# *<tt>:hundred</tt>, <tt>:thousand</tt>, <tt>:million</tt>,
-
# *<tt>:billion</tt>, <tt>:trillion</tt>,
-
# *<tt>:quadrillion</tt>
-
# * *fractionals*: <tt>:deci</tt>, <tt>:centi</tt>,
-
# *<tt>:mili</tt>, <tt>:micro</tt>, <tt>:nano</tt>,
-
# *<tt>:pico</tt>, <tt>:femto</tt>
-
# * <tt>:format</tt> - Sets the format of the output string
-
# (defaults to "%n %u"). The field types are:
-
# * %u - The quantifier (ex.: 'thousand')
-
# * %n - The number
-
# * <tt>:raise</tt> - If true, raises +InvalidNumberError+ when
-
# the argument is invalid.
-
#
-
# ==== Examples
-
#
-
# number_to_human(123) # => "123"
-
# number_to_human(1234) # => "1.23 Thousand"
-
# number_to_human(12345) # => "12.3 Thousand"
-
# number_to_human(1234567) # => "1.23 Million"
-
# number_to_human(1234567890) # => "1.23 Billion"
-
# number_to_human(1234567890123) # => "1.23 Trillion"
-
# number_to_human(1234567890123456) # => "1.23 Quadrillion"
-
# number_to_human(1234567890123456789) # => "1230 Quadrillion"
-
# number_to_human(489939, precision: 2) # => "490 Thousand"
-
# number_to_human(489939, precision: 4) # => "489.9 Thousand"
-
# number_to_human(1234567, precision: 4,
-
# significant: false) # => "1.2346 Million"
-
# number_to_human(1234567, precision: 1,
-
# separator: ',',
-
# significant: false) # => "1,2 Million"
-
#
-
# Non-significant zeros after the decimal separator are stripped
-
# out by default (set <tt>:strip_insignificant_zeros</tt> to
-
# +false+ to change that):
-
# number_to_human(12345012345, significant_digits: 6) # => "12.345 Billion"
-
# number_to_human(500000000, precision: 5) # => "500 Million"
-
#
-
# ==== Custom Unit Quantifiers
-
#
-
# You can also use your own custom unit quantifiers:
-
# number_to_human(500000, units: {unit: "ml", thousand: "lt"}) # => "500 lt"
-
#
-
# If in your I18n locale you have:
-
# distance:
-
# centi:
-
# one: "centimeter"
-
# other: "centimeters"
-
# unit:
-
# one: "meter"
-
# other: "meters"
-
# thousand:
-
# one: "kilometer"
-
# other: "kilometers"
-
# billion: "gazillion-distance"
-
#
-
# Then you could do:
-
#
-
# number_to_human(543934, units: :distance) # => "544 kilometers"
-
# number_to_human(54393498, units: :distance) # => "54400 kilometers"
-
# number_to_human(54393498000, units: :distance) # => "54.4 gazillion-distance"
-
# number_to_human(343, units: :distance, precision: 1) # => "300 meters"
-
# number_to_human(1, units: :distance) # => "1 meter"
-
# number_to_human(0.34, units: :distance) # => "34 centimeters"
-
#
-
2
def number_to_human(number, options = {})
-
delegate_number_helper_method(:number_to_human, number, options)
-
end
-
-
2
private
-
-
2
def delegate_number_helper_method(method, number, options)
-
return unless number
-
options = escape_unsafe_options(options.symbolize_keys)
-
-
wrap_with_output_safety_handling(number, options.delete(:raise)) {
-
ActiveSupport::NumberHelper.public_send(method, number, options)
-
}
-
end
-
-
2
def escape_unsafe_options(options)
-
options[:format] = ERB::Util.html_escape(options[:format]) if options[:format]
-
options[:negative_format] = ERB::Util.html_escape(options[:negative_format]) if options[:negative_format]
-
options[:separator] = ERB::Util.html_escape(options[:separator]) if options[:separator]
-
options[:delimiter] = ERB::Util.html_escape(options[:delimiter]) if options[:delimiter]
-
options[:unit] = ERB::Util.html_escape(options[:unit]) if options[:unit] && !options[:unit].html_safe?
-
options[:units] = escape_units(options[:units]) if options[:units] && Hash === options[:units]
-
options
-
end
-
-
2
def escape_units(units)
-
Hash[units.map do |k, v|
-
[k, ERB::Util.html_escape(v)]
-
end]
-
end
-
-
2
def wrap_with_output_safety_handling(number, raise_on_invalid, &block)
-
valid_float = valid_float?(number)
-
raise InvalidNumberError, number if raise_on_invalid && !valid_float
-
-
formatted_number = yield
-
-
if valid_float || number.html_safe?
-
formatted_number.html_safe
-
else
-
formatted_number
-
end
-
end
-
-
2
def valid_float?(number)
-
!parse_float(number, false).nil?
-
end
-
-
2
def parse_float(number, raise_error)
-
Float(number)
-
rescue ArgumentError, TypeError
-
raise InvalidNumberError, number if raise_error
-
end
-
end
-
end
-
end
-
2
require 'active_support/core_ext/string/output_safety'
-
-
2
module ActionView #:nodoc:
-
# = Action View Raw Output Helper
-
2
module Helpers #:nodoc:
-
2
module OutputSafetyHelper
-
# This method outputs without escaping a string. Since escaping tags is
-
# now default, this can be used when you don't want Rails to automatically
-
# escape tags. This is not recommended if the data is coming from the user's
-
# input.
-
#
-
# For example:
-
#
-
# raw @user.name
-
# # => 'Jimmy <alert>Tables</alert>'
-
2
def raw(stringish)
-
stringish.to_s.html_safe
-
end
-
-
# This method returns a html safe string similar to what <tt>Array#join</tt>
-
# would return. All items in the array, including the supplied separator, are
-
# html escaped unless they are html safe, and the returned string is marked
-
# as html safe.
-
#
-
# safe_join(["<p>foo</p>".html_safe, "<p>bar</p>"], "<br />")
-
# # => "<p>foo</p><br /><p>bar</p>"
-
#
-
# safe_join(["<p>foo</p>".html_safe, "<p>bar</p>".html_safe], "<br />".html_safe)
-
# # => "<p>foo</p><br /><p>bar</p>"
-
#
-
2
def safe_join(array, sep=$,)
-
sep = ERB::Util.html_escape(sep)
-
-
array.map { |i| ERB::Util.html_escape(i) }.join(sep).html_safe
-
end
-
end
-
end
-
end
-
2
require 'action_view/record_identifier'
-
-
2
module ActionView
-
# = Action View Record Tag Helpers
-
2
module Helpers
-
2
module RecordTagHelper
-
2
include ActionView::RecordIdentifier
-
-
# Produces a wrapper DIV element with id and class parameters that
-
# relate to the specified Active Record object. Usage example:
-
#
-
# <%= div_for(@person, class: "foo") do %>
-
# <%= @person.name %>
-
# <% end %>
-
#
-
# produces:
-
#
-
# <div id="person_123" class="person foo"> Joe Bloggs </div>
-
#
-
# You can also pass an array of Active Record objects, which will then
-
# get iterated over and yield each record as an argument for the block.
-
# For example:
-
#
-
# <%= div_for(@people, class: "foo") do |person| %>
-
# <%= person.name %>
-
# <% end %>
-
#
-
# produces:
-
#
-
# <div id="person_123" class="person foo"> Joe Bloggs </div>
-
# <div id="person_124" class="person foo"> Jane Bloggs </div>
-
#
-
2
def div_for(record, *args, &block)
-
content_tag_for(:div, record, *args, &block)
-
end
-
-
# content_tag_for creates an HTML element with id and class parameters
-
# that relate to the specified Active Record object. For example:
-
#
-
# <%= content_tag_for(:tr, @person) do %>
-
# <td><%= @person.first_name %></td>
-
# <td><%= @person.last_name %></td>
-
# <% end %>
-
#
-
# would produce the following HTML (assuming @person is an instance of
-
# a Person object, with an id value of 123):
-
#
-
# <tr id="person_123" class="person">....</tr>
-
#
-
# If you require the HTML id attribute to have a prefix, you can specify it:
-
#
-
# <%= content_tag_for(:tr, @person, :foo) do %> ...
-
#
-
# produces:
-
#
-
# <tr id="foo_person_123" class="person">...
-
#
-
# You can also pass an array of objects which this method will loop through
-
# and yield the current object to the supplied block, reducing the need for
-
# having to iterate through the object (using <tt>each</tt>) beforehand.
-
# For example (assuming @people is an array of Person objects):
-
#
-
# <%= content_tag_for(:tr, @people) do |person| %>
-
# <td><%= person.first_name %></td>
-
# <td><%= person.last_name %></td>
-
# <% end %>
-
#
-
# produces:
-
#
-
# <tr id="person_123" class="person">...</tr>
-
# <tr id="person_124" class="person">...</tr>
-
#
-
# content_tag_for also accepts a hash of options, which will be converted to
-
# additional HTML attributes. If you specify a <tt>:class</tt> value, it will be combined
-
# with the default class name for your object. For example:
-
#
-
# <%= content_tag_for(:li, @person, class: "bar") %>...
-
#
-
# produces:
-
#
-
# <li id="person_123" class="person bar">...
-
#
-
2
def content_tag_for(tag_name, single_or_multiple_records, prefix = nil, options = nil, &block)
-
options, prefix = prefix, nil if prefix.is_a?(Hash)
-
-
Array(single_or_multiple_records).map do |single_record|
-
content_tag_for_single_record(tag_name, single_record, prefix, options, &block)
-
end.join("\n").html_safe
-
end
-
-
2
private
-
-
# Called by <tt>content_tag_for</tt> internally to render a content tag
-
# for each record.
-
2
def content_tag_for_single_record(tag_name, record, prefix, options, &block)
-
options = options ? options.dup : {}
-
options[:class] = [ dom_class(record, prefix), options[:class] ].compact
-
options[:id] = dom_id(record, prefix)
-
-
if block_given?
-
content_tag(tag_name, capture(record, &block), options)
-
else
-
content_tag(tag_name, "", options)
-
end
-
end
-
end
-
end
-
end
-
2
module ActionView
-
2
module Helpers
-
# = Action View Rendering
-
#
-
# Implements methods that allow rendering from a view context.
-
# In order to use this module, all you need is to implement
-
# view_renderer that returns an ActionView::Renderer object.
-
2
module RenderingHelper
-
# Returns the result of a render that's dictated by the options hash. The primary options are:
-
#
-
# * <tt>:partial</tt> - See <tt>ActionView::PartialRenderer</tt>.
-
# * <tt>:file</tt> - Renders an explicit template file (this used to be the old default), add :locals to pass in those.
-
# * <tt>:inline</tt> - Renders an inline template similar to how it's done in the controller.
-
# * <tt>:text</tt> - Renders the text passed in out.
-
# * <tt>:plain</tt> - Renders the text passed in out. Setting the content
-
# type as <tt>text/plain</tt>.
-
# * <tt>:html</tt> - Renders the html safe string passed in out, otherwise
-
# performs html escape on the string first. Setting the content type as
-
# <tt>text/html</tt>.
-
# * <tt>:body</tt> - Renders the text passed in, and inherits the content
-
# type of <tt>text/html</tt> from <tt>ActionDispatch::Response</tt>
-
# object.
-
#
-
# If no options hash is passed or :update specified, the default is to render a partial and use the second parameter
-
# as the locals hash.
-
2
def render(options = {}, locals = {}, &block)
-
13
case options
-
when Hash
-
if block_given?
-
view_renderer.render_partial(self, options.merge(:partial => options[:layout]), &block)
-
else
-
view_renderer.render(self, options)
-
end
-
else
-
13
view_renderer.render_partial(self, :partial => options, :locals => locals)
-
end
-
end
-
-
# Overwrites _layout_for in the context object so it supports the case a block is
-
# passed to a partial. Returns the contents that are yielded to a layout, given a
-
# name or a block.
-
#
-
# You can think of a layout as a method that is called with a block. If the user calls
-
# <tt>yield :some_name</tt>, the block, by default, returns <tt>content_for(:some_name)</tt>.
-
# If the user calls simply +yield+, the default block returns <tt>content_for(:layout)</tt>.
-
#
-
# The user can override this default by passing a block to the layout:
-
#
-
# # The template
-
# <%= render layout: "my_layout" do %>
-
# Content
-
# <% end %>
-
#
-
# # The layout
-
# <html>
-
# <%= yield %>
-
# </html>
-
#
-
# In this case, instead of the default block, which would return <tt>content_for(:layout)</tt>,
-
# this method returns the block that was passed in to <tt>render :layout</tt>, and the response
-
# would be
-
#
-
# <html>
-
# Content
-
# </html>
-
#
-
# Finally, the block can take block arguments, which can be passed in by +yield+:
-
#
-
# # The template
-
# <%= render layout: "my_layout" do |customer| %>
-
# Hello <%= customer.name %>
-
# <% end %>
-
#
-
# # The layout
-
# <html>
-
# <%= yield Struct.new(:name).new("David") %>
-
# </html>
-
#
-
# In this case, the layout would receive the block passed into <tt>render :layout</tt>,
-
# and the struct specified would be passed into the block as an argument. The result
-
# would be
-
#
-
# <html>
-
# Hello David
-
# </html>
-
#
-
2
def _layout_for(*args, &block)
-
13
name = args.first
-
-
13
if block && !name.is_a?(Symbol)
-
capture(*args, &block)
-
else
-
13
super
-
end
-
end
-
end
-
end
-
end
-
2
require 'active_support/core_ext/object/try'
-
2
require 'action_view/vendor/html-scanner'
-
-
2
module ActionView
-
# = Action View Sanitize Helpers
-
2
module Helpers
-
# The SanitizeHelper module provides a set of methods for scrubbing text of undesired HTML elements.
-
# These helper methods extend Action View making them callable within your template files.
-
2
module SanitizeHelper
-
2
extend ActiveSupport::Concern
-
# This +sanitize+ helper will html encode all tags and strip all attributes that
-
# aren't specifically allowed.
-
#
-
# It also strips href/src tags with invalid protocols, like javascript: especially.
-
# It does its best to counter any tricks that hackers may use, like throwing in
-
# unicode/ascii/hex values to get past the javascript: filters. Check out
-
# the extensive test suite.
-
#
-
# <%= sanitize @article.body %>
-
#
-
# You can add or remove tags/attributes if you want to customize it a bit.
-
# See ActionView::Base for full docs on the available options. You can add
-
# tags/attributes for single uses of +sanitize+ by passing either the
-
# <tt>:attributes</tt> or <tt>:tags</tt> options:
-
#
-
# Normal Use
-
#
-
# <%= sanitize @article.body %>
-
#
-
# Custom Use (only the mentioned tags and attributes are allowed, nothing else)
-
#
-
# <%= sanitize @article.body, tags: %w(table tr td), attributes: %w(id class style) %>
-
#
-
# Add table tags to the default allowed tags
-
#
-
# class Application < Rails::Application
-
# config.action_view.sanitized_allowed_tags = ['table', 'tr', 'td']
-
# end
-
#
-
# Remove tags to the default allowed tags
-
#
-
# class Application < Rails::Application
-
# config.after_initialize do
-
# ActionView::Base.sanitized_allowed_tags.delete 'div'
-
# end
-
# end
-
#
-
# Change allowed default attributes
-
#
-
# class Application < Rails::Application
-
# config.action_view.sanitized_allowed_attributes = ['id', 'class', 'style']
-
# end
-
#
-
# Please note that sanitizing user-provided text does not guarantee that the
-
# resulting markup is valid (conforming to a document type) or even well-formed.
-
# The output may still contain e.g. unescaped '<', '>', '&' characters and
-
# confuse browsers.
-
#
-
2
def sanitize(html, options = {})
-
self.class.white_list_sanitizer.sanitize(html, options).try(:html_safe)
-
end
-
-
# Sanitizes a block of CSS code. Used by +sanitize+ when it comes across a style attribute.
-
2
def sanitize_css(style)
-
self.class.white_list_sanitizer.sanitize_css(style)
-
end
-
-
# Strips all HTML tags from the +html+, including comments. This uses the
-
# html-scanner tokenizer and so its HTML parsing ability is limited by
-
# that of html-scanner.
-
#
-
# strip_tags("Strip <i>these</i> tags!")
-
# # => Strip these tags!
-
#
-
# strip_tags("<b>Bold</b> no more! <a href='more.html'>See more here</a>...")
-
# # => Bold no more! See more here...
-
#
-
# strip_tags("<div id='top-bar'>Welcome to my website!</div>")
-
# # => Welcome to my website!
-
2
def strip_tags(html)
-
self.class.full_sanitizer.sanitize(html)
-
end
-
-
# Strips all link tags from +text+ leaving just the link text.
-
#
-
# strip_links('<a href="http://www.rubyonrails.org">Ruby on Rails</a>')
-
# # => Ruby on Rails
-
#
-
# strip_links('Please e-mail me at <a href="mailto:me@email.com">me@email.com</a>.')
-
# # => Please e-mail me at me@email.com.
-
#
-
# strip_links('Blog: <a href="http://www.myblog.com/" class="nav" target=\"_blank\">Visit</a>.')
-
# # => Blog: Visit.
-
2
def strip_links(html)
-
self.class.link_sanitizer.sanitize(html)
-
end
-
-
2
module ClassMethods #:nodoc:
-
2
attr_writer :full_sanitizer, :link_sanitizer, :white_list_sanitizer
-
-
2
def sanitized_protocol_separator
-
white_list_sanitizer.protocol_separator
-
end
-
-
2
def sanitized_uri_attributes
-
white_list_sanitizer.uri_attributes
-
end
-
-
2
def sanitized_bad_tags
-
white_list_sanitizer.bad_tags
-
end
-
-
2
def sanitized_allowed_tags
-
white_list_sanitizer.allowed_tags
-
end
-
-
2
def sanitized_allowed_attributes
-
white_list_sanitizer.allowed_attributes
-
end
-
-
2
def sanitized_allowed_css_properties
-
white_list_sanitizer.allowed_css_properties
-
end
-
-
2
def sanitized_allowed_css_keywords
-
white_list_sanitizer.allowed_css_keywords
-
end
-
-
2
def sanitized_shorthand_css_properties
-
white_list_sanitizer.shorthand_css_properties
-
end
-
-
2
def sanitized_allowed_protocols
-
white_list_sanitizer.allowed_protocols
-
end
-
-
2
def sanitized_protocol_separator=(value)
-
white_list_sanitizer.protocol_separator = value
-
end
-
-
# Gets the HTML::FullSanitizer instance used by +strip_tags+. Replace with
-
# any object that responds to +sanitize+.
-
#
-
# class Application < Rails::Application
-
# config.action_view.full_sanitizer = MySpecialSanitizer.new
-
# end
-
#
-
2
def full_sanitizer
-
@full_sanitizer ||= HTML::FullSanitizer.new
-
end
-
-
# Gets the HTML::LinkSanitizer instance used by +strip_links+. Replace with
-
# any object that responds to +sanitize+.
-
#
-
# class Application < Rails::Application
-
# config.action_view.link_sanitizer = MySpecialSanitizer.new
-
# end
-
#
-
2
def link_sanitizer
-
@link_sanitizer ||= HTML::LinkSanitizer.new
-
end
-
-
# Gets the HTML::WhiteListSanitizer instance used by sanitize and +sanitize_css+.
-
# Replace with any object that responds to +sanitize+.
-
#
-
# class Application < Rails::Application
-
# config.action_view.white_list_sanitizer = MySpecialSanitizer.new
-
# end
-
#
-
2
def white_list_sanitizer
-
@white_list_sanitizer ||= HTML::WhiteListSanitizer.new
-
end
-
-
# Adds valid HTML attributes that the +sanitize+ helper checks for URIs.
-
#
-
# class Application < Rails::Application
-
# config.action_view.sanitized_uri_attributes = ['lowsrc', 'target']
-
# end
-
#
-
2
def sanitized_uri_attributes=(attributes)
-
HTML::WhiteListSanitizer.uri_attributes.merge(attributes)
-
end
-
-
# Adds to the Set of 'bad' tags for the +sanitize+ helper.
-
#
-
# class Application < Rails::Application
-
# config.action_view.sanitized_bad_tags = ['embed', 'object']
-
# end
-
#
-
2
def sanitized_bad_tags=(attributes)
-
HTML::WhiteListSanitizer.bad_tags.merge(attributes)
-
end
-
-
# Adds to the Set of allowed tags for the +sanitize+ helper.
-
#
-
# class Application < Rails::Application
-
# config.action_view.sanitized_allowed_tags = ['table', 'tr', 'td']
-
# end
-
#
-
2
def sanitized_allowed_tags=(attributes)
-
HTML::WhiteListSanitizer.allowed_tags.merge(attributes)
-
end
-
-
# Adds to the Set of allowed HTML attributes for the +sanitize+ helper.
-
#
-
# class Application < Rails::Application
-
# config.action_view.sanitized_allowed_attributes = ['onclick', 'longdesc']
-
# end
-
#
-
2
def sanitized_allowed_attributes=(attributes)
-
HTML::WhiteListSanitizer.allowed_attributes.merge(attributes)
-
end
-
-
# Adds to the Set of allowed CSS properties for the #sanitize and +sanitize_css+ helpers.
-
#
-
# class Application < Rails::Application
-
# config.action_view.sanitized_allowed_css_properties = ['expression']
-
# end
-
#
-
2
def sanitized_allowed_css_properties=(attributes)
-
HTML::WhiteListSanitizer.allowed_css_properties.merge(attributes)
-
end
-
-
# Adds to the Set of allowed CSS keywords for the +sanitize+ and +sanitize_css+ helpers.
-
#
-
# class Application < Rails::Application
-
# config.action_view.sanitized_allowed_css_keywords = ['expression']
-
# end
-
#
-
2
def sanitized_allowed_css_keywords=(attributes)
-
HTML::WhiteListSanitizer.allowed_css_keywords.merge(attributes)
-
end
-
-
# Adds to the Set of allowed shorthand CSS properties for the +sanitize+ and +sanitize_css+ helpers.
-
#
-
# class Application < Rails::Application
-
# config.action_view.sanitized_shorthand_css_properties = ['expression']
-
# end
-
#
-
2
def sanitized_shorthand_css_properties=(attributes)
-
HTML::WhiteListSanitizer.shorthand_css_properties.merge(attributes)
-
end
-
-
# Adds to the Set of allowed protocols for the +sanitize+ helper.
-
#
-
# class Application < Rails::Application
-
# config.action_view.sanitized_allowed_protocols = ['ssh', 'feed']
-
# end
-
#
-
2
def sanitized_allowed_protocols=(attributes)
-
HTML::WhiteListSanitizer.allowed_protocols.merge(attributes)
-
end
-
end
-
end
-
end
-
end
-
2
require 'active_support/core_ext/string/output_safety'
-
2
require 'set'
-
-
2
module ActionView
-
# = Action View Tag Helpers
-
2
module Helpers #:nodoc:
-
# Provides methods to generate HTML tags programmatically when you can't use
-
# a Builder. By default, they output XHTML compliant tags.
-
2
module TagHelper
-
2
extend ActiveSupport::Concern
-
2
include CaptureHelper
-
-
2
BOOLEAN_ATTRIBUTES = %w(disabled readonly multiple checked autobuffer
-
autoplay controls loop selected hidden scoped async
-
defer reversed ismap seamless muted required
-
autofocus novalidate formnovalidate open pubdate
-
itemscope allowfullscreen default inert sortable
-
truespeed typemustmatch).to_set
-
-
62
BOOLEAN_ATTRIBUTES.merge(BOOLEAN_ATTRIBUTES.map {|attribute| attribute.to_sym })
-
-
2
PRE_CONTENT_STRINGS = {
-
:textarea => "\n"
-
}
-
-
# Returns an empty HTML tag of type +name+ which by default is XHTML
-
# compliant. Set +open+ to true to create an open tag compatible
-
# with HTML 4.0 and below. Add HTML attributes by passing an attributes
-
# hash to +options+. Set +escape+ to false to disable attribute value
-
# escaping.
-
#
-
# ==== Options
-
# You can use symbols or strings for the attribute names.
-
#
-
# Use +true+ with boolean attributes that can render with no value, like
-
# +disabled+ and +readonly+.
-
#
-
# HTML5 <tt>data-*</tt> attributes can be set with a single +data+ key
-
# pointing to a hash of sub-attributes.
-
#
-
# To play nicely with JavaScript conventions sub-attributes are dasherized.
-
# For example, a key +user_id+ would render as <tt>data-user-id</tt> and
-
# thus accessed as <tt>dataset.userId</tt>.
-
#
-
# Values are encoded to JSON, with the exception of strings and symbols.
-
# This may come in handy when using jQuery's HTML5-aware <tt>.data()</tt>
-
# from 1.4.3.
-
#
-
# ==== Examples
-
# tag("br")
-
# # => <br />
-
#
-
# tag("br", nil, true)
-
# # => <br>
-
#
-
# tag("input", type: 'text', disabled: true)
-
# # => <input type="text" disabled="disabled" />
-
#
-
# tag("img", src: "open & shut.png")
-
# # => <img src="open & shut.png" />
-
#
-
# tag("img", {src: "open & shut.png"}, false, false)
-
# # => <img src="open & shut.png" />
-
#
-
# tag("div", data: {name: 'Stephen', city_state: %w(Chicago IL)})
-
# # => <div data-name="Stephen" data-city-state="["Chicago","IL"]" />
-
2
def tag(name, options = nil, open = false, escape = true)
-
87
"<#{name}#{tag_options(options, escape) if options}#{open ? ">" : " />"}".html_safe
-
end
-
-
# Returns an HTML block tag of type +name+ surrounding the +content+. Add
-
# HTML attributes by passing an attributes hash to +options+.
-
# Instead of passing the content as an argument, you can also use a block
-
# in which case, you pass your +options+ as the second parameter.
-
# Set escape to false to disable attribute value escaping.
-
#
-
# ==== Options
-
# The +options+ hash is used with attributes with no value like (<tt>disabled</tt> and
-
# <tt>readonly</tt>), which you can give a value of true in the +options+ hash. You can use
-
# symbols or strings for the attribute names.
-
#
-
# ==== Examples
-
# content_tag(:p, "Hello world!")
-
# # => <p>Hello world!</p>
-
# content_tag(:div, content_tag(:p, "Hello world!"), class: "strong")
-
# # => <div class="strong"><p>Hello world!</p></div>
-
# content_tag("select", options, multiple: true)
-
# # => <select multiple="multiple">...options...</select>
-
#
-
# <%= content_tag :div, class: "strong" do -%>
-
# Hello world!
-
# <% end -%>
-
# # => <div class="strong">Hello world!</div>
-
2
def content_tag(name, content_or_options_with_block = nil, options = nil, escape = true, &block)
-
88
if block_given?
-
options = content_or_options_with_block if content_or_options_with_block.is_a?(Hash)
-
content_tag_string(name, capture(&block), options, escape)
-
else
-
88
content_tag_string(name, content_or_options_with_block, options, escape)
-
end
-
end
-
-
# Returns a CDATA section with the given +content+. CDATA sections
-
# are used to escape blocks of text containing characters which would
-
# otherwise be recognized as markup. CDATA sections begin with the string
-
# <tt><![CDATA[</tt> and end with (and may not contain) the string <tt>]]></tt>.
-
#
-
# cdata_section("<hello world>")
-
# # => <![CDATA[<hello world>]]>
-
#
-
# cdata_section(File.read("hello_world.txt"))
-
# # => <![CDATA[<hello from a text file]]>
-
#
-
# cdata_section("hello]]>world")
-
# # => <![CDATA[hello]]]]><![CDATA[>world]]>
-
2
def cdata_section(content)
-
splitted = content.to_s.gsub(']]>', ']]]]><![CDATA[>')
-
"<![CDATA[#{splitted}]]>".html_safe
-
end
-
-
# Returns an escaped version of +html+ without affecting existing escaped entities.
-
#
-
# escape_once("1 < 2 & 3")
-
# # => "1 < 2 & 3"
-
#
-
# escape_once("<< Accept & Checkout")
-
# # => "<< Accept & Checkout"
-
2
def escape_once(html)
-
ERB::Util.html_escape_once(html)
-
end
-
-
2
private
-
-
2
def content_tag_string(name, content, options, escape = true)
-
96
tag_options = tag_options(options, escape) if options
-
96
content = ERB::Util.h(content) if escape
-
96
"<#{name}#{tag_options}>#{PRE_CONTENT_STRINGS[name.to_sym]}#{content}</#{name}>".html_safe
-
end
-
-
2
def tag_options(options, escape = true)
-
183
return if options.blank?
-
183
attrs = []
-
183
options.each_pair do |key, value|
-
608
if key.to_s == 'data' && value.is_a?(Hash)
-
value.each_pair do |k, v|
-
attrs << data_tag_option(k, v, escape)
-
end
-
elsif BOOLEAN_ATTRIBUTES.include?(key)
-
16
attrs << boolean_tag_option(key) if value
-
elsif !value.nil?
-
532
attrs << tag_option(key, value, escape)
-
end
-
end
-
183
" #{attrs.sort! * ' '}" unless attrs.empty?
-
end
-
-
2
def data_tag_option(key, value, escape)
-
key = "data-#{key.to_s.dasherize}"
-
unless value.is_a?(String) || value.is_a?(Symbol) || value.is_a?(BigDecimal)
-
value = value.to_json
-
end
-
tag_option(key, value, escape)
-
end
-
-
2
def boolean_tag_option(key)
-
%(#{key}="#{key}")
-
end
-
-
2
def tag_option(key, value, escape)
-
532
value = value.join(" ") if value.is_a?(Array)
-
532
value = ERB::Util.h(value) if escape
-
532
%(#{key}="#{value}")
-
end
-
end
-
end
-
end
-
1
module ActionView
-
1
module Helpers
-
1
module Tags #:nodoc:
-
1
extend ActiveSupport::Autoload
-
-
1
eager_autoload do
-
1
autoload :Base
-
1
autoload :CheckBox
-
1
autoload :CollectionCheckBoxes
-
1
autoload :CollectionRadioButtons
-
1
autoload :CollectionSelect
-
1
autoload :ColorField
-
1
autoload :DateField
-
1
autoload :DateSelect
-
1
autoload :DatetimeField
-
1
autoload :DatetimeLocalField
-
1
autoload :DatetimeSelect
-
1
autoload :EmailField
-
1
autoload :FileField
-
1
autoload :GroupedCollectionSelect
-
1
autoload :HiddenField
-
1
autoload :Label
-
1
autoload :MonthField
-
1
autoload :NumberField
-
1
autoload :PasswordField
-
1
autoload :RadioButton
-
1
autoload :RangeField
-
1
autoload :SearchField
-
1
autoload :Select
-
1
autoload :TelField
-
1
autoload :TextArea
-
1
autoload :TextField
-
1
autoload :TimeField
-
1
autoload :TimeSelect
-
1
autoload :TimeZoneSelect
-
1
autoload :UrlField
-
1
autoload :WeekField
-
end
-
end
-
end
-
end
-
1
module ActionView
-
1
module Helpers
-
1
module Tags # :nodoc:
-
1
class Base # :nodoc:
-
1
include Helpers::ActiveModelInstanceTag, Helpers::TagHelper, Helpers::FormTagHelper
-
1
include FormOptionsHelper
-
-
1
attr_reader :object
-
-
1
def initialize(object_name, method_name, template_object, options = {})
-
48
@object_name, @method_name = object_name.to_s.dup, method_name.to_s.dup
-
48
@template_object = template_object
-
-
48
@object_name.sub!(/\[\]$/,"") || @object_name.sub!(/\[\]\]$/,"]")
-
48
@object = retrieve_object(options.delete(:object))
-
48
@options = options
-
48
@auto_index = retrieve_autoindex(Regexp.last_match.pre_match) if Regexp.last_match
-
end
-
-
# This is what child classes implement.
-
1
def render
-
raise NotImplementedError, "Subclasses must implement a render method"
-
end
-
-
1
private
-
-
1
def value(object)
-
8
object.public_send @method_name if object
-
end
-
-
1
def value_before_type_cast(object)
-
17
unless object.nil?
-
12
method_before_type_cast = @method_name + "_before_type_cast"
-
-
12
object.respond_to?(method_before_type_cast) ?
-
object.send(method_before_type_cast) :
-
value(object)
-
end
-
end
-
-
1
def retrieve_object(object)
-
48
if object
-
28
object
-
20
elsif @template_object.instance_variable_defined?("@#{@object_name}")
-
@template_object.instance_variable_get("@#{@object_name}")
-
end
-
rescue NameError
-
# As @object_name may contain the nested syntax (item[subobject]) we need to fallback to nil.
-
nil
-
end
-
-
1
def retrieve_autoindex(pre_match)
-
object = self.object || @template_object.instance_variable_get("@#{pre_match}")
-
if object && object.respond_to?(:to_param)
-
object.to_param
-
else
-
raise ArgumentError, "object[] naming but object param and @object var don't exist or don't respond to to_param: #{object.inspect}"
-
end
-
end
-
-
1
def add_default_name_and_id_for_value(tag_value, options)
-
10
if tag_value.nil?
-
10
add_default_name_and_id(options)
-
else
-
specified_id = options["id"]
-
add_default_name_and_id(options)
-
-
if specified_id.blank? && options["id"].present?
-
options["id"] += "_#{sanitized_value(tag_value)}"
-
end
-
end
-
end
-
-
1
def add_default_name_and_id(options)
-
48
if options.has_key?("index")
-
options["name"] ||= options.fetch("name"){ tag_name_with_index(options["index"], options["multiple"]) }
-
options["id"] = options.fetch("id"){ tag_id_with_index(options["index"]) }
-
options.delete("index")
-
elsif defined?(@auto_index)
-
options["name"] ||= options.fetch("name"){ tag_name_with_index(@auto_index, options["multiple"]) }
-
options["id"] = options.fetch("id"){ tag_id_with_index(@auto_index) }
-
else
-
96
options["name"] ||= options.fetch("name"){ tag_name(options["multiple"]) }
-
96
options["id"] = options.fetch("id"){ tag_id }
-
end
-
-
48
options["id"] = [options.delete('namespace'), options["id"]].compact.join("_").presence
-
end
-
-
1
def tag_name(multiple = false)
-
48
"#{@object_name}[#{sanitized_method_name}]#{"[]" if multiple}"
-
end
-
-
1
def tag_name_with_index(index, multiple = false)
-
"#{@object_name}[#{index}][#{sanitized_method_name}]#{"[]" if multiple}"
-
end
-
-
1
def tag_id
-
48
"#{sanitized_object_name}_#{sanitized_method_name}"
-
end
-
-
1
def tag_id_with_index(index)
-
"#{sanitized_object_name}_#{index}_#{sanitized_method_name}"
-
end
-
-
1
def sanitized_object_name
-
48
@sanitized_object_name ||= @object_name.gsub(/\]\[|[^-a-zA-Z0-9:.]/, "_").sub(/_$/, "")
-
end
-
-
1
def sanitized_method_name
-
96
@sanitized_method_name ||= @method_name.sub(/\?$/,"")
-
end
-
-
1
def sanitized_value(value)
-
value.to_s.gsub(/\s/, "_").gsub(/[^-\w]/, "").downcase
-
end
-
-
1
def select_content_tag(option_tags, options, html_options)
-
4
html_options = html_options.stringify_keys
-
4
add_default_name_and_id(html_options)
-
4
options[:include_blank] ||= true unless options[:prompt] || select_not_required?(html_options)
-
8
value = options.fetch(:selected) { value(object) }
-
4
select = content_tag("select", add_options(option_tags, options, value), html_options)
-
-
4
if html_options["multiple"] && options.fetch(:include_hidden, true)
-
tag("input", :disabled => html_options["disabled"], :name => html_options["name"], :type => "hidden", :value => "") + select
-
else
-
4
select
-
end
-
end
-
-
1
def select_not_required?(html_options)
-
4
!html_options["required"] || html_options["multiple"] || html_options["size"].to_i > 1
-
end
-
-
1
def add_options(option_tags, options, value = nil)
-
4
if options[:include_blank]
-
option_tags = content_tag_string('option', options[:include_blank].kind_of?(String) ? options[:include_blank] : nil, :value => '') + "\n" + option_tags
-
end
-
4
if value.blank? && options[:prompt]
-
option_tags = content_tag_string('option', prompt_text(options[:prompt]), :value => '') + "\n" + option_tags
-
end
-
4
option_tags
-
end
-
end
-
end
-
end
-
end
-
1
module ActionView
-
1
module Helpers
-
1
module Tags # :nodoc:
-
1
class FileField < TextField # :nodoc:
-
end
-
end
-
end
-
end
-
1
module ActionView
-
1
module Helpers
-
1
module Tags # :nodoc:
-
1
class Label < Base # :nodoc:
-
1
def initialize(object_name, method_name, template_object, content_or_options = nil, options = nil)
-
10
options ||= {}
-
-
10
content_is_options = content_or_options.is_a?(Hash)
-
10
if content_is_options
-
options.merge! content_or_options
-
@content = nil
-
else
-
10
@content = content_or_options
-
end
-
-
10
super(object_name, method_name, template_object, options)
-
end
-
-
1
def render(&block)
-
10
options = @options.stringify_keys
-
10
tag_value = options.delete("value")
-
10
name_and_id = options.dup
-
-
10
if name_and_id["for"]
-
name_and_id["id"] = name_and_id["for"]
-
else
-
10
name_and_id.delete("id")
-
end
-
-
10
add_default_name_and_id_for_value(tag_value, name_and_id)
-
10
options.delete("index")
-
10
options.delete("namespace")
-
10
options["for"] = name_and_id["id"] unless options.key?("for")
-
-
10
if block_given?
-
content = @template_object.capture(&block)
-
else
-
10
content = if @content.blank?
-
10
@object_name.gsub!(/\[(.*)_attributes\]\[\d+\]/, '.\1')
-
10
method_and_value = tag_value.present? ? "#{@method_name}.#{tag_value}" : @method_name
-
-
10
if object.respond_to?(:to_model)
-
key = object.class.model_name.i18n_key
-
i18n_default = ["#{key}.#{method_and_value}".to_sym, ""]
-
end
-
-
10
i18n_default ||= ""
-
10
I18n.t("#{@object_name}.#{method_and_value}", :default => i18n_default, :scope => "helpers.label").presence
-
else
-
@content.to_s
-
end
-
-
content ||= if object && object.class.respond_to?(:human_attribute_name)
-
object.class.human_attribute_name(@method_name)
-
10
end
-
-
10
content ||= @method_name.humanize
-
end
-
-
10
label_tag(name_and_id["id"], content, options)
-
end
-
end
-
end
-
end
-
end
-
1
module ActionView
-
1
module Helpers
-
1
module Tags # :nodoc:
-
1
class PasswordField < TextField # :nodoc:
-
1
def render
-
13
@options = {:value => nil}.merge!(@options)
-
13
super
-
end
-
end
-
end
-
end
-
end
-
1
module ActionView
-
1
module Helpers
-
1
module Tags # :nodoc:
-
1
class Select < Base # :nodoc:
-
1
def initialize(object_name, method_name, template_object, choices, options, html_options)
-
4
@choices = block_given? ? template_object.capture { yield || "" } : choices
-
4
@choices = @choices.to_a if @choices.is_a?(Range)
-
-
4
@html_options = html_options
-
-
4
super(object_name, method_name, template_object, options)
-
end
-
-
1
def render
-
4
option_tags_options = {
-
4
:selected => @options.fetch(:selected) { value(@object) },
-
:disabled => @options[:disabled]
-
}
-
-
4
option_tags = if grouped_choices?
-
grouped_options_for_select(@choices, option_tags_options)
-
else
-
4
options_for_select(@choices, option_tags_options)
-
end
-
-
4
select_content_tag(option_tags, @options, @html_options)
-
end
-
-
1
private
-
-
# Grouped choices look like this:
-
#
-
# [nil, []]
-
# { nil => [] }
-
1
def grouped_choices?
-
4
!@choices.empty? && @choices.first.respond_to?(:last) && Array === @choices.first.last
-
end
-
end
-
end
-
end
-
end
-
1
module ActionView
-
1
module Helpers
-
1
module Tags # :nodoc:
-
1
class TextField < Base # :nodoc:
-
1
def render
-
34
options = @options.stringify_keys
-
34
options["size"] = options["maxlength"] unless options.key?("size")
-
34
options["type"] ||= field_type
-
51
options["value"] = options.fetch("value") { value_before_type_cast(object) } unless field_type == "file"
-
34
options["value"] &&= ERB::Util.html_escape(options["value"])
-
34
add_default_name_and_id(options)
-
34
tag("input", options)
-
end
-
-
1
class << self
-
1
def field_type
-
68
@field_type ||= self.name.split("::").last.sub("Field", "").downcase
-
end
-
end
-
-
1
private
-
-
1
def field_type
-
68
self.class.field_type
-
end
-
end
-
end
-
end
-
end
-
2
require 'active_support/core_ext/string/filters'
-
2
require 'active_support/core_ext/array/extract_options'
-
-
2
module ActionView
-
# = Action View Text Helpers
-
2
module Helpers #:nodoc:
-
# The TextHelper module provides a set of methods for filtering, formatting
-
# and transforming strings, which can reduce the amount of inline Ruby code in
-
# your views. These helper methods extend Action View making them callable
-
# within your template files.
-
#
-
# ==== Sanitization
-
#
-
# Most text helpers by default sanitize the given content, but do not escape it.
-
# This means HTML tags will appear in the page but all malicious code will be removed.
-
# Let's look at some examples using the +simple_format+ method:
-
#
-
# simple_format('<a href="http://example.com/">Example</a>')
-
# # => "<p><a href=\"http://example.com/\">Example</a></p>"
-
#
-
# simple_format('<a href="javascript:alert(\'no!\')">Example</a>')
-
# # => "<p><a>Example</a></p>"
-
#
-
# If you want to escape all content, you should invoke the +h+ method before
-
# calling the text helper.
-
#
-
# simple_format h('<a href="http://example.com/">Example</a>')
-
# # => "<p><a href=\"http://example.com/\">Example</a></p>"
-
2
module TextHelper
-
2
extend ActiveSupport::Concern
-
-
2
include SanitizeHelper
-
2
include TagHelper
-
2
include OutputSafetyHelper
-
-
# The preferred method of outputting text in your views is to use the
-
# <%= "text" %> eRuby syntax. The regular _puts_ and _print_ methods
-
# do not operate as expected in an eRuby code block. If you absolutely must
-
# output text within a non-output code block (i.e., <% %>), you can use the concat method.
-
#
-
# <%
-
# concat "hello"
-
# # is the equivalent of <%= "hello" %>
-
#
-
# if logged_in
-
# concat "Logged in!"
-
# else
-
# concat link_to('login', action: :login)
-
# end
-
# # will either display "Logged in!" or a login link
-
# %>
-
2
def concat(string)
-
output_buffer << string
-
end
-
-
2
def safe_concat(string)
-
output_buffer.respond_to?(:safe_concat) ? output_buffer.safe_concat(string) : concat(string)
-
end
-
-
# Truncates a given +text+ after a given <tt>:length</tt> if +text+ is longer than <tt>:length</tt>
-
# (defaults to 30). The last characters will be replaced with the <tt>:omission</tt> (defaults to "...")
-
# for a total length not exceeding <tt>:length</tt>.
-
#
-
# Pass a <tt>:separator</tt> to truncate +text+ at a natural break.
-
#
-
# Pass a block if you want to show extra content when the text is truncated.
-
#
-
# The result is marked as HTML-safe, but it is escaped by default, unless <tt>:escape</tt> is
-
# +false+. Care should be taken if +text+ contains HTML tags or entities, because truncation
-
# may produce invalid HTML (such as unbalanced or incomplete tags).
-
#
-
# truncate("Once upon a time in a world far far away")
-
# # => "Once upon a time in a world..."
-
#
-
# truncate("Once upon a time in a world far far away", length: 17)
-
# # => "Once upon a ti..."
-
#
-
# truncate("Once upon a time in a world far far away", length: 17, separator: ' ')
-
# # => "Once upon a..."
-
#
-
# truncate("And they found that many people were sleeping better.", length: 25, omission: '... (continued)')
-
# # => "And they f... (continued)"
-
#
-
# truncate("<p>Once upon a time in a world far far away</p>")
-
# # => "<p>Once upon a time in a wo..."
-
#
-
# truncate("<p>Once upon a time in a world far far away</p>", escape: false)
-
# # => "<p>Once upon a time in a wo..."
-
#
-
# truncate("Once upon a time in a world far far away") { link_to "Continue", "#" }
-
# # => "Once upon a time in a wo...<a href="#">Continue</a>"
-
2
def truncate(text, options = {}, &block)
-
if text
-
length = options.fetch(:length, 30)
-
-
content = text.truncate(length, options)
-
content = options[:escape] == false ? content.html_safe : ERB::Util.html_escape(content)
-
content << capture(&block) if block_given? && text.length > length
-
content
-
end
-
end
-
-
# Highlights one or more +phrases+ everywhere in +text+ by inserting it into
-
# a <tt>:highlighter</tt> string. The highlighter can be specialized by passing <tt>:highlighter</tt>
-
# as a single-quoted string with <tt>\1</tt> where the phrase is to be inserted (defaults to
-
# '<mark>\1</mark>')
-
#
-
# highlight('You searched for: rails', 'rails')
-
# # => You searched for: <mark>rails</mark>
-
#
-
# highlight('You searched for: ruby, rails, dhh', 'actionpack')
-
# # => You searched for: ruby, rails, dhh
-
#
-
# highlight('You searched for: rails', ['for', 'rails'], highlighter: '<em>\1</em>')
-
# # => You searched <em>for</em>: <em>rails</em>
-
#
-
# highlight('You searched for: rails', 'rails', highlighter: '<a href="search?q=\1">\1</a>')
-
# # => You searched for: <a href="search?q=rails">rails</a>
-
2
def highlight(text, phrases, options = {})
-
text = sanitize(text) if options.fetch(:sanitize, true)
-
-
if text.blank? || phrases.blank?
-
text
-
else
-
highlighter = options.fetch(:highlighter, '<mark>\1</mark>')
-
match = Array(phrases).map { |p| Regexp.escape(p) }.join('|')
-
text.gsub(/(#{match})(?![^<]*?>)/i, highlighter)
-
end.html_safe
-
end
-
-
# Extracts an excerpt from +text+ that matches the first instance of +phrase+.
-
# The <tt>:radius</tt> option expands the excerpt on each side of the first occurrence of +phrase+ by the number of characters
-
# defined in <tt>:radius</tt> (which defaults to 100). If the excerpt radius overflows the beginning or end of the +text+,
-
# then the <tt>:omission</tt> option (which defaults to "...") will be prepended/appended accordingly. Use the
-
# <tt>:separator</tt> option to choose the delimitation. The resulting string will be stripped in any case. If the +phrase+
-
# isn't found, nil is returned.
-
#
-
# excerpt('This is an example', 'an', radius: 5)
-
# # => ...s is an exam...
-
#
-
# excerpt('This is an example', 'is', radius: 5)
-
# # => This is a...
-
#
-
# excerpt('This is an example', 'is')
-
# # => This is an example
-
#
-
# excerpt('This next thing is an example', 'ex', radius: 2)
-
# # => ...next...
-
#
-
# excerpt('This is also an example', 'an', radius: 8, omission: '<chop> ')
-
# # => <chop> is also an example
-
#
-
# excerpt('This is a very beautiful morning', 'very', separator: ' ', radius: 1)
-
# # => ...a very beautiful...
-
2
def excerpt(text, phrase, options = {})
-
return unless text && phrase
-
-
separator = options[:separator] || ''
-
phrase = Regexp.escape(phrase)
-
regex = /#{phrase}/i
-
-
return unless matches = text.match(regex)
-
phrase = matches[0]
-
-
unless separator.empty?
-
text.split(separator).each do |value|
-
if value.match(regex)
-
regex = phrase = value
-
break
-
end
-
end
-
end
-
-
first_part, second_part = text.split(regex, 2)
-
-
prefix, first_part = cut_excerpt_part(:first, first_part, separator, options)
-
postfix, second_part = cut_excerpt_part(:second, second_part, separator, options)
-
-
affix = [first_part, separator, phrase, separator, second_part].join.strip
-
[prefix, affix, postfix].join
-
end
-
-
# Attempts to pluralize the +singular+ word unless +count+ is 1. If
-
# +plural+ is supplied, it will use that when count is > 1, otherwise
-
# it will use the Inflector to determine the plural form.
-
#
-
# pluralize(1, 'person')
-
# # => 1 person
-
#
-
# pluralize(2, 'person')
-
# # => 2 people
-
#
-
# pluralize(3, 'person', 'users')
-
# # => 3 users
-
#
-
# pluralize(0, 'person')
-
# # => 0 people
-
2
def pluralize(count, singular, plural = nil)
-
word = if (count == 1 || count =~ /^1(\.0+)?$/)
-
singular
-
else
-
plural || singular.pluralize
-
end
-
-
"#{count || 0} #{word}"
-
end
-
-
# Wraps the +text+ into lines no longer than +line_width+ width. This method
-
# breaks on the first whitespace character that does not exceed +line_width+
-
# (which is 80 by default).
-
#
-
# word_wrap('Once upon a time')
-
# # => Once upon a time
-
#
-
# word_wrap('Once upon a time, in a kingdom called Far Far Away, a king fell ill, and finding a successor to the throne turned out to be more trouble than anyone could have imagined...')
-
# # => Once upon a time, in a kingdom called Far Far Away, a king fell ill, and finding\na successor to the throne turned out to be more trouble than anyone could have\nimagined...
-
#
-
# word_wrap('Once upon a time', line_width: 8)
-
# # => Once\nupon a\ntime
-
#
-
# word_wrap('Once upon a time', line_width: 1)
-
# # => Once\nupon\na\ntime
-
2
def word_wrap(text, options = {})
-
line_width = options.fetch(:line_width, 80)
-
-
text.split("\n").collect! do |line|
-
line.length > line_width ? line.gsub(/(.{1,#{line_width}})(\s+|$)/, "\\1\n").strip : line
-
end * "\n"
-
end
-
-
# Returns +text+ transformed into HTML using simple formatting rules.
-
# Two or more consecutive newlines(<tt>\n\n</tt>) are considered as a
-
# paragraph and wrapped in <tt><p></tt> tags. One newline (<tt>\n</tt>) is
-
# considered as a linebreak and a <tt><br /></tt> tag is appended. This
-
# method does not remove the newlines from the +text+.
-
#
-
# You can pass any HTML attributes into <tt>html_options</tt>. These
-
# will be added to all created paragraphs.
-
#
-
# ==== Options
-
# * <tt>:sanitize</tt> - If +false+, does not sanitize +text+.
-
# * <tt>:wrapper_tag</tt> - String representing the wrapper tag, defaults to <tt>"p"</tt>
-
#
-
# ==== Examples
-
# my_text = "Here is some basic text...\n...with a line break."
-
#
-
# simple_format(my_text)
-
# # => "<p>Here is some basic text...\n<br />...with a line break.</p>"
-
#
-
# simple_format(my_text, {}, wrapper_tag: "div")
-
# # => "<div>Here is some basic text...\n<br />...with a line break.</div>"
-
#
-
# more_text = "We want to put a paragraph...\n\n...right there."
-
#
-
# simple_format(more_text)
-
# # => "<p>We want to put a paragraph...</p>\n\n<p>...right there.</p>"
-
#
-
# simple_format("Look ma! A class!", class: 'description')
-
# # => "<p class='description'>Look ma! A class!</p>"
-
#
-
# simple_format("<blink>Unblinkable.</blink>")
-
# # => "<p>Unblinkable.</p>"
-
#
-
# simple_format("<blink>Blinkable!</blink> It's true.", {}, sanitize: false)
-
# # => "<p><blink>Blinkable!</blink> It's true.</p>"
-
2
def simple_format(text, html_options = {}, options = {})
-
wrapper_tag = options.fetch(:wrapper_tag, :p)
-
-
text = sanitize(text) if options.fetch(:sanitize, true)
-
paragraphs = split_paragraphs(text)
-
-
if paragraphs.empty?
-
content_tag(wrapper_tag, nil, html_options)
-
else
-
paragraphs.map! { |paragraph|
-
content_tag(wrapper_tag, raw(paragraph), html_options)
-
}.join("\n\n").html_safe
-
end
-
end
-
-
# Creates a Cycle object whose _to_s_ method cycles through elements of an
-
# array every time it is called. This can be used for example, to alternate
-
# classes for table rows. You can use named cycles to allow nesting in loops.
-
# Passing a Hash as the last parameter with a <tt>:name</tt> key will create a
-
# named cycle. The default name for a cycle without a +:name+ key is
-
# <tt>"default"</tt>. You can manually reset a cycle by calling reset_cycle
-
# and passing the name of the cycle. The current cycle string can be obtained
-
# anytime using the current_cycle method.
-
#
-
# # Alternate CSS classes for even and odd numbers...
-
# @items = [1,2,3,4]
-
# <table>
-
# <% @items.each do |item| %>
-
# <tr class="<%= cycle("odd", "even") -%>">
-
# <td>item</td>
-
# </tr>
-
# <% end %>
-
# </table>
-
#
-
#
-
# # Cycle CSS classes for rows, and text colors for values within each row
-
# @items = x = [{first: 'Robert', middle: 'Daniel', last: 'James'},
-
# {first: 'Emily', middle: 'Shannon', maiden: 'Pike', last: 'Hicks'},
-
# {first: 'June', middle: 'Dae', last: 'Jones'}]
-
# <% @items.each do |item| %>
-
# <tr class="<%= cycle("odd", "even", name: "row_class") -%>">
-
# <td>
-
# <% item.values.each do |value| %>
-
# <%# Create a named cycle "colors" %>
-
# <span style="color:<%= cycle("red", "green", "blue", name: "colors") -%>">
-
# <%= value %>
-
# </span>
-
# <% end %>
-
# <% reset_cycle("colors") %>
-
# </td>
-
# </tr>
-
# <% end %>
-
2
def cycle(first_value, *values)
-
options = values.extract_options!
-
name = options.fetch(:name, 'default')
-
-
values.unshift(*first_value)
-
-
cycle = get_cycle(name)
-
unless cycle && cycle.values == values
-
cycle = set_cycle(name, Cycle.new(*values))
-
end
-
cycle.to_s
-
end
-
-
# Returns the current cycle string after a cycle has been started. Useful
-
# for complex table highlighting or any other design need which requires
-
# the current cycle string in more than one place.
-
#
-
# # Alternate background colors
-
# @items = [1,2,3,4]
-
# <% @items.each do |item| %>
-
# <div style="background-color:<%= cycle("red","white","blue") %>">
-
# <span style="background-color:<%= current_cycle %>"><%= item %></span>
-
# </div>
-
# <% end %>
-
2
def current_cycle(name = "default")
-
cycle = get_cycle(name)
-
cycle.current_value if cycle
-
end
-
-
# Resets a cycle so that it starts from the first element the next time
-
# it is called. Pass in +name+ to reset a named cycle.
-
#
-
# # Alternate CSS classes for even and odd numbers...
-
# @items = [[1,2,3,4], [5,6,3], [3,4,5,6,7,4]]
-
# <table>
-
# <% @items.each do |item| %>
-
# <tr class="<%= cycle("even", "odd") -%>">
-
# <% item.each do |value| %>
-
# <span style="color:<%= cycle("#333", "#666", "#999", name: "colors") -%>">
-
# <%= value %>
-
# </span>
-
# <% end %>
-
#
-
# <% reset_cycle("colors") %>
-
# </tr>
-
# <% end %>
-
# </table>
-
2
def reset_cycle(name = "default")
-
cycle = get_cycle(name)
-
cycle.reset if cycle
-
end
-
-
2
class Cycle #:nodoc:
-
2
attr_reader :values
-
-
2
def initialize(first_value, *values)
-
@values = values.unshift(first_value)
-
reset
-
end
-
-
2
def reset
-
@index = 0
-
end
-
-
2
def current_value
-
@values[previous_index].to_s
-
end
-
-
2
def to_s
-
value = @values[@index].to_s
-
@index = next_index
-
return value
-
end
-
-
2
private
-
-
2
def next_index
-
step_index(1)
-
end
-
-
2
def previous_index
-
step_index(-1)
-
end
-
-
2
def step_index(n)
-
(@index + n) % @values.size
-
end
-
end
-
-
2
private
-
# The cycle helpers need to store the cycles in a place that is
-
# guaranteed to be reset every time a page is rendered, so it
-
# uses an instance variable of ActionView::Base.
-
2
def get_cycle(name)
-
@_cycles = Hash.new unless defined?(@_cycles)
-
return @_cycles[name]
-
end
-
-
2
def set_cycle(name, cycle_object)
-
@_cycles = Hash.new unless defined?(@_cycles)
-
@_cycles[name] = cycle_object
-
end
-
-
2
def split_paragraphs(text)
-
return [] if text.blank?
-
-
text.to_str.gsub(/\r\n?/, "\n").split(/\n\n+/).map! do |t|
-
t.gsub!(/([^\n]\n)(?=[^\n])/, '\1<br />') || t
-
end
-
end
-
-
2
def cut_excerpt_part(part_position, part, separator, options)
-
return "", "" unless part
-
-
radius = options.fetch(:radius, 100)
-
omission = options.fetch(:omission, "...")
-
-
part = part.split(separator)
-
part.delete("")
-
affix = part.size > radius ? omission : ""
-
-
part = if part_position == :first
-
drop_index = [part.length - radius, 0].max
-
part.drop(drop_index)
-
else
-
part.first(radius)
-
end
-
-
return affix, part.join(separator)
-
end
-
end
-
end
-
end
-
2
require 'action_view/helpers/tag_helper'
-
2
require 'i18n/exceptions'
-
-
2
module ActionView
-
# = Action View Translation Helpers
-
2
module Helpers
-
2
module TranslationHelper
-
2
include TagHelper
-
# Delegates to <tt>I18n#translate</tt> but also performs three additional functions.
-
#
-
# First, it will ensure that any thrown +MissingTranslation+ messages will be turned
-
# into inline spans that:
-
#
-
# * have a "translation-missing" class set,
-
# * contain the missing key as a title attribute and
-
# * a titleized version of the last key segment as a text.
-
#
-
# E.g. the value returned for a missing translation key :"blog.post.title" will be
-
# <span class="translation_missing" title="translation missing: en.blog.post.title">Title</span>.
-
# This way your views will display rather reasonable strings but it will still
-
# be easy to spot missing translations.
-
#
-
# Second, it'll scope the key by the current partial if the key starts
-
# with a period. So if you call <tt>translate(".foo")</tt> from the
-
# <tt>people/index.html.erb</tt> template, you'll actually be calling
-
# <tt>I18n.translate("people.index.foo")</tt>. This makes it less repetitive
-
# to translate many keys within the same partials and gives you a simple framework
-
# for scoping them consistently. If you don't prepend the key with a period,
-
# nothing is converted.
-
#
-
# Third, it'll mark the translation as safe HTML if the key has the suffix
-
# "_html" or the last element of the key is the word "html". For example,
-
# calling translate("footer_html") or translate("footer.html") will return
-
# a safe HTML string that won't be escaped by other HTML helper methods. This
-
# naming convention helps to identify translations that include HTML tags so that
-
# you know what kind of output to expect when you call translate in a template.
-
2
def translate(key, options = {})
-
options[:default] = wrap_translate_defaults(options[:default]) if options[:default]
-
-
# If the user has specified rescue_format then pass it all through, otherwise use
-
# raise and do the work ourselves
-
options[:raise] ||= ActionView::Base.raise_on_missing_translations
-
-
raise_error = options[:raise] || options.key?(:rescue_format)
-
unless raise_error
-
options[:raise] = true
-
end
-
-
if html_safe_translation_key?(key)
-
html_safe_options = options.dup
-
options.except(*I18n::RESERVED_KEYS).each do |name, value|
-
unless name == :count && value.is_a?(Numeric)
-
html_safe_options[name] = ERB::Util.html_escape(value.to_s)
-
end
-
end
-
translation = I18n.translate(scope_key_by_partial(key), html_safe_options)
-
-
translation.respond_to?(:html_safe) ? translation.html_safe : translation
-
else
-
I18n.translate(scope_key_by_partial(key), options)
-
end
-
rescue I18n::MissingTranslationData => e
-
raise e if raise_error
-
-
keys = I18n.normalize_keys(e.locale, e.key, e.options[:scope])
-
content_tag('span', keys.last.to_s.titleize, :class => 'translation_missing', :title => "translation missing: #{keys.join('.')}")
-
end
-
2
alias :t :translate
-
-
# Delegates to <tt>I18n.localize</tt> with no additional functionality.
-
#
-
# See http://rubydoc.info/github/svenfuchs/i18n/master/I18n/Backend/Base:localize
-
# for more information.
-
2
def localize(*args)
-
I18n.localize(*args)
-
end
-
2
alias :l :localize
-
-
2
private
-
2
def scope_key_by_partial(key)
-
if key.to_s.first == "."
-
if @virtual_path
-
@virtual_path.gsub(%r{/_?}, ".") + key.to_s
-
else
-
raise "Cannot use t(#{key.inspect}) shortcut because path is not available"
-
end
-
else
-
key
-
end
-
end
-
-
2
def html_safe_translation_key?(key)
-
key.to_s =~ /(\b|_|\.)html$/
-
end
-
-
2
def wrap_translate_defaults(defaults)
-
new_defaults = []
-
defaults = Array(defaults)
-
while key = defaults.shift
-
if key.is_a?(Symbol)
-
new_defaults << lambda { |_, options| translate key, options.merge(:default => defaults) }
-
break
-
else
-
new_defaults << key
-
end
-
end
-
-
new_defaults
-
end
-
end
-
end
-
end
-
2
require 'action_view/helpers/javascript_helper'
-
2
require 'active_support/core_ext/array/access'
-
2
require 'active_support/core_ext/hash/keys'
-
2
require 'active_support/core_ext/string/output_safety'
-
-
2
module ActionView
-
# = Action View URL Helpers
-
2
module Helpers #:nodoc:
-
# Provides a set of methods for making links and getting URLs that
-
# depend on the routing subsystem (see ActionDispatch::Routing).
-
# This allows you to use the same format for links in views
-
# and controllers.
-
2
module UrlHelper
-
# This helper may be included in any class that includes the
-
# URL helpers of a routes (routes.url_helpers). Some methods
-
# provided here will only work in the context of a request
-
# (link_to_unless_current, for instance), which must be provided
-
# as a method called #request on the context.
-
2
BUTTON_TAG_METHOD_VERBS = %w{patch put delete}
-
2
extend ActiveSupport::Concern
-
-
2
include TagHelper
-
-
2
module ClassMethods
-
2
def _url_for_modules
-
8
ActionView::RoutingUrlFor
-
end
-
end
-
-
# Basic implementation of url_for to allow use helpers without routes existence
-
2
def url_for(options = nil) # :nodoc:
-
case options
-
when String
-
options
-
when :back
-
_back_url
-
else
-
raise ArgumentError, "arguments passed to url_for can't be handled. Please require " +
-
"routes or provide your own implementation"
-
end
-
end
-
-
2
def _back_url # :nodoc:
-
referrer = controller.respond_to?(:request) && controller.request.env["HTTP_REFERER"]
-
referrer || 'javascript:history.back()'
-
end
-
2
protected :_back_url
-
-
# Creates a link tag of the given +name+ using a URL created by the set of +options+.
-
# See the valid options in the documentation for +url_for+. It's also possible to
-
# pass a String instead of an options hash, which generates a link tag that uses the
-
# value of the String as the href for the link. Using a <tt>:back</tt> Symbol instead
-
# of an options hash will generate a link to the referrer (a JavaScript back link
-
# will be used in place of a referrer if none exists). If +nil+ is passed as the name
-
# the value of the link itself will become the name.
-
#
-
# ==== Signatures
-
#
-
# link_to(body, url, html_options = {})
-
# # url is a String; you can use URL helpers like
-
# # posts_path
-
#
-
# link_to(body, url_options = {}, html_options = {})
-
# # url_options, except :method, is passed to url_for
-
#
-
# link_to(options = {}, html_options = {}) do
-
# # name
-
# end
-
#
-
# link_to(url, html_options = {}) do
-
# # name
-
# end
-
#
-
# ==== Options
-
# * <tt>:data</tt> - This option can be used to add custom data attributes.
-
# * <tt>method: symbol of HTTP verb</tt> - This modifier will dynamically
-
# create an HTML form and immediately submit the form for processing using
-
# the HTTP verb specified. Useful for having links perform a POST operation
-
# in dangerous actions like deleting a record (which search bots can follow
-
# while spidering your site). Supported verbs are <tt>:post</tt>, <tt>:delete</tt>, <tt>:patch</tt>, and <tt>:put</tt>.
-
# Note that if the user has JavaScript disabled, the request will fall back
-
# to using GET. If <tt>href: '#'</tt> is used and the user has JavaScript
-
# disabled clicking the link will have no effect. If you are relying on the
-
# POST behavior, you should check for it in your controller's action by using
-
# the request object's methods for <tt>post?</tt>, <tt>delete?</tt>, <tt>patch?</tt>, or <tt>put?</tt>.
-
# * <tt>remote: true</tt> - This will allow the unobtrusive JavaScript
-
# driver to make an Ajax request to the URL in question instead of following
-
# the link. The drivers each provide mechanisms for listening for the
-
# completion of the Ajax request and performing JavaScript operations once
-
# they're complete
-
#
-
# ==== Data attributes
-
#
-
# * <tt>confirm: 'question?'</tt> - This will allow the unobtrusive JavaScript
-
# driver to prompt with the question specified (in this case, the
-
# resulting text would be <tt>question?</tt>. If the user accepts, the
-
# link is processed normally, otherwise no action is taken.
-
# * <tt>:disable_with</tt> - Value of this parameter will be
-
# used as the value for a disabled version of the submit
-
# button when the form is submitted. This feature is provided
-
# by the unobtrusive JavaScript driver.
-
#
-
# ==== Examples
-
# Because it relies on +url_for+, +link_to+ supports both older-style controller/action/id arguments
-
# and newer RESTful routes. Current Rails style favors RESTful routes whenever possible, so base
-
# your application on resources and use
-
#
-
# link_to "Profile", profile_path(@profile)
-
# # => <a href="/profiles/1">Profile</a>
-
#
-
# or the even pithier
-
#
-
# link_to "Profile", @profile
-
# # => <a href="/profiles/1">Profile</a>
-
#
-
# in place of the older more verbose, non-resource-oriented
-
#
-
# link_to "Profile", controller: "profiles", action: "show", id: @profile
-
# # => <a href="/profiles/show/1">Profile</a>
-
#
-
# Similarly,
-
#
-
# link_to "Profiles", profiles_path
-
# # => <a href="/profiles">Profiles</a>
-
#
-
# is better than
-
#
-
# link_to "Profiles", controller: "profiles"
-
# # => <a href="/profiles">Profiles</a>
-
#
-
# You can use a block as well if your link target is hard to fit into the name parameter. ERB example:
-
#
-
# <%= link_to(@profile) do %>
-
# <strong><%= @profile.name %></strong> -- <span>Check it out!</span>
-
# <% end %>
-
# # => <a href="/profiles/1">
-
# <strong>David</strong> -- <span>Check it out!</span>
-
# </a>
-
#
-
# Classes and ids for CSS are easy to produce:
-
#
-
# link_to "Articles", articles_path, id: "news", class: "article"
-
# # => <a href="/articles" class="article" id="news">Articles</a>
-
#
-
# Be careful when using the older argument style, as an extra literal hash is needed:
-
#
-
# link_to "Articles", { controller: "articles" }, id: "news", class: "article"
-
# # => <a href="/articles" class="article" id="news">Articles</a>
-
#
-
# Leaving the hash off gives the wrong link:
-
#
-
# link_to "WRONG!", controller: "articles", id: "news", class: "article"
-
# # => <a href="/articles/index/news?class=article">WRONG!</a>
-
#
-
# +link_to+ can also produce links with anchors or query strings:
-
#
-
# link_to "Comment wall", profile_path(@profile, anchor: "wall")
-
# # => <a href="/profiles/1#wall">Comment wall</a>
-
#
-
# link_to "Ruby on Rails search", controller: "searches", query: "ruby on rails"
-
# # => <a href="/searches?query=ruby+on+rails">Ruby on Rails search</a>
-
#
-
# link_to "Nonsense search", searches_path(foo: "bar", baz: "quux")
-
# # => <a href="/searches?foo=bar&baz=quux">Nonsense search</a>
-
#
-
# The only option specific to +link_to+ (<tt>:method</tt>) is used as follows:
-
#
-
# link_to("Destroy", "http://www.example.com", method: :delete)
-
# # => <a href='http://www.example.com' rel="nofollow" data-method="delete">Destroy</a>
-
#
-
# You can also use custom data attributes using the <tt>:data</tt> option:
-
#
-
# link_to "Visit Other Site", "http://www.rubyonrails.org/", data: { confirm: "Are you sure?" }
-
# # => <a href="http://www.rubyonrails.org/" data-confirm="Are you sure?">Visit Other Site</a>
-
2
def link_to(name = nil, options = nil, html_options = nil, &block)
-
52
html_options, options, name = options, name, block if block_given?
-
52
options ||= {}
-
-
52
html_options = convert_options_to_data_attributes(options, html_options)
-
-
52
url = url_for(options)
-
52
html_options['href'] ||= url
-
-
52
content_tag(:a, name || url, html_options, &block)
-
end
-
-
# Generates a form containing a single button that submits to the URL created
-
# by the set of +options+. This is the safest method to ensure links that
-
# cause changes to your data are not triggered by search bots or accelerators.
-
# If the HTML button does not work with your layout, you can also consider
-
# using the +link_to+ method with the <tt>:method</tt> modifier as described in
-
# the +link_to+ documentation.
-
#
-
# By default, the generated form element has a class name of <tt>button_to</tt>
-
# to allow styling of the form itself and its children. This can be changed
-
# using the <tt>:form_class</tt> modifier within +html_options+. You can control
-
# the form submission and input element behavior using +html_options+.
-
# This method accepts the <tt>:method</tt> modifier described in the +link_to+ documentation.
-
# If no <tt>:method</tt> modifier is given, it will default to performing a POST operation.
-
# You can also disable the button by passing <tt>disabled: true</tt> in +html_options+.
-
# If you are using RESTful routes, you can pass the <tt>:method</tt>
-
# to change the HTTP verb used to submit the form.
-
#
-
# ==== Options
-
# The +options+ hash accepts the same options as +url_for+.
-
#
-
# There are a few special +html_options+:
-
# * <tt>:method</tt> - Symbol of HTTP verb. Supported verbs are <tt>:post</tt>, <tt>:get</tt>,
-
# <tt>:delete</tt>, <tt>:patch</tt>, and <tt>:put</tt>. By default it will be <tt>:post</tt>.
-
# * <tt>:disabled</tt> - If set to true, it will generate a disabled button.
-
# * <tt>:data</tt> - This option can be used to add custom data attributes.
-
# * <tt>:remote</tt> - If set to true, will allow the Unobtrusive JavaScript drivers to control the
-
# submit behavior. By default this behavior is an ajax submit.
-
# * <tt>:form</tt> - This hash will be form attributes
-
# * <tt>:form_class</tt> - This controls the class of the form within which the submit button will
-
# be placed
-
# * <tt>:params</tt> - Hash of parameters to be rendered as hidden fields within the form.
-
#
-
# ==== Data attributes
-
#
-
# * <tt>:confirm</tt> - This will use the unobtrusive JavaScript driver to
-
# prompt with the question specified. If the user accepts, the link is
-
# processed normally, otherwise no action is taken.
-
# * <tt>:disable_with</tt> - Value of this parameter will be
-
# used as the value for a disabled version of the submit
-
# button when the form is submitted. This feature is provided
-
# by the unobtrusive JavaScript driver.
-
#
-
# ==== Examples
-
# <%= button_to "New", action: "new" %>
-
# # => "<form method="post" action="/controller/new" class="button_to">
-
# # <div><input value="New" type="submit" /></div>
-
# # </form>"
-
#
-
# <%= button_to "New", new_articles_path %>
-
# # => "<form method="post" action="/articles/new" class="button_to">
-
# # <div><input value="New" type="submit" /></div>
-
# # </form>"
-
#
-
# <%= button_to [:make_happy, @user] do %>
-
# Make happy <strong><%= @user.name %></strong>
-
# <% end %>
-
# # => "<form method="post" action="/users/1/make_happy" class="button_to">
-
# # <div>
-
# # <button type="submit">
-
# # Make happy <strong><%= @user.name %></strong>
-
# # </button>
-
# # </div>
-
# # </form>"
-
#
-
# <%= button_to "New", { action: "new" }, form_class: "new-thing" %>
-
# # => "<form method="post" action="/controller/new" class="new-thing">
-
# # <div><input value="New" type="submit" /></div>
-
# # </form>"
-
#
-
#
-
# <%= button_to "Create", { action: "create" }, remote: true, form: { "data-type" => "json" } %>
-
# # => "<form method="post" action="/images/create" class="button_to" data-remote="true" data-type="json">
-
# # <div>
-
# # <input value="Create" type="submit" />
-
# # <input name="authenticity_token" type="hidden" value="10f2163b45388899ad4d5ae948988266befcb6c3d1b2451cf657a0c293d605a6"/>
-
# # </div>
-
# # </form>"
-
#
-
#
-
# <%= button_to "Delete Image", { action: "delete", id: @image.id },
-
# method: :delete, data: { confirm: "Are you sure?" } %>
-
# # => "<form method="post" action="/images/delete/1" class="button_to">
-
# # <div>
-
# # <input type="hidden" name="_method" value="delete" />
-
# # <input data-confirm='Are you sure?' value="Delete Image" type="submit" />
-
# # <input name="authenticity_token" type="hidden" value="10f2163b45388899ad4d5ae948988266befcb6c3d1b2451cf657a0c293d605a6"/>
-
# # </div>
-
# # </form>"
-
#
-
#
-
# <%= button_to('Destroy', 'http://www.example.com',
-
# method: "delete", remote: true, data: { confirm: 'Are you sure?', disable_with: 'loading...' }) %>
-
# # => "<form class='button_to' method='post' action='http://www.example.com' data-remote='true'>
-
# # <div>
-
# # <input name='_method' value='delete' type='hidden' />
-
# # <input value='Destroy' type='submit' data-disable-with='loading...' data-confirm='Are you sure?' />
-
# # <input name="authenticity_token" type="hidden" value="10f2163b45388899ad4d5ae948988266befcb6c3d1b2451cf657a0c293d605a6"/>
-
# # </div>
-
# # </form>"
-
# #
-
2
def button_to(name = nil, options = nil, html_options = nil, &block)
-
html_options, options = options, name if block_given?
-
options ||= {}
-
html_options ||= {}
-
-
html_options = html_options.stringify_keys
-
convert_boolean_attributes!(html_options, %w(disabled))
-
-
url = options.is_a?(String) ? options : url_for(options)
-
remote = html_options.delete('remote')
-
params = html_options.delete('params')
-
-
method = html_options.delete('method').to_s
-
method_tag = BUTTON_TAG_METHOD_VERBS.include?(method) ? method_tag(method) : ''.html_safe
-
-
form_method = method == 'get' ? 'get' : 'post'
-
form_options = html_options.delete('form') || {}
-
form_options[:class] ||= html_options.delete('form_class') || 'button_to'
-
form_options.merge!(method: form_method, action: url)
-
form_options.merge!("data-remote" => "true") if remote
-
-
request_token_tag = form_method == 'post' ? token_tag : ''
-
-
html_options = convert_options_to_data_attributes(options, html_options)
-
html_options['type'] = 'submit'
-
-
button = if block_given?
-
content_tag('button', html_options, &block)
-
else
-
html_options['value'] = name || url
-
tag('input', html_options)
-
end
-
-
inner_tags = method_tag.safe_concat(button).safe_concat(request_token_tag)
-
if params
-
params.each do |param_name, value|
-
inner_tags.safe_concat tag(:input, type: "hidden", name: param_name, value: value.to_param)
-
end
-
end
-
content_tag('form', content_tag('div', inner_tags), form_options)
-
end
-
-
# Creates a link tag of the given +name+ using a URL created by the set of
-
# +options+ unless the current request URI is the same as the links, in
-
# which case only the name is returned (or the given block is yielded, if
-
# one exists). You can give +link_to_unless_current+ a block which will
-
# specialize the default behavior (e.g., show a "Start Here" link rather
-
# than the link's text).
-
#
-
# ==== Examples
-
# Let's say you have a navigation menu...
-
#
-
# <ul id="navbar">
-
# <li><%= link_to_unless_current("Home", { action: "index" }) %></li>
-
# <li><%= link_to_unless_current("About Us", { action: "about" }) %></li>
-
# </ul>
-
#
-
# If in the "about" action, it will render...
-
#
-
# <ul id="navbar">
-
# <li><a href="/controller/index">Home</a></li>
-
# <li>About Us</li>
-
# </ul>
-
#
-
# ...but if in the "index" action, it will render:
-
#
-
# <ul id="navbar">
-
# <li>Home</li>
-
# <li><a href="/controller/about">About Us</a></li>
-
# </ul>
-
#
-
# The implicit block given to +link_to_unless_current+ is evaluated if the current
-
# action is the action given. So, if we had a comments page and wanted to render a
-
# "Go Back" link instead of a link to the comments page, we could do something like this...
-
#
-
# <%=
-
# link_to_unless_current("Comment", { controller: "comments", action: "new" }) do
-
# link_to("Go back", { controller: "posts", action: "index" })
-
# end
-
# %>
-
2
def link_to_unless_current(name, options = {}, html_options = {}, &block)
-
link_to_unless current_page?(options), name, options, html_options, &block
-
end
-
-
# Creates a link tag of the given +name+ using a URL created by the set of
-
# +options+ unless +condition+ is true, in which case only the name is
-
# returned. To specialize the default behavior (i.e., show a login link rather
-
# than just the plaintext link text), you can pass a block that
-
# accepts the name or the full argument list for +link_to_unless+.
-
#
-
# ==== Examples
-
# <%= link_to_unless(@current_user.nil?, "Reply", { action: "reply" }) %>
-
# # If the user is logged in...
-
# # => <a href="/controller/reply/">Reply</a>
-
#
-
# <%=
-
# link_to_unless(@current_user.nil?, "Reply", { action: "reply" }) do |name|
-
# link_to(name, { controller: "accounts", action: "signup" })
-
# end
-
# %>
-
# # If the user is logged in...
-
# # => <a href="/controller/reply/">Reply</a>
-
# # If not...
-
# # => <a href="/accounts/signup">Reply</a>
-
2
def link_to_unless(condition, name, options = {}, html_options = {}, &block)
-
if condition
-
if block_given?
-
block.arity <= 1 ? capture(name, &block) : capture(name, options, html_options, &block)
-
else
-
ERB::Util.html_escape(name)
-
end
-
else
-
link_to(name, options, html_options)
-
end
-
end
-
-
# Creates a link tag of the given +name+ using a URL created by the set of
-
# +options+ if +condition+ is true, otherwise only the name is
-
# returned. To specialize the default behavior, you can pass a block that
-
# accepts the name or the full argument list for +link_to_unless+ (see the examples
-
# in +link_to_unless+).
-
#
-
# ==== Examples
-
# <%= link_to_if(@current_user.nil?, "Login", { controller: "sessions", action: "new" }) %>
-
# # If the user isn't logged in...
-
# # => <a href="/sessions/new/">Login</a>
-
#
-
# <%=
-
# link_to_if(@current_user.nil?, "Login", { controller: "sessions", action: "new" }) do
-
# link_to(@current_user.login, { controller: "accounts", action: "show", id: @current_user })
-
# end
-
# %>
-
# # If the user isn't logged in...
-
# # => <a href="/sessions/new/">Login</a>
-
# # If they are logged in...
-
# # => <a href="/accounts/show/3">my_username</a>
-
2
def link_to_if(condition, name, options = {}, html_options = {}, &block)
-
link_to_unless !condition, name, options, html_options, &block
-
end
-
-
# Creates a mailto link tag to the specified +email_address+, which is
-
# also used as the name of the link unless +name+ is specified. Additional
-
# HTML attributes for the link can be passed in +html_options+.
-
#
-
# +mail_to+ has several methods for customizing the email itself by
-
# passing special keys to +html_options+.
-
#
-
# ==== Options
-
# * <tt>:subject</tt> - Preset the subject line of the email.
-
# * <tt>:body</tt> - Preset the body of the email.
-
# * <tt>:cc</tt> - Carbon Copy additional recipients on the email.
-
# * <tt>:bcc</tt> - Blind Carbon Copy additional recipients on the email.
-
#
-
# ==== Obfuscation
-
# Prior to Rails 4.0, +mail_to+ provided options for encoding the address
-
# in order to hinder email harvesters. To take advantage of these options,
-
# install the +actionview-encoded_mail_to+ gem.
-
#
-
# ==== Examples
-
# mail_to "me@domain.com"
-
# # => <a href="mailto:me@domain.com">me@domain.com</a>
-
#
-
# mail_to "me@domain.com", "My email"
-
# # => <a href="mailto:me@domain.com">My email</a>
-
#
-
# mail_to "me@domain.com", "My email", cc: "ccaddress@domain.com",
-
# subject: "This is an example email"
-
# # => <a href="mailto:me@domain.com?cc=ccaddress@domain.com&subject=This%20is%20an%20example%20email">My email</a>
-
#
-
# You can use a block as well if your link target is hard to fit into the name parameter. ERB example:
-
#
-
# <%= mail_to "me@domain.com" do %>
-
# <strong>Email me:</strong> <span>me@domain.com</span>
-
# <% end %>
-
# # => <a href="mailto:me@domain.com">
-
# <strong>Email me:</strong> <span>me@domain.com</span>
-
# </a>
-
2
def mail_to(email_address, name = nil, html_options = {}, &block)
-
email_address = ERB::Util.html_escape(email_address)
-
-
html_options, name = name, nil if block_given?
-
html_options = (html_options || {}).stringify_keys
-
-
extras = %w{ cc bcc body subject }.map! { |item|
-
option = html_options.delete(item) || next
-
"#{item}=#{Rack::Utils.escape_path(option)}"
-
}.compact
-
extras = extras.empty? ? '' : '?' + ERB::Util.html_escape(extras.join('&'))
-
-
html_options["href"] = "mailto:#{email_address}#{extras}".html_safe
-
-
content_tag(:a, name || email_address.html_safe, html_options, &block)
-
end
-
-
# True if the current request URI was generated by the given +options+.
-
#
-
# ==== Examples
-
# Let's say we're in the <tt>http://www.example.com/shop/checkout?order=desc</tt> action.
-
#
-
# current_page?(action: 'process')
-
# # => false
-
#
-
# current_page?(controller: 'shop', action: 'checkout')
-
# # => true
-
#
-
# current_page?(controller: 'shop', action: 'checkout', order: 'asc')
-
# # => false
-
#
-
# current_page?(action: 'checkout')
-
# # => true
-
#
-
# current_page?(controller: 'library', action: 'checkout')
-
# # => false
-
#
-
# current_page?('http://www.example.com/shop/checkout')
-
# # => true
-
#
-
# current_page?('/shop/checkout')
-
# # => true
-
#
-
# Let's say we're in the <tt>http://www.example.com/shop/checkout?order=desc&page=1</tt> action.
-
#
-
# current_page?(action: 'process')
-
# # => false
-
#
-
# current_page?(controller: 'shop', action: 'checkout')
-
# # => true
-
#
-
# current_page?(controller: 'shop', action: 'checkout', order: 'desc', page: '1')
-
# # => true
-
#
-
# current_page?(controller: 'shop', action: 'checkout', order: 'desc', page: '2')
-
# # => false
-
#
-
# current_page?(controller: 'shop', action: 'checkout', order: 'desc')
-
# # => false
-
#
-
# current_page?(action: 'checkout')
-
# # => true
-
#
-
# current_page?(controller: 'library', action: 'checkout')
-
# # => false
-
#
-
# Let's say we're in the <tt>http://www.example.com/products</tt> action with method POST in case of invalid product.
-
#
-
# current_page?(controller: 'product', action: 'index')
-
# # => false
-
#
-
2
def current_page?(options)
-
unless request
-
raise "You cannot use helpers that need to determine the current " \
-
"page unless your view context provides a Request object " \
-
"in a #request method"
-
end
-
-
return false unless request.get? || request.head?
-
-
url_string = URI.parser.unescape(url_for(options)).force_encoding(Encoding::BINARY)
-
-
# We ignore any extra parameters in the request_uri if the
-
# submitted url doesn't have any either. This lets the function
-
# work with things like ?order=asc
-
request_uri = url_string.index("?") ? request.fullpath : request.path
-
request_uri = URI.parser.unescape(request_uri).force_encoding(Encoding::BINARY)
-
-
if url_string =~ /^\w+:\/\//
-
url_string == "#{request.protocol}#{request.host_with_port}#{request_uri}"
-
else
-
url_string == request_uri
-
end
-
end
-
-
2
private
-
2
def convert_options_to_data_attributes(options, html_options)
-
52
if html_options
-
47
html_options = html_options.stringify_keys
-
47
html_options['data-remote'] = 'true' if link_to_remote_options?(options) || link_to_remote_options?(html_options)
-
-
47
method = html_options.delete('method')
-
-
47
add_method_to_attributes!(html_options, method) if method
-
-
47
html_options
-
else
-
5
link_to_remote_options?(options) ? {'data-remote' => 'true'} : {}
-
end
-
end
-
-
2
def link_to_remote_options?(options)
-
99
if options.is_a?(Hash)
-
55
options.delete('remote') || options.delete(:remote)
-
end
-
end
-
-
2
def add_method_to_attributes!(html_options, method)
-
if method && method.to_s.downcase != "get" && html_options["rel"] !~ /nofollow/
-
html_options["rel"] = "#{html_options["rel"]} nofollow".lstrip
-
end
-
html_options["data-method"] = method
-
end
-
-
# Processes the +html_options+ hash, converting the boolean
-
# attributes from true/false form into the form required by
-
# HTML/XHTML. (An attribute is considered to be boolean if
-
# its name is listed in the given +bool_attrs+ array.)
-
#
-
# More specifically, for each boolean attribute in +html_options+
-
# given as:
-
#
-
# "attr" => bool_value
-
#
-
# if the associated +bool_value+ evaluates to true, it is
-
# replaced with the attribute's name; otherwise the attribute is
-
# removed from the +html_options+ hash. (See the XHTML 1.0 spec,
-
# section 4.5 "Attribute Minimization" for more:
-
# http://www.w3.org/TR/xhtml1/#h-4.5)
-
#
-
# Returns the updated +html_options+ hash, which is also modified
-
# in place.
-
#
-
# Example:
-
#
-
# convert_boolean_attributes!( html_options,
-
# %w( checked disabled readonly ) )
-
2
def convert_boolean_attributes!(html_options, bool_attrs)
-
bool_attrs.each { |x| html_options[x] = x if html_options.delete(x) }
-
html_options
-
end
-
-
2
def token_tag(token=nil)
-
9
if token != false && protect_against_forgery?
-
token ||= form_authenticity_token
-
tag(:input, type: "hidden", name: request_forgery_protection_token.to_s, value: token)
-
else
-
9
''
-
end
-
end
-
-
2
def method_tag(method)
-
tag('input', type: 'hidden', name: '_method', value: method.to_s)
-
end
-
end
-
end
-
end
-
2
require "action_view/rendering"
-
2
require "active_support/core_ext/module/remove_method"
-
-
2
module ActionView
-
# Layouts reverse the common pattern of including shared headers and footers in many templates to isolate changes in
-
# repeated setups. The inclusion pattern has pages that look like this:
-
#
-
# <%= render "shared/header" %>
-
# Hello World
-
# <%= render "shared/footer" %>
-
#
-
# This approach is a decent way of keeping common structures isolated from the changing content, but it's verbose
-
# and if you ever want to change the structure of these two includes, you'll have to change all the templates.
-
#
-
# With layouts, you can flip it around and have the common structure know where to insert changing content. This means
-
# that the header and footer are only mentioned in one place, like this:
-
#
-
# // The header part of this layout
-
# <%= yield %>
-
# // The footer part of this layout
-
#
-
# And then you have content pages that look like this:
-
#
-
# hello world
-
#
-
# At rendering time, the content page is computed and then inserted in the layout, like this:
-
#
-
# // The header part of this layout
-
# hello world
-
# // The footer part of this layout
-
#
-
# == Accessing shared variables
-
#
-
# Layouts have access to variables specified in the content pages and vice versa. This allows you to have layouts with
-
# references that won't materialize before rendering time:
-
#
-
# <h1><%= @page_title %></h1>
-
# <%= yield %>
-
#
-
# ...and content pages that fulfill these references _at_ rendering time:
-
#
-
# <% @page_title = "Welcome" %>
-
# Off-world colonies offers you a chance to start a new life
-
#
-
# The result after rendering is:
-
#
-
# <h1>Welcome</h1>
-
# Off-world colonies offers you a chance to start a new life
-
#
-
# == Layout assignment
-
#
-
# You can either specify a layout declaratively (using the #layout class method) or give
-
# it the same name as your controller, and place it in <tt>app/views/layouts</tt>.
-
# If a subclass does not have a layout specified, it inherits its layout using normal Ruby inheritance.
-
#
-
# For instance, if you have PostsController and a template named <tt>app/views/layouts/posts.html.erb</tt>,
-
# that template will be used for all actions in PostsController and controllers inheriting
-
# from PostsController.
-
#
-
# If you use a module, for instance Weblog::PostsController, you will need a template named
-
# <tt>app/views/layouts/weblog/posts.html.erb</tt>.
-
#
-
# Since all your controllers inherit from ApplicationController, they will use
-
# <tt>app/views/layouts/application.html.erb</tt> if no other layout is specified
-
# or provided.
-
#
-
# == Inheritance Examples
-
#
-
# class BankController < ActionController::Base
-
# # bank.html.erb exists
-
#
-
# class ExchangeController < BankController
-
# # exchange.html.erb exists
-
#
-
# class CurrencyController < BankController
-
#
-
# class InformationController < BankController
-
# layout "information"
-
#
-
# class TellerController < InformationController
-
# # teller.html.erb exists
-
#
-
# class EmployeeController < InformationController
-
# # employee.html.erb exists
-
# layout nil
-
#
-
# class VaultController < BankController
-
# layout :access_level_layout
-
#
-
# class TillController < BankController
-
# layout false
-
#
-
# In these examples, we have three implicit lookup scenarios:
-
# * The BankController uses the "bank" layout.
-
# * The ExchangeController uses the "exchange" layout.
-
# * The CurrencyController inherits the layout from BankController.
-
#
-
# However, when a layout is explicitly set, the explicitly set layout wins:
-
# * The InformationController uses the "information" layout, explicitly set.
-
# * The TellerController also uses the "information" layout, because the parent explicitly set it.
-
# * The EmployeeController uses the "employee" layout, because it set the layout to nil, resetting the parent configuration.
-
# * The VaultController chooses a layout dynamically by calling the <tt>access_level_layout</tt> method.
-
# * The TillController does not use a layout at all.
-
#
-
# == Types of layouts
-
#
-
# Layouts are basically just regular templates, but the name of this template needs not be specified statically. Sometimes
-
# you want to alternate layouts depending on runtime information, such as whether someone is logged in or not. This can
-
# be done either by specifying a method reference as a symbol or using an inline method (as a proc).
-
#
-
# The method reference is the preferred approach to variable layouts and is used like this:
-
#
-
# class WeblogController < ActionController::Base
-
# layout :writers_and_readers
-
#
-
# def index
-
# # fetching posts
-
# end
-
#
-
# private
-
# def writers_and_readers
-
# logged_in? ? "writer_layout" : "reader_layout"
-
# end
-
# end
-
#
-
# Now when a new request for the index action is processed, the layout will vary depending on whether the person accessing
-
# is logged in or not.
-
#
-
# If you want to use an inline method, such as a proc, do something like this:
-
#
-
# class WeblogController < ActionController::Base
-
# layout proc { |controller| controller.logged_in? ? "writer_layout" : "reader_layout" }
-
# end
-
#
-
# If an argument isn't given to the proc, it's evaluated in the context of
-
# the current controller anyway.
-
#
-
# class WeblogController < ActionController::Base
-
# layout proc { logged_in? ? "writer_layout" : "reader_layout" }
-
# end
-
#
-
# Of course, the most common way of specifying a layout is still just as a plain template name:
-
#
-
# class WeblogController < ActionController::Base
-
# layout "weblog_standard"
-
# end
-
#
-
# The template will be looked always in <tt>app/views/layouts/</tt> folder. But you can point
-
# <tt>layouts</tt> folder direct also. <tt>layout "layouts/demo"</tt> is the same as <tt>layout "demo"</tt>.
-
#
-
# Setting the layout to nil forces it to be looked up in the filesystem and fallbacks to the parent behavior if none exists.
-
# Setting it to nil is useful to re-enable template lookup overriding a previous configuration set in the parent:
-
#
-
# class ApplicationController < ActionController::Base
-
# layout "application"
-
# end
-
#
-
# class PostsController < ApplicationController
-
# # Will use "application" layout
-
# end
-
#
-
# class CommentsController < ApplicationController
-
# # Will search for "comments" layout and fallback "application" layout
-
# layout nil
-
# end
-
#
-
# == Conditional layouts
-
#
-
# If you have a layout that by default is applied to all the actions of a controller, you still have the option of rendering
-
# a given action or set of actions without a layout, or restricting a layout to only a single action or a set of actions. The
-
# <tt>:only</tt> and <tt>:except</tt> options can be passed to the layout call. For example:
-
#
-
# class WeblogController < ActionController::Base
-
# layout "weblog_standard", except: :rss
-
#
-
# # ...
-
#
-
# end
-
#
-
# This will assign "weblog_standard" as the WeblogController's layout for all actions except for the +rss+ action, which will
-
# be rendered directly, without wrapping a layout around the rendered view.
-
#
-
# Both the <tt>:only</tt> and <tt>:except</tt> condition can accept an arbitrary number of method references, so
-
# #<tt>except: [ :rss, :text_only ]</tt> is valid, as is <tt>except: :rss</tt>.
-
#
-
# == Using a different layout in the action render call
-
#
-
# If most of your actions use the same layout, it makes perfect sense to define a controller-wide layout as described above.
-
# Sometimes you'll have exceptions where one action wants to use a different layout than the rest of the controller.
-
# You can do this by passing a <tt>:layout</tt> option to the <tt>render</tt> call. For example:
-
#
-
# class WeblogController < ActionController::Base
-
# layout "weblog_standard"
-
#
-
# def help
-
# render action: "help", layout: "help"
-
# end
-
# end
-
#
-
# This will override the controller-wide "weblog_standard" layout, and will render the help action with the "help" layout instead.
-
2
module Layouts
-
2
extend ActiveSupport::Concern
-
-
2
include ActionView::Rendering
-
-
2
included do
-
4
class_attribute :_layout, :_layout_conditions, :instance_accessor => false
-
4
self._layout = nil
-
4
self._layout_conditions = {}
-
4
_write_layout_method
-
end
-
-
2
delegate :_layout_conditions, to: :class
-
-
2
module ClassMethods
-
2
def inherited(klass) # :nodoc:
-
13
super
-
13
klass._write_layout_method
-
end
-
-
# This module is mixed in if layout conditions are provided. This means
-
# that if no layout conditions are used, this method is not used
-
2
module LayoutConditions # :nodoc:
-
2
private
-
-
# Determines whether the current action has a layout definition by
-
# checking the action name against the :only and :except conditions
-
# set by the <tt>layout</tt> method.
-
#
-
# ==== Returns
-
# * <tt> Boolean</tt> - True if the action has a layout definition, false otherwise.
-
2
def _conditional_layout?
-
return unless super
-
-
conditions = _layout_conditions
-
-
if only = conditions[:only]
-
only.include?(action_name)
-
elsif except = conditions[:except]
-
!except.include?(action_name)
-
else
-
true
-
end
-
end
-
end
-
-
# Specify the layout to use for this class.
-
#
-
# If the specified layout is a:
-
# String:: the String is the template name
-
# Symbol:: call the method specified by the symbol, which will return the template name
-
# false:: There is no layout
-
# true:: raise an ArgumentError
-
# nil:: Force default layout behavior with inheritance
-
#
-
# ==== Parameters
-
# * <tt>layout</tt> - The layout to use.
-
#
-
# ==== Options (conditions)
-
# * :only - A list of actions to apply this layout to.
-
# * :except - Apply this layout to all actions but this one.
-
2
def layout(layout, conditions = {})
-
include LayoutConditions unless conditions.empty?
-
-
conditions.each {|k, v| conditions[k] = Array(v).map {|a| a.to_s} }
-
self._layout_conditions = conditions
-
-
self._layout = layout
-
_write_layout_method
-
end
-
-
# Creates a _layout method to be called by _default_layout .
-
#
-
# If a layout is not explicitly mentioned then look for a layout with the controller's name.
-
# if nothing is found then try same procedure to find super class's layout.
-
2
def _write_layout_method # :nodoc:
-
17
remove_possible_method(:_layout)
-
-
17
prefixes = _implied_layout_name =~ /\blayouts/ ? [] : ["layouts"]
-
17
default_behavior = "lookup_context.find_all('#{_implied_layout_name}', #{prefixes.inspect}).first || super"
-
17
name_clause = if name
-
17
default_behavior
-
else
-
<<-RUBY
-
super
-
RUBY
-
end
-
-
17
layout_definition = case _layout
-
when String
-
_layout.inspect
-
when Symbol
-
<<-RUBY
-
#{_layout}.tap do |layout|
-
return #{default_behavior} if layout.nil?
-
unless layout.is_a?(String) || !layout
-
raise ArgumentError, "Your layout method :#{_layout} returned \#{layout}. It " \
-
"should have returned a String, false, or nil"
-
end
-
end
-
RUBY
-
when Proc
-
define_method :_layout_from_proc, &_layout
-
protected :_layout_from_proc
-
<<-RUBY
-
result = _layout_from_proc(#{_layout.arity == 0 ? '' : 'self'})
-
return #{default_behavior} if result.nil?
-
result
-
RUBY
-
when false
-
nil
-
when true
-
raise ArgumentError, "Layouts must be specified as a String, Symbol, Proc, false, or nil"
-
when nil
-
17
name_clause
-
end
-
-
17
self.class_eval <<-RUBY, __FILE__, __LINE__ + 1
-
def _layout
-
if _conditional_layout?
-
#{layout_definition}
-
else
-
#{name_clause}
-
end
-
end
-
private :_layout
-
RUBY
-
end
-
-
2
private
-
-
# If no layout is supplied, look for a template named the return
-
# value of this method.
-
#
-
# ==== Returns
-
# * <tt>String</tt> - A template name
-
2
def _implied_layout_name # :nodoc:
-
34
controller_path
-
end
-
end
-
-
2
def _normalize_options(options) # :nodoc:
-
24
super
-
-
24
if _include_layout?(options)
-
48
layout = options.delete(:layout) { :default }
-
24
options[:layout] = _layout_for_option(layout)
-
end
-
end
-
-
2
attr_internal_writer :action_has_layout
-
-
2
def initialize(*) # :nodoc:
-
28
@_action_has_layout = true
-
28
super
-
end
-
-
# Controls whether an action should be rendered using a layout.
-
# If you want to disable any <tt>layout</tt> settings for the
-
# current action so that it is rendered without a layout then
-
# either override this method in your controller to return false
-
# for that action or set the <tt>action_has_layout</tt> attribute
-
# to false before rendering.
-
2
def action_has_layout?
-
24
@_action_has_layout
-
end
-
-
2
private
-
-
2
def _conditional_layout?
-
48
true
-
end
-
-
# This will be overwritten by _write_layout_method
-
2
def _layout; end
-
-
# Determine the layout for a given name, taking into account the name type.
-
#
-
# ==== Parameters
-
# * <tt>name</tt> - The name of the template
-
2
def _layout_for_option(name)
-
24
case name
-
when String then _normalize_layout(name)
-
when Proc then name
-
when true then Proc.new { _default_layout(true) }
-
48
when :default then Proc.new { _default_layout(false) }
-
when false, nil then nil
-
else
-
raise ArgumentError,
-
"String, Proc, :default, true, or false, expected for `layout'; you passed #{name.inspect}"
-
end
-
end
-
-
2
def _normalize_layout(value)
-
24
value.is_a?(String) && value !~ /\blayouts/ ? "layouts/#{value}" : value
-
end
-
-
# Returns the default layout for this controller.
-
# Optionally raises an exception if the layout could not be found.
-
#
-
# ==== Parameters
-
# * <tt>require_layout</tt> - If set to true and layout is not found,
-
# an ArgumentError exception is raised (defaults to false)
-
#
-
# ==== Returns
-
# * <tt>template</tt> - The template object for the default layout (or nil)
-
2
def _default_layout(require_layout = false)
-
24
begin
-
24
value = _layout if action_has_layout?
-
rescue NameError => e
-
raise e, "Could not render layout: #{e.message}"
-
end
-
-
24
if require_layout && action_has_layout? && !value
-
raise ArgumentError,
-
"There was no default layout for #{self.class} in #{view_paths.inspect}"
-
end
-
-
24
_normalize_layout(value)
-
end
-
-
2
def _include_layout?(options)
-
24
(options.keys & [:body, :text, :plain, :html, :inline, :partial]).empty? || options.key?(:layout)
-
end
-
end
-
end
-
2
require 'active_support/log_subscriber'
-
-
2
module ActionView
-
# = Action View Log Subscriber
-
#
-
# Provides functionality so that Rails can output logs from Action View.
-
2
class LogSubscriber < ActiveSupport::LogSubscriber
-
2
VIEWS_PATTERN = /^app\/views\//
-
-
2
def initialize
-
2
@root = nil
-
2
super
-
end
-
-
2
def render_template(event)
-
27
return unless logger.info?
-
27
message = " Rendered #{from_rails_root(event.payload[:identifier])}"
-
27
message << " within #{from_rails_root(event.payload[:layout])}" if event.payload[:layout]
-
27
message << " (#{event.duration.round(1)}ms)"
-
27
info(message)
-
end
-
2
alias :render_partial :render_template
-
2
alias :render_collection :render_template
-
-
2
def logger
-
135
ActionView::Base.logger
-
end
-
-
2
protected
-
-
2
EMPTY = ''
-
2
def from_rails_root(string)
-
41
string = string.sub(rails_root, EMPTY)
-
41
string.sub!(VIEWS_PATTERN, EMPTY)
-
41
string
-
end
-
-
2
def rails_root
-
41
@root ||= "#{Rails.root}/"
-
end
-
end
-
end
-
-
2
ActionView::LogSubscriber.attach_to :action_view
-
2
require 'thread_safe'
-
2
require 'active_support/core_ext/module/remove_method'
-
2
require 'active_support/core_ext/module/attribute_accessors'
-
2
require 'action_view/template/resolver'
-
-
2
module ActionView
-
# = Action View Lookup Context
-
#
-
# LookupContext is the object responsible to hold all information required to lookup
-
# templates, i.e. view paths and details. The LookupContext is also responsible to
-
# generate a key, given to view paths, used in the resolver cache lookup. Since
-
# this key is generated just once during the request, it speeds up all cache accesses.
-
2
class LookupContext #:nodoc:
-
2
attr_accessor :prefixes, :rendered_format
-
-
2
mattr_accessor :fallbacks
-
2
@@fallbacks = FallbackFileSystemResolver.instances
-
-
2
mattr_accessor :registered_details
-
2
self.registered_details = []
-
-
2
def self.register_detail(name, options = {}, &block)
-
8
self.registered_details << name
-
28
initialize = registered_details.map { |n| "@details[:#{n}] = details[:#{n}] || default_#{n}" }
-
-
8
Accessors.send :define_method, :"default_#{name}", &block
-
8
Accessors.module_eval <<-METHOD, __FILE__, __LINE__ + 1
-
def #{name}
-
@details.fetch(:#{name}, [])
-
end
-
-
def #{name}=(value)
-
value = value.present? ? Array(value) : default_#{name}
-
_set_detail(:#{name}, value) if value != @details[:#{name}]
-
end
-
-
remove_possible_method :initialize_details
-
def initialize_details(details)
-
#{initialize.join("\n")}
-
end
-
METHOD
-
end
-
-
# Holds accessors for the registered details.
-
2
module Accessors #:nodoc:
-
end
-
-
2
register_detail(:locale) do
-
24
locales = [I18n.locale]
-
24
locales.concat(I18n.fallbacks[I18n.locale]) if I18n.respond_to? :fallbacks
-
24
locales << I18n.default_locale
-
24
locales.uniq!
-
24
locales
-
end
-
48
register_detail(:formats) { ActionView::Base.default_formats || [:html, :text, :js, :css, :xml, :json] }
-
26
register_detail(:variants) { [] }
-
26
register_detail(:handlers){ Template::Handlers.extensions }
-
-
2
class DetailsKey #:nodoc:
-
2
alias :eql? :equal?
-
2
alias :object_hash :hash
-
-
2
attr_reader :hash
-
2
@details_keys = ThreadSafe::Cache.new
-
-
2
def self.get(details)
-
24
if details[:formats]
-
24
details = details.dup
-
24
syms = Set.new Mime::SET.symbols
-
24
details[:formats] = details[:formats].select { |v|
-
24
syms.include? v
-
}
-
end
-
24
@details_keys[details] ||= new
-
end
-
-
2
def self.clear
-
@details_keys.clear
-
end
-
-
2
def initialize
-
2
@hash = object_hash
-
end
-
end
-
-
# Add caching behavior on top of Details.
-
2
module DetailsCache
-
2
attr_accessor :cache
-
-
# Calculate the details key. Remove the handlers from calculation to improve performance
-
# since the user cannot modify it explicitly.
-
2
def details_key #:nodoc:
-
85
@details_key ||= DetailsKey.get(@details) if @cache
-
end
-
-
# Temporary skip passing the details_key forward.
-
2
def disable_cache
-
old_value, @cache = @cache, false
-
yield
-
ensure
-
@cache = old_value
-
end
-
-
2
protected
-
-
2
def _set_detail(key, value)
-
24
@details = @details.dup if @details_key
-
24
@details_key = nil
-
24
@details[key] = value
-
end
-
end
-
-
# Helpers related to template lookup using the lookup context information.
-
2
module ViewPaths
-
2
attr_reader :view_paths, :html_fallback_for_js
-
-
# Whenever setting view paths, makes a copy so we can manipulate then in
-
# instance objects as we wish.
-
2
def view_paths=(paths)
-
24
@view_paths = ActionView::PathSet.new(Array(paths))
-
end
-
-
2
def find(name, prefixes = [], partial = false, keys = [], options = {})
-
37
@view_paths.find(*args_for_lookup(name, prefixes, partial, keys, options))
-
end
-
2
alias :find_template :find
-
-
2
def find_all(name, prefixes = [], partial = false, keys = [], options = {})
-
48
@view_paths.find_all(*args_for_lookup(name, prefixes, partial, keys, options))
-
end
-
-
2
def exists?(name, prefixes = [], partial = false, keys = [], options = {})
-
@view_paths.exists?(*args_for_lookup(name, prefixes, partial, keys, options))
-
end
-
2
alias :template_exists? :exists?
-
-
# Add fallbacks to the view paths. Useful in cases you are rendering a :file.
-
2
def with_fallbacks
-
added_resolvers = 0
-
self.class.fallbacks.each do |resolver|
-
next if view_paths.include?(resolver)
-
view_paths.push(resolver)
-
added_resolvers += 1
-
end
-
yield
-
ensure
-
added_resolvers.times { view_paths.pop }
-
end
-
-
2
protected
-
-
2
def args_for_lookup(name, prefixes, partial, keys, details_options) #:nodoc:
-
85
name, prefixes = normalize_name(name, prefixes)
-
85
details, details_key = detail_args_for(details_options)
-
85
[name, prefixes, partial || false, details, details_key, keys]
-
end
-
-
# Compute details hash and key according to user options (e.g. passed from #render).
-
2
def detail_args_for(options)
-
85
return @details, details_key if options.empty? # most common path.
-
user_details = @details.merge(options)
-
-
if @cache
-
details_key = DetailsKey.get(user_details)
-
else
-
details_key = nil
-
end
-
-
[user_details, details_key]
-
end
-
-
# Support legacy foo.erb names even though we now ignore .erb
-
# as well as incorrectly putting part of the path in the template
-
# name instead of the prefix.
-
2
def normalize_name(name, prefixes) #:nodoc:
-
85
prefixes = prefixes.presence
-
85
parts = name.to_s.split('/')
-
85
parts.shift if parts.first.empty?
-
85
name = parts.pop
-
-
85
return name, prefixes || [""] if parts.empty?
-
-
13
parts = parts.join('/')
-
13
prefixes = prefixes ? prefixes.map { |p| "#{p}/#{parts}" } : [parts]
-
-
13
return name, prefixes
-
end
-
end
-
-
2
include Accessors
-
2
include DetailsCache
-
2
include ViewPaths
-
-
2
def initialize(view_paths, details = {}, prefixes = [])
-
24
@details, @details_key = {}, nil
-
24
@skip_default_locale = false
-
24
@cache = true
-
24
@prefixes = prefixes
-
24
@rendered_format = nil
-
-
24
self.view_paths = view_paths
-
24
initialize_details(details)
-
end
-
-
# Override formats= to expand ["*/*"] values and automatically
-
# add :html as fallback to :js.
-
2
def formats=(values)
-
94
if values
-
72
values.concat(default_formats) if values.delete "*/*"
-
72
if values == [:js]
-
values << :html
-
@html_fallback_for_js = true
-
end
-
end
-
94
super(values)
-
end
-
-
# Do not use the default locale on template lookup.
-
2
def skip_default_locale!
-
@skip_default_locale = true
-
self.locale = nil
-
end
-
-
# Override locale to return a symbol instead of array.
-
2
def locale
-
@details[:locale].first
-
end
-
-
# Overload locale= to also set the I18n.locale. If the current I18n.config object responds
-
# to original_config, it means that it's has a copy of the original I18n configuration and it's
-
# acting as proxy, which we need to skip.
-
2
def locale=(value)
-
if value
-
config = I18n.config.respond_to?(:original_config) ? I18n.config.original_config : I18n.config
-
config.locale = value
-
end
-
-
super(@skip_default_locale ? I18n.locale : default_locale)
-
end
-
-
# A method which only uses the first format in the formats array for layout lookup.
-
2
def with_layout_format
-
24
if formats.size == 1
-
24
yield
-
else
-
old_formats = formats
-
_set_detail(:formats, formats[0,1])
-
-
begin
-
yield
-
ensure
-
_set_detail(:formats, old_formats)
-
end
-
end
-
end
-
end
-
end
-
2
module ActionView
-
2
module ModelNaming
-
# Converts the given object to an ActiveModel compliant one.
-
2
def convert_to_model(object)
-
object.respond_to?(:to_model) ? object.to_model : object
-
end
-
-
2
def model_name_from_record_or_class(record_or_class)
-
(record_or_class.is_a?(Class) ? record_or_class : convert_to_model(record_or_class).class).model_name
-
end
-
end
-
end
-
2
module ActionView #:nodoc:
-
# = Action View PathSet
-
#
-
# This class is used to store and access paths in Action View. A number of
-
# operations are defined so that you can search among the paths in this
-
# set and also perform operations on other +PathSet+ objects.
-
#
-
# A +LookupContext+ will use a +PathSet+ to store the paths in its context.
-
2
class PathSet #:nodoc:
-
2
include Enumerable
-
-
2
attr_reader :paths
-
-
2
delegate :[], :include?, :pop, :size, :each, to: :paths
-
-
2
def initialize(paths = [])
-
70
@paths = typecast paths
-
end
-
-
2
def initialize_copy(other)
-
@paths = other.paths.dup
-
self
-
end
-
-
2
def to_ary
-
51
paths.dup
-
end
-
-
2
def compact
-
PathSet.new paths.compact
-
end
-
-
2
def +(array)
-
PathSet.new(paths + array)
-
end
-
-
2
%w(<< concat push insert unshift).each do |method|
-
10
class_eval <<-METHOD, __FILE__, __LINE__ + 1
-
def #{method}(*args)
-
paths.#{method}(*typecast(args))
-
end
-
METHOD
-
end
-
-
2
def find(*args)
-
37
find_all(*args).first || raise(MissingTemplate.new(self, *args))
-
end
-
-
2
def find_all(path, prefixes = [], *args)
-
85
prefixes = [prefixes] if String === prefixes
-
85
prefixes.each do |prefix|
-
85
paths.each do |resolver|
-
133
templates = resolver.find_all(path, prefix, *args)
-
133
return templates unless templates.empty?
-
end
-
end
-
24
[]
-
end
-
-
2
def exists?(path, prefixes, *args)
-
find_all(path, prefixes, *args).any?
-
end
-
-
2
private
-
-
2
def typecast(paths)
-
70
paths.map do |path|
-
186
case path
-
when Pathname, String
-
12
OptimizedFileSystemResolver.new path.to_s
-
else
-
174
path
-
end
-
end
-
end
-
end
-
end
-
2
require "action_view"
-
2
require "rails"
-
-
2
module ActionView
-
# = Action View Railtie
-
2
class Railtie < Rails::Railtie # :nodoc:
-
2
config.action_view = ActiveSupport::OrderedOptions.new
-
2
config.action_view.embed_authenticity_token_in_remote_forms = false
-
-
2
config.eager_load_namespaces << ActionView
-
-
2
initializer "action_view.embed_authenticity_token_in_remote_forms" do |app|
-
2
ActiveSupport.on_load(:action_view) do
-
2
ActionView::Helpers::FormTagHelper.embed_authenticity_token_in_remote_forms =
-
app.config.action_view.delete(:embed_authenticity_token_in_remote_forms)
-
end
-
end
-
-
2
initializer "action_view.logger" do
-
4
ActiveSupport.on_load(:action_view) { self.logger ||= Rails.logger }
-
end
-
-
2
initializer "action_view.set_configs" do |app|
-
2
ActiveSupport.on_load(:action_view) do
-
2
app.config.action_view.each do |k,v|
-
send "#{k}=", v
-
end
-
end
-
end
-
-
2
initializer "action_view.caching" do |app|
-
2
ActiveSupport.on_load(:action_view) do
-
2
if app.config.action_view.cache_template_loading.nil?
-
2
ActionView::Resolver.caching = app.config.cache_classes
-
end
-
end
-
end
-
-
2
initializer "action_view.setup_action_pack" do |app|
-
2
ActiveSupport.on_load(:action_controller) do
-
2
ActionView::RoutingUrlFor.send(:include, ActionDispatch::Routing::UrlFor)
-
end
-
end
-
-
2
rake_tasks do
-
load "action_view/tasks/dependencies.rake"
-
end
-
end
-
end
-
2
require 'active_support/core_ext/module'
-
2
require 'action_view/model_naming'
-
-
2
module ActionView
-
# The record identifier encapsulates a number of naming conventions for dealing with records, like Active Records or
-
# pretty much any other model type that has an id. These patterns are then used to try elevate the view actions to
-
# a higher logical level.
-
#
-
# # routes
-
# resources :posts
-
#
-
# # view
-
# <%= div_for(post) do %> <div id="post_45" class="post">
-
# <%= post.body %> What a wonderful world!
-
# <% end %> </div>
-
#
-
# # controller
-
# def update
-
# post = Post.find(params[:id])
-
# post.update(params[:post])
-
#
-
# redirect_to(post) # Calls polymorphic_url(post) which in turn calls post_url(post)
-
# end
-
#
-
# As the example above shows, you can stop caring to a large extent what the actual id of the post is.
-
# You just know that one is being assigned and that the subsequent calls in redirect_to expect that
-
# same naming convention and allows you to write less code if you follow it.
-
2
module RecordIdentifier
-
2
extend self
-
2
extend ModelNaming
-
-
2
include ModelNaming
-
-
2
JOIN = '_'.freeze
-
2
NEW = 'new'.freeze
-
-
# The DOM class convention is to use the singular form of an object or class.
-
#
-
# dom_class(post) # => "post"
-
# dom_class(Person) # => "person"
-
#
-
# If you need to address multiple instances of the same class in the same view, you can prefix the dom_class:
-
#
-
# dom_class(post, :edit) # => "edit_post"
-
# dom_class(Person, :edit) # => "edit_person"
-
2
def dom_class(record_or_class, prefix = nil)
-
8
singular = model_name_from_record_or_class(record_or_class).param_key
-
8
prefix ? "#{prefix}#{JOIN}#{singular}" : singular
-
end
-
-
# The DOM id convention is to use the singular form of an object or class with the id following an underscore.
-
# If no id is found, prefix with "new_" instead.
-
#
-
# dom_id(Post.find(45)) # => "post_45"
-
# dom_id(Post.new) # => "new_post"
-
#
-
# If you need to address multiple instances of the same class in the same view, you can prefix the dom_id:
-
#
-
# dom_id(Post.find(45), :edit) # => "edit_post_45"
-
# dom_id(Post.new, :custom) # => "custom_post"
-
2
def dom_id(record, prefix = nil)
-
4
if record_id = record_key_for_dom_id(record)
-
"#{dom_class(record, prefix)}#{JOIN}#{record_id}"
-
else
-
4
dom_class(record, prefix || NEW)
-
end
-
end
-
-
2
protected
-
-
# Returns a string representation of the key attribute(s) that is suitable for use in an HTML DOM id.
-
# This can be overwritten to customize the default generated string representation if desired.
-
# If you need to read back a key from a dom_id in order to query for the underlying database record,
-
# you should write a helper like 'person_record_from_dom_id' that will extract the key either based
-
# on the default implementation (which just joins all key attributes with '_') or on your own
-
# overwritten version of the method. By default, this implementation passes the key string through a
-
# method that replaces all characters that are invalid inside DOM ids, with valid ones. You need to
-
# make sure yourself that your dom ids are valid, in case you overwrite this method.
-
2
def record_key_for_dom_id(record)
-
4
key = convert_to_model(record).to_key
-
4
key ? key.join('_') : key
-
end
-
end
-
end
-
2
module ActionView
-
# This class defines the interface for a renderer. Each class that
-
# subclasses +AbstractRenderer+ is used by the base +Renderer+ class to
-
# render a specific type of object.
-
#
-
# The base +Renderer+ class uses its +render+ method to delegate to the
-
# renderers. These currently consist of
-
#
-
# PartialRenderer - Used for rendering partials
-
# TemplateRenderer - Used for rendering other types of templates
-
# StreamingTemplateRenderer - Used for streaming
-
#
-
# Whenever the +render+ method is called on the base +Renderer+ class, a new
-
# renderer object of the correct type is created, and the +render+ method on
-
# that new object is called in turn. This abstracts the setup and rendering
-
# into a separate classes for partials and templates.
-
2
class AbstractRenderer #:nodoc:
-
2
delegate :find_template, :template_exists?, :with_fallbacks, :with_layout_format, :formats, :to => :@lookup_context
-
-
2
def initialize(lookup_context)
-
37
@lookup_context = lookup_context
-
end
-
-
2
def render
-
raise NotImplementedError
-
end
-
-
2
protected
-
-
2
def extract_details(options)
-
37
@lookup_context.registered_details.each_with_object({}) do |key, details|
-
148
next unless value = options[key]
-
details[key] = Array(value)
-
end
-
end
-
-
2
def instrument(name, options={})
-
74
ActiveSupport::Notifications.instrument("render_#{name}.action_view", options){ yield }
-
end
-
-
2
def prepend_formats(formats)
-
37
formats = Array(formats)
-
37
return if formats.empty? || @lookup_context.html_fallback_for_js
-
24
@lookup_context.formats = formats | @lookup_context.formats
-
end
-
end
-
end
-
1
require 'thread_safe'
-
-
1
module ActionView
-
# = Action View Partials
-
#
-
# There's also a convenience method for rendering sub templates within the current controller that depends on a
-
# single object (we call this kind of sub templates for partials). It relies on the fact that partials should
-
# follow the naming convention of being prefixed with an underscore -- as to separate them from regular
-
# templates that could be rendered on their own.
-
#
-
# In a template for Advertiser#account:
-
#
-
# <%= render partial: "account" %>
-
#
-
# This would render "advertiser/_account.html.erb".
-
#
-
# In another template for Advertiser#buy, we could have:
-
#
-
# <%= render partial: "account", locals: { account: @buyer } %>
-
#
-
# <% @advertisements.each do |ad| %>
-
# <%= render partial: "ad", locals: { ad: ad } %>
-
# <% end %>
-
#
-
# This would first render "advertiser/_account.html.erb" with @buyer passed in as the local variable +account+, then
-
# render "advertiser/_ad.html.erb" and pass the local variable +ad+ to the template for display.
-
#
-
# == The :as and :object options
-
#
-
# By default <tt>ActionView::PartialRenderer</tt> doesn't have any local variables.
-
# The <tt>:object</tt> option can be used to pass an object to the partial. For instance:
-
#
-
# <%= render partial: "account", object: @buyer %>
-
#
-
# would provide the <tt>@buyer</tt> object to the partial, available under the local variable +account+ and is
-
# equivalent to:
-
#
-
# <%= render partial: "account", locals: { account: @buyer } %>
-
#
-
# With the <tt>:as</tt> option we can specify a different name for said local variable. For example, if we
-
# wanted it to be +user+ instead of +account+ we'd do:
-
#
-
# <%= render partial: "account", object: @buyer, as: 'user' %>
-
#
-
# This is equivalent to
-
#
-
# <%= render partial: "account", locals: { user: @buyer } %>
-
#
-
# == Rendering a collection of partials
-
#
-
# The example of partial use describes a familiar pattern where a template needs to iterate over an array and
-
# render a sub template for each of the elements. This pattern has been implemented as a single method that
-
# accepts an array and renders a partial by the same name as the elements contained within. So the three-lined
-
# example in "Using partials" can be rewritten with a single line:
-
#
-
# <%= render partial: "ad", collection: @advertisements %>
-
#
-
# This will render "advertiser/_ad.html.erb" and pass the local variable +ad+ to the template for display. An
-
# iteration counter will automatically be made available to the template with a name of the form
-
# +partial_name_counter+. In the case of the example above, the template would be fed +ad_counter+.
-
#
-
# The <tt>:as</tt> option may be used when rendering partials.
-
#
-
# You can specify a partial to be rendered between elements via the <tt>:spacer_template</tt> option.
-
# The following example will render <tt>advertiser/_ad_divider.html.erb</tt> between each ad partial:
-
#
-
# <%= render partial: "ad", collection: @advertisements, spacer_template: "ad_divider" %>
-
#
-
# If the given <tt>:collection</tt> is nil or empty, <tt>render</tt> will return nil. This will allow you
-
# to specify a text which will displayed instead by using this form:
-
#
-
# <%= render(partial: "ad", collection: @advertisements) || "There's no ad to be displayed" %>
-
#
-
# NOTE: Due to backwards compatibility concerns, the collection can't be one of hashes. Normally you'd also
-
# just keep domain objects, like Active Records, in there.
-
#
-
# == Rendering shared partials
-
#
-
# Two controllers can share a set of partials and render them like this:
-
#
-
# <%= render partial: "advertisement/ad", locals: { ad: @advertisement } %>
-
#
-
# This will render the partial "advertisement/_ad.html.erb" regardless of which controller this is being called from.
-
#
-
# == Rendering objects that respond to `to_partial_path`
-
#
-
# Instead of explicitly naming the location of a partial, you can also let PartialRenderer do the work
-
# and pick the proper path by checking `to_partial_path` method.
-
#
-
# # @account.to_partial_path returns 'accounts/account', so it can be used to replace:
-
# # <%= render partial: "accounts/account", locals: { account: @account} %>
-
# <%= render partial: @account %>
-
#
-
# # @posts is an array of Post instances, so every post record returns 'posts/post' on `to_partial_path`,
-
# # that's why we can replace:
-
# # <%= render partial: "posts/post", collection: @posts %>
-
# <%= render partial: @posts %>
-
#
-
# == Rendering the default case
-
#
-
# If you're not going to be using any of the options like collections or layouts, you can also use the short-hand
-
# defaults of render to render partials. Examples:
-
#
-
# # Instead of <%= render partial: "account" %>
-
# <%= render "account" %>
-
#
-
# # Instead of <%= render partial: "account", locals: { account: @buyer } %>
-
# <%= render "account", account: @buyer %>
-
#
-
# # @account.to_partial_path returns 'accounts/account', so it can be used to replace:
-
# # <%= render partial: "accounts/account", locals: { account: @account} %>
-
# <%= render @account %>
-
#
-
# # @posts is an array of Post instances, so every post record returns 'posts/post' on `to_partial_path`,
-
# # that's why we can replace:
-
# # <%= render partial: "posts/post", collection: @posts %>
-
# <%= render @posts %>
-
#
-
# == Rendering partials with layouts
-
#
-
# Partials can have their own layouts applied to them. These layouts are different than the ones that are
-
# specified globally for the entire action, but they work in a similar fashion. Imagine a list with two types
-
# of users:
-
#
-
# <%# app/views/users/index.html.erb &>
-
# Here's the administrator:
-
# <%= render partial: "user", layout: "administrator", locals: { user: administrator } %>
-
#
-
# Here's the editor:
-
# <%= render partial: "user", layout: "editor", locals: { user: editor } %>
-
#
-
# <%# app/views/users/_user.html.erb &>
-
# Name: <%= user.name %>
-
#
-
# <%# app/views/users/_administrator.html.erb &>
-
# <div id="administrator">
-
# Budget: $<%= user.budget %>
-
# <%= yield %>
-
# </div>
-
#
-
# <%# app/views/users/_editor.html.erb &>
-
# <div id="editor">
-
# Deadline: <%= user.deadline %>
-
# <%= yield %>
-
# </div>
-
#
-
# ...this will return:
-
#
-
# Here's the administrator:
-
# <div id="administrator">
-
# Budget: $<%= user.budget %>
-
# Name: <%= user.name %>
-
# </div>
-
#
-
# Here's the editor:
-
# <div id="editor">
-
# Deadline: <%= user.deadline %>
-
# Name: <%= user.name %>
-
# </div>
-
#
-
# If a collection is given, the layout will be rendered once for each item in
-
# the collection. For example, these two snippets have the same output:
-
#
-
# <%# app/views/users/_user.html.erb %>
-
# Name: <%= user.name %>
-
#
-
# <%# app/views/users/index.html.erb %>
-
# <%# This does not use layouts %>
-
# <ul>
-
# <% users.each do |user| -%>
-
# <li>
-
# <%= render partial: "user", locals: { user: user } %>
-
# </li>
-
# <% end -%>
-
# </ul>
-
#
-
# <%# app/views/users/_li_layout.html.erb %>
-
# <li>
-
# <%= yield %>
-
# </li>
-
#
-
# <%# app/views/users/index.html.erb %>
-
# <ul>
-
# <%= render partial: "user", layout: "li_layout", collection: users %>
-
# </ul>
-
#
-
# Given two users whose names are Alice and Bob, these snippets return:
-
#
-
# <ul>
-
# <li>
-
# Name: Alice
-
# </li>
-
# <li>
-
# Name: Bob
-
# </li>
-
# </ul>
-
#
-
# The current object being rendered, as well as the object_counter, will be
-
# available as local variables inside the layout template under the same names
-
# as available in the partial.
-
#
-
# You can also apply a layout to a block within any template:
-
#
-
# <%# app/views/users/_chief.html.erb &>
-
# <%= render(layout: "administrator", locals: { user: chief }) do %>
-
# Title: <%= chief.title %>
-
# <% end %>
-
#
-
# ...this will return:
-
#
-
# <div id="administrator">
-
# Budget: $<%= user.budget %>
-
# Title: <%= chief.name %>
-
# </div>
-
#
-
# As you can see, the <tt>:locals</tt> hash is shared between both the partial and its layout.
-
#
-
# If you pass arguments to "yield" then this will be passed to the block. One way to use this is to pass
-
# an array to layout and treat it as an enumerable.
-
#
-
# <%# app/views/users/_user.html.erb &>
-
# <div class="user">
-
# Budget: $<%= user.budget %>
-
# <%= yield user %>
-
# </div>
-
#
-
# <%# app/views/users/index.html.erb &>
-
# <%= render layout: @users do |user| %>
-
# Title: <%= user.title %>
-
# <% end %>
-
#
-
# This will render the layout for each user and yield to the block, passing the user, each time.
-
#
-
# You can also yield multiple times in one layout and use block arguments to differentiate the sections.
-
#
-
# <%# app/views/users/_user.html.erb &>
-
# <div class="user">
-
# <%= yield user, :header %>
-
# Budget: $<%= user.budget %>
-
# <%= yield user, :footer %>
-
# </div>
-
#
-
# <%# app/views/users/index.html.erb &>
-
# <%= render layout: @users do |user, section| %>
-
# <%- case section when :header -%>
-
# Title: <%= user.title %>
-
# <%- when :footer -%>
-
# Deadline: <%= user.deadline %>
-
# <%- end -%>
-
# <% end %>
-
1
class PartialRenderer < AbstractRenderer
-
1
PREFIXED_PARTIAL_NAMES = ThreadSafe::Cache.new do |h, k|
-
h[k] = ThreadSafe::Cache.new
-
end
-
-
1
def initialize(*)
-
13
super
-
13
@context_prefix = @lookup_context.prefixes.first
-
end
-
-
1
def render(context, options, block)
-
13
setup(context, options, block)
-
13
identifier = (@template = find_partial) ? @template.identifier : @path
-
-
13
@lookup_context.rendered_format ||= begin
-
if @template && @template.formats.present?
-
@template.formats.first
-
else
-
formats.first
-
end
-
end
-
-
13
if @collection
-
instrument(:collection, :identifier => identifier || "collection", :count => @collection.size) do
-
render_collection
-
end
-
else
-
13
instrument(:partial, :identifier => identifier) do
-
13
render_partial
-
end
-
end
-
end
-
-
1
def render_collection
-
return nil if @collection.blank?
-
-
if @options.key?(:spacer_template)
-
spacer = find_template(@options[:spacer_template], @locals.keys).render(@view, @locals)
-
end
-
-
result = @template ? collection_with_template : collection_without_template
-
result.join(spacer).html_safe
-
end
-
-
1
def render_partial
-
13
view, locals, block = @view, @locals, @block
-
13
object, as = @object, @variable
-
-
13
if !block && (layout = @options[:layout])
-
layout = find_template(layout.to_s, @template_keys)
-
end
-
-
13
object ||= locals[as]
-
13
locals[as] = object
-
-
13
content = @template.render(view, locals) do |*name|
-
view._layout_for(*name, &block)
-
end
-
-
13
content = layout.render(view, locals){ content } if layout
-
13
content
-
end
-
-
1
private
-
-
# Sets up instance variables needed for rendering a partial. This method
-
# finds the options and details and extracts them. The method also contains
-
# logic that handles the type of object passed in as the partial.
-
#
-
# If +options[:partial]+ is a string, then the +@path+ instance variable is
-
# set to that string. Otherwise, the +options[:partial]+ object must
-
# respond to +to_partial_path+ in order to setup the path.
-
1
def setup(context, options, block)
-
13
@view = context
-
13
partial = options[:partial]
-
-
13
@options = options
-
13
@locals = options[:locals] || {}
-
13
@block = block
-
13
@details = extract_details(options)
-
-
13
prepend_formats(options[:formats])
-
-
13
if String === partial
-
13
@object = options[:object]
-
13
@path = partial
-
13
@collection = collection
-
else
-
@object = partial
-
-
if @collection = collection_from_object || collection
-
paths = @collection_data = @collection.map { |o| partial_path(o) }
-
@path = paths.uniq.size == 1 ? paths.first : nil
-
else
-
@path = partial_path
-
end
-
end
-
-
13
if as = options[:as]
-
raise_invalid_identifier(as) unless as.to_s =~ /\A[a-z_]\w*\z/
-
as = as.to_sym
-
end
-
-
13
if @path
-
13
@variable, @variable_counter = retrieve_variable(@path, as)
-
13
@template_keys = retrieve_template_keys
-
else
-
paths.map! { |path| retrieve_variable(path, as).unshift(path) }
-
end
-
-
13
self
-
end
-
-
1
def collection
-
13
if @options.key?(:collection)
-
collection = @options[:collection]
-
collection.respond_to?(:to_ary) ? collection.to_ary : []
-
end
-
end
-
-
1
def collection_from_object
-
@object.to_ary if @object.respond_to?(:to_ary)
-
end
-
-
1
def find_partial
-
13
if path = @path
-
13
find_template(path, @template_keys)
-
end
-
end
-
-
1
def find_template(path, locals)
-
13
prefixes = path.include?(?/) ? [] : @lookup_context.prefixes
-
13
@lookup_context.find_template(path, prefixes, true, locals, @details)
-
end
-
-
1
def collection_with_template
-
view, locals, template = @view, @locals, @template
-
as, counter = @variable, @variable_counter
-
-
if layout = @options[:layout]
-
layout = find_template(layout, @template_keys)
-
end
-
-
index = -1
-
@collection.map do |object|
-
locals[as] = object
-
locals[counter] = (index += 1)
-
-
content = template.render(view, locals)
-
content = layout.render(view, locals) { content } if layout
-
content
-
end
-
end
-
-
1
def collection_without_template
-
view, locals, collection_data = @view, @locals, @collection_data
-
cache = {}
-
keys = @locals.keys
-
-
index = -1
-
@collection.map do |object|
-
index += 1
-
path, as, counter = collection_data[index]
-
-
locals[as] = object
-
locals[counter] = index
-
-
template = (cache[path] ||= find_template(path, keys + [as, counter]))
-
template.render(view, locals)
-
end
-
end
-
-
# Obtains the path to where the object's partial is located. If the object
-
# responds to +to_partial_path+, then +to_partial_path+ will be called and
-
# will provide the path. If the object does not respond to +to_partial_path+,
-
# then an +ArgumentError+ is raised.
-
#
-
# If +prefix_partial_path_with_controller_namespace+ is true, then this
-
# method will prefix the partial paths with a namespace.
-
1
def partial_path(object = @object)
-
object = object.to_model if object.respond_to?(:to_model)
-
-
path = if object.respond_to?(:to_partial_path)
-
object.to_partial_path
-
else
-
raise ArgumentError.new("'#{object.inspect}' is not an ActiveModel-compatible object. It must implement :to_partial_path.")
-
end
-
-
if @view.prefix_partial_path_with_controller_namespace
-
prefixed_partial_names[path] ||= merge_prefix_into_object_path(@context_prefix, path.dup)
-
else
-
path
-
end
-
end
-
-
1
def prefixed_partial_names
-
@prefixed_partial_names ||= PREFIXED_PARTIAL_NAMES[@context_prefix]
-
end
-
-
1
def merge_prefix_into_object_path(prefix, object_path)
-
if prefix.include?(?/) && object_path.include?(?/)
-
prefixes = []
-
prefix_array = File.dirname(prefix).split('/')
-
object_path_array = object_path.split('/')[0..-3] # skip model dir & partial
-
-
prefix_array.each_with_index do |dir, index|
-
break if dir == object_path_array[index]
-
prefixes << dir
-
end
-
-
(prefixes << object_path).join("/")
-
else
-
object_path
-
end
-
end
-
-
1
def retrieve_template_keys
-
13
keys = @locals.keys
-
13
keys << @variable if @object || @collection
-
13
keys << @variable_counter if @collection
-
13
keys
-
end
-
-
1
def retrieve_variable(path, as)
-
13
variable = as || begin
-
13
base = path[-1] == "/" ? "" : File.basename(path)
-
13
raise_invalid_identifier(path) unless base =~ /\A_?([a-z]\w*)(\.\w+)*\z/
-
13
$1.to_sym
-
end
-
13
variable_counter = :"#{variable}_counter" if @collection
-
13
[variable, variable_counter]
-
end
-
-
1
IDENTIFIER_ERROR_MESSAGE = "The partial name (%s) is not a valid Ruby identifier; " +
-
"make sure your partial name starts with a lowercase letter or underscore, " +
-
"and is followed by any combination of letters, numbers and underscores."
-
-
1
def raise_invalid_identifier(path)
-
raise ArgumentError.new(IDENTIFIER_ERROR_MESSAGE % (path))
-
end
-
end
-
end
-
2
module ActionView
-
# This is the main entry point for rendering. It basically delegates
-
# to other objects like TemplateRenderer and PartialRenderer which
-
# actually renders the template.
-
#
-
# The Renderer will parse the options from the +render+ or +render_body+
-
# method and render a partial or a template based on the options. The
-
# +TemplateRenderer+ and +PartialRenderer+ objects are wrappers which do all
-
# the setup and logic necessary to render a view and a new object is created
-
# each time +render+ is called.
-
2
class Renderer
-
2
attr_accessor :lookup_context
-
-
2
def initialize(lookup_context)
-
24
@lookup_context = lookup_context
-
end
-
-
# Main render entry point shared by AV and AC.
-
2
def render(context, options)
-
24
if options.key?(:partial)
-
render_partial(context, options)
-
else
-
24
render_template(context, options)
-
end
-
end
-
-
# Render but returns a valid Rack body. If fibers are defined, we return
-
# a streaming body that renders the template piece by piece.
-
#
-
# Note that partials are not supported to be rendered with streaming,
-
# so in such cases, we just wrap them in an array.
-
2
def render_body(context, options)
-
if options.key?(:partial)
-
[render_partial(context, options)]
-
else
-
StreamingTemplateRenderer.new(@lookup_context).render(context, options)
-
end
-
end
-
-
# Direct accessor to template rendering.
-
2
def render_template(context, options) #:nodoc:
-
24
TemplateRenderer.new(@lookup_context).render(context, options)
-
end
-
-
# Direct access to partial rendering.
-
2
def render_partial(context, options, &block) #:nodoc:
-
13
PartialRenderer.new(@lookup_context).render(context, options, block)
-
end
-
end
-
end
-
2
require 'active_support/core_ext/object/try'
-
-
2
module ActionView
-
2
class TemplateRenderer < AbstractRenderer #:nodoc:
-
2
def render(context, options)
-
24
@view = context
-
24
@details = extract_details(options)
-
24
template = determine_template(options)
-
24
context = @lookup_context
-
-
24
prepend_formats(template.formats)
-
-
24
unless context.rendered_format
-
24
context.rendered_format = template.formats.first || formats.first
-
end
-
-
24
render_template(template, options[:layout], options[:locals])
-
end
-
-
# Determine the template to be rendered using the given options.
-
2
def determine_template(options) #:nodoc:
-
24
keys = options.fetch(:locals, {}).keys
-
-
24
if options.key?(:body)
-
Template::Text.new(options[:body])
-
24
elsif options.key?(:text)
-
Template::Text.new(options[:text], formats.first)
-
24
elsif options.key?(:plain)
-
Template::Text.new(options[:plain])
-
24
elsif options.key?(:html)
-
Template::HTML.new(options[:html], formats.first)
-
24
elsif options.key?(:file)
-
with_fallbacks { find_template(options[:file], nil, false, keys, @details) }
-
24
elsif options.key?(:inline)
-
handler = Template.handler_for_extension(options[:type] || "erb")
-
Template.new(options[:inline], "inline template", handler, :locals => keys)
-
24
elsif options.key?(:template)
-
24
if options[:template].respond_to?(:render)
-
options[:template]
-
else
-
24
find_template(options[:template], options[:prefixes], false, keys, @details)
-
end
-
else
-
raise ArgumentError, "You invoked render but did not give any of :partial, :template, :inline, :file, :plain, :text or :body option."
-
end
-
end
-
-
# Renders the given template. A string representing the layout can be
-
# supplied as well.
-
2
def render_template(template, layout_name = nil, locals = nil) #:nodoc:
-
24
view, locals = @view, locals || {}
-
-
24
render_with_layout(layout_name, locals) do |layout|
-
24
instrument(:template, :identifier => template.identifier, :layout => layout.try(:virtual_path)) do
-
24
template.render(view, locals) { |*name| view._layout_for(*name) }
-
end
-
end
-
end
-
-
2
def render_with_layout(path, locals) #:nodoc:
-
24
layout = path && find_layout(path, locals.keys)
-
24
content = yield(layout)
-
-
24
if layout
-
24
view = @view
-
24
view.view_flow.set(:layout, content)
-
37
layout.render(view, locals){ |*name| view._layout_for(*name) }
-
else
-
content
-
end
-
end
-
-
# This is the method which actually finds the layout using details in the lookup
-
# context object. If no layout is found, it checks if at least a layout with
-
# the given name exists across all details before raising the error.
-
2
def find_layout(layout, keys)
-
48
with_layout_format { resolve_layout(layout, keys) }
-
end
-
-
2
def resolve_layout(layout, keys)
-
48
case layout
-
when String
-
begin
-
if layout =~ /^\//
-
with_fallbacks { find_template(layout, nil, false, keys, @details) }
-
else
-
find_template(layout, nil, false, keys, @details)
-
end
-
rescue ActionView::MissingTemplate
-
all_details = @details.merge(:formats => @lookup_context.default_formats)
-
raise unless template_exists?(layout, nil, false, keys, all_details)
-
end
-
when Proc
-
24
resolve_layout(layout.call, keys)
-
when FalseClass
-
nil
-
else
-
24
layout
-
end
-
end
-
end
-
end
-
2
require "action_view/view_paths"
-
-
2
module ActionView
-
# This is a class to fix I18n global state. Whenever you provide I18n.locale during a request,
-
# it will trigger the lookup_context and consequently expire the cache.
-
2
class I18nProxy < ::I18n::Config #:nodoc:
-
2
attr_reader :original_config, :lookup_context
-
-
2
def initialize(original_config, lookup_context)
-
24
original_config = original_config.original_config if original_config.respond_to?(:original_config)
-
24
@original_config, @lookup_context = original_config, lookup_context
-
end
-
-
2
def locale
-
46
@original_config.locale
-
end
-
-
2
def locale=(value)
-
@lookup_context.locale = value
-
end
-
end
-
-
2
module Rendering
-
2
extend ActiveSupport::Concern
-
2
include ActionView::ViewPaths
-
-
# Overwrite process to setup I18n proxy.
-
2
def process(*) #:nodoc:
-
24
old_config, I18n.config = I18n.config, I18nProxy.new(I18n.config, lookup_context)
-
24
super
-
ensure
-
24
I18n.config = old_config
-
end
-
-
2
module ClassMethods
-
2
def view_context_class
-
@view_context_class ||= begin
-
8
routes = respond_to?(:_routes) && _routes
-
8
helpers = respond_to?(:_helpers) && _helpers
-
-
8
Class.new(ActionView::Base) do
-
8
if routes
-
8
include routes.url_helpers
-
8
include routes.mounted_helpers
-
end
-
-
8
if helpers
-
8
include helpers
-
end
-
end
-
24
end
-
end
-
end
-
-
2
attr_internal_writer :view_context_class
-
-
2
def view_context_class
-
24
@_view_context_class ||= self.class.view_context_class
-
end
-
-
# An instance of a view class. The default view class is ActionView::Base
-
#
-
# The view class must have the following methods:
-
# View.new[lookup_context, assigns, controller]
-
# Create a new ActionView instance for a controller
-
# View#render[options]
-
# Returns String with the rendered template
-
#
-
# Override this method in a module to change the default behavior.
-
2
def view_context
-
24
view_context_class.new(view_renderer, view_assigns, self)
-
end
-
-
# Returns an object that is able to render templates.
-
# :api: private
-
2
def view_renderer
-
48
@_view_renderer ||= ActionView::Renderer.new(lookup_context)
-
end
-
-
2
def render_to_body(options = {})
-
24
_process_options(options)
-
24
_render_template(options)
-
end
-
-
2
def rendered_format
-
48
Mime[lookup_context.rendered_format]
-
end
-
-
2
private
-
-
# Find and render a template based on the options given.
-
# :api: private
-
2
def _render_template(options) #:nodoc:
-
24
variant = options[:variant]
-
-
24
lookup_context.rendered_format = nil if options[:formats]
-
24
lookup_context.variants = variant if variant
-
-
24
view_renderer.render(view_context, options)
-
end
-
-
# Assign the rendered format to lookup context.
-
2
def _process_format(format, options = {}) #:nodoc:
-
24
super
-
24
lookup_context.formats = [format.to_sym]
-
24
lookup_context.rendered_format = lookup_context.formats.first
-
end
-
-
# Normalize args by converting render "foo" to render :action => "foo" and
-
# render "foo/bar" to render :file => "foo/bar".
-
# :api: private
-
2
def _normalize_args(action=nil, options={})
-
24
options = super(action, options)
-
24
case action
-
when NilClass
-
when Hash
-
options = action
-
when String, Symbol
-
4
action = action.to_s
-
4
key = action.include?(?/) ? :file : :action
-
4
options[key] = action
-
else
-
options[:partial] = action
-
end
-
-
24
options
-
end
-
-
# Normalize options.
-
# :api: private
-
2
def _normalize_options(options)
-
24
options = super(options)
-
24
if options[:partial] == true
-
options[:partial] = action_name
-
end
-
-
24
if (options.keys & [:partial, :file, :template]).empty?
-
24
options[:prefixes] ||= _prefixes
-
end
-
-
24
options[:template] ||= (options[:action] || action_name).to_s
-
24
options
-
end
-
end
-
end
-
2
module ActionView
-
2
module RoutingUrlFor
-
-
# Returns the URL for the set of +options+ provided. This takes the
-
# same options as +url_for+ in Action Controller (see the
-
# documentation for <tt>ActionController::Base#url_for</tt>). Note that by default
-
# <tt>:only_path</tt> is <tt>true</tt> so you'll get the relative "/controller/action"
-
# instead of the fully qualified URL like "http://example.com/controller/action".
-
#
-
# ==== Options
-
# * <tt>:anchor</tt> - Specifies the anchor name to be appended to the path.
-
# * <tt>:only_path</tt> - If true, returns the relative URL (omitting the protocol, host name, and port) (<tt>true</tt> by default unless <tt>:host</tt> is specified).
-
# * <tt>:trailing_slash</tt> - If true, adds a trailing slash, as in "/archive/2005/". Note that this
-
# is currently not recommended since it breaks caching.
-
# * <tt>:host</tt> - Overrides the default (current) host if provided.
-
# * <tt>:protocol</tt> - Overrides the default (current) protocol if provided.
-
# * <tt>:user</tt> - Inline HTTP authentication (only plucked out if <tt>:password</tt> is also present).
-
# * <tt>:password</tt> - Inline HTTP authentication (only plucked out if <tt>:user</tt> is also present).
-
#
-
# ==== Relying on named routes
-
#
-
# Passing a record (like an Active Record) instead of a hash as the options parameter will
-
# trigger the named route for that record. The lookup will happen on the name of the class. So passing a
-
# Workshop object will attempt to use the +workshop_path+ route. If you have a nested route, such as
-
# +admin_workshop_path+ you'll have to call that explicitly (it's impossible for +url_for+ to guess that route).
-
#
-
# ==== Implicit Controller Namespacing
-
#
-
# Controllers passed in using the +:controller+ option will retain their namespace unless it is an absolute one.
-
#
-
# ==== Examples
-
# <%= url_for(action: 'index') %>
-
# # => /blog/
-
#
-
# <%= url_for(action: 'find', controller: 'books') %>
-
# # => /books/find
-
#
-
# <%= url_for(action: 'login', controller: 'members', only_path: false, protocol: 'https') %>
-
# # => https://www.example.com/members/login/
-
#
-
# <%= url_for(action: 'play', anchor: 'player') %>
-
# # => /messages/play/#player
-
#
-
# <%= url_for(action: 'jump', anchor: 'tax&ship') %>
-
# # => /testing/jump/#tax&ship
-
#
-
# <%= url_for(Workshop.new) %>
-
# # relies on Workshop answering a persisted? call (and in this case returning false)
-
# # => /workshops
-
#
-
# <%= url_for(@workshop) %>
-
# # calls @workshop.to_param which by default returns the id
-
# # => /workshops/5
-
#
-
# # to_param can be re-defined in a model to provide different URL names:
-
# # => /workshops/1-workshop-name
-
#
-
# <%= url_for("http://www.example.com") %>
-
# # => http://www.example.com
-
#
-
# <%= url_for(:back) %>
-
# # if request.env["HTTP_REFERER"] is set to "http://www.example.com"
-
# # => http://www.example.com
-
#
-
# <%= url_for(:back) %>
-
# # if request.env["HTTP_REFERER"] is not set or is blank
-
# # => javascript:history.back()
-
#
-
# <%= url_for(action: 'index', controller: 'users') %>
-
# # Assuming an "admin" namespace
-
# # => /admin/users
-
#
-
# <%= url_for(action: 'index', controller: '/users') %>
-
# # Specify absolute path with beginning slash
-
# # => /users
-
2
def url_for(options = nil)
-
65
case options
-
when String
-
53
options
-
when nil, Hash
-
12
options ||= {}
-
12
options = { :only_path => options[:host].nil? }.merge!(options.symbolize_keys)
-
12
super
-
when :back
-
_back_url
-
when Array
-
polymorphic_path(options, options.extract_options!)
-
else
-
polymorphic_path(options)
-
end
-
end
-
-
2
def url_options #:nodoc:
-
61
return super unless controller.respond_to?(:url_options)
-
61
controller.url_options
-
end
-
-
2
def _routes_context #:nodoc:
-
controller
-
end
-
2
protected :_routes_context
-
-
2
def optimize_routes_generation? #:nodoc:
-
49
controller.respond_to?(:optimize_routes_generation?, true) ?
-
controller.optimize_routes_generation? : super
-
end
-
2
protected :optimize_routes_generation?
-
end
-
end
-
2
require 'active_support/core_ext/object/try'
-
2
require 'active_support/core_ext/kernel/singleton_class'
-
2
require 'thread'
-
-
2
module ActionView
-
# = Action View Template
-
2
class Template
-
2
extend ActiveSupport::Autoload
-
-
# === Encodings in ActionView::Template
-
#
-
# ActionView::Template is one of a few sources of potential
-
# encoding issues in Rails. This is because the source for
-
# templates are usually read from disk, and Ruby (like most
-
# encoding-aware programming languages) assumes that the
-
# String retrieved through File IO is encoded in the
-
# <tt>default_external</tt> encoding. In Rails, the default
-
# <tt>default_external</tt> encoding is UTF-8.
-
#
-
# As a result, if a user saves their template as ISO-8859-1
-
# (for instance, using a non-Unicode-aware text editor),
-
# and uses characters outside of the ASCII range, their
-
# users will see diamonds with question marks in them in
-
# the browser.
-
#
-
# For the rest of this documentation, when we say "UTF-8",
-
# we mean "UTF-8 or whatever the default_internal encoding
-
# is set to". By default, it will be UTF-8.
-
#
-
# To mitigate this problem, we use a few strategies:
-
# 1. If the source is not valid UTF-8, we raise an exception
-
# when the template is compiled to alert the user
-
# to the problem.
-
# 2. The user can specify the encoding using Ruby-style
-
# encoding comments in any template engine. If such
-
# a comment is supplied, Rails will apply that encoding
-
# to the resulting compiled source returned by the
-
# template handler.
-
# 3. In all cases, we transcode the resulting String to
-
# the UTF-8.
-
#
-
# This means that other parts of Rails can always assume
-
# that templates are encoded in UTF-8, even if the original
-
# source of the template was not UTF-8.
-
#
-
# From a user's perspective, the easiest thing to do is
-
# to save your templates as UTF-8. If you do this, you
-
# do not need to do anything else for things to "just work".
-
#
-
# === Instructions for template handlers
-
#
-
# The easiest thing for you to do is to simply ignore
-
# encodings. Rails will hand you the template source
-
# as the default_internal (generally UTF-8), raising
-
# an exception for the user before sending the template
-
# to you if it could not determine the original encoding.
-
#
-
# For the greatest simplicity, you can support only
-
# UTF-8 as the <tt>default_internal</tt>. This means
-
# that from the perspective of your handler, the
-
# entire pipeline is just UTF-8.
-
#
-
# === Advanced: Handlers with alternate metadata sources
-
#
-
# If you want to provide an alternate mechanism for
-
# specifying encodings (like ERB does via <%# encoding: ... %>),
-
# you may indicate that you will handle encodings yourself
-
# by implementing <tt>self.handles_encoding?</tt>
-
# on your handler.
-
#
-
# If you do, Rails will not try to encode the String
-
# into the default_internal, passing you the unaltered
-
# bytes tagged with the assumed encoding (from
-
# default_external).
-
#
-
# In this case, make sure you return a String from
-
# your handler encoded in the default_internal. Since
-
# you are handling out-of-band metadata, you are
-
# also responsible for alerting the user to any
-
# problems with converting the user's data to
-
# the <tt>default_internal</tt>.
-
#
-
# To do so, simply raise +WrongEncodingError+ as follows:
-
#
-
# raise WrongEncodingError.new(
-
# problematic_string,
-
# expected_encoding
-
# )
-
-
2
eager_autoload do
-
2
autoload :Error
-
2
autoload :Handlers
-
2
autoload :HTML
-
2
autoload :Text
-
2
autoload :Types
-
end
-
-
2
extend Template::Handlers
-
-
2
attr_accessor :locals, :formats, :variants, :virtual_path
-
-
2
attr_reader :source, :identifier, :handler, :original_encoding, :updated_at
-
-
# This finalizer is needed (and exactly with a proc inside another proc)
-
# otherwise templates leak in development.
-
2
Finalizer = proc do |method_name, mod|
-
18
proc do
-
mod.module_eval do
-
remove_possible_method method_name
-
end
-
end
-
end
-
-
2
def initialize(source, identifier, handler, details)
-
30
format = details[:format] || (handler.default_format if handler.respond_to?(:default_format))
-
-
30
@source = source
-
30
@identifier = identifier
-
30
@handler = handler
-
30
@compiled = false
-
30
@original_encoding = nil
-
30
@locals = details[:locals] || []
-
30
@virtual_path = details[:virtual_path]
-
30
@updated_at = details[:updated_at] || Time.now
-
60
@formats = Array(format).map { |f| f.respond_to?(:ref) ? f.ref : f }
-
30
@variants = [details[:variant]]
-
30
@compile_mutex = Mutex.new
-
end
-
-
# Returns if the underlying handler supports streaming. If so,
-
# a streaming buffer *may* be passed when it start rendering.
-
2
def supports_streaming?
-
handler.respond_to?(:supports_streaming?) && handler.supports_streaming?
-
end
-
-
# Render a template. If the template was not compiled yet, it is done
-
# exactly before rendering.
-
#
-
# This method is instrumented as "!render_template.action_view". Notice that
-
# we use a bang in this instrumentation because you don't want to
-
# consume this in production. This is only slow if it's being listened to.
-
2
def render(view, locals, buffer=nil, &block)
-
61
instrument("!render_template") do
-
61
compile!(view)
-
61
view.send(method_name, locals, buffer, &block)
-
end
-
rescue => e
-
handle_render_error(view, e)
-
end
-
-
2
def type
-
6
@type ||= Types[@formats.first] if @formats.first
-
end
-
-
# Receives a view object and return a template similar to self by using @virtual_path.
-
#
-
# This method is useful if you have a template object but it does not contain its source
-
# anymore since it was already compiled. In such cases, all you need to do is to call
-
# refresh passing in the view object.
-
#
-
# Notice this method raises an error if the template to be refreshed does not have a
-
# virtual path set (true just for inline templates).
-
2
def refresh(view)
-
raise "A template needs to have a virtual path in order to be refreshed" unless @virtual_path
-
lookup = view.lookup_context
-
pieces = @virtual_path.split("/")
-
name = pieces.pop
-
partial = !!name.sub!(/^_/, "")
-
lookup.disable_cache do
-
lookup.find_template(name, [ pieces.join('/') ], partial, @locals)
-
end
-
end
-
-
2
def inspect
-
18
@inspect ||= defined?(Rails.root) ? identifier.sub("#{Rails.root}/", '') : identifier
-
end
-
-
# This method is responsible for properly setting the encoding of the
-
# source. Until this point, we assume that the source is BINARY data.
-
# If no additional information is supplied, we assume the encoding is
-
# the same as <tt>Encoding.default_external</tt>.
-
#
-
# The user can also specify the encoding via a comment on the first
-
# line of the template (# encoding: NAME-OF-ENCODING). This will work
-
# with any template engine, as we process out the encoding comment
-
# before passing the source on to the template engine, leaving a
-
# blank line in its stead.
-
2
def encode!
-
18
return unless source.encoding == Encoding::BINARY
-
-
# Look for # encoding: *. If we find one, we'll encode the
-
# String in that encoding, otherwise, we'll use the
-
# default external encoding.
-
6
if source.sub!(/\A#{ENCODING_FLAG}/, '')
-
encoding = magic_encoding = $1
-
else
-
6
encoding = Encoding.default_external
-
end
-
-
# Tag the source with the default external encoding
-
# or the encoding specified in the file
-
6
source.force_encoding(encoding)
-
-
# If the user didn't specify an encoding, and the handler
-
# handles encodings, we simply pass the String as is to
-
# the handler (with the default_external tag)
-
6
if !magic_encoding && @handler.respond_to?(:handles_encoding?) && @handler.handles_encoding?
-
6
source
-
# Otherwise, if the String is valid in the encoding,
-
# encode immediately to default_internal. This means
-
# that if a handler doesn't handle encodings, it will
-
# always get Strings in the default_internal
-
elsif source.valid_encoding?
-
source.encode!
-
# Otherwise, since the String is invalid in the encoding
-
# specified, raise an exception
-
else
-
raise WrongEncodingError.new(source, encoding)
-
end
-
end
-
-
2
protected
-
-
# Compile a template. This method ensures a template is compiled
-
# just once and removes the source after it is compiled.
-
2
def compile!(view) #:nodoc:
-
61
return if @compiled
-
-
# Templates can be used concurrently in threaded environments
-
# so compilation and any instance variable modification must
-
# be synchronized
-
18
@compile_mutex.synchronize do
-
# Any thread holding this lock will be compiling the template needed
-
# by the threads waiting. So re-check the @compiled flag to avoid
-
# re-compilation
-
18
return if @compiled
-
-
18
if view.is_a?(ActionView::CompiledTemplates)
-
18
mod = ActionView::CompiledTemplates
-
else
-
mod = view.singleton_class
-
end
-
-
18
instrument("!compile_template") do
-
18
compile(view, mod)
-
end
-
-
# Just discard the source if we have a virtual path. This
-
# means we can get the template back.
-
18
@source = nil if @virtual_path
-
18
@compiled = true
-
end
-
end
-
-
# Among other things, this method is responsible for properly setting
-
# the encoding of the compiled template.
-
#
-
# If the template engine handles encodings, we send the encoded
-
# String to the engine without further processing. This allows
-
# the template engine to support additional mechanisms for
-
# specifying the encoding. For instance, ERB supports <%# encoding: %>
-
#
-
# Otherwise, after we figure out the correct encoding, we then
-
# encode the source into <tt>Encoding.default_internal</tt>.
-
# In general, this means that templates will be UTF-8 inside of Rails,
-
# regardless of the original source encoding.
-
2
def compile(view, mod) #:nodoc:
-
18
encode!
-
18
method_name = self.method_name
-
18
code = @handler.call(self)
-
-
# Make sure that the resulting String to be eval'd is in the
-
# encoding of the code
-
18
source = <<-end_src
-
def #{method_name}(local_assigns, output_buffer)
-
_old_virtual_path, @virtual_path = @virtual_path, #{@virtual_path.inspect};_old_output_buffer = @output_buffer;#{locals_code};#{code}
-
ensure
-
@virtual_path, @output_buffer = _old_virtual_path, _old_output_buffer
-
end
-
end_src
-
-
# Make sure the source is in the encoding of the returned code
-
18
source.force_encoding(code.encoding)
-
-
# In case we get back a String from a handler that is not in
-
# BINARY or the default_internal, encode it to the default_internal
-
18
source.encode!
-
-
# Now, validate that the source we got back from the template
-
# handler is valid in the default_internal. This is for handlers
-
# that handle encoding but screw up
-
18
unless source.valid_encoding?
-
raise WrongEncodingError.new(@source, Encoding.default_internal)
-
end
-
-
18
begin
-
18
mod.module_eval(source, identifier, 0)
-
18
ObjectSpace.define_finalizer(self, Finalizer[method_name, mod])
-
rescue => e # errors from template code
-
if logger = (view && view.logger)
-
logger.debug "ERROR: compiling #{method_name} RAISED #{e}"
-
logger.debug "Function body: #{source}"
-
logger.debug "Backtrace: #{e.backtrace.join("\n")}"
-
end
-
-
raise ActionView::Template::Error.new(self, e)
-
end
-
end
-
-
2
def handle_render_error(view, e) #:nodoc:
-
if e.is_a?(Template::Error)
-
e.sub_template_of(self)
-
raise e
-
else
-
template = self
-
unless template.source
-
template = refresh(view)
-
template.encode!
-
end
-
raise Template::Error.new(template, e)
-
end
-
end
-
-
2
def locals_code #:nodoc:
-
# Double assign to suppress the dreaded 'assigned but unused variable' warning
-
18
@locals.map { |key| "#{key} = #{key} = local_assigns[:#{key}];" }.join
-
end
-
-
2
def method_name #:nodoc:
-
79
@method_name ||= "_#{identifier_method_name}__#{@identifier.hash}_#{__id__}".gsub('-', "_")
-
end
-
-
2
def identifier_method_name #:nodoc:
-
18
inspect.gsub(/[^a-z_]/, '_')
-
end
-
-
2
def instrument(action, &block)
-
79
payload = { virtual_path: @virtual_path, identifier: @identifier }
-
79
ActiveSupport::Notifications.instrument("#{action}.action_view", payload, &block)
-
end
-
end
-
end
-
2
module ActionView #:nodoc:
-
# = Action View Template Handlers
-
2
class Template
-
2
module Handlers #:nodoc:
-
2
autoload :ERB, 'action_view/template/handlers/erb'
-
2
autoload :Builder, 'action_view/template/handlers/builder'
-
2
autoload :Raw, 'action_view/template/handlers/raw'
-
-
2
def self.extended(base)
-
2
base.register_default_template_handler :erb, ERB.new
-
2
base.register_template_handler :builder, Builder.new
-
2
base.register_template_handler :raw, Raw.new
-
2
base.register_template_handler :ruby, :source.to_proc
-
end
-
-
2
@@template_handlers = {}
-
2
@@default_template_handlers = nil
-
-
2
def self.extensions
-
24
@@template_extensions ||= @@template_handlers.keys
-
end
-
-
# Register an object that knows how to handle template files with the given
-
# extensions. This can be used to implement new template types.
-
# The handler must respond to `:call`, which will be passed the template
-
# and should return the rendered template as a String.
-
2
def register_template_handler(*extensions, handler)
-
12
raise(ArgumentError, "Extension is required") if extensions.empty?
-
12
extensions.each do |extension|
-
12
@@template_handlers[extension.to_sym] = handler
-
end
-
12
@@template_extensions = nil
-
end
-
-
2
def template_handler_extensions
-
@@template_handlers.keys.map {|key| key.to_s }.sort
-
end
-
-
2
def registered_template_handler(extension)
-
22
extension && @@template_handlers[extension.to_sym]
-
end
-
-
2
def register_default_template_handler(extension, klass)
-
2
register_template_handler(extension, klass)
-
2
@@default_template_handlers = klass
-
end
-
-
2
def handler_for_extension(extension)
-
22
registered_template_handler(extension) || @@default_template_handlers
-
end
-
end
-
end
-
end
-
2
module ActionView
-
2
module Template::Handlers
-
2
class Builder
-
# Default format used by Builder.
-
2
class_attribute :default_format
-
2
self.default_format = :xml
-
-
2
def call(template)
-
require_engine
-
"xml = ::Builder::XmlMarkup.new(:indent => 2);" +
-
"self.output_buffer = xml.target!;" +
-
template.source +
-
";xml.target!;"
-
end
-
-
2
protected
-
-
2
def require_engine
-
@required ||= begin
-
require "builder"
-
true
-
end
-
end
-
end
-
end
-
end
-
2
require 'erubis'
-
-
2
module ActionView
-
2
class Template
-
2
module Handlers
-
2
class Erubis < ::Erubis::Eruby
-
2
def add_preamble(src)
-
6
@newline_pending = 0
-
6
src << "@output_buffer = output_buffer || ActionView::OutputBuffer.new;"
-
end
-
-
2
def add_text(src, text)
-
80
return if text.empty?
-
-
80
if text == "\n"
-
17
@newline_pending += 1
-
else
-
63
src << "@output_buffer.safe_append='"
-
63
src << "\n" * @newline_pending if @newline_pending > 0
-
63
src << escape_text(text)
-
63
src << "'.freeze;"
-
-
63
@newline_pending = 0
-
end
-
end
-
-
# Erubis toggles <%= and <%== behavior when escaping is enabled.
-
# We override to always treat <%== as escaped.
-
2
def add_expr(src, code, indicator)
-
37
case indicator
-
when '=='
-
add_expr_escaped(src, code)
-
else
-
37
super
-
end
-
end
-
-
2
BLOCK_EXPR = /\s+(do|\{)(\s*\|[^|]*\|)?\s*\Z/
-
-
2
def add_expr_literal(src, code)
-
37
flush_newline_if_pending(src)
-
37
if code =~ BLOCK_EXPR
-
3
src << '@output_buffer.append= ' << code
-
else
-
34
src << '@output_buffer.append=(' << code << ');'
-
end
-
end
-
-
2
def add_expr_escaped(src, code)
-
flush_newline_if_pending(src)
-
if code =~ BLOCK_EXPR
-
src << "@output_buffer.safe_append= " << code
-
else
-
src << "@output_buffer.safe_append=(" << code << ");"
-
end
-
end
-
-
2
def add_stmt(src, code)
-
5
flush_newline_if_pending(src)
-
5
super
-
end
-
-
2
def add_postamble(src)
-
6
flush_newline_if_pending(src)
-
6
src << '@output_buffer.to_s'
-
end
-
-
2
def flush_newline_if_pending(src)
-
48
if @newline_pending > 0
-
src << "@output_buffer.safe_append='#{"\n" * @newline_pending}'.freeze;"
-
@newline_pending = 0
-
end
-
end
-
end
-
-
2
class ERB
-
# Specify trim mode for the ERB compiler. Defaults to '-'.
-
# See ERB documentation for suitable values.
-
2
class_attribute :erb_trim_mode
-
2
self.erb_trim_mode = '-'
-
-
# Default implementation used.
-
2
class_attribute :erb_implementation
-
2
self.erb_implementation = Erubis
-
-
# Do not escape templates of these mime types.
-
2
class_attribute :escape_whitelist
-
2
self.escape_whitelist = ["text/plain"]
-
-
2
ENCODING_TAG = Regexp.new("\\A(<%#{ENCODING_FLAG}-?%>)[ \\t]*")
-
-
2
def self.call(template)
-
new.call(template)
-
end
-
-
2
def supports_streaming?
-
true
-
end
-
-
2
def handles_encoding?
-
6
true
-
end
-
-
2
def call(template)
-
# First, convert to BINARY, so in case the encoding is
-
# wrong, we can still find an encoding tag
-
# (<%# encoding %>) inside the String using a regular
-
# expression
-
6
template_source = template.source.dup.force_encoding(Encoding::ASCII_8BIT)
-
-
6
erb = template_source.gsub(ENCODING_TAG, '')
-
6
encoding = $2
-
-
6
erb.force_encoding valid_encoding(template.source.dup, encoding)
-
-
# Always make sure we return a String in the default_internal
-
6
erb.encode!
-
-
self.class.erb_implementation.new(
-
erb,
-
6
:escape => (self.class.escape_whitelist.include? template.type),
-
6
:trim => (self.class.erb_trim_mode == "-")
-
6
).src
-
end
-
-
2
private
-
-
2
def valid_encoding(string, encoding)
-
# If a magic encoding comment was found, tag the
-
# String with this encoding. This is for a case
-
# where the original String was assumed to be,
-
# for instance, UTF-8, but a magic comment
-
# proved otherwise
-
6
string.force_encoding(encoding) if encoding
-
-
# If the String is valid, return the encoding we found
-
6
return string.encoding if string.valid_encoding?
-
-
# Otherwise, raise an exception
-
raise WrongEncodingError.new(string, string.encoding)
-
end
-
end
-
end
-
end
-
end
-
2
module ActionView
-
2
module Template::Handlers
-
2
class Raw
-
2
def call(template)
-
escaped = template.source.gsub(':', '\:')
-
-
'%q:' + escaped + ':;'
-
end
-
end
-
end
-
end
-
2
require "pathname"
-
2
require "active_support/core_ext/class"
-
2
require "active_support/core_ext/module/attribute_accessors"
-
2
require "action_view/template"
-
2
require "thread"
-
2
require "thread_safe"
-
-
2
module ActionView
-
# = Action View Resolver
-
2
class Resolver
-
# Keeps all information about view path and builds virtual path.
-
2
class Path
-
2
attr_reader :name, :prefix, :partial, :virtual
-
2
alias_method :partial?, :partial
-
-
2
def self.build(name, prefix, partial)
-
42
virtual = ""
-
42
virtual << "#{prefix}/" unless prefix.empty?
-
42
virtual << (partial ? "_#{name}" : name)
-
42
new name, prefix, partial, virtual
-
end
-
-
2
def initialize(name, prefix, partial, virtual)
-
42
@name = name
-
42
@prefix = prefix
-
42
@partial = partial
-
42
@virtual = virtual
-
end
-
-
2
def to_str
-
18
@virtual
-
end
-
2
alias :to_s :to_str
-
end
-
-
# Threadsafe template cache
-
2
class Cache #:nodoc:
-
2
class SmallCache < ThreadSafe::Cache
-
2
def initialize(options = {})
-
148
super(options.merge(:initial_capacity => 2))
-
end
-
end
-
-
# preallocate all the default blocks for performance/memory consumption reasons
-
44
PARTIAL_BLOCK = lambda {|cache, partial| cache[partial] = SmallCache.new}
-
44
PREFIX_BLOCK = lambda {|cache, prefix| cache[prefix] = SmallCache.new(&PARTIAL_BLOCK)}
-
41
NAME_BLOCK = lambda {|cache, name| cache[name] = SmallCache.new(&PREFIX_BLOCK)}
-
8
KEY_BLOCK = lambda {|cache, key| cache[key] = SmallCache.new(&NAME_BLOCK)}
-
-
# usually a majority of template look ups return nothing, use this canonical preallocated array to save memory
-
2
NO_TEMPLATES = [].freeze
-
-
2
def initialize
-
19
@data = SmallCache.new(&KEY_BLOCK)
-
end
-
-
# Cache the templates returned by the block
-
2
def cache(key, name, prefix, partial, locals)
-
133
if Resolver.caching?
-
133
@data[key][name][prefix][partial][locals] ||= canonical_no_templates(yield)
-
else
-
fresh_templates = yield
-
cached_templates = @data[key][name][prefix][partial][locals]
-
-
if templates_have_changed?(cached_templates, fresh_templates)
-
@data[key][name][prefix][partial][locals] = canonical_no_templates(fresh_templates)
-
else
-
cached_templates || NO_TEMPLATES
-
end
-
end
-
end
-
-
2
def clear
-
@data.clear
-
end
-
-
2
private
-
-
2
def canonical_no_templates(templates)
-
42
templates.empty? ? NO_TEMPLATES : templates
-
end
-
-
2
def templates_have_changed?(cached_templates, fresh_templates)
-
# if either the old or new template list is empty, we don't need to (and can't)
-
# compare modification times, and instead just check whether the lists are different
-
if cached_templates.blank? || fresh_templates.blank?
-
return fresh_templates.blank? != cached_templates.blank?
-
end
-
-
cached_templates_max_updated_at = cached_templates.map(&:updated_at).max
-
-
# if a template has changed, it will be now be newer than all the cached templates
-
fresh_templates.any? { |t| t.updated_at > cached_templates_max_updated_at }
-
end
-
end
-
-
2
cattr_accessor :caching
-
2
self.caching = true
-
-
2
class << self
-
2
alias :caching? :caching
-
end
-
-
2
def initialize
-
19
@cache = Cache.new
-
end
-
-
2
def clear_cache
-
@cache.clear
-
end
-
-
# Normalizes the arguments and passes it on to find_templates.
-
2
def find_all(name, prefix=nil, partial=false, details={}, key=nil, locals=[])
-
133
cached(key, [name, prefix, partial], details, locals) do
-
42
find_templates(name, prefix, partial, details)
-
end
-
end
-
-
2
private
-
-
2
delegate :caching?, to: :class
-
-
# This is what child classes implement. No defaults are needed
-
# because Resolver guarantees that the arguments are present and
-
# normalized.
-
2
def find_templates(name, prefix, partial, details)
-
raise NotImplementedError, "Subclasses must implement a find_templates(name, prefix, partial, details) method"
-
end
-
-
# Helpers that builds a path. Useful for building virtual paths.
-
2
def build_path(name, prefix, partial)
-
Path.build(name, prefix, partial)
-
end
-
-
# Handles templates caching. If a key is given and caching is on
-
# always check the cache before hitting the resolver. Otherwise,
-
# it always hits the resolver but if the key is present, check if the
-
# resolver is fresher before returning it.
-
2
def cached(key, path_info, details, locals) #:nodoc:
-
133
name, prefix, partial = path_info
-
133
locals = locals.map { |x| x.to_s }.sort!
-
-
133
if key
-
133
@cache.cache(key, name, prefix, partial, locals) do
-
42
decorate(yield, path_info, details, locals)
-
end
-
else
-
decorate(yield, path_info, details, locals)
-
end
-
end
-
-
# Ensures all the resolver information is set in the template.
-
2
def decorate(templates, path_info, details, locals) #:nodoc:
-
42
cached = nil
-
42
templates.each do |t|
-
18
t.locals = locals
-
18
t.formats = details[:formats] || [:html] if t.formats.empty?
-
18
t.variants = details[:variants] || [] if t.variants.empty?
-
18
t.virtual_path ||= (cached ||= build_path(*path_info))
-
end
-
end
-
end
-
-
# An abstract class that implements a Resolver with path semantics.
-
2
class PathResolver < Resolver #:nodoc:
-
2
EXTENSIONS = { :locale => ".", :formats => ".", :variants => "+", :handlers => "." }
-
2
DEFAULT_PATTERN = ":prefix/:action{.:locale,}{.:formats,}{+:variants,}{.:handlers,}"
-
-
2
def initialize(pattern=nil)
-
19
@pattern = pattern || DEFAULT_PATTERN
-
19
super()
-
end
-
-
2
private
-
-
2
def find_templates(name, prefix, partial, details)
-
42
path = Path.build(name, prefix, partial)
-
42
query(path, details, details[:formats])
-
end
-
-
2
def query(path, details, formats)
-
42
query = build_query(path, details)
-
-
42
template_paths = find_template_paths query
-
-
42
template_paths.map { |template|
-
18
handler, format, variant = extract_handler_and_format_and_variant(template, formats)
-
18
contents = File.binread(template)
-
-
18
Template.new(contents, File.expand_path(template), handler,
-
:virtual_path => path.virtual,
-
:format => format,
-
:variant => variant,
-
:updated_at => mtime(template)
-
)
-
}
-
end
-
-
2
if RUBY_VERSION >= '2.2.0'
-
2
def find_template_paths(query)
-
42
Dir[query].reject { |filename|
-
File.directory?(filename) ||
-
# deals with case-insensitive file systems.
-
18
!File.fnmatch(query, filename, File::FNM_EXTGLOB)
-
}
-
end
-
else
-
def find_template_paths(query)
-
# deals with case-insensitive file systems.
-
sanitizer = Hash.new { |h,dir| h[dir] = Dir["#{dir}/*"] }
-
-
Dir[query].reject { |filename|
-
File.directory?(filename) ||
-
!sanitizer[File.dirname(filename)].include?(filename)
-
}
-
end
-
end
-
-
# Helper for building query glob string based on resolver's pattern.
-
2
def build_query(path, details)
-
24
query = @pattern.dup
-
-
24
prefix = path.prefix.empty? ? "" : "#{escape_entry(path.prefix)}\\1"
-
24
query.gsub!(/\:prefix(\/)?/, prefix)
-
-
24
partial = escape_entry(path.partial? ? "_#{path.name}" : path.name)
-
24
query.gsub!(/\:action/, partial)
-
-
24
details.each do |ext, variants|
-
96
query.gsub!(/\:#{ext}/, "{#{variants.compact.uniq.join(',')}}")
-
end
-
-
24
File.expand_path(query, @path)
-
end
-
-
2
def escape_entry(entry)
-
66
entry.gsub(/[*?{}\[\]]/, '\\\\\\&')
-
end
-
-
# Returns the file mtime from the filesystem.
-
2
def mtime(p)
-
18
File.mtime(p)
-
end
-
-
# Extract handler and formats from path. If a format cannot be a found neither
-
# from the path, or the handler, we should return the array of formats given
-
# to the resolver.
-
2
def extract_handler_and_format_and_variant(path, default_formats)
-
18
pieces = File.basename(path).split(".")
-
18
pieces.shift
-
-
18
extension = pieces.pop
-
18
unless extension
-
message = "The file #{path} did not specify a template handler. The default is currently ERB, " \
-
"but will change to RAW in the future."
-
ActiveSupport::Deprecation.warn message
-
end
-
-
18
handler = Template.handler_for_extension(extension)
-
18
format, variant = pieces.last.split(EXTENSIONS[:variants], 2) if pieces.last
-
18
format &&= Template::Types[format]
-
-
18
[handler, format, variant]
-
end
-
end
-
-
# A resolver that loads files from the filesystem. It allows setting your own
-
# resolving pattern. Such pattern can be a glob string supported by some variables.
-
#
-
# ==== Examples
-
#
-
# Default pattern, loads views the same way as previous versions of rails, eg. when you're
-
# looking for `users/new` it will produce query glob: `users/new{.{en},}{.{html,js},}{.{erb,haml},}`
-
#
-
# FileSystemResolver.new("/path/to/views", ":prefix/:action{.:locale,}{.:formats,}{.:handlers,}")
-
#
-
# This one allows you to keep files with different formats in separate subdirectories,
-
# eg. `users/new.html` will be loaded from `users/html/new.erb` or `users/new.html.erb`,
-
# `users/new.js` from `users/js/new.erb` or `users/new.js.erb`, etc.
-
#
-
# FileSystemResolver.new("/path/to/views", ":prefix/{:formats/,}:action{.:locale,}{.:formats,}{.:handlers,}")
-
#
-
# If you don't specify a pattern then the default will be used.
-
#
-
# In order to use any of the customized resolvers above in a Rails application, you just need
-
# to configure ActionController::Base.view_paths in an initializer, for example:
-
#
-
# ActionController::Base.view_paths = FileSystemResolver.new(
-
# Rails.root.join("app/views"),
-
# ":prefix{/:locale}/:action{.:formats,}{.:handlers,}"
-
# )
-
#
-
# ==== Pattern format and variables
-
#
-
# Pattern has to be a valid glob string, and it allows you to use the
-
# following variables:
-
#
-
# * <tt>:prefix</tt> - usually the controller path
-
# * <tt>:action</tt> - name of the action
-
# * <tt>:locale</tt> - possible locale versions
-
# * <tt>:formats</tt> - possible request formats (for example html, json, xml...)
-
# * <tt>:handlers</tt> - possible handlers (for example erb, haml, builder...)
-
#
-
2
class FileSystemResolver < PathResolver
-
2
def initialize(path, pattern=nil)
-
19
raise ArgumentError, "path already is a Resolver class" if path.is_a?(Resolver)
-
19
super(pattern)
-
19
@path = File.expand_path(path)
-
end
-
-
2
def to_s
-
45
@path.to_s
-
end
-
2
alias :to_path :to_s
-
-
2
def eql?(resolver)
-
self.class.equal?(resolver.class) && to_path == resolver.to_path
-
end
-
2
alias :== :eql?
-
end
-
-
# An Optimized resolver for Rails' most common case.
-
2
class OptimizedFileSystemResolver < FileSystemResolver #:nodoc:
-
2
def build_query(path, details)
-
18
query = escape_entry(File.join(@path, path))
-
-
18
exts = EXTENSIONS.map do |ext, prefix|
-
216
"{#{details[ext].compact.uniq.map { |e| "#{prefix}#{e}," }.join}}"
-
end.join
-
-
18
query + exts
-
end
-
end
-
-
# The same as FileSystemResolver but does not allow templates to store
-
# a virtual path since it is invalid for such resolvers.
-
2
class FallbackFileSystemResolver < FileSystemResolver #:nodoc:
-
2
def self.instances
-
2
[new(""), new("/")]
-
end
-
-
2
def decorate(*)
-
super.each { |t| t.virtual_path = nil }
-
end
-
end
-
end
-
2
require 'set'
-
2
require 'active_support/core_ext/module/attribute_accessors'
-
-
2
module ActionView
-
2
class Template
-
2
class Types
-
2
class Type
-
2
cattr_accessor :types
-
2
self.types = Set.new
-
-
2
def self.register(*t)
-
14
types.merge(t.map { |type| type.to_s })
-
end
-
-
2
register :html, :text, :js, :css, :xml, :json
-
-
2
def self.[](type)
-
return type if type.is_a?(self)
-
-
if type.is_a?(Symbol) || types.member?(type.to_s)
-
new(type)
-
end
-
end
-
-
2
attr_reader :symbol
-
-
2
def initialize(symbol)
-
@symbol = symbol.to_sym
-
end
-
-
2
delegate :to_s, :to_sym, :to => :symbol
-
2
alias to_str to_s
-
-
2
def ref
-
to_sym || to_s
-
end
-
-
2
def ==(type)
-
return false if type.blank?
-
symbol.to_sym == type.to_sym
-
end
-
end
-
-
2
cattr_accessor :type_klass
-
-
2
def self.delegate_to(klass)
-
4
self.type_klass = klass
-
end
-
-
2
delegate_to Type
-
-
2
def self.[](type)
-
24
type_klass[type]
-
end
-
end
-
end
-
end
-
1
require 'active_support/core_ext/module/remove_method'
-
1
require 'action_controller'
-
1
require 'action_controller/test_case'
-
1
require 'action_view'
-
-
1
module ActionView
-
# = Action View Test Case
-
1
class TestCase < ActiveSupport::TestCase
-
1
class TestController < ActionController::Base
-
1
include ActionDispatch::TestProcess
-
-
1
attr_accessor :request, :response, :params
-
-
1
class << self
-
1
attr_writer :controller_path
-
end
-
-
1
def controller_path=(path)
-
self.class.controller_path=(path)
-
end
-
-
1
def initialize
-
super
-
self.class.controller_path = ""
-
@request = ActionController::TestRequest.new
-
@response = ActionController::TestResponse.new
-
-
@request.env.delete('PATH_INFO')
-
@params = {}
-
end
-
end
-
-
1
module Behavior
-
1
extend ActiveSupport::Concern
-
-
1
include ActionDispatch::Assertions, ActionDispatch::TestProcess
-
1
include ActionController::TemplateAssertions
-
1
include ActionView::Context
-
-
1
include ActionDispatch::Routing::PolymorphicRoutes
-
-
1
include AbstractController::Helpers
-
1
include ActionView::Helpers
-
1
include ActionView::RecordIdentifier
-
1
include ActionView::RoutingUrlFor
-
-
1
include ActiveSupport::Testing::ConstantLookup
-
-
1
delegate :lookup_context, :to => :controller
-
1
attr_accessor :controller, :output_buffer, :rendered
-
-
1
module ClassMethods
-
1
def tests(helper_class)
-
case helper_class
-
when String, Symbol
-
self.helper_class = "#{helper_class.to_s.underscore}_helper".camelize.safe_constantize
-
when Module
-
self.helper_class = helper_class
-
end
-
end
-
-
1
def determine_default_helper_class(name)
-
determine_constant_from_test_name(name) do |constant|
-
Module === constant && !(Class === constant)
-
end
-
end
-
-
1
def helper_method(*methods)
-
# Almost a duplicate from ActionController::Helpers
-
methods.flatten.each do |method|
-
_helpers.module_eval <<-end_eval
-
def #{method}(*args, &block) # def current_user(*args, &block)
-
_test_case.send(%(#{method}), *args, &block) # _test_case.send(%(current_user), *args, &block)
-
end # end
-
end_eval
-
end
-
end
-
-
1
attr_writer :helper_class
-
-
1
def helper_class
-
@helper_class ||= determine_default_helper_class(name)
-
end
-
-
1
def new(*)
-
include_helper_modules!
-
super
-
end
-
-
1
private
-
-
1
def include_helper_modules!
-
helper(helper_class) if helper_class
-
include _helpers
-
end
-
-
end
-
-
1
def setup_with_controller
-
@controller = ActionView::TestCase::TestController.new
-
@request = @controller.request
-
@output_buffer = ActiveSupport::SafeBuffer.new
-
@rendered = ''
-
-
make_test_case_available_to_view!
-
say_no_to_protect_against_forgery!
-
end
-
-
1
def config
-
@controller.config if @controller.respond_to?(:config)
-
end
-
-
1
def render(options = {}, local_assigns = {}, &block)
-
view.assign(view_assigns)
-
@rendered << output = view.render(options, local_assigns, &block)
-
output
-
end
-
-
1
def rendered_views
-
@_rendered_views ||= RenderedViewsCollection.new
-
end
-
-
1
class RenderedViewsCollection
-
1
def initialize
-
@rendered_views ||= Hash.new { |hash, key| hash[key] = [] }
-
end
-
-
1
def add(view, locals)
-
@rendered_views[view] ||= []
-
@rendered_views[view] << locals
-
end
-
-
1
def locals_for(view)
-
@rendered_views[view]
-
end
-
-
1
def rendered_views
-
@rendered_views.keys
-
end
-
-
1
def view_rendered?(view, expected_locals)
-
locals_for(view).any? do |actual_locals|
-
expected_locals.all? {|key, value| value == actual_locals[key] }
-
end
-
end
-
end
-
-
1
included do
-
1
setup :setup_with_controller
-
end
-
-
1
private
-
-
# Support the selector assertions
-
#
-
# Need to experiment if this priority is the best one: rendered => output_buffer
-
1
def response_from_page
-
HTML::Document.new(@rendered.blank? ? @output_buffer : @rendered).root
-
end
-
-
1
def say_no_to_protect_against_forgery!
-
_helpers.module_eval do
-
remove_possible_method :protect_against_forgery?
-
def protect_against_forgery?
-
false
-
end
-
end
-
end
-
-
1
def make_test_case_available_to_view!
-
test_case_instance = self
-
_helpers.module_eval do
-
unless private_method_defined?(:_test_case)
-
define_method(:_test_case) { test_case_instance }
-
private :_test_case
-
end
-
end
-
end
-
-
1
module Locals
-
1
attr_accessor :rendered_views
-
-
1
def render(options = {}, local_assigns = {})
-
case options
-
when Hash
-
if block_given?
-
rendered_views.add options[:layout], options[:locals]
-
elsif options.key?(:partial)
-
rendered_views.add options[:partial], options[:locals]
-
end
-
else
-
rendered_views.add options, local_assigns
-
end
-
-
super
-
end
-
end
-
-
# The instance of ActionView::Base that is used by +render+.
-
1
def view
-
@view ||= begin
-
view = @controller.view_context
-
view.singleton_class.send :include, _helpers
-
view.extend(Locals)
-
view.rendered_views = self.rendered_views
-
view.output_buffer = self.output_buffer
-
view
-
end
-
end
-
-
1
alias_method :_view, :view
-
-
1
INTERNAL_IVARS = [
-
:@NAME,
-
:@failures,
-
:@assertions,
-
:@__io__,
-
:@_assertion_wrapped,
-
:@_assertions,
-
:@_result,
-
:@_routes,
-
:@controller,
-
:@_layouts,
-
:@_files,
-
:@_rendered_views,
-
:@method_name,
-
:@output_buffer,
-
:@_partials,
-
:@passed,
-
:@rendered,
-
:@request,
-
:@routes,
-
:@tagged_logger,
-
:@_templates,
-
:@options,
-
:@test_passed,
-
:@view,
-
:@view_context_class
-
]
-
-
1
def _user_defined_ivars
-
instance_variables - INTERNAL_IVARS
-
end
-
-
# Returns a Hash of instance variables and their values, as defined by
-
# the user in the test case, which are then assigned to the view being
-
# rendered. This is generally intended for internal use and extension
-
# frameworks.
-
1
def view_assigns
-
Hash[_user_defined_ivars.map do |ivar|
-
[ivar[1..-1].to_sym, instance_variable_get(ivar)]
-
end]
-
end
-
-
1
def _routes
-
@controller._routes if @controller.respond_to?(:_routes)
-
end
-
-
1
def method_missing(selector, *args)
-
if @controller.respond_to?(:_routes) &&
-
( @controller._routes.named_routes.helpers.include?(selector) ||
-
@controller._routes.mounted_helpers.method_defined?(selector) )
-
@controller.__send__(selector, *args)
-
else
-
super
-
end
-
end
-
end
-
-
1
include Behavior
-
end
-
end
-
1
require 'action_view/template/resolver'
-
-
1
module ActionView #:nodoc:
-
# Use FixtureResolver in your tests to simulate the presence of files on the
-
# file system. This is used internally by Rails' own test suite, and is
-
# useful for testing extensions that have no way of knowing what the file
-
# system will look like at runtime.
-
1
class FixtureResolver < PathResolver
-
1
attr_reader :hash
-
-
1
def initialize(hash = {}, pattern=nil)
-
super(pattern)
-
@hash = hash
-
end
-
-
1
def to_s
-
@hash.keys.join(', ')
-
end
-
-
1
private
-
-
1
def query(path, exts, formats)
-
query = ""
-
EXTENSIONS.each_key do |ext|
-
query << '(' << exts[ext].map {|e| e && Regexp.escape(".#{e}") }.join('|') << '|)'
-
end
-
query = /^(#{Regexp.escape(path)})#{query}$/
-
-
templates = []
-
@hash.each do |_path, array|
-
source, updated_at = array
-
next unless _path =~ query
-
handler, format, variant = extract_handler_and_format_and_variant(_path, formats)
-
templates << Template.new(source, _path, handler,
-
:virtual_path => path.virtual,
-
:format => format,
-
:variant => variant,
-
:updated_at => updated_at
-
)
-
end
-
-
templates.sort_by {|t| -t.identifier.match(/^#{query}$/).captures.reject(&:blank?).size }
-
end
-
end
-
-
1
class NullResolver < PathResolver
-
1
def query(path, exts, formats)
-
handler, format, variant = extract_handler_and_format_and_variant(path, formats)
-
[ActionView::Template.new("Template generated by Null Resolver", path, handler, :virtual_path => path, :format => format, :variant => variant)]
-
end
-
end
-
-
end
-
-
2
$LOAD_PATH.unshift "#{File.dirname(__FILE__)}/html-scanner"
-
-
2
module HTML
-
2
extend ActiveSupport::Autoload
-
-
2
eager_autoload do
-
2
autoload :CDATA, 'html/node'
-
2
autoload :Document, 'html/document'
-
2
autoload :FullSanitizer, 'html/sanitizer'
-
2
autoload :LinkSanitizer, 'html/sanitizer'
-
2
autoload :Node, 'html/node'
-
2
autoload :Sanitizer, 'html/sanitizer'
-
2
autoload :Selector, 'html/selector'
-
2
autoload :Tag, 'html/node'
-
2
autoload :Text, 'html/node'
-
2
autoload :Tokenizer, 'html/tokenizer'
-
2
autoload :Version, 'html/version'
-
2
autoload :WhiteListSanitizer, 'html/sanitizer'
-
end
-
end
-
2
require_relative 'gem_version'
-
-
2
module ActionView
-
# Returns the version of the currently loaded ActionView as a <tt>Gem::Version</tt>
-
2
def self.version
-
gem_version
-
end
-
end
-
2
require 'action_view/base'
-
-
2
module ActionView
-
2
module ViewPaths
-
2
extend ActiveSupport::Concern
-
-
2
included do
-
4
class_attribute :_view_paths
-
4
self._view_paths = ActionView::PathSet.new
-
4
self._view_paths.freeze
-
end
-
-
2
delegate :template_exists?, :view_paths, :formats, :formats=,
-
:locale, :locale=, :to => :lookup_context
-
-
2
module ClassMethods
-
2
def parent_prefixes
-
@parent_prefixes ||= begin
-
8
parent_controller = superclass
-
8
prefixes = []
-
-
8
until parent_controller.abstract?
-
8
prefixes << parent_controller.controller_path
-
8
parent_controller = parent_controller.superclass
-
end
-
-
8
prefixes
-
24
end
-
end
-
end
-
-
# The prefixes used in render "foo" shortcuts.
-
2
def _prefixes
-
@_prefixes ||= begin
-
24
parent_prefixes = self.class.parent_prefixes
-
24
parent_prefixes.dup.unshift(controller_path)
-
48
end
-
end
-
-
# LookupContext is the object responsible to hold all information required to lookup
-
# templates, i.e. view paths and details. Check ActionView::LookupContext for more
-
# information.
-
2
def lookup_context
-
@_lookup_context ||=
-
262
ActionView::LookupContext.new(self.class._view_paths, details_for_lookup, _prefixes)
-
end
-
-
2
def details_for_lookup
-
24
{ }
-
end
-
-
2
def append_view_path(path)
-
lookup_context.view_paths.push(*path)
-
end
-
-
2
def prepend_view_path(path)
-
lookup_context.view_paths.unshift(*path)
-
end
-
-
2
module ClassMethods
-
# Append a path to the list of view paths for this controller.
-
#
-
# ==== Parameters
-
# * <tt>path</tt> - If a String is provided, it gets converted into
-
# the default view path. You may also provide a custom view path
-
# (see ActionView::PathSet for more information)
-
2
def append_view_path(path)
-
self._view_paths = view_paths + Array(path)
-
end
-
-
# Prepend a path to the list of view paths for this controller.
-
#
-
# ==== Parameters
-
# * <tt>path</tt> - If a String is provided, it gets converted into
-
# the default view path. You may also provide a custom view path
-
# (see ActionView::PathSet for more information)
-
2
def prepend_view_path(path)
-
12
self._view_paths = ActionView::PathSet.new(Array(path) + view_paths)
-
end
-
-
# A list of all of the default view paths for this controller.
-
2
def view_paths
-
27
_view_paths
-
end
-
-
# Set the view paths.
-
#
-
# ==== Parameters
-
# * <tt>paths</tt> - If a PathSet is provided, use that;
-
# otherwise, process the parameter into a PathSet.
-
2
def view_paths=(paths)
-
30
self._view_paths = ActionView::PathSet.new(Array(paths))
-
end
-
end
-
end
-
end
-
#--
-
# Copyright (c) 2004-2014 David Heinemeier Hansson
-
#
-
# Permission is hereby granted, free of charge, to any person obtaining
-
# a copy of this software and associated documentation files (the
-
# "Software"), to deal in the Software without restriction, including
-
# without limitation the rights to use, copy, modify, merge, publish,
-
# distribute, sublicense, and/or sell copies of the Software, and to
-
# permit persons to whom the Software is furnished to do so, subject to
-
# the following conditions:
-
#
-
# The above copyright notice and this permission notice shall be
-
# included in all copies or substantial portions of the Software.
-
#
-
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
-
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
-
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
-
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-
#++
-
-
2
require 'active_support'
-
2
require 'active_support/rails'
-
2
require 'active_model/version'
-
-
2
module ActiveModel
-
2
extend ActiveSupport::Autoload
-
-
2
autoload :AttributeMethods
-
2
autoload :BlockValidator, 'active_model/validator'
-
2
autoload :Callbacks
-
2
autoload :Conversion
-
2
autoload :Dirty
-
2
autoload :EachValidator, 'active_model/validator'
-
2
autoload :ForbiddenAttributesProtection
-
2
autoload :Lint
-
2
autoload :Model
-
2
autoload :Name, 'active_model/naming'
-
2
autoload :Naming
-
2
autoload :SecurePassword
-
2
autoload :Serialization
-
2
autoload :TestCase
-
2
autoload :Translation
-
2
autoload :Validations
-
2
autoload :Validator
-
-
2
eager_autoload do
-
2
autoload :Errors
-
2
autoload :StrictValidationFailed, 'active_model/errors'
-
end
-
-
2
module Serializers
-
2
extend ActiveSupport::Autoload
-
-
2
eager_autoload do
-
2
autoload :JSON
-
2
autoload :Xml
-
end
-
end
-
-
2
def self.eager_load!
-
super
-
ActiveModel::Serializers.eager_load!
-
end
-
end
-
-
2
ActiveSupport.on_load(:i18n) do
-
2
I18n.load_path << File.dirname(__FILE__) + '/active_model/locale/en.yml'
-
end
-
2
require 'thread_safe'
-
2
require 'mutex_m'
-
-
2
module ActiveModel
-
# Raised when an attribute is not defined.
-
#
-
# class User < ActiveRecord::Base
-
# has_many :pets
-
# end
-
#
-
# user = User.first
-
# user.pets.select(:id).first.user_id
-
# # => ActiveModel::MissingAttributeError: missing attribute: user_id
-
2
class MissingAttributeError < NoMethodError
-
end
-
-
# == Active \Model \Attribute \Methods
-
#
-
# Provides a way to add prefixes and suffixes to your methods as
-
# well as handling the creation of <tt>ActiveRecord::Base</tt>-like
-
# class methods such as +table_name+.
-
#
-
# The requirements to implement <tt>ActiveModel::AttributeMethods</tt> are to:
-
#
-
# * <tt>include ActiveModel::AttributeMethods</tt> in your class.
-
# * Call each of its method you want to add, such as +attribute_method_suffix+
-
# or +attribute_method_prefix+.
-
# * Call +define_attribute_methods+ after the other methods are called.
-
# * Define the various generic +_attribute+ methods that you have declared.
-
# * Define an +attributes+ method which returns a hash with each
-
# attribute name in your model as hash key and the attribute value as hash value.
-
# Hash keys must be strings.
-
#
-
# A minimal implementation could be:
-
#
-
# class Person
-
# include ActiveModel::AttributeMethods
-
#
-
# attribute_method_affix prefix: 'reset_', suffix: '_to_default!'
-
# attribute_method_suffix '_contrived?'
-
# attribute_method_prefix 'clear_'
-
# define_attribute_methods :name
-
#
-
# attr_accessor :name
-
#
-
# def attributes
-
# { 'name' => @name }
-
# end
-
#
-
# private
-
#
-
# def attribute_contrived?(attr)
-
# true
-
# end
-
#
-
# def clear_attribute(attr)
-
# send("#{attr}=", nil)
-
# end
-
#
-
# def reset_attribute_to_default!(attr)
-
# send("#{attr}=", 'Default Name')
-
# end
-
# end
-
2
module AttributeMethods
-
2
extend ActiveSupport::Concern
-
-
2
NAME_COMPILABLE_REGEXP = /\A[a-zA-Z_]\w*[!?=]?\z/
-
2
CALL_COMPILABLE_REGEXP = /\A[a-zA-Z_]\w*[!?]?\z/
-
-
2
included do
-
2
class_attribute :attribute_aliases, :attribute_method_matchers, instance_writer: false
-
2
self.attribute_aliases = {}
-
2
self.attribute_method_matchers = [ClassMethods::AttributeMethodMatcher.new]
-
end
-
-
2
module ClassMethods
-
# Declares a method available for all attributes with the given prefix.
-
# Uses +method_missing+ and <tt>respond_to?</tt> to rewrite the method.
-
#
-
# #{prefix}#{attr}(*args, &block)
-
#
-
# to
-
#
-
# #{prefix}attribute(#{attr}, *args, &block)
-
#
-
# An instance method <tt>#{prefix}attribute</tt> must exist and accept
-
# at least the +attr+ argument.
-
#
-
# class Person
-
# include ActiveModel::AttributeMethods
-
#
-
# attr_accessor :name
-
# attribute_method_prefix 'clear_'
-
# define_attribute_methods :name
-
#
-
# private
-
#
-
# def clear_attribute(attr)
-
# send("#{attr}=", nil)
-
# end
-
# end
-
#
-
# person = Person.new
-
# person.name = 'Bob'
-
# person.name # => "Bob"
-
# person.clear_name
-
# person.name # => nil
-
2
def attribute_method_prefix(*prefixes)
-
self.attribute_method_matchers += prefixes.map! { |prefix| AttributeMethodMatcher.new prefix: prefix }
-
undefine_attribute_methods
-
end
-
-
# Declares a method available for all attributes with the given suffix.
-
# Uses +method_missing+ and <tt>respond_to?</tt> to rewrite the method.
-
#
-
# #{attr}#{suffix}(*args, &block)
-
#
-
# to
-
#
-
# attribute#{suffix}(#{attr}, *args, &block)
-
#
-
# An <tt>attribute#{suffix}</tt> instance method must exist and accept at
-
# least the +attr+ argument.
-
#
-
# class Person
-
# include ActiveModel::AttributeMethods
-
#
-
# attr_accessor :name
-
# attribute_method_suffix '_short?'
-
# define_attribute_methods :name
-
#
-
# private
-
#
-
# def attribute_short?(attr)
-
# send(attr).length < 5
-
# end
-
# end
-
#
-
# person = Person.new
-
# person.name = 'Bob'
-
# person.name # => "Bob"
-
# person.name_short? # => true
-
2
def attribute_method_suffix(*suffixes)
-
22
self.attribute_method_matchers += suffixes.map! { |suffix| AttributeMethodMatcher.new suffix: suffix }
-
8
undefine_attribute_methods
-
end
-
-
# Declares a method available for all attributes with the given prefix
-
# and suffix. Uses +method_missing+ and <tt>respond_to?</tt> to rewrite
-
# the method.
-
#
-
# #{prefix}#{attr}#{suffix}(*args, &block)
-
#
-
# to
-
#
-
# #{prefix}attribute#{suffix}(#{attr}, *args, &block)
-
#
-
# An <tt>#{prefix}attribute#{suffix}</tt> instance method must exist and
-
# accept at least the +attr+ argument.
-
#
-
# class Person
-
# include ActiveModel::AttributeMethods
-
#
-
# attr_accessor :name
-
# attribute_method_affix prefix: 'reset_', suffix: '_to_default!'
-
# define_attribute_methods :name
-
#
-
# private
-
#
-
# def reset_attribute_to_default!(attr)
-
# send("#{attr}=", 'Default Name')
-
# end
-
# end
-
#
-
# person = Person.new
-
# person.name # => 'Gem'
-
# person.reset_name_to_default!
-
# person.name # => 'Default Name'
-
2
def attribute_method_affix(*affixes)
-
4
self.attribute_method_matchers += affixes.map! { |affix| AttributeMethodMatcher.new prefix: affix[:prefix], suffix: affix[:suffix] }
-
2
undefine_attribute_methods
-
end
-
-
# Allows you to make aliases for attributes.
-
#
-
# class Person
-
# include ActiveModel::AttributeMethods
-
#
-
# attr_accessor :name
-
# attribute_method_suffix '_short?'
-
# define_attribute_methods :name
-
#
-
# alias_attribute :nickname, :name
-
#
-
# private
-
#
-
# def attribute_short?(attr)
-
# send(attr).length < 5
-
# end
-
# end
-
#
-
# person = Person.new
-
# person.name = 'Bob'
-
# person.name # => "Bob"
-
# person.nickname # => "Bob"
-
# person.name_short? # => true
-
# person.nickname_short? # => true
-
2
def alias_attribute(new_name, old_name)
-
self.attribute_aliases = attribute_aliases.merge(new_name.to_s => old_name.to_s)
-
attribute_method_matchers.each do |matcher|
-
matcher_new = matcher.method_name(new_name).to_s
-
matcher_old = matcher.method_name(old_name).to_s
-
define_proxy_call false, self, matcher_new, matcher_old
-
end
-
end
-
-
# Is +new_name+ an alias?
-
2
def attribute_alias?(new_name)
-
210
attribute_aliases.key? new_name.to_s
-
end
-
-
# Returns the original name for the alias +name+
-
2
def attribute_alias(name)
-
attribute_aliases[name.to_s]
-
end
-
-
# Declares the attributes that should be prefixed and suffixed by
-
# ActiveModel::AttributeMethods.
-
#
-
# To use, pass attribute names (as strings or symbols), be sure to declare
-
# +define_attribute_methods+ after you define any prefix, suffix or affix
-
# methods, or they will not hook in.
-
#
-
# class Person
-
# include ActiveModel::AttributeMethods
-
#
-
# attr_accessor :name, :age, :address
-
# attribute_method_prefix 'clear_'
-
#
-
# # Call to define_attribute_methods must appear after the
-
# # attribute_method_prefix, attribute_method_suffix or
-
# # attribute_method_affix declares.
-
# define_attribute_methods :name, :age, :address
-
#
-
# private
-
#
-
# def clear_attribute(attr)
-
# send("#{attr}=", nil)
-
# end
-
# end
-
2
def define_attribute_methods(*attr_names)
-
122
attr_names.flatten.each { |attr_name| define_attribute_method(attr_name) }
-
end
-
-
# Declares an attribute that should be prefixed and suffixed by
-
# ActiveModel::AttributeMethods.
-
#
-
# To use, pass an attribute name (as string or symbol), be sure to declare
-
# +define_attribute_method+ after you define any prefix, suffix or affix
-
# method, or they will not hook in.
-
#
-
# class Person
-
# include ActiveModel::AttributeMethods
-
#
-
# attr_accessor :name
-
# attribute_method_suffix '_short?'
-
#
-
# # Call to define_attribute_method must appear after the
-
# # attribute_method_prefix, attribute_method_suffix or
-
# # attribute_method_affix declares.
-
# define_attribute_method :name
-
#
-
# private
-
#
-
# def attribute_short?(attr)
-
# send(attr).length < 5
-
# end
-
# end
-
#
-
# person = Person.new
-
# person.name = 'Bob'
-
# person.name # => "Bob"
-
# person.name_short? # => true
-
2
def define_attribute_method(attr_name)
-
111
attribute_method_matchers.each do |matcher|
-
999
method_name = matcher.method_name(attr_name)
-
-
999
unless instance_method_already_implemented?(method_name)
-
999
generate_method = "define_method_#{matcher.method_missing_target}"
-
-
999
if respond_to?(generate_method, true)
-
222
send(generate_method, attr_name)
-
else
-
777
define_proxy_call true, generated_attribute_methods, method_name, matcher.method_missing_target, attr_name.to_s
-
end
-
end
-
end
-
111
attribute_method_matchers_cache.clear
-
end
-
-
# Removes all the previously dynamically defined methods from the class.
-
#
-
# class Person
-
# include ActiveModel::AttributeMethods
-
#
-
# attr_accessor :name
-
# attribute_method_suffix '_short?'
-
# define_attribute_method :name
-
#
-
# private
-
#
-
# def attribute_short?(attr)
-
# send(attr).length < 5
-
# end
-
# end
-
#
-
# person = Person.new
-
# person.name = 'Bob'
-
# person.name_short? # => true
-
#
-
# Person.undefine_attribute_methods
-
#
-
# person.name_short? # => NoMethodError
-
2
def undefine_attribute_methods
-
generated_attribute_methods.module_eval do
-
instance_methods.each { |m| undef_method(m) }
-
end
-
attribute_method_matchers_cache.clear
-
end
-
-
2
def generated_attribute_methods #:nodoc:
-
@generated_attribute_methods ||= Module.new {
-
extend Mutex_m
-
2028
}.tap { |mod| include mod }
-
end
-
-
2
protected
-
2
def instance_method_already_implemented?(method_name) #:nodoc:
-
999
generated_attribute_methods.method_defined?(method_name)
-
end
-
-
2
private
-
# The methods +method_missing+ and +respond_to?+ of this module are
-
# invoked often in a typical rails, both of which invoke the method
-
# +match_attribute_method?+. The latter method iterates through an
-
# array doing regular expression matches, which results in a lot of
-
# object creations. Most of the time it returns a +nil+ match. As the
-
# match result is always the same given a +method_name+, this cache is
-
# used to alleviate the GC, which ultimately also speeds up the app
-
# significantly (in our case our test suite finishes 10% faster with
-
# this cache).
-
2
def attribute_method_matchers_cache #:nodoc:
-
645
@attribute_method_matchers_cache ||= ThreadSafe::Cache.new(initial_capacity: 4)
-
end
-
-
2
def attribute_method_matcher(method_name) #:nodoc:
-
534
attribute_method_matchers_cache.compute_if_absent(method_name) do
-
# Must try to match prefixes/suffixes first, or else the matcher with no prefix/suffix
-
# will match every time.
-
10
matchers = attribute_method_matchers.partition(&:plain?).reverse.flatten(1)
-
10
match = nil
-
100
matchers.detect { |method| match = method.match(method_name) }
-
10
match
-
end
-
end
-
-
# Define a method `name` in `mod` that dispatches to `send`
-
# using the given `extra` args. This fallbacks `define_method`
-
# and `send` if the given names cannot be compiled.
-
2
def define_proxy_call(include_private, mod, name, send, *extra) #:nodoc:
-
777
defn = if name =~ NAME_COMPILABLE_REGEXP
-
777
"def #{name}(*args)"
-
else
-
"define_method(:'#{name}') do |*args|"
-
end
-
-
777
extra = (extra.map!(&:inspect) << "*args").join(", ")
-
-
777
target = if send =~ CALL_COMPILABLE_REGEXP
-
777
"#{"self." unless include_private}#{send}(#{extra})"
-
else
-
"send(:'#{send}', #{extra})"
-
end
-
-
777
mod.module_eval <<-RUBY, __FILE__, __LINE__ + 1
-
#{defn}
-
#{target}
-
end
-
RUBY
-
end
-
-
2
class AttributeMethodMatcher #:nodoc:
-
2
attr_reader :prefix, :suffix, :method_missing_target
-
-
2
AttributeMethodMatch = Struct.new(:target, :attr_name, :method_name)
-
-
2
def initialize(options = {})
-
18
@prefix, @suffix = options.fetch(:prefix, ''), options.fetch(:suffix, '')
-
18
@regex = /^(?:#{Regexp.escape(@prefix)})(.*)(?:#{Regexp.escape(@suffix)})$/
-
18
@method_missing_target = "#{@prefix}attribute#{@suffix}"
-
18
@method_name = "#{prefix}%s#{suffix}"
-
end
-
-
2
def match(method_name)
-
90
if @regex =~ method_name
-
10
AttributeMethodMatch.new(method_missing_target, $1, method_name)
-
end
-
end
-
-
2
def method_name(attr_name)
-
999
@method_name % attr_name
-
end
-
-
2
def plain?
-
90
prefix.empty? && suffix.empty?
-
end
-
end
-
end
-
-
# Allows access to the object attributes, which are held in the hash
-
# returned by <tt>attributes</tt>, as though they were first-class
-
# methods. So a +Person+ class with a +name+ attribute can for example use
-
# <tt>Person#name</tt> and <tt>Person#name=</tt> and never directly use
-
# the attributes hash -- except for multiple assigns with
-
# <tt>ActiveRecord::Base#attributes=</tt>.
-
#
-
# It's also possible to instantiate related objects, so a <tt>Client</tt>
-
# class belonging to the +clients+ table with a +master_id+ foreign key
-
# can instantiate master through <tt>Client#master</tt>.
-
2
def method_missing(method, *args, &block)
-
if respond_to_without_attributes?(method, true)
-
super
-
else
-
match = match_attribute_method?(method.to_s)
-
match ? attribute_missing(match, *args, &block) : super
-
end
-
end
-
-
# +attribute_missing+ is like +method_missing+, but for attributes. When
-
# +method_missing+ is called we check to see if there is a matching
-
# attribute method. If so, we tell +attribute_missing+ to dispatch the
-
# attribute. This method can be overloaded to customize the behavior.
-
2
def attribute_missing(match, *args, &block)
-
__send__(match.target, match.attr_name, *args, &block)
-
end
-
-
# A +Person+ instance with a +name+ attribute can ask
-
# <tt>person.respond_to?(:name)</tt>, <tt>person.respond_to?(:name=)</tt>,
-
# and <tt>person.respond_to?(:name?)</tt> which will all return +true+.
-
2
alias :respond_to_without_attributes? :respond_to?
-
2
def respond_to?(method, include_private_methods = false)
-
1678
if super
-
1144
true
-
534
elsif !include_private_methods && super(method, true)
-
# If we're here then we haven't found among non-private methods
-
# but found among all methods. Which means that the given method is private.
-
false
-
else
-
534
!match_attribute_method?(method.to_s).nil?
-
end
-
end
-
-
2
protected
-
2
def attribute_method?(attr_name) #:nodoc:
-
respond_to_without_attributes?(:attributes) && attributes.include?(attr_name)
-
end
-
-
2
private
-
# Returns a struct representing the matching attribute method.
-
# The struct's attributes are prefix, base and suffix.
-
2
def match_attribute_method?(method_name)
-
534
match = self.class.send(:attribute_method_matcher, method_name)
-
534
match if match && attribute_method?(match.attr_name)
-
end
-
-
2
def missing_attribute(attr_name, stack)
-
raise ActiveModel::MissingAttributeError, "missing attribute: #{attr_name}", stack
-
end
-
end
-
end
-
2
require 'active_support/core_ext/array/extract_options'
-
-
2
module ActiveModel
-
# == Active \Model \Callbacks
-
#
-
# Provides an interface for any class to have Active Record like callbacks.
-
#
-
# Like the Active Record methods, the callback chain is aborted as soon as
-
# one of the methods in the chain returns +false+.
-
#
-
# First, extend ActiveModel::Callbacks from the class you are creating:
-
#
-
# class MyModel
-
# extend ActiveModel::Callbacks
-
# end
-
#
-
# Then define a list of methods that you want callbacks attached to:
-
#
-
# define_model_callbacks :create, :update
-
#
-
# This will provide all three standard callbacks (before, around and after)
-
# for both the <tt>:create</tt> and <tt>:update</tt> methods. To implement,
-
# you need to wrap the methods you want callbacks on in a block so that the
-
# callbacks get a chance to fire:
-
#
-
# def create
-
# run_callbacks :create do
-
# # Your create action methods here
-
# end
-
# end
-
#
-
# Then in your class, you can use the +before_create+, +after_create+ and
-
# +around_create+ methods, just as you would in an Active Record model.
-
#
-
# before_create :action_before_create
-
#
-
# def action_before_create
-
# # Your code here
-
# end
-
#
-
# When defining an around callback remember to yield to the block, otherwise
-
# it won't be executed:
-
#
-
# around_create :log_status
-
#
-
# def log_status
-
# puts 'going to call the block...'
-
# yield
-
# puts 'block successfully called.'
-
# end
-
#
-
# You can choose not to have all three callbacks by passing a hash to the
-
# +define_model_callbacks+ method.
-
#
-
# define_model_callbacks :create, only: [:after, :before]
-
#
-
# Would only create the +after_create+ and +before_create+ callback methods in
-
# your class.
-
2
module Callbacks
-
2
def self.extended(base) #:nodoc:
-
2
base.class_eval do
-
2
include ActiveSupport::Callbacks
-
end
-
end
-
-
# define_model_callbacks accepts the same options +define_callbacks+ does,
-
# in case you want to overwrite a default. Besides that, it also accepts an
-
# <tt>:only</tt> option, where you can choose if you want all types (before,
-
# around or after) or just some.
-
#
-
# define_model_callbacks :initializer, only: :after
-
#
-
# Note, the <tt>only: <type></tt> hash will apply to all callbacks defined
-
# on that method call. To get around this you can call the define_model_callbacks
-
# method as many times as you need.
-
#
-
# define_model_callbacks :create, only: :after
-
# define_model_callbacks :update, only: :before
-
# define_model_callbacks :destroy, only: :around
-
#
-
# Would create +after_create+, +before_update+ and +around_destroy+ methods
-
# only.
-
#
-
# You can pass in a class to before_<type>, after_<type> and around_<type>,
-
# in which case the callback will call that class's <action>_<type> method
-
# passing the object that the callback is being called on.
-
#
-
# class MyModel
-
# extend ActiveModel::Callbacks
-
# define_model_callbacks :create
-
#
-
# before_create AnotherClass
-
# end
-
#
-
# class AnotherClass
-
# def self.before_create( obj )
-
# # obj is the MyModel instance that the callback is being called on
-
# end
-
# end
-
2
def define_model_callbacks(*callbacks)
-
4
options = callbacks.extract_options!
-
4
options = {
-
799
terminator: ->(_,result) { result == false },
-
skip_after_callbacks_if_terminated: true,
-
scope: [:kind, :name],
-
only: [:before, :around, :after]
-
}.merge!(options)
-
-
4
types = Array(options.delete(:only))
-
-
4
callbacks.each do |callback|
-
14
define_callbacks(callback, options)
-
-
14
types.each do |type|
-
30
send("_define_#{type}_model_callback", self, callback)
-
end
-
end
-
end
-
-
2
private
-
-
2
def _define_before_model_callback(klass, callback) #:nodoc:
-
8
klass.define_singleton_method("before_#{callback}") do |*args, &block|
-
56
set_callback(:"#{callback}", :before, *args, &block)
-
end
-
end
-
-
2
def _define_around_model_callback(klass, callback) #:nodoc:
-
8
klass.define_singleton_method("around_#{callback}") do |*args, &block|
-
set_callback(:"#{callback}", :around, *args, &block)
-
end
-
end
-
-
2
def _define_after_model_callback(klass, callback) #:nodoc:
-
14
klass.define_singleton_method("after_#{callback}") do |*args, &block|
-
72
options = args.extract_options!
-
72
options[:prepend] = true
-
72
conditional = ActiveSupport::Callbacks::Conditionals::Value.new { |v|
-
1760
v != false
-
}
-
72
options[:if] = Array(options[:if]) << conditional
-
72
set_callback(:"#{callback}", :after, *(args << options), &block)
-
end
-
end
-
end
-
end
-
2
module ActiveModel
-
# == Active \Model \Conversion
-
#
-
# Handles default conversions: to_model, to_key, to_param, and to_partial_path.
-
#
-
# Let's take for example this non-persisted object.
-
#
-
# class ContactMessage
-
# include ActiveModel::Conversion
-
#
-
# # ContactMessage are never persisted in the DB
-
# def persisted?
-
# false
-
# end
-
# end
-
#
-
# cm = ContactMessage.new
-
# cm.to_model == cm # => true
-
# cm.to_key # => nil
-
# cm.to_param # => nil
-
# cm.to_partial_path # => "contact_messages/contact_message"
-
2
module Conversion
-
2
extend ActiveSupport::Concern
-
-
# If your object is already designed to implement all of the Active Model
-
# you can use the default <tt>:to_model</tt> implementation, which simply
-
# returns +self+.
-
#
-
# class Person
-
# include ActiveModel::Conversion
-
# end
-
#
-
# person = Person.new
-
# person.to_model == person # => true
-
#
-
# If your model does not act like an Active Model object, then you should
-
# define <tt>:to_model</tt> yourself returning a proxy object that wraps
-
# your object with Active Model compliant methods.
-
2
def to_model
-
28
self
-
end
-
-
# Returns an Enumerable of all key attributes if any is set, regardless if
-
# the object is persisted or not. Returns +nil+ if there are no key attributes.
-
#
-
# class Person < ActiveRecord::Base
-
# end
-
#
-
# person = Person.create
-
# person.to_key # => [1]
-
2
def to_key
-
key = respond_to?(:id) && id
-
key ? [key] : nil
-
end
-
-
# Returns a +string+ representing the object's key suitable for use in URLs,
-
# or +nil+ if <tt>persisted?</tt> is +false+.
-
#
-
# class Person < ActiveRecord::Base
-
# end
-
#
-
# person = Person.create
-
# person.to_param # => "1"
-
2
def to_param
-
(persisted? && key = to_key) ? key.join('-') : nil
-
end
-
-
# Returns a +string+ identifying the path associated with the object.
-
# ActionPack uses this to find a suitable partial to represent the object.
-
#
-
# class Person
-
# include ActiveModel::Conversion
-
# end
-
#
-
# person = Person.new
-
# person.to_partial_path # => "people/person"
-
2
def to_partial_path
-
self.class._to_partial_path
-
end
-
-
2
module ClassMethods #:nodoc:
-
# Provide a class level cache for #to_partial_path. This is an
-
# internal method and should not be accessed directly.
-
2
def _to_partial_path #:nodoc:
-
@_to_partial_path ||= begin
-
element = ActiveSupport::Inflector.underscore(ActiveSupport::Inflector.demodulize(self))
-
collection = ActiveSupport::Inflector.tableize(self)
-
"#{collection}/#{element}".freeze
-
end
-
end
-
end
-
end
-
end
-
2
require 'active_support/hash_with_indifferent_access'
-
2
require 'active_support/core_ext/object/duplicable'
-
-
2
module ActiveModel
-
# == Active \Model \Dirty
-
#
-
# Provides a way to track changes in your object in the same way as
-
# Active Record does.
-
#
-
# The requirements for implementing ActiveModel::Dirty are:
-
#
-
# * <tt>include ActiveModel::Dirty</tt> in your object.
-
# * Call <tt>define_attribute_methods</tt> passing each method you want to
-
# track.
-
# * Call <tt>attr_name_will_change!</tt> before each change to the tracked
-
# attribute.
-
# * Call <tt>changes_applied</tt> after the changes are persisted.
-
# * Call <tt>reset_changes</tt> when you want to reset the changes
-
# information.
-
#
-
# A minimal implementation could be:
-
#
-
# class Person
-
# include ActiveModel::Dirty
-
#
-
# define_attribute_methods :name
-
#
-
# def name
-
# @name
-
# end
-
#
-
# def name=(val)
-
# name_will_change! unless val == @name
-
# @name = val
-
# end
-
#
-
# def save
-
# # do persistence work
-
# changes_applied
-
# end
-
#
-
# def reload!
-
# reset_changes
-
# end
-
# end
-
#
-
# A newly instantiated object is unchanged:
-
#
-
# person = Person.find_by(name: 'Uncle Bob')
-
# person.changed? # => false
-
#
-
# Change the name:
-
#
-
# person.name = 'Bob'
-
# person.changed? # => true
-
# person.name_changed? # => true
-
# person.name_changed?(from: "Uncle Bob", to: "Bob") # => true
-
# person.name_was # => "Uncle Bob"
-
# person.name_change # => ["Uncle Bob", "Bob"]
-
# person.name = 'Bill'
-
# person.name_change # => ["Uncle Bob", "Bill"]
-
#
-
# Save the changes:
-
#
-
# person.save
-
# person.changed? # => false
-
# person.name_changed? # => false
-
#
-
# Reset the changes:
-
#
-
# person.previous_changes # => {"name" => ["Uncle Bob", "Bill"]}
-
# person.reload!
-
# person.previous_changes # => {}
-
#
-
# Assigning the same value leaves the attribute unchanged:
-
#
-
# person.name = 'Bill'
-
# person.name_changed? # => false
-
# person.name_change # => nil
-
#
-
# Which attributes have changed?
-
#
-
# person.name = 'Bob'
-
# person.changed # => ["name"]
-
# person.changes # => {"name" => ["Bill", "Bob"]}
-
#
-
# If an attribute is modified in-place then make use of <tt>[attribute_name]_will_change!</tt>
-
# to mark that the attribute is changing. Otherwise ActiveModel can't track
-
# changes to in-place attributes.
-
#
-
# person.name_will_change!
-
# person.name_change # => ["Bill", "Bill"]
-
# person.name << 'y'
-
# person.name_change # => ["Bill", "Billy"]
-
2
module Dirty
-
2
extend ActiveSupport::Concern
-
2
include ActiveModel::AttributeMethods
-
-
2
included do
-
2
attribute_method_suffix '_changed?', '_change', '_will_change!', '_was'
-
2
attribute_method_affix prefix: 'reset_', suffix: '!'
-
end
-
-
# Returns +true+ if any attribute have unsaved changes, +false+ otherwise.
-
#
-
# person.changed? # => false
-
# person.name = 'bob'
-
# person.changed? # => true
-
2
def changed?
-
changed_attributes.present?
-
end
-
-
# Returns an array with the name of the attributes with unsaved changes.
-
#
-
# person.changed # => []
-
# person.name = 'bob'
-
# person.changed # => ["name"]
-
2
def changed
-
606
changed_attributes.keys
-
end
-
-
# Returns a hash of changed attributes indicating their original
-
# and new values like <tt>attr => [original value, new value]</tt>.
-
#
-
# person.changes # => {}
-
# person.name = 'bob'
-
# person.changes # => { "name" => ["bill", "bob"] }
-
2
def changes
-
1939
ActiveSupport::HashWithIndifferentAccess[changed.map { |attr| [attr, attribute_change(attr)] }]
-
end
-
-
# Returns a hash of attributes that were changed before the model was saved.
-
#
-
# person.name # => "bob"
-
# person.name = 'robert'
-
# person.save
-
# person.previous_changes # => {"name" => ["bob", "robert"]}
-
2
def previous_changes
-
@previously_changed ||= ActiveSupport::HashWithIndifferentAccess.new
-
end
-
-
# Returns a hash of the attributes with unsaved changes indicating their original
-
# values like <tt>attr => original value</tt>.
-
#
-
# person.name # => "bob"
-
# person.name = 'robert'
-
# person.changed_attributes # => {"name" => "bob"}
-
2
def changed_attributes
-
8752
@changed_attributes ||= ActiveSupport::HashWithIndifferentAccess.new
-
end
-
-
# Handle <tt>*_changed?</tt> for +method_missing+.
-
2
def attribute_changed?(attr, options = {}) #:nodoc:
-
4182
result = changed_attributes.include?(attr)
-
4182
result &&= options[:to] == __send__(attr) if options.key?(:to)
-
4182
result &&= options[:from] == changed_attributes[attr] if options.key?(:from)
-
4182
result
-
end
-
-
# Handle <tt>*_was</tt> for +method_missing+.
-
2
def attribute_was(attr) # :nodoc:
-
attribute_changed?(attr) ? changed_attributes[attr] : __send__(attr)
-
end
-
-
2
private
-
-
# Removes current changes and makes them accessible through +previous_changes+.
-
2
def changes_applied
-
267
@previously_changed = changes
-
267
@changed_attributes = ActiveSupport::HashWithIndifferentAccess.new
-
end
-
-
# Removes all dirty data: current changes and previous changes
-
2
def reset_changes
-
@previously_changed = ActiveSupport::HashWithIndifferentAccess.new
-
@changed_attributes = ActiveSupport::HashWithIndifferentAccess.new
-
end
-
-
# Handle <tt>*_change</tt> for +method_missing+.
-
2
def attribute_change(attr)
-
1672
[changed_attributes[attr], __send__(attr)] if attribute_changed?(attr)
-
end
-
-
# Handle <tt>*_will_change!</tt> for +method_missing+.
-
2
def attribute_will_change!(attr)
-
return if attribute_changed?(attr)
-
-
begin
-
value = __send__(attr)
-
value = value.duplicable? ? value.clone : value
-
rescue TypeError, NoMethodError
-
end
-
-
changed_attributes[attr] = value
-
end
-
-
# Handle <tt>reset_*!</tt> for +method_missing+.
-
2
def reset_attribute!(attr)
-
if attribute_changed?(attr)
-
__send__("#{attr}=", changed_attributes[attr])
-
changed_attributes.delete(attr)
-
end
-
end
-
end
-
end
-
# -*- coding: utf-8 -*-
-
-
2
require 'active_support/core_ext/array/conversions'
-
2
require 'active_support/core_ext/string/inflections'
-
-
2
module ActiveModel
-
# == Active \Model \Errors
-
#
-
# Provides a modified +Hash+ that you can include in your object
-
# for handling error messages and interacting with Action View helpers.
-
#
-
# A minimal implementation could be:
-
#
-
# class Person
-
# # Required dependency for ActiveModel::Errors
-
# extend ActiveModel::Naming
-
#
-
# def initialize
-
# @errors = ActiveModel::Errors.new(self)
-
# end
-
#
-
# attr_accessor :name
-
# attr_reader :errors
-
#
-
# def validate!
-
# errors.add(:name, "cannot be nil") if name == nil
-
# end
-
#
-
# # The following methods are needed to be minimally implemented
-
#
-
# def read_attribute_for_validation(attr)
-
# send(attr)
-
# end
-
#
-
# def Person.human_attribute_name(attr, options = {})
-
# attr
-
# end
-
#
-
# def Person.lookup_ancestors
-
# [self]
-
# end
-
# end
-
#
-
# The last three methods are required in your object for Errors to be
-
# able to generate error messages correctly and also handle multiple
-
# languages. Of course, if you extend your object with ActiveModel::Translation
-
# you will not need to implement the last two. Likewise, using
-
# ActiveModel::Validations will handle the validation related methods
-
# for you.
-
#
-
# The above allows you to do:
-
#
-
# person = Person.new
-
# person.validate! # => ["cannot be nil"]
-
# person.errors.full_messages # => ["name cannot be nil"]
-
# # etc..
-
2
class Errors
-
2
include Enumerable
-
-
2
CALLBACKS_OPTIONS = [:if, :unless, :on, :allow_nil, :allow_blank, :strict]
-
-
2
attr_reader :messages
-
-
# Pass in the instance of the object that is using the errors object.
-
#
-
# class Person
-
# def initialize
-
# @errors = ActiveModel::Errors.new(self)
-
# end
-
# end
-
2
def initialize(base)
-
271
@base = base
-
271
@messages = {}
-
end
-
-
2
def initialize_dup(other) # :nodoc:
-
@messages = other.messages.dup
-
super
-
end
-
-
# Clear the error messages.
-
#
-
# person.errors.full_messages # => ["name cannot be nil"]
-
# person.errors.clear
-
# person.errors.full_messages # => []
-
2
def clear
-
269
messages.clear
-
end
-
-
# Returns +true+ if the error messages include an error for the given key
-
# +attribute+, +false+ otherwise.
-
#
-
# person.errors.messages # => {:name=>["cannot be nil"]}
-
# person.errors.include?(:name) # => true
-
# person.errors.include?(:age) # => false
-
2
def include?(attribute)
-
messages[attribute].present?
-
end
-
# aliases include?
-
2
alias :has_key? :include?
-
-
# Get messages for +key+.
-
#
-
# person.errors.messages # => {:name=>["cannot be nil"]}
-
# person.errors.get(:name) # => ["cannot be nil"]
-
# person.errors.get(:age) # => nil
-
2
def get(key)
-
44
messages[key]
-
end
-
-
# Set messages for +key+ to +value+.
-
#
-
# person.errors.get(:name) # => ["cannot be nil"]
-
# person.errors.set(:name, ["can't be nil"])
-
# person.errors.get(:name) # => ["can't be nil"]
-
2
def set(key, value)
-
28
messages[key] = value
-
end
-
-
# Delete messages for +key+. Returns the deleted messages.
-
#
-
# person.errors.get(:name) # => ["cannot be nil"]
-
# person.errors.delete(:name) # => ["cannot be nil"]
-
# person.errors.get(:name) # => nil
-
2
def delete(key)
-
messages.delete(key)
-
end
-
-
# When passed a symbol or a name of a method, returns an array of errors
-
# for the method.
-
#
-
# person.errors[:name] # => ["cannot be nil"]
-
# person.errors['name'] # => ["cannot be nil"]
-
2
def [](attribute)
-
44
get(attribute.to_sym) || set(attribute.to_sym, [])
-
end
-
-
# Adds to the supplied attribute the supplied error message.
-
#
-
# person.errors[:name] = "must be set"
-
# person.errors[:name] # => ['must be set']
-
2
def []=(attribute, error)
-
self[attribute] << error
-
end
-
-
# Iterates through each error key, value pair in the error messages hash.
-
# Yields the attribute and the error for that attribute. If the attribute
-
# has more than one error message, yields once for each error message.
-
#
-
# person.errors.add(:name, "can't be blank")
-
# person.errors.each do |attribute, error|
-
# # Will yield :name and "can't be blank"
-
# end
-
#
-
# person.errors.add(:name, "must be specified")
-
# person.errors.each do |attribute, error|
-
# # Will yield :name and "can't be blank"
-
# # then yield :name and "must be specified"
-
# end
-
2
def each
-
538
messages.each_key do |attribute|
-
8
self[attribute].each { |error| yield attribute, error }
-
end
-
end
-
-
# Returns the number of error messages.
-
#
-
# person.errors.add(:name, "can't be blank")
-
# person.errors.size # => 1
-
# person.errors.add(:name, "must be specified")
-
# person.errors.size # => 2
-
2
def size
-
values.flatten.size
-
end
-
-
# Returns all message values.
-
#
-
# person.errors.messages # => {:name=>["cannot be nil", "must be specified"]}
-
# person.errors.values # => [["cannot be nil", "must be specified"]]
-
2
def values
-
messages.values
-
end
-
-
# Returns all message keys.
-
#
-
# person.errors.messages # => {:name=>["cannot be nil", "must be specified"]}
-
# person.errors.keys # => [:name]
-
2
def keys
-
messages.keys
-
end
-
-
# Returns an array of error messages, with the attribute name included.
-
#
-
# person.errors.add(:name, "can't be blank")
-
# person.errors.add(:name, "must be specified")
-
# person.errors.to_a # => ["name can't be blank", "name must be specified"]
-
2
def to_a
-
full_messages
-
end
-
-
# Returns the number of error messages.
-
#
-
# person.errors.add(:name, "can't be blank")
-
# person.errors.count # => 1
-
# person.errors.add(:name, "must be specified")
-
# person.errors.count # => 2
-
2
def count
-
to_a.size
-
end
-
-
# Returns +true+ if no errors are found, +false+ otherwise.
-
# If the error message is a string it can be empty.
-
#
-
# person.errors.full_messages # => ["name cannot be nil"]
-
# person.errors.empty? # => false
-
2
def empty?
-
542
all? { |k, v| v && v.empty? && !v.is_a?(String) }
-
end
-
# aliases empty?
-
2
alias_method :blank?, :empty?
-
-
# Returns an xml formatted representation of the Errors hash.
-
#
-
# person.errors.add(:name, "can't be blank")
-
# person.errors.add(:name, "must be specified")
-
# person.errors.to_xml
-
# # =>
-
# # <?xml version=\"1.0\" encoding=\"UTF-8\"?>
-
# # <errors>
-
# # <error>name can't be blank</error>
-
# # <error>name must be specified</error>
-
# # </errors>
-
2
def to_xml(options={})
-
to_a.to_xml({ root: "errors", skip_types: true }.merge!(options))
-
end
-
-
# Returns a Hash that can be used as the JSON representation for this
-
# object. You can pass the <tt>:full_messages</tt> option. This determines
-
# if the json object should contain full messages or not (false by default).
-
#
-
# person.errors.as_json # => {:name=>["cannot be nil"]}
-
# person.errors.as_json(full_messages: true) # => {:name=>["name cannot be nil"]}
-
2
def as_json(options=nil)
-
to_hash(options && options[:full_messages])
-
end
-
-
# Returns a Hash of attributes with their error messages. If +full_messages+
-
# is +true+, it will contain full messages (see +full_message+).
-
#
-
# person.errors.to_hash # => {:name=>["cannot be nil"]}
-
# person.errors.to_hash(true) # => {:name=>["name cannot be nil"]}
-
2
def to_hash(full_messages = false)
-
if full_messages
-
messages = {}
-
self.messages.each do |attribute, array|
-
messages[attribute] = array.map { |message| full_message(attribute, message) }
-
end
-
messages
-
else
-
self.messages.dup
-
end
-
end
-
-
# Adds +message+ to the error messages on +attribute+. More than one error
-
# can be added to the same +attribute+. If no +message+ is supplied,
-
# <tt>:invalid</tt> is assumed.
-
#
-
# person.errors.add(:name)
-
# # => ["is invalid"]
-
# person.errors.add(:name, 'must be implemented')
-
# # => ["is invalid", "must be implemented"]
-
#
-
# person.errors.messages
-
# # => {:name=>["must be implemented", "is invalid"]}
-
#
-
# If +message+ is a symbol, it will be translated using the appropriate
-
# scope (see +generate_message+).
-
#
-
# If +message+ is a proc, it will be called, allowing for things like
-
# <tt>Time.now</tt> to be used within an error.
-
#
-
# If the <tt>:strict</tt> option is set to +true+, it will raise
-
# ActiveModel::StrictValidationFailed instead of adding the error.
-
# <tt>:strict</tt> option can also be set to any other exception.
-
#
-
# person.errors.add(:name, nil, strict: true)
-
# # => ActiveModel::StrictValidationFailed: name is invalid
-
# person.errors.add(:name, nil, strict: NameIsInvalid)
-
# # => NameIsInvalid: name is invalid
-
#
-
# person.errors.messages # => {}
-
2
def add(attribute, message = :invalid, options = {})
-
12
message = normalize_message(attribute, message, options)
-
12
if exception = options[:strict]
-
exception = ActiveModel::StrictValidationFailed if exception == true
-
raise exception, full_message(attribute, message)
-
end
-
-
12
self[attribute] << message
-
end
-
-
# Will add an error message to each of the attributes in +attributes+
-
# that is empty.
-
#
-
# person.errors.add_on_empty(:name)
-
# person.errors.messages
-
# # => {:name=>["can't be empty"]}
-
2
def add_on_empty(attributes, options = {})
-
Array(attributes).each do |attribute|
-
value = @base.send(:read_attribute_for_validation, attribute)
-
is_empty = value.respond_to?(:empty?) ? value.empty? : false
-
add(attribute, :empty, options) if value.nil? || is_empty
-
end
-
end
-
-
# Will add an error message to each of the attributes in +attributes+ that
-
# is blank (using Object#blank?).
-
#
-
# person.errors.add_on_blank(:name)
-
# person.errors.messages
-
# # => {:name=>["can't be blank"]}
-
2
def add_on_blank(attributes, options = {})
-
Array(attributes).each do |attribute|
-
value = @base.send(:read_attribute_for_validation, attribute)
-
add(attribute, :blank, options) if value.blank?
-
end
-
end
-
-
# Returns +true+ if an error on the attribute with the given message is
-
# present, +false+ otherwise. +message+ is treated the same as for +add+.
-
#
-
# person.errors.add :name, :blank
-
# person.errors.added? :name, :blank # => true
-
2
def added?(attribute, message = :invalid, options = {})
-
message = normalize_message(attribute, message, options)
-
self[attribute].include? message
-
end
-
-
# Returns all the full error messages in an array.
-
#
-
# class Person
-
# validates_presence_of :name, :address, :email
-
# validates_length_of :name, in: 5..30
-
# end
-
#
-
# person = Person.create(address: '123 First St.')
-
# person.errors.full_messages
-
# # => ["Name is too short (minimum is 5 characters)", "Name can't be blank", "Email can't be blank"]
-
2
def full_messages
-
map { |attribute, message| full_message(attribute, message) }
-
end
-
-
# Returns all the full error messages for a given attribute in an array.
-
#
-
# class Person
-
# validates_presence_of :name, :email
-
# validates_length_of :name, in: 5..30
-
# end
-
#
-
# person = Person.create()
-
# person.errors.full_messages_for(:name)
-
# # => ["Name is too short (minimum is 5 characters)", "Name can't be blank"]
-
2
def full_messages_for(attribute)
-
(get(attribute) || []).map { |message| full_message(attribute, message) }
-
end
-
-
# Returns a full message for a given attribute.
-
#
-
# person.errors.full_message(:name, 'is invalid') # => "Name is invalid"
-
2
def full_message(attribute, message)
-
return message if attribute == :base
-
attr_name = attribute.to_s.tr('.', '_').humanize
-
attr_name = @base.class.human_attribute_name(attribute, default: attr_name)
-
I18n.t(:"errors.format", {
-
default: "%{attribute} %{message}",
-
attribute: attr_name,
-
message: message
-
})
-
end
-
-
# Translates an error message in its default scope
-
# (<tt>activemodel.errors.messages</tt>).
-
#
-
# Error messages are first looked up in <tt>models.MODEL.attributes.ATTRIBUTE.MESSAGE</tt>,
-
# if it's not there, it's looked up in <tt>models.MODEL.MESSAGE</tt> and if
-
# that is not there also, it returns the translation of the default message
-
# (e.g. <tt>activemodel.errors.messages.MESSAGE</tt>). The translated model
-
# name, translated attribute name and the value are available for
-
# interpolation.
-
#
-
# When using inheritance in your models, it will check all the inherited
-
# models too, but only if the model itself hasn't been found. Say you have
-
# <tt>class Admin < User; end</tt> and you wanted the translation for
-
# the <tt>:blank</tt> error message for the <tt>title</tt> attribute,
-
# it looks for these translations:
-
#
-
# * <tt>activemodel.errors.models.admin.attributes.title.blank</tt>
-
# * <tt>activemodel.errors.models.admin.blank</tt>
-
# * <tt>activemodel.errors.models.user.attributes.title.blank</tt>
-
# * <tt>activemodel.errors.models.user.blank</tt>
-
# * any default you provided through the +options+ hash (in the <tt>activemodel.errors</tt> scope)
-
# * <tt>activemodel.errors.messages.blank</tt>
-
# * <tt>errors.attributes.title.blank</tt>
-
# * <tt>errors.messages.blank</tt>
-
2
def generate_message(attribute, type = :invalid, options = {})
-
12
type = options.delete(:message) if options[:message].is_a?(Symbol)
-
-
12
if @base.class.respond_to?(:i18n_scope)
-
12
defaults = @base.class.lookup_ancestors.map do |klass|
-
12
[ :"#{@base.class.i18n_scope}.errors.models.#{klass.model_name.i18n_key}.attributes.#{attribute}.#{type}",
-
:"#{@base.class.i18n_scope}.errors.models.#{klass.model_name.i18n_key}.#{type}" ]
-
end
-
else
-
defaults = []
-
end
-
-
12
defaults << options.delete(:message)
-
12
defaults << :"#{@base.class.i18n_scope}.errors.messages.#{type}" if @base.class.respond_to?(:i18n_scope)
-
12
defaults << :"errors.attributes.#{attribute}.#{type}"
-
12
defaults << :"errors.messages.#{type}"
-
-
12
defaults.compact!
-
12
defaults.flatten!
-
-
12
key = defaults.shift
-
12
value = (attribute != :base ? @base.send(:read_attribute_for_validation, attribute) : nil)
-
-
12
options = {
-
default: defaults,
-
model: @base.class.model_name.human,
-
attribute: @base.class.human_attribute_name(attribute),
-
value: value
-
}.merge!(options)
-
-
12
I18n.translate(key, options)
-
end
-
-
2
private
-
2
def normalize_message(attribute, message, options)
-
12
case message
-
when Symbol
-
12
generate_message(attribute, message, options.except(*CALLBACKS_OPTIONS))
-
when Proc
-
message.call
-
else
-
message
-
end
-
end
-
end
-
-
# Raised when a validation cannot be corrected by end users and are considered
-
# exceptional.
-
#
-
# class Person
-
# include ActiveModel::Validations
-
#
-
# attr_accessor :name
-
#
-
# validates_presence_of :name, strict: true
-
# end
-
#
-
# person = Person.new
-
# person.name = nil
-
# person.valid?
-
# # => ActiveModel::StrictValidationFailed: Name can't be blank
-
2
class StrictValidationFailed < StandardError
-
end
-
end
-
2
module ActiveModel
-
# Raised when forbidden attributes are used for mass assignment.
-
#
-
# class Person < ActiveRecord::Base
-
# end
-
#
-
# params = ActionController::Parameters.new(name: 'Bob')
-
# Person.new(params)
-
# # => ActiveModel::ForbiddenAttributesError
-
#
-
# params.permit!
-
# Person.new(params)
-
# # => #<Person id: nil, name: "Bob">
-
2
class ForbiddenAttributesError < StandardError
-
end
-
-
2
module ForbiddenAttributesProtection # :nodoc:
-
2
protected
-
2
def sanitize_for_mass_assignment(attributes)
-
362
if attributes.respond_to?(:permitted?) && !attributes.permitted?
-
raise ActiveModel::ForbiddenAttributesError
-
else
-
362
attributes
-
end
-
end
-
2
alias :sanitize_forbidden_attributes :sanitize_for_mass_assignment
-
end
-
end
-
2
module ActiveModel
-
# Returns the version of the currently loaded ActiveModel as a <tt>Gem::Version</tt>
-
2
def self.gem_version
-
Gem::Version.new VERSION::STRING
-
end
-
-
2
module VERSION
-
2
MAJOR = 4
-
2
MINOR = 1
-
2
TINY = 8
-
2
PRE = nil
-
-
2
STRING = [MAJOR, MINOR, TINY, PRE].compact.join(".")
-
end
-
end
-
2
require 'active_support/core_ext/hash/except'
-
2
require 'active_support/core_ext/module/introspection'
-
-
2
module ActiveModel
-
2
class Name
-
2
include Comparable
-
-
2
attr_reader :singular, :plural, :element, :collection,
-
:singular_route_key, :route_key, :param_key, :i18n_key,
-
:name
-
-
2
alias_method :cache_key, :collection
-
-
##
-
# :method: ==
-
#
-
# :call-seq:
-
# ==(other)
-
#
-
# Equivalent to <tt>String#==</tt>. Returns +true+ if the class name and
-
# +other+ are equal, otherwise +false+.
-
#
-
# class BlogPost
-
# extend ActiveModel::Naming
-
# end
-
#
-
# BlogPost.model_name == 'BlogPost' # => true
-
# BlogPost.model_name == 'Blog Post' # => false
-
-
##
-
# :method: ===
-
#
-
# :call-seq:
-
# ===(other)
-
#
-
# Equivalent to <tt>#==</tt>.
-
#
-
# class BlogPost
-
# extend ActiveModel::Naming
-
# end
-
#
-
# BlogPost.model_name === 'BlogPost' # => true
-
# BlogPost.model_name === 'Blog Post' # => false
-
-
##
-
# :method: <=>
-
#
-
# :call-seq:
-
# ==(other)
-
#
-
# Equivalent to <tt>String#<=></tt>.
-
#
-
# class BlogPost
-
# extend ActiveModel::Naming
-
# end
-
#
-
# BlogPost.model_name <=> 'BlogPost' # => 0
-
# BlogPost.model_name <=> 'Blog' # => 1
-
# BlogPost.model_name <=> 'BlogPosts' # => -1
-
-
##
-
# :method: =~
-
#
-
# :call-seq:
-
# =~(regexp)
-
#
-
# Equivalent to <tt>String#=~</tt>. Match the class name against the given
-
# regexp. Returns the position where the match starts or +nil+ if there is
-
# no match.
-
#
-
# class BlogPost
-
# extend ActiveModel::Naming
-
# end
-
#
-
# BlogPost.model_name =~ /Post/ # => 4
-
# BlogPost.model_name =~ /\d/ # => nil
-
-
##
-
# :method: !~
-
#
-
# :call-seq:
-
# !~(regexp)
-
#
-
# Equivalent to <tt>String#!~</tt>. Match the class name against the given
-
# regexp. Returns +true+ if there is no match, otherwise +false+.
-
#
-
# class BlogPost
-
# extend ActiveModel::Naming
-
# end
-
#
-
# BlogPost.model_name !~ /Post/ # => false
-
# BlogPost.model_name !~ /\d/ # => true
-
-
##
-
# :method: eql?
-
#
-
# :call-seq:
-
# eql?(other)
-
#
-
# Equivalent to <tt>String#eql?</tt>. Returns +true+ if the class name and
-
# +other+ have the same length and content, otherwise +false+.
-
#
-
# class BlogPost
-
# extend ActiveModel::Naming
-
# end
-
#
-
# BlogPost.model_name.eql?('BlogPost') # => true
-
# BlogPost.model_name.eql?('Blog Post') # => false
-
-
##
-
# :method: to_s
-
#
-
# :call-seq:
-
# to_s()
-
#
-
# Returns the class name.
-
#
-
# class BlogPost
-
# extend ActiveModel::Naming
-
# end
-
#
-
# BlogPost.model_name.to_s # => "BlogPost"
-
-
##
-
# :method: to_str
-
#
-
# :call-seq:
-
# to_str()
-
#
-
# Equivalent to +to_s+.
-
2
delegate :==, :===, :<=>, :=~, :"!~", :eql?, :to_s,
-
:to_str, to: :name
-
-
# Returns a new ActiveModel::Name instance. By default, the +namespace+
-
# and +name+ option will take the namespace and name of the given class
-
# respectively.
-
#
-
# module Foo
-
# class Bar
-
# end
-
# end
-
#
-
# ActiveModel::Name.new(Foo::Bar).to_s
-
# # => "Foo::Bar"
-
2
def initialize(klass, namespace = nil, name = nil)
-
2
@name = name || klass.name
-
-
2
raise ArgumentError, "Class name cannot be blank. You need to supply a name argument when anonymous class given" if @name.blank?
-
-
2
@unnamespaced = @name.sub(/^#{namespace.name}::/, '') if namespace
-
2
@klass = klass
-
2
@singular = _singularize(@name)
-
2
@plural = ActiveSupport::Inflector.pluralize(@singular)
-
2
@element = ActiveSupport::Inflector.underscore(ActiveSupport::Inflector.demodulize(@name))
-
2
@human = ActiveSupport::Inflector.humanize(@element)
-
2
@collection = ActiveSupport::Inflector.tableize(@name)
-
2
@param_key = (namespace ? _singularize(@unnamespaced) : @singular)
-
2
@i18n_key = @name.underscore.to_sym
-
-
2
@route_key = (namespace ? ActiveSupport::Inflector.pluralize(@param_key) : @plural.dup)
-
2
@singular_route_key = ActiveSupport::Inflector.singularize(@route_key)
-
2
@route_key << "_index" if @plural == @singular
-
end
-
-
# Transform the model name into a more humane format, using I18n. By default,
-
# it will underscore then humanize the class name.
-
#
-
# class BlogPost
-
# extend ActiveModel::Naming
-
# end
-
#
-
# BlogPost.model_name.human # => "Blog post"
-
#
-
# Specify +options+ with additional translating options.
-
2
def human(options={})
-
return @human unless @klass.respond_to?(:lookup_ancestors) &&
-
12
@klass.respond_to?(:i18n_scope)
-
-
12
defaults = @klass.lookup_ancestors.map do |klass|
-
12
klass.model_name.i18n_key
-
end
-
-
12
defaults << options[:default] if options[:default]
-
12
defaults << @human
-
-
12
options = { scope: [@klass.i18n_scope, :models], count: 1, default: defaults }.merge!(options.except(:default))
-
12
I18n.translate(defaults.shift, options)
-
end
-
-
2
private
-
-
2
def _singularize(string, replacement='_')
-
2
ActiveSupport::Inflector.underscore(string).tr('/', replacement)
-
end
-
end
-
-
# == Active \Model \Naming
-
#
-
# Creates a +model_name+ method on your object.
-
#
-
# To implement, just extend ActiveModel::Naming in your object:
-
#
-
# class BookCover
-
# extend ActiveModel::Naming
-
# end
-
#
-
# BookCover.model_name # => "BookCover"
-
# BookCover.model_name.human # => "Book cover"
-
#
-
# BookCover.model_name.i18n_key # => :book_cover
-
# BookModule::BookCover.model_name.i18n_key # => :"book_module/book_cover"
-
#
-
# Providing the functionality that ActiveModel::Naming provides in your object
-
# is required to pass the Active Model Lint test. So either extending the
-
# provided method below, or rolling your own is required.
-
2
module Naming
-
# Returns an ActiveModel::Name object for module. It can be
-
# used to retrieve all kinds of naming-related information
-
# (See ActiveModel::Name for more information).
-
#
-
# class Person < ActiveModel::Model
-
# end
-
#
-
# Person.model_name # => Person
-
# Person.model_name.class # => ActiveModel::Name
-
# Person.model_name.singular # => "person"
-
# Person.model_name.plural # => "people"
-
2
def model_name
-
@_model_name ||= begin
-
2
namespace = self.parents.detect do |n|
-
2
n.respond_to?(:use_relative_model_naming?) && n.use_relative_model_naming?
-
end
-
2
ActiveModel::Name.new(self, namespace)
-
76
end
-
end
-
-
# Returns the plural class name of a record or class.
-
#
-
# ActiveModel::Naming.plural(post) # => "posts"
-
# ActiveModel::Naming.plural(Highrise::Person) # => "highrise_people"
-
2
def self.plural(record_or_class)
-
model_name_from_record_or_class(record_or_class).plural
-
end
-
-
# Returns the singular class name of a record or class.
-
#
-
# ActiveModel::Naming.singular(post) # => "post"
-
# ActiveModel::Naming.singular(Highrise::Person) # => "highrise_person"
-
2
def self.singular(record_or_class)
-
model_name_from_record_or_class(record_or_class).singular
-
end
-
-
# Identifies whether the class name of a record or class is uncountable.
-
#
-
# ActiveModel::Naming.uncountable?(Sheep) # => true
-
# ActiveModel::Naming.uncountable?(Post) # => false
-
2
def self.uncountable?(record_or_class)
-
plural(record_or_class) == singular(record_or_class)
-
end
-
-
# Returns string to use while generating route names. It differs for
-
# namespaced models regarding whether it's inside isolated engine.
-
#
-
# # For isolated engine:
-
# ActiveModel::Naming.singular_route_key(Blog::Post) # => "post"
-
#
-
# # For shared engine:
-
# ActiveModel::Naming.singular_route_key(Blog::Post) # => "blog_post"
-
2
def self.singular_route_key(record_or_class)
-
model_name_from_record_or_class(record_or_class).singular_route_key
-
end
-
-
# Returns string to use while generating route names. It differs for
-
# namespaced models regarding whether it's inside isolated engine.
-
#
-
# # For isolated engine:
-
# ActiveModel::Naming.route_key(Blog::Post) # => "posts"
-
#
-
# # For shared engine:
-
# ActiveModel::Naming.route_key(Blog::Post) # => "blog_posts"
-
#
-
# The route key also considers if the noun is uncountable and, in
-
# such cases, automatically appends _index.
-
2
def self.route_key(record_or_class)
-
model_name_from_record_or_class(record_or_class).route_key
-
end
-
-
# Returns string to use for params names. It differs for
-
# namespaced models regarding whether it's inside isolated engine.
-
#
-
# # For isolated engine:
-
# ActiveModel::Naming.param_key(Blog::Post) # => "post"
-
#
-
# # For shared engine:
-
# ActiveModel::Naming.param_key(Blog::Post) # => "blog_post"
-
2
def self.param_key(record_or_class)
-
model_name_from_record_or_class(record_or_class).param_key
-
end
-
-
2
def self.model_name_from_record_or_class(record_or_class) #:nodoc:
-
if record_or_class.respond_to?(:model_name)
-
record_or_class.model_name
-
elsif record_or_class.respond_to?(:to_model)
-
record_or_class.to_model.class.model_name
-
else
-
record_or_class.class.model_name
-
end
-
end
-
2
private_class_method :model_name_from_record_or_class
-
end
-
end
-
2
require "active_model"
-
2
require "rails"
-
-
2
module ActiveModel
-
2
class Railtie < Rails::Railtie # :nodoc:
-
2
config.eager_load_namespaces << ActiveModel
-
-
2
initializer "active_model.secure_password" do
-
2
ActiveModel::SecurePassword.min_cost = Rails.env.test?
-
end
-
end
-
end
-
2
module ActiveModel
-
2
module SecurePassword
-
2
extend ActiveSupport::Concern
-
-
2
class << self
-
2
attr_accessor :min_cost # :nodoc:
-
end
-
2
self.min_cost = false
-
-
2
module ClassMethods
-
# Adds methods to set and authenticate against a BCrypt password.
-
# This mechanism requires you to have a +password_digest+ attribute.
-
#
-
# Validations for presence of password on create, confirmation of password
-
# (using a +password_confirmation+ attribute) are automatically added. If
-
# you wish to turn off validations, pass <tt>validations: false</tt> as an
-
# argument. You can add more validations by hand if need be.
-
#
-
# If you don't need the confirmation validation, just don't set any
-
# value to the password_confirmation attribute and the validation
-
# will not be triggered.
-
#
-
# You need to add bcrypt (~> 3.1.7) to Gemfile to use #has_secure_password:
-
#
-
# gem 'bcrypt', '~> 3.1.7'
-
#
-
# Example using Active Record (which automatically includes ActiveModel::SecurePassword):
-
#
-
# # Schema: User(name:string, password_digest:string)
-
# class User < ActiveRecord::Base
-
# has_secure_password
-
# end
-
#
-
# user = User.new(name: 'david', password: '', password_confirmation: 'nomatch')
-
# user.save # => false, password required
-
# user.password = 'mUc3m00RsqyRe'
-
# user.save # => false, confirmation doesn't match
-
# user.password_confirmation = 'mUc3m00RsqyRe'
-
# user.save # => true
-
# user.authenticate('notright') # => false
-
# user.authenticate('mUc3m00RsqyRe') # => user
-
# User.find_by(name: 'david').try(:authenticate, 'notright') # => false
-
# User.find_by(name: 'david').try(:authenticate, 'mUc3m00RsqyRe') # => user
-
2
def has_secure_password(options = {})
-
# Load bcrypt gem only when has_secure_password is used.
-
# This is to avoid ActiveModel (and by extension the entire framework)
-
# being dependent on a binary library.
-
6
begin
-
6
require 'bcrypt'
-
rescue LoadError
-
$stderr.puts "You don't have bcrypt installed in your application. Please add it to your Gemfile and run bundle install"
-
raise
-
end
-
-
6
attr_reader :password
-
-
6
include InstanceMethodsOnActivation
-
-
6
if options.fetch(:validations, true)
-
# This ensures the model has a password by checking whether the password_digest
-
# is present, so that this works with both new and existing records. However,
-
# when there is an error, the message is added to the password attribute instead
-
# so that the error message will make sense to the end-user.
-
6
validate do |record|
-
195
record.errors.add(:password, :blank) unless record.password_digest.present?
-
end
-
-
201
validates_confirmation_of :password, if: ->{ password.present? }
-
end
-
-
6
if respond_to?(:attributes_protected_by_default)
-
def self.attributes_protected_by_default #:nodoc:
-
super + ['password_digest']
-
end
-
end
-
end
-
end
-
-
2
module InstanceMethodsOnActivation
-
# Returns +self+ if the password is correct, otherwise +false+.
-
#
-
# class User < ActiveRecord::Base
-
# has_secure_password validations: false
-
# end
-
#
-
# user = User.new(name: 'david', password: 'mUc3m00RsqyRe')
-
# user.save
-
# user.authenticate('notright') # => false
-
# user.authenticate('mUc3m00RsqyRe') # => user
-
2
def authenticate(unencrypted_password)
-
BCrypt::Password.new(password_digest) == unencrypted_password && self
-
end
-
-
# Encrypts the password into the +password_digest+ attribute, only if the
-
# new password is not blank.
-
#
-
# class User < ActiveRecord::Base
-
# has_secure_password validations: false
-
# end
-
#
-
# user = User.new
-
# user.password = nil
-
# user.password_digest # => nil
-
# user.password = 'mUc3m00RsqyRe'
-
# user.password_digest # => "$2a$10$4LEA7r4YmNHtvlAvHhsYAeZmk/xeUVtMTYqwIvYY76EW5GUqDiP4."
-
2
def password=(unencrypted_password)
-
198
if unencrypted_password.nil?
-
self.password_digest = nil
-
198
elsif unencrypted_password.present?
-
196
@password = unencrypted_password
-
196
cost = ActiveModel::SecurePassword.min_cost ? BCrypt::Engine::MIN_COST : BCrypt::Engine.cost
-
196
self.password_digest = BCrypt::Password.create(unencrypted_password, cost: cost)
-
end
-
end
-
-
2
def password_confirmation=(unencrypted_password)
-
2
@password_confirmation = unencrypted_password
-
end
-
end
-
end
-
end
-
2
require 'active_support/core_ext/hash/except'
-
2
require 'active_support/core_ext/hash/slice'
-
-
2
module ActiveModel
-
# == Active \Model \Serialization
-
#
-
# Provides a basic serialization to a serializable_hash for your object.
-
#
-
# A minimal implementation could be:
-
#
-
# class Person
-
# include ActiveModel::Serialization
-
#
-
# attr_accessor :name
-
#
-
# def attributes
-
# {'name' => nil}
-
# end
-
# end
-
#
-
# Which would provide you with:
-
#
-
# person = Person.new
-
# person.serializable_hash # => {"name"=>nil}
-
# person.name = "Bob"
-
# person.serializable_hash # => {"name"=>"Bob"}
-
#
-
# You need to declare an attributes hash which contains the attributes you
-
# want to serialize. Attributes must be strings, not symbols. When called,
-
# serializable hash will use instance methods that match the name of the
-
# attributes hash's keys. In order to override this behavior, take a look at
-
# the private method +read_attribute_for_serialization+.
-
#
-
# Most of the time though, you will want to include the JSON or XML
-
# serializations. Both of these modules automatically include the
-
# <tt>ActiveModel::Serialization</tt> module, so there is no need to
-
# explicitly include it.
-
#
-
# A minimal implementation including XML and JSON would be:
-
#
-
# class Person
-
# include ActiveModel::Serializers::JSON
-
# include ActiveModel::Serializers::Xml
-
#
-
# attr_accessor :name
-
#
-
# def attributes
-
# {'name' => nil}
-
# end
-
# end
-
#
-
# Which would provide you with:
-
#
-
# person = Person.new
-
# person.serializable_hash # => {"name"=>nil}
-
# person.as_json # => {"name"=>nil}
-
# person.to_json # => "{\"name\":null}"
-
# person.to_xml # => "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<serial-person...
-
#
-
# person.name = "Bob"
-
# person.serializable_hash # => {"name"=>"Bob"}
-
# person.as_json # => {"name"=>"Bob"}
-
# person.to_json # => "{\"name\":\"Bob\"}"
-
# person.to_xml # => "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<serial-person...
-
#
-
# Valid options are <tt>:only</tt>, <tt>:except</tt>, <tt>:methods</tt> and
-
# <tt>:include</tt>. The following are all valid examples:
-
#
-
# person.serializable_hash(only: 'name')
-
# person.serializable_hash(include: :address)
-
# person.serializable_hash(include: { address: { only: 'city' }})
-
2
module Serialization
-
# Returns a serialized hash of your object.
-
#
-
# class Person
-
# include ActiveModel::Serialization
-
#
-
# attr_accessor :name, :age
-
#
-
# def attributes
-
# {'name' => nil, 'age' => nil}
-
# end
-
#
-
# def capitalized_name
-
# name.capitalize
-
# end
-
# end
-
#
-
# person = Person.new
-
# person.name = 'bob'
-
# person.age = 22
-
# person.serializable_hash # => {"name"=>"bob", "age"=>22}
-
# person.serializable_hash(only: :name) # => {"name"=>"bob"}
-
# person.serializable_hash(except: :name) # => {"age"=>22}
-
# person.serializable_hash(methods: :capitalized_name)
-
# # => {"name"=>"bob", "age"=>22, "capitalized_name"=>"Bob"}
-
2
def serializable_hash(options = nil)
-
options ||= {}
-
-
attribute_names = attributes.keys
-
if only = options[:only]
-
attribute_names &= Array(only).map(&:to_s)
-
elsif except = options[:except]
-
attribute_names -= Array(except).map(&:to_s)
-
end
-
-
hash = {}
-
attribute_names.each { |n| hash[n] = read_attribute_for_serialization(n) }
-
-
Array(options[:methods]).each { |m| hash[m.to_s] = send(m) if respond_to?(m) }
-
-
serializable_add_includes(options) do |association, records, opts|
-
hash[association.to_s] = if records.respond_to?(:to_ary)
-
records.to_ary.map { |a| a.serializable_hash(opts) }
-
else
-
records.serializable_hash(opts)
-
end
-
end
-
-
hash
-
end
-
-
2
private
-
-
# Hook method defining how an attribute value should be retrieved for
-
# serialization. By default this is assumed to be an instance named after
-
# the attribute. Override this method in subclasses should you need to
-
# retrieve the value for a given attribute differently:
-
#
-
# class MyClass
-
# include ActiveModel::Serialization
-
#
-
# def initialize(data = {})
-
# @data = data
-
# end
-
#
-
# def read_attribute_for_serialization(key)
-
# @data[key]
-
# end
-
# end
-
2
alias :read_attribute_for_serialization :send
-
-
# Add associations specified via the <tt>:include</tt> option.
-
#
-
# Expects a block that takes as arguments:
-
# +association+ - name of the association
-
# +records+ - the association record(s) to be serialized
-
# +opts+ - options for the association records
-
2
def serializable_add_includes(options = {}) #:nodoc:
-
return unless includes = options[:include]
-
-
unless includes.is_a?(Hash)
-
includes = Hash[Array(includes).map { |n| n.is_a?(Hash) ? n.to_a.first : [n, {}] }]
-
end
-
-
includes.each do |association, opts|
-
if records = send(association)
-
yield association, records, opts
-
end
-
end
-
end
-
end
-
end
-
2
require 'active_support/json'
-
-
2
module ActiveModel
-
2
module Serializers
-
# == Active \Model \JSON \Serializer
-
2
module JSON
-
2
extend ActiveSupport::Concern
-
2
include ActiveModel::Serialization
-
-
2
included do
-
2
extend ActiveModel::Naming
-
-
2
class_attribute :include_root_in_json
-
2
self.include_root_in_json = false
-
end
-
-
# Returns a hash representing the model. Some configuration can be
-
# passed through +options+.
-
#
-
# The option <tt>include_root_in_json</tt> controls the top-level behavior
-
# of +as_json+. If +true+, +as_json+ will emit a single root node named
-
# after the object's type. The default value for <tt>include_root_in_json</tt>
-
# option is +false+.
-
#
-
# user = User.find(1)
-
# user.as_json
-
# # => { "id" => 1, "name" => "Konata Izumi", "age" => 16,
-
# # "created_at" => "2006/08/01", "awesome" => true}
-
#
-
# ActiveRecord::Base.include_root_in_json = true
-
#
-
# user.as_json
-
# # => { "user" => { "id" => 1, "name" => "Konata Izumi", "age" => 16,
-
# # "created_at" => "2006/08/01", "awesome" => true } }
-
#
-
# This behavior can also be achieved by setting the <tt>:root</tt> option
-
# to +true+ as in:
-
#
-
# user = User.find(1)
-
# user.as_json(root: true)
-
# # => { "user" => { "id" => 1, "name" => "Konata Izumi", "age" => 16,
-
# # "created_at" => "2006/08/01", "awesome" => true } }
-
#
-
# Without any +options+, the returned Hash will include all the model's
-
# attributes.
-
#
-
# user = User.find(1)
-
# user.as_json
-
# # => { "id" => 1, "name" => "Konata Izumi", "age" => 16,
-
# # "created_at" => "2006/08/01", "awesome" => true}
-
#
-
# The <tt>:only</tt> and <tt>:except</tt> options can be used to limit
-
# the attributes included, and work similar to the +attributes+ method.
-
#
-
# user.as_json(only: [:id, :name])
-
# # => { "id" => 1, "name" => "Konata Izumi" }
-
#
-
# user.as_json(except: [:id, :created_at, :age])
-
# # => { "name" => "Konata Izumi", "awesome" => true }
-
#
-
# To include the result of some method calls on the model use <tt>:methods</tt>:
-
#
-
# user.as_json(methods: :permalink)
-
# # => { "id" => 1, "name" => "Konata Izumi", "age" => 16,
-
# # "created_at" => "2006/08/01", "awesome" => true,
-
# # "permalink" => "1-konata-izumi" }
-
#
-
# To include associations use <tt>:include</tt>:
-
#
-
# user.as_json(include: :posts)
-
# # => { "id" => 1, "name" => "Konata Izumi", "age" => 16,
-
# # "created_at" => "2006/08/01", "awesome" => true,
-
# # "posts" => [ { "id" => 1, "author_id" => 1, "title" => "Welcome to the weblog" },
-
# # { "id" => 2, "author_id" => 1, "title" => "So I was thinking" } ] }
-
#
-
# Second level and higher order associations work as well:
-
#
-
# user.as_json(include: { posts: {
-
# include: { comments: {
-
# only: :body } },
-
# only: :title } })
-
# # => { "id" => 1, "name" => "Konata Izumi", "age" => 16,
-
# # "created_at" => "2006/08/01", "awesome" => true,
-
# # "posts" => [ { "comments" => [ { "body" => "1st post!" }, { "body" => "Second!" } ],
-
# # "title" => "Welcome to the weblog" },
-
# # { "comments" => [ { "body" => "Don't think too hard" } ],
-
# # "title" => "So I was thinking" } ] }
-
2
def as_json(options = nil)
-
root = if options && options.key?(:root)
-
options[:root]
-
else
-
include_root_in_json
-
end
-
-
if root
-
root = self.class.model_name.element if root == true
-
{ root => serializable_hash(options) }
-
else
-
serializable_hash(options)
-
end
-
end
-
-
# Sets the model +attributes+ from a JSON string. Returns +self+.
-
#
-
# class Person
-
# include ActiveModel::Serializers::JSON
-
#
-
# attr_accessor :name, :age, :awesome
-
#
-
# def attributes=(hash)
-
# hash.each do |key, value|
-
# send("#{key}=", value)
-
# end
-
# end
-
#
-
# def attributes
-
# instance_values
-
# end
-
# end
-
#
-
# json = { name: 'bob', age: 22, awesome:true }.to_json
-
# person = Person.new
-
# person.from_json(json) # => #<Person:0x007fec5e7a0088 @age=22, @awesome=true, @name="bob">
-
# person.name # => "bob"
-
# person.age # => 22
-
# person.awesome # => true
-
#
-
# The default value for +include_root+ is +false+. You can change it to
-
# +true+ if the given JSON string includes a single root node.
-
#
-
# json = { person: { name: 'bob', age: 22, awesome:true } }.to_json
-
# person = Person.new
-
# person.from_json(json) # => #<Person:0x007fec5e7a0088 @age=22, @awesome=true, @name="bob">
-
# person.name # => "bob"
-
# person.age # => 22
-
# person.awesome # => true
-
2
def from_json(json, include_root=include_root_in_json)
-
hash = ActiveSupport::JSON.decode(json)
-
hash = hash.values.first if include_root
-
self.attributes = hash
-
self
-
end
-
end
-
end
-
end
-
2
require 'active_support/core_ext/module/attribute_accessors'
-
2
require 'active_support/core_ext/array/conversions'
-
2
require 'active_support/core_ext/hash/conversions'
-
2
require 'active_support/core_ext/hash/slice'
-
2
require 'active_support/core_ext/time/acts_like'
-
-
2
module ActiveModel
-
2
module Serializers
-
# == Active Model XML Serializer
-
2
module Xml
-
2
extend ActiveSupport::Concern
-
2
include ActiveModel::Serialization
-
-
2
included do
-
2
extend ActiveModel::Naming
-
end
-
-
2
class Serializer #:nodoc:
-
2
class Attribute #:nodoc:
-
2
attr_reader :name, :value, :type
-
-
2
def initialize(name, serializable, value)
-
@name, @serializable = name, serializable
-
-
if value.acts_like?(:time) && value.respond_to?(:in_time_zone)
-
value = value.in_time_zone
-
end
-
-
@value = value
-
@type = compute_type
-
end
-
-
2
def decorations
-
decorations = {}
-
decorations[:encoding] = 'base64' if type == :binary
-
decorations[:type] = (type == :string) ? nil : type
-
decorations[:nil] = true if value.nil?
-
decorations
-
end
-
-
2
protected
-
-
2
def compute_type
-
return if value.nil?
-
type = ActiveSupport::XmlMini::TYPE_NAMES[value.class.name]
-
type ||= :string if value.respond_to?(:to_str)
-
type ||= :yaml
-
type
-
end
-
end
-
-
2
class MethodAttribute < Attribute #:nodoc:
-
end
-
-
2
attr_reader :options
-
-
2
def initialize(serializable, options = nil)
-
@serializable = serializable
-
@options = options ? options.dup : {}
-
end
-
-
2
def serializable_hash
-
@serializable.serializable_hash(@options.except(:include))
-
end
-
-
2
def serializable_collection
-
methods = Array(options[:methods]).map(&:to_s)
-
serializable_hash.map do |name, value|
-
name = name.to_s
-
if methods.include?(name)
-
self.class::MethodAttribute.new(name, @serializable, value)
-
else
-
self.class::Attribute.new(name, @serializable, value)
-
end
-
end
-
end
-
-
2
def serialize
-
require 'builder' unless defined? ::Builder
-
-
options[:indent] ||= 2
-
options[:builder] ||= ::Builder::XmlMarkup.new(indent: options[:indent])
-
-
@builder = options[:builder]
-
@builder.instruct! unless options[:skip_instruct]
-
-
root = (options[:root] || @serializable.class.model_name.element).to_s
-
root = ActiveSupport::XmlMini.rename_key(root, options)
-
-
args = [root]
-
args << { xmlns: options[:namespace] } if options[:namespace]
-
args << { type: options[:type] } if options[:type] && !options[:skip_types]
-
-
@builder.tag!(*args) do
-
add_attributes_and_methods
-
add_includes
-
add_extra_behavior
-
add_procs
-
yield @builder if block_given?
-
end
-
end
-
-
2
private
-
-
2
def add_extra_behavior
-
end
-
-
2
def add_attributes_and_methods
-
serializable_collection.each do |attribute|
-
key = ActiveSupport::XmlMini.rename_key(attribute.name, options)
-
ActiveSupport::XmlMini.to_tag(key, attribute.value,
-
options.merge(attribute.decorations))
-
end
-
end
-
-
2
def add_includes
-
@serializable.send(:serializable_add_includes, options) do |association, records, opts|
-
add_associations(association, records, opts)
-
end
-
end
-
-
# TODO: This can likely be cleaned up to simple use ActiveSupport::XmlMini.to_tag as well.
-
2
def add_associations(association, records, opts)
-
merged_options = opts.merge(options.slice(:builder, :indent))
-
merged_options[:skip_instruct] = true
-
-
[:skip_types, :dasherize, :camelize].each do |key|
-
merged_options[key] = options[key] if merged_options[key].nil? && !options[key].nil?
-
end
-
-
if records.respond_to?(:to_ary)
-
records = records.to_ary
-
-
tag = ActiveSupport::XmlMini.rename_key(association.to_s, options)
-
type = options[:skip_types] ? { } : { type: "array" }
-
association_name = association.to_s.singularize
-
merged_options[:root] = association_name
-
-
if records.empty?
-
@builder.tag!(tag, type)
-
else
-
@builder.tag!(tag, type) do
-
records.each do |record|
-
if options[:skip_types]
-
record_type = {}
-
else
-
record_class = (record.class.to_s.underscore == association_name) ? nil : record.class.name
-
record_type = { type: record_class }
-
end
-
-
record.to_xml merged_options.merge(record_type)
-
end
-
end
-
end
-
else
-
merged_options[:root] = association.to_s
-
-
unless records.class.to_s.underscore == association.to_s
-
merged_options[:type] = records.class.name
-
end
-
-
records.to_xml merged_options
-
end
-
end
-
-
2
def add_procs
-
if procs = options.delete(:procs)
-
Array(procs).each do |proc|
-
if proc.arity == 1
-
proc.call(options)
-
else
-
proc.call(options, @serializable)
-
end
-
end
-
end
-
end
-
end
-
-
# Returns XML representing the model. Configuration can be
-
# passed through +options+.
-
#
-
# Without any +options+, the returned XML string will include all the
-
# model's attributes.
-
#
-
# user = User.find(1)
-
# user.to_xml
-
#
-
# <?xml version="1.0" encoding="UTF-8"?>
-
# <user>
-
# <id type="integer">1</id>
-
# <name>David</name>
-
# <age type="integer">16</age>
-
# <created-at type="dateTime">2011-01-30T22:29:23Z</created-at>
-
# </user>
-
#
-
# The <tt>:only</tt> and <tt>:except</tt> options can be used to limit the
-
# attributes included, and work similar to the +attributes+ method.
-
#
-
# To include the result of some method calls on the model use <tt>:methods</tt>.
-
#
-
# To include associations use <tt>:include</tt>.
-
#
-
# For further documentation, see <tt>ActiveRecord::Serialization#to_xml</tt>
-
2
def to_xml(options = {}, &block)
-
Serializer.new(self, options).serialize(&block)
-
end
-
-
# Sets the model +attributes+ from an XML string. Returns +self+.
-
#
-
# class Person
-
# include ActiveModel::Serializers::Xml
-
#
-
# attr_accessor :name, :age, :awesome
-
#
-
# def attributes=(hash)
-
# hash.each do |key, value|
-
# instance_variable_set("@#{key}", value)
-
# end
-
# end
-
#
-
# def attributes
-
# instance_values
-
# end
-
# end
-
#
-
# xml = { name: 'bob', age: 22, awesome:true }.to_xml
-
# person = Person.new
-
# person.from_xml(xml) # => #<Person:0x007fec5e3b3c40 @age=22, @awesome=true, @name="bob">
-
# person.name # => "bob"
-
# person.age # => 22
-
# person.awesome # => true
-
2
def from_xml(xml)
-
self.attributes = Hash.from_xml(xml).values.first
-
self
-
end
-
end
-
end
-
end
-
2
module ActiveModel
-
-
# == Active \Model \Translation
-
#
-
# Provides integration between your object and the Rails internationalization
-
# (i18n) framework.
-
#
-
# A minimal implementation could be:
-
#
-
# class TranslatedPerson
-
# extend ActiveModel::Translation
-
# end
-
#
-
# TranslatedPerson.human_attribute_name('my_attribute')
-
# # => "My attribute"
-
#
-
# This also provides the required class methods for hooking into the
-
# Rails internationalization API, including being able to define a
-
# class based +i18n_scope+ and +lookup_ancestors+ to find translations in
-
# parent classes.
-
2
module Translation
-
2
include ActiveModel::Naming
-
-
# Returns the +i18n_scope+ for the class. Overwrite if you want custom lookup.
-
2
def i18n_scope
-
:activemodel
-
end
-
-
# When localizing a string, it goes through the lookup returned by this
-
# method, which is used in ActiveModel::Name#human,
-
# ActiveModel::Errors#full_messages and
-
# ActiveModel::Translation#human_attribute_name.
-
2
def lookup_ancestors
-
self.ancestors.select { |x| x.respond_to?(:model_name) }
-
end
-
-
# Transforms attribute names into a more human format, such as "First name"
-
# instead of "first_name".
-
#
-
# Person.human_attribute_name("first_name") # => "First name"
-
#
-
# Specify +options+ with additional translating options.
-
2
def human_attribute_name(attribute, options = {})
-
12
options = { count: 1 }.merge!(options)
-
12
parts = attribute.to_s.split(".")
-
12
attribute = parts.pop
-
12
namespace = parts.join("/") unless parts.empty?
-
12
attributes_scope = "#{self.i18n_scope}.attributes"
-
-
12
if namespace
-
defaults = lookup_ancestors.map do |klass|
-
:"#{attributes_scope}.#{klass.model_name.i18n_key}/#{namespace}.#{attribute}"
-
end
-
defaults << :"#{attributes_scope}.#{namespace}.#{attribute}"
-
else
-
12
defaults = lookup_ancestors.map do |klass|
-
12
:"#{attributes_scope}.#{klass.model_name.i18n_key}.#{attribute}"
-
end
-
end
-
-
12
defaults << :"attributes.#{attribute}"
-
12
defaults << options.delete(:default) if options[:default]
-
12
defaults << attribute.humanize
-
-
12
options[:default] = defaults
-
12
I18n.translate(defaults.shift, options)
-
end
-
end
-
end
-
2
require 'active_support/core_ext/array/extract_options'
-
2
require 'active_support/core_ext/hash/keys'
-
2
require 'active_support/core_ext/hash/except'
-
-
2
module ActiveModel
-
-
# == Active \Model \Validations
-
#
-
# Provides a full validation framework to your objects.
-
#
-
# A minimal implementation could be:
-
#
-
# class Person
-
# include ActiveModel::Validations
-
#
-
# attr_accessor :first_name, :last_name
-
#
-
# validates_each :first_name, :last_name do |record, attr, value|
-
# record.errors.add attr, 'starts with z.' if value.to_s[0] == ?z
-
# end
-
# end
-
#
-
# Which provides you with the full standard validation stack that you
-
# know from Active Record:
-
#
-
# person = Person.new
-
# person.valid? # => true
-
# person.invalid? # => false
-
#
-
# person.first_name = 'zoolander'
-
# person.valid? # => false
-
# person.invalid? # => true
-
# person.errors.messages # => {first_name:["starts with z."]}
-
#
-
# Note that <tt>ActiveModel::Validations</tt> automatically adds an +errors+
-
# method to your instances initialized with a new <tt>ActiveModel::Errors</tt>
-
# object, so there is no need for you to do this manually.
-
2
module Validations
-
2
extend ActiveSupport::Concern
-
-
2
included do
-
2
extend ActiveModel::Callbacks
-
2
extend ActiveModel::Translation
-
-
2
extend HelperMethods
-
2
include HelperMethods
-
-
2
attr_accessor :validation_context
-
2
define_callbacks :validate, scope: :name
-
-
2
class_attribute :_validators
-
24
self._validators = Hash.new { |h,k| h[k] = [] }
-
end
-
-
2
module ClassMethods
-
# Validates each attribute against a block.
-
#
-
# class Person
-
# include ActiveModel::Validations
-
#
-
# attr_accessor :first_name, :last_name
-
#
-
# validates_each :first_name, :last_name, allow_blank: true do |record, attr, value|
-
# record.errors.add attr, 'starts with z.' if value.to_s[0] == ?z
-
# end
-
# end
-
#
-
# Options:
-
# * <tt>:on</tt> - Specifies the contexts where this validation is active.
-
# You can pass a symbol or an array of symbols.
-
# (e.g. <tt>on: :create</tt> or <tt>on: :custom_validation_context</tt> or
-
# <tt>on: [:create, :custom_validation_context]</tt>)
-
# * <tt>:allow_nil</tt> - Skip validation if attribute is +nil+.
-
# * <tt>:allow_blank</tt> - Skip validation if attribute is blank.
-
# * <tt>:if</tt> - Specifies a method, proc or string to call to determine
-
# if the validation should occur (e.g. <tt>if: :allow_validation</tt>,
-
# or <tt>if: Proc.new { |user| user.signup_step > 2 }</tt>). The method,
-
# proc or string should return or evaluate to a +true+ or +false+ value.
-
# * <tt>:unless</tt> - Specifies a method, proc or string to call to
-
# determine if the validation should not occur (e.g. <tt>unless: :skip_validation</tt>,
-
# or <tt>unless: Proc.new { |user| user.signup_step <= 2 }</tt>). The
-
# method, proc or string should return or evaluate to a +true+ or +false+
-
# value.
-
2
def validates_each(*attr_names, &block)
-
validates_with BlockValidator, _merge_attributes(attr_names), &block
-
end
-
-
# Adds a validation method or block to the class. This is useful when
-
# overriding the +validate+ instance method becomes too unwieldy and
-
# you're looking for more descriptive declaration of your validations.
-
#
-
# This can be done with a symbol pointing to a method:
-
#
-
# class Comment
-
# include ActiveModel::Validations
-
#
-
# validate :must_be_friends
-
#
-
# def must_be_friends
-
# errors.add(:base, 'Must be friends to leave a comment') unless commenter.friend_of?(commentee)
-
# end
-
# end
-
#
-
# With a block which is passed with the current record to be validated:
-
#
-
# class Comment
-
# include ActiveModel::Validations
-
#
-
# validate do |comment|
-
# comment.must_be_friends
-
# end
-
#
-
# def must_be_friends
-
# errors.add(:base, 'Must be friends to leave a comment') unless commenter.friend_of?(commentee)
-
# end
-
# end
-
#
-
# Or with a block where self points to the current record to be validated:
-
#
-
# class Comment
-
# include ActiveModel::Validations
-
#
-
# validate do
-
# errors.add(:base, 'Must be friends to leave a comment') unless commenter.friend_of?(commentee)
-
# end
-
# end
-
#
-
# Options:
-
# * <tt>:on</tt> - Specifies the contexts where this validation is active.
-
# You can pass a symbol or an array of symbols.
-
# (e.g. <tt>on: :create</tt> or <tt>on: :custom_validation_context</tt> or
-
# <tt>on: [:create, :custom_validation_context]</tt>)
-
# * <tt>:if</tt> - Specifies a method, proc or string to call to determine
-
# if the validation should occur (e.g. <tt>if: :allow_validation</tt>,
-
# or <tt>if: Proc.new { |user| user.signup_step > 2 }</tt>). The method,
-
# proc or string should return or evaluate to a +true+ or +false+ value.
-
# * <tt>:unless</tt> - Specifies a method, proc or string to call to
-
# determine if the validation should not occur (e.g. <tt>unless: :skip_validation</tt>,
-
# or <tt>unless: Proc.new { |user| user.signup_step <= 2 }</tt>). The
-
# method, proc or string should return or evaluate to a +true+ or +false+
-
# value.
-
2
def validate(*args, &block)
-
99
options = args.extract_options!
-
99
if options.key?(:on)
-
options = options.dup
-
options[:if] = Array(options[:if])
-
options[:if].unshift lambda { |o|
-
Array(options[:on]).include?(o.validation_context)
-
}
-
end
-
99
args << options
-
99
set_callback(:validate, *args, &block)
-
end
-
-
# List all validators that are being used to validate the model using
-
# +validates_with+ method.
-
#
-
# class Person
-
# include ActiveModel::Validations
-
#
-
# validates_with MyValidator
-
# validates_with OtherValidator, on: :create
-
# validates_with StrictValidator, strict: true
-
# end
-
#
-
# Person.validators
-
# # => [
-
# # #<MyValidator:0x007fbff403e808 @options={}>,
-
# # #<OtherValidator:0x007fbff403d930 @options={on: :create}>,
-
# # #<StrictValidator:0x007fbff3204a30 @options={strict:true}>
-
# # ]
-
2
def validators
-
_validators.values.flatten.uniq
-
end
-
-
# Clears all of the validators and validations.
-
#
-
# Note that this will clear anything that is being used to validate
-
# the model for both the +validates_with+ and +validate+ methods.
-
# It clears the validators that are created with an invocation of
-
# +validates_with+ and the callbacks that are set by an invocation
-
# of +validate+.
-
#
-
# class Person
-
# include ActiveModel::Validations
-
#
-
# validates_with MyValidator
-
# validates_with OtherValidator, on: :create
-
# validates_with StrictValidator, strict: true
-
# validate :cannot_be_robot
-
#
-
# def cannot_be_robot
-
# errors.add(:base, 'A person cannot be a robot') if person_is_robot
-
# end
-
# end
-
#
-
# Person.validators
-
# # => [
-
# # #<MyValidator:0x007fbff403e808 @options={}>,
-
# # #<OtherValidator:0x007fbff403d930 @options={on: :create}>,
-
# # #<StrictValidator:0x007fbff3204a30 @options={strict:true}>
-
# # ]
-
#
-
# If one runs <tt>Person.clear_validators!</tt> and then checks to see what
-
# validators this class has, you would obtain:
-
#
-
# Person.validators # => []
-
#
-
# Also, the callback set by <tt>validate :cannot_be_robot</tt> will be erased
-
# so that:
-
#
-
# Person._validate_callbacks.empty? # => true
-
#
-
2
def clear_validators!
-
reset_callbacks(:validate)
-
_validators.clear
-
end
-
-
# List all validators that are being used to validate a specific attribute.
-
#
-
# class Person
-
# include ActiveModel::Validations
-
#
-
# attr_accessor :name , :age
-
#
-
# validates_presence_of :name
-
# validates_inclusion_of :age, in: 0..99
-
# end
-
#
-
# Person.validators_on(:name)
-
# # => [
-
# # #<ActiveModel::Validations::PresenceValidator:0x007fe604914e60 @attributes=[:name], @options={}>,
-
# # ]
-
2
def validators_on(*attributes)
-
attributes.flat_map do |attribute|
-
_validators[attribute.to_sym]
-
end
-
end
-
-
# Returns +true+ if +attribute+ is an attribute method, +false+ otherwise.
-
#
-
# class Person
-
# include ActiveModel::Validations
-
#
-
# attr_accessor :name
-
# end
-
#
-
# User.attribute_method?(:name) # => true
-
# User.attribute_method?(:age) # => false
-
2
def attribute_method?(attribute)
-
method_defined?(attribute)
-
end
-
-
# Copy validators on inheritance.
-
2
def inherited(base) #:nodoc:
-
13
dup = _validators.dup
-
13
base._validators = dup.each { |k, v| dup[k] = v.dup }
-
13
super
-
end
-
end
-
-
# Clean the +Errors+ object if instance is duped.
-
2
def initialize_dup(other) #:nodoc:
-
@errors = nil
-
super
-
end
-
-
# Returns the +Errors+ object that holds all information about attribute
-
# error messages.
-
#
-
# class Person
-
# include ActiveModel::Validations
-
#
-
# attr_accessor :name
-
# validates_presence_of :name
-
# end
-
#
-
# person = Person.new
-
# person.valid? # => false
-
# person.errors # => #<ActiveModel::Errors:0x007fe603816640 @messages={name:["can't be blank"]}>
-
2
def errors
-
875
@errors ||= Errors.new(self)
-
end
-
-
# Runs all the specified validations and returns +true+ if no errors were
-
# added otherwise +false+.
-
#
-
# class Person
-
# include ActiveModel::Validations
-
#
-
# attr_accessor :name
-
# validates_presence_of :name
-
# end
-
#
-
# person = Person.new
-
# person.name = ''
-
# person.valid? # => false
-
# person.name = 'david'
-
# person.valid? # => true
-
#
-
# Context can optionally be supplied to define which callbacks to test
-
# against (the context is defined on the validations using <tt>:on</tt>).
-
#
-
# class Person
-
# include ActiveModel::Validations
-
#
-
# attr_accessor :name
-
# validates_presence_of :name, on: :new
-
# end
-
#
-
# person = Person.new
-
# person.valid? # => true
-
# person.valid?(:new) # => false
-
2
def valid?(context = nil)
-
269
current_context, self.validation_context = validation_context, context
-
269
errors.clear
-
269
run_validations!
-
ensure
-
269
self.validation_context = current_context
-
end
-
-
# Performs the opposite of <tt>valid?</tt>. Returns +true+ if errors were
-
# added, +false+ otherwise.
-
#
-
# class Person
-
# include ActiveModel::Validations
-
#
-
# attr_accessor :name
-
# validates_presence_of :name
-
# end
-
#
-
# person = Person.new
-
# person.name = ''
-
# person.invalid? # => true
-
# person.name = 'david'
-
# person.invalid? # => false
-
#
-
# Context can optionally be supplied to define which callbacks to test
-
# against (the context is defined on the validations using <tt>:on</tt>).
-
#
-
# class Person
-
# include ActiveModel::Validations
-
#
-
# attr_accessor :name
-
# validates_presence_of :name, on: :new
-
# end
-
#
-
# person = Person.new
-
# person.invalid? # => false
-
# person.invalid?(:new) # => true
-
2
def invalid?(context = nil)
-
!valid?(context)
-
end
-
-
# Hook method defining how an attribute value should be retrieved. By default
-
# this is assumed to be an instance named after the attribute. Override this
-
# method in subclasses should you need to retrieve the value for a given
-
# attribute differently:
-
#
-
# class MyClass
-
# include ActiveModel::Validations
-
#
-
# def initialize(data = {})
-
# @data = data
-
# end
-
#
-
# def read_attribute_for_validation(key)
-
# @data[key]
-
# end
-
# end
-
2
alias :read_attribute_for_validation :send
-
-
2
protected
-
-
2
def run_validations! #:nodoc:
-
269
run_callbacks :validate
-
269
errors.empty?
-
end
-
end
-
end
-
-
28
Dir[File.dirname(__FILE__) + "/validations/*.rb"].each { |file| require file }
-
2
module ActiveModel
-
2
module Validations
-
# == Active Model Absence Validator
-
2
class AbsenceValidator < EachValidator #:nodoc:
-
2
def validate_each(record, attr_name, value)
-
record.errors.add(attr_name, :present, options) if value.present?
-
end
-
end
-
-
2
module HelperMethods
-
# Validates that the specified attributes are blank (as defined by
-
# Object#blank?). Happens by default on save.
-
#
-
# class Person < ActiveRecord::Base
-
# validates_absence_of :first_name
-
# end
-
#
-
# The first_name attribute must be in the object and it must be blank.
-
#
-
# Configuration options:
-
# * <tt>:message</tt> - A custom error message (default is: "must be blank").
-
#
-
# There is also a list of default options supported by every validator:
-
# +:if+, +:unless+, +:on+, +:allow_nil+, +:allow_blank+, and +:strict+.
-
# See <tt>ActiveModel::Validation#validates</tt> for more information
-
2
def validates_absence_of(*attr_names)
-
validates_with AbsenceValidator, _merge_attributes(attr_names)
-
end
-
end
-
end
-
end
-
2
module ActiveModel
-
-
2
module Validations
-
2
class AcceptanceValidator < EachValidator # :nodoc:
-
2
def initialize(options)
-
super({ allow_nil: true, accept: "1" }.merge!(options))
-
setup!(options[:class])
-
end
-
-
2
def validate_each(record, attribute, value)
-
unless value == options[:accept]
-
record.errors.add(attribute, :accepted, options.except(:accept, :allow_nil))
-
end
-
end
-
-
2
private
-
2
def setup!(klass)
-
attr_readers = attributes.reject { |name| klass.attribute_method?(name) }
-
attr_writers = attributes.reject { |name| klass.attribute_method?("#{name}=") }
-
klass.send(:attr_reader, *attr_readers)
-
klass.send(:attr_writer, *attr_writers)
-
end
-
end
-
-
2
module HelperMethods
-
# Encapsulates the pattern of wanting to validate the acceptance of a
-
# terms of service check box (or similar agreement).
-
#
-
# class Person < ActiveRecord::Base
-
# validates_acceptance_of :terms_of_service
-
# validates_acceptance_of :eula, message: 'must be abided'
-
# end
-
#
-
# If the database column does not exist, the +terms_of_service+ attribute
-
# is entirely virtual. This check is performed only if +terms_of_service+
-
# is not +nil+ and by default on save.
-
#
-
# Configuration options:
-
# * <tt>:message</tt> - A custom error message (default is: "must be
-
# accepted").
-
# * <tt>:accept</tt> - Specifies value that is considered accepted.
-
# The default value is a string "1", which makes it easy to relate to
-
# an HTML checkbox. This should be set to +true+ if you are validating
-
# a database column, since the attribute is typecast from "1" to +true+
-
# before validation.
-
#
-
# There is also a list of default options supported by every validator:
-
# +:if+, +:unless+, +:on+, +:allow_nil+, +:allow_blank+, and +:strict+.
-
# See <tt>ActiveModel::Validation#validates</tt> for more information.
-
2
def validates_acceptance_of(*attr_names)
-
validates_with AcceptanceValidator, _merge_attributes(attr_names)
-
end
-
end
-
end
-
end
-
2
module ActiveModel
-
2
module Validations
-
# == Active \Model \Validation \Callbacks
-
#
-
# Provides an interface for any class to have +before_validation+ and
-
# +after_validation+ callbacks.
-
#
-
# First, include ActiveModel::Validations::Callbacks from the class you are
-
# creating:
-
#
-
# class MyModel
-
# include ActiveModel::Validations::Callbacks
-
#
-
# before_validation :do_stuff_before_validation
-
# after_validation :do_stuff_after_validation
-
# end
-
#
-
# Like other <tt>before_*</tt> callbacks if +before_validation+ returns
-
# +false+ then <tt>valid?</tt> will not be called.
-
2
module Callbacks
-
2
extend ActiveSupport::Concern
-
-
2
included do
-
2
include ActiveSupport::Callbacks
-
2
define_callbacks :validation,
-
terminator: ->(_,result) { result == false },
-
skip_after_callbacks_if_terminated: true,
-
scope: [:kind, :name]
-
end
-
-
2
module ClassMethods
-
# Defines a callback that will get called right before validation
-
# happens.
-
#
-
# class Person
-
# include ActiveModel::Validations
-
# include ActiveModel::Validations::Callbacks
-
#
-
# attr_accessor :name
-
#
-
# validates_length_of :name, maximum: 6
-
#
-
# before_validation :remove_whitespaces
-
#
-
# private
-
#
-
# def remove_whitespaces
-
# name.strip!
-
# end
-
# end
-
#
-
# person = Person.new
-
# person.name = ' bob '
-
# person.valid? # => true
-
# person.name # => "bob"
-
2
def before_validation(*args, &block)
-
options = args.last
-
if options.is_a?(Hash) && options[:on]
-
options[:if] = Array(options[:if])
-
options[:on] = Array(options[:on])
-
options[:if].unshift lambda { |o|
-
options[:on].include? o.validation_context
-
}
-
end
-
set_callback(:validation, :before, *args, &block)
-
end
-
-
# Defines a callback that will get called right after validation
-
# happens.
-
#
-
# class Person
-
# include ActiveModel::Validations
-
# include ActiveModel::Validations::Callbacks
-
#
-
# attr_accessor :name, :status
-
#
-
# validates_presence_of :name
-
#
-
# after_validation :set_status
-
#
-
# private
-
#
-
# def set_status
-
# self.status = errors.empty?
-
# end
-
# end
-
#
-
# person = Person.new
-
# person.name = ''
-
# person.valid? # => false
-
# person.status # => false
-
# person.name = 'bob'
-
# person.valid? # => true
-
# person.status # => true
-
2
def after_validation(*args, &block)
-
options = args.extract_options!
-
options[:prepend] = true
-
options[:if] = Array(options[:if])
-
if options[:on]
-
options[:on] = Array(options[:on])
-
options[:if].unshift("#{options[:on]}.include? self.validation_context")
-
end
-
set_callback(:validation, :after, *(args << options), &block)
-
end
-
end
-
-
2
protected
-
-
# Overwrite run validations to include callbacks.
-
2
def run_validations! #:nodoc:
-
538
run_callbacks(:validation) { super }
-
end
-
end
-
end
-
end
-
2
require 'active_support/core_ext/range'
-
-
2
module ActiveModel
-
2
module Validations
-
2
module Clusivity #:nodoc:
-
2
ERROR_MESSAGE = "An object with the method #include? or a proc, lambda or symbol is required, " \
-
"and must be supplied as the :in (or :within) option of the configuration hash"
-
-
2
def check_validity!
-
unless delimiter.respond_to?(:include?) || delimiter.respond_to?(:call) || delimiter.respond_to?(:to_sym)
-
raise ArgumentError, ERROR_MESSAGE
-
end
-
end
-
-
2
private
-
-
2
def include?(record, value)
-
members = if delimiter.respond_to?(:call)
-
delimiter.call(record)
-
elsif delimiter.respond_to?(:to_sym)
-
record.send(delimiter)
-
else
-
delimiter
-
end
-
-
members.send(inclusion_method(members), value)
-
end
-
-
2
def delimiter
-
@delimiter ||= options[:in] || options[:within]
-
end
-
-
# In Ruby 1.9 <tt>Range#include?</tt> on non-number-or-time-ish ranges checks all
-
# possible values in the range for equality, which is slower but more accurate.
-
# <tt>Range#cover?</tt> uses the previous logic of comparing a value with the range
-
# endpoints, which is fast but is only accurate on Numeric, Time, or DateTime ranges.
-
2
def inclusion_method(enumerable)
-
if enumerable.is_a? Range
-
case enumerable.first
-
when Numeric, Time, DateTime
-
:cover?
-
else
-
:include?
-
end
-
else
-
:include?
-
end
-
end
-
end
-
end
-
end
-
2
module ActiveModel
-
-
2
module Validations
-
2
class ConfirmationValidator < EachValidator # :nodoc:
-
2
def initialize(options)
-
6
super
-
6
setup!(options[:class])
-
end
-
-
2
def validate_each(record, attribute, value)
-
193
if (confirmed = record.send("#{attribute}_confirmation")) && (value != confirmed)
-
human_attribute_name = record.class.human_attribute_name(attribute)
-
record.errors.add(:"#{attribute}_confirmation", :confirmation, options.merge(attribute: human_attribute_name))
-
end
-
end
-
-
2
private
-
2
def setup!(klass)
-
6
klass.send(:attr_reader, *attributes.map do |attribute|
-
6
:"#{attribute}_confirmation" unless klass.method_defined?(:"#{attribute}_confirmation")
-
end.compact)
-
-
6
klass.send(:attr_writer, *attributes.map do |attribute|
-
6
:"#{attribute}_confirmation" unless klass.method_defined?(:"#{attribute}_confirmation=")
-
end.compact)
-
end
-
end
-
-
2
module HelperMethods
-
# Encapsulates the pattern of wanting to validate a password or email
-
# address field with a confirmation.
-
#
-
# Model:
-
# class Person < ActiveRecord::Base
-
# validates_confirmation_of :user_name, :password
-
# validates_confirmation_of :email_address,
-
# message: 'should match confirmation'
-
# end
-
#
-
# View:
-
# <%= password_field "person", "password" %>
-
# <%= password_field "person", "password_confirmation" %>
-
#
-
# The added +password_confirmation+ attribute is virtual; it exists only
-
# as an in-memory attribute for validating the password. To achieve this,
-
# the validation adds accessors to the model for the confirmation
-
# attribute.
-
#
-
# NOTE: This check is performed only if +password_confirmation+ is not
-
# +nil+. To require confirmation, make sure to add a presence check for
-
# the confirmation attribute:
-
#
-
# validates_presence_of :password_confirmation, if: :password_changed?
-
#
-
# Configuration options:
-
# * <tt>:message</tt> - A custom error message (default is: "doesn't match
-
# confirmation").
-
#
-
# There is also a list of default options supported by every validator:
-
# +:if+, +:unless+, +:on+, +:allow_nil+, +:allow_blank+, and +:strict+.
-
# See <tt>ActiveModel::Validation#validates</tt> for more information
-
2
def validates_confirmation_of(*attr_names)
-
6
validates_with ConfirmationValidator, _merge_attributes(attr_names)
-
end
-
end
-
end
-
end
-
2
require "active_model/validations/clusivity"
-
-
2
module ActiveModel
-
-
2
module Validations
-
2
class ExclusionValidator < EachValidator # :nodoc:
-
2
include Clusivity
-
-
2
def validate_each(record, attribute, value)
-
if include?(record, value)
-
record.errors.add(attribute, :exclusion, options.except(:in, :within).merge!(value: value))
-
end
-
end
-
end
-
-
2
module HelperMethods
-
# Validates that the value of the specified attribute is not in a
-
# particular enumerable object.
-
#
-
# class Person < ActiveRecord::Base
-
# validates_exclusion_of :username, in: %w( admin superuser ), message: "You don't belong here"
-
# validates_exclusion_of :age, in: 30..60, message: 'This site is only for under 30 and over 60'
-
# validates_exclusion_of :format, in: %w( mov avi ), message: "extension %{value} is not allowed"
-
# validates_exclusion_of :password, in: ->(person) { [person.username, person.first_name] },
-
# message: 'should not be the same as your username or first name'
-
# validates_exclusion_of :karma, in: :reserved_karmas
-
# end
-
#
-
# Configuration options:
-
# * <tt>:in</tt> - An enumerable object of items that the value shouldn't
-
# be part of. This can be supplied as a proc, lambda or symbol which returns an
-
# enumerable. If the enumerable is a range the test is performed with
-
# * <tt>:within</tt> - A synonym(or alias) for <tt>:in</tt>
-
# <tt>Range#cover?</tt>, otherwise with <tt>include?</tt>.
-
# * <tt>:message</tt> - Specifies a custom error message (default is: "is
-
# reserved").
-
#
-
# There is also a list of default options supported by every validator:
-
# +:if+, +:unless+, +:on+, +:allow_nil+, +:allow_blank+, and +:strict+.
-
# See <tt>ActiveModel::Validation#validates</tt> for more information
-
2
def validates_exclusion_of(*attr_names)
-
validates_with ExclusionValidator, _merge_attributes(attr_names)
-
end
-
end
-
end
-
end
-
2
module ActiveModel
-
-
2
module Validations
-
2
class FormatValidator < EachValidator # :nodoc:
-
2
def validate_each(record, attribute, value)
-
195
if options[:with]
-
195
regexp = option_call(record, :with)
-
195
record_error(record, attribute, :with, value) if value.to_s !~ regexp
-
elsif options[:without]
-
regexp = option_call(record, :without)
-
record_error(record, attribute, :without, value) if value.to_s =~ regexp
-
end
-
end
-
-
2
def check_validity!
-
6
unless options.include?(:with) ^ options.include?(:without) # ^ == xor, or "exclusive or"
-
raise ArgumentError, "Either :with or :without must be supplied (but not both)"
-
end
-
-
6
check_options_validity :with
-
6
check_options_validity :without
-
end
-
-
2
private
-
-
2
def option_call(record, name)
-
195
option = options[name]
-
195
option.respond_to?(:call) ? option.call(record) : option
-
end
-
-
2
def record_error(record, attribute, name, value)
-
2
record.errors.add(attribute, :invalid, options.except(name).merge!(value: value))
-
end
-
-
2
def check_options_validity(name)
-
12
if option = options[name]
-
6
if option.is_a?(Regexp)
-
6
if options[:multiline] != true && regexp_using_multiline_anchors?(option)
-
raise ArgumentError, "The provided regular expression is using multiline anchors (^ or $), " \
-
"which may present a security risk. Did you mean to use \\A and \\z, or forgot to add the " \
-
":multiline => true option?"
-
end
-
elsif !option.respond_to?(:call)
-
raise ArgumentError, "A regular expression or a proc or lambda must be supplied as :#{name}"
-
end
-
end
-
end
-
-
2
def regexp_using_multiline_anchors?(regexp)
-
6
source = regexp.source
-
6
source.start_with?("^") || (source.end_with?("$") && !source.end_with?("\\$"))
-
end
-
end
-
-
2
module HelperMethods
-
# Validates whether the value of the specified attribute is of the correct
-
# form, going by the regular expression provided.You can require that the
-
# attribute matches the regular expression:
-
#
-
# class Person < ActiveRecord::Base
-
# validates_format_of :email, with: /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i, on: :create
-
# end
-
#
-
# Alternatively, you can require that the specified attribute does _not_
-
# match the regular expression:
-
#
-
# class Person < ActiveRecord::Base
-
# validates_format_of :email, without: /NOSPAM/
-
# end
-
#
-
# You can also provide a proc or lambda which will determine the regular
-
# expression that will be used to validate the attribute.
-
#
-
# class Person < ActiveRecord::Base
-
# # Admin can have number as a first letter in their screen name
-
# validates_format_of :screen_name,
-
# with: ->(person) { person.admin? ? /\A[a-z0-9][a-z0-9_\-]*\z/i : /\A[a-z][a-z0-9_\-]*\z/i }
-
# end
-
#
-
# Note: use <tt>\A</tt> and <tt>\Z</tt> to match the start and end of the
-
# string, <tt>^</tt> and <tt>$</tt> match the start/end of a line.
-
#
-
# Due to frequent misuse of <tt>^</tt> and <tt>$</tt>, you need to pass
-
# the <tt>multiline: true</tt> option in case you use any of these two
-
# anchors in the provided regular expression. In most cases, you should be
-
# using <tt>\A</tt> and <tt>\z</tt>.
-
#
-
# You must pass either <tt>:with</tt> or <tt>:without</tt> as an option.
-
# In addition, both must be a regular expression or a proc or lambda, or
-
# else an exception will be raised.
-
#
-
# Configuration options:
-
# * <tt>:message</tt> - A custom error message (default is: "is invalid").
-
# * <tt>:with</tt> - Regular expression that if the attribute matches will
-
# result in a successful validation. This can be provided as a proc or
-
# lambda returning regular expression which will be called at runtime.
-
# * <tt>:without</tt> - Regular expression that if the attribute does not
-
# match will result in a successful validation. This can be provided as
-
# a proc or lambda returning regular expression which will be called at
-
# runtime.
-
# * <tt>:multiline</tt> - Set to true if your regular expression contains
-
# anchors that match the beginning or end of lines as opposed to the
-
# beginning or end of the string. These anchors are <tt>^</tt> and <tt>$</tt>.
-
#
-
# There is also a list of default options supported by every validator:
-
# +:if+, +:unless+, +:on+, +:allow_nil+, +:allow_blank+, and +:strict+.
-
# See <tt>ActiveModel::Validation#validates</tt> for more information
-
2
def validates_format_of(*attr_names)
-
validates_with FormatValidator, _merge_attributes(attr_names)
-
end
-
end
-
end
-
end
-
2
require "active_model/validations/clusivity"
-
-
2
module ActiveModel
-
-
2
module Validations
-
2
class InclusionValidator < EachValidator # :nodoc:
-
2
include Clusivity
-
-
2
def validate_each(record, attribute, value)
-
unless include?(record, value)
-
record.errors.add(attribute, :inclusion, options.except(:in, :within).merge!(value: value))
-
end
-
end
-
end
-
-
2
module HelperMethods
-
# Validates whether the value of the specified attribute is available in a
-
# particular enumerable object.
-
#
-
# class Person < ActiveRecord::Base
-
# validates_inclusion_of :gender, in: %w( m f )
-
# validates_inclusion_of :age, in: 0..99
-
# validates_inclusion_of :format, in: %w( jpg gif png ), message: "extension %{value} is not included in the list"
-
# validates_inclusion_of :states, in: ->(person) { STATES[person.country] }
-
# validates_inclusion_of :karma, in: :available_karmas
-
# end
-
#
-
# Configuration options:
-
# * <tt>:in</tt> - An enumerable object of available items. This can be
-
# supplied as a proc, lambda or symbol which returns an enumerable. If the
-
# enumerable is a numerical range the test is performed with <tt>Range#cover?</tt>,
-
# otherwise with <tt>include?</tt>. When using a proc or lambda the instance
-
# under validation is passed as an argument.
-
# * <tt>:within</tt> - A synonym(or alias) for <tt>:in</tt>
-
# * <tt>:message</tt> - Specifies a custom error message (default is: "is
-
# not included in the list").
-
#
-
# There is also a list of default options supported by every validator:
-
# +:if+, +:unless+, +:on+, +:allow_nil+, +:allow_blank+, and +:strict+.
-
# See <tt>ActiveModel::Validation#validates</tt> for more information
-
2
def validates_inclusion_of(*attr_names)
-
validates_with InclusionValidator, _merge_attributes(attr_names)
-
end
-
end
-
end
-
end
-
2
module ActiveModel
-
-
# == Active \Model Length Validator
-
2
module Validations
-
2
class LengthValidator < EachValidator # :nodoc:
-
2
MESSAGES = { is: :wrong_length, minimum: :too_short, maximum: :too_long }.freeze
-
2
CHECKS = { is: :==, minimum: :>=, maximum: :<= }.freeze
-
-
2
RESERVED_OPTIONS = [:minimum, :maximum, :within, :is, :tokenizer, :too_short, :too_long]
-
-
2
def initialize(options)
-
18
if range = (options.delete(:in) || options.delete(:within))
-
raise ArgumentError, ":in and :within must be a Range" unless range.is_a?(Range)
-
options[:minimum], options[:maximum] = range.min, range.max
-
end
-
-
18
if options[:allow_blank] == false && options[:minimum].nil? && options[:is].nil?
-
options[:minimum] = 1
-
end
-
-
18
super
-
end
-
-
2
def check_validity!
-
18
keys = CHECKS.keys & options.keys
-
-
18
if keys.empty?
-
raise ArgumentError, 'Range unspecified. Specify the :in, :within, :maximum, :minimum, or :is option.'
-
end
-
-
18
keys.each do |key|
-
18
value = options[key]
-
-
18
unless (value.is_a?(Integer) && value >= 0) || value == Float::INFINITY
-
raise ArgumentError, ":#{key} must be a nonnegative Integer or Infinity"
-
end
-
end
-
end
-
-
2
def validate_each(record, attribute, value)
-
585
value = tokenize(value)
-
585
value_length = value.respond_to?(:length) ? value.length : value.to_s.length
-
585
errors_options = options.except(*RESERVED_OPTIONS)
-
-
585
CHECKS.each do |key, validity_check|
-
1755
next unless check_value = options[key]
-
-
585
if !value.nil? || skip_nil_check?(key)
-
583
next if value_length.send(validity_check, check_value)
-
end
-
-
2
errors_options[:count] = check_value
-
-
2
default_message = options[MESSAGES[key]]
-
2
errors_options[:message] ||= default_message if default_message
-
-
2
record.errors.add(attribute, MESSAGES[key], errors_options)
-
end
-
end
-
-
2
private
-
-
2
def tokenize(value)
-
if options[:tokenizer] && value.kind_of?(String)
-
options[:tokenizer].call(value)
-
585
end || value
-
end
-
-
2
def skip_nil_check?(key)
-
2
key == :maximum && options[:allow_nil].nil? && options[:allow_blank].nil?
-
end
-
end
-
-
2
module HelperMethods
-
-
# Validates that the specified attribute matches the length restrictions
-
# supplied. Only one option can be used at a time:
-
#
-
# class Person < ActiveRecord::Base
-
# validates_length_of :first_name, maximum: 30
-
# validates_length_of :last_name, maximum: 30, message: "less than 30 if you don't mind"
-
# validates_length_of :fax, in: 7..32, allow_nil: true
-
# validates_length_of :phone, in: 7..32, allow_blank: true
-
# validates_length_of :user_name, within: 6..20, too_long: 'pick a shorter name', too_short: 'pick a longer name'
-
# validates_length_of :zip_code, minimum: 5, too_short: 'please enter at least 5 characters'
-
# validates_length_of :smurf_leader, is: 4, message: "papa is spelled with 4 characters... don't play me."
-
# validates_length_of :essay, minimum: 100, too_short: 'Your essay must be at least 100 words.',
-
# tokenizer: ->(str) { str.scan(/\w+/) }
-
# end
-
#
-
# Configuration options:
-
# * <tt>:minimum</tt> - The minimum size of the attribute.
-
# * <tt>:maximum</tt> - The maximum size of the attribute. Allows +nil+ by
-
# default if not used with :minimum.
-
# * <tt>:is</tt> - The exact size of the attribute.
-
# * <tt>:within</tt> - A range specifying the minimum and maximum size of
-
# the attribute.
-
# * <tt>:in</tt> - A synonym (or alias) for <tt>:within</tt>.
-
# * <tt>:allow_nil</tt> - Attribute may be +nil+; skip validation.
-
# * <tt>:allow_blank</tt> - Attribute may be blank; skip validation.
-
# * <tt>:too_long</tt> - The error message if the attribute goes over the
-
# maximum (default is: "is too long (maximum is %{count} characters)").
-
# * <tt>:too_short</tt> - The error message if the attribute goes under the
-
# minimum (default is: "is too short (min is %{count} characters)").
-
# * <tt>:wrong_length</tt> - The error message if using the <tt>:is</tt>
-
# method and the attribute is the wrong size (default is: "is the wrong
-
# length (should be %{count} characters)").
-
# * <tt>:message</tt> - The error message to use for a <tt>:minimum</tt>,
-
# <tt>:maximum</tt>, or <tt>:is</tt> violation. An alias of the appropriate
-
# <tt>too_long</tt>/<tt>too_short</tt>/<tt>wrong_length</tt> message.
-
# * <tt>:tokenizer</tt> - Specifies how to split up the attribute string.
-
# (e.g. <tt>tokenizer: ->(str) { str.scan(/\w+/) }</tt> to count words
-
# as in above example). Defaults to <tt>->(value) { value.split(//) }</tt>
-
# which counts individual characters.
-
#
-
# There is also a list of default options supported by every validator:
-
# +:if+, +:unless+, +:on+ and +:strict+.
-
# See <tt>ActiveModel::Validation#validates</tt> for more information
-
2
def validates_length_of(*attr_names)
-
validates_with LengthValidator, _merge_attributes(attr_names)
-
end
-
-
2
alias_method :validates_size_of, :validates_length_of
-
end
-
end
-
end
-
2
module ActiveModel
-
-
2
module Validations
-
2
class NumericalityValidator < EachValidator # :nodoc:
-
2
CHECKS = { greater_than: :>, greater_than_or_equal_to: :>=,
-
equal_to: :==, less_than: :<, less_than_or_equal_to: :<=,
-
odd: :odd?, even: :even?, other_than: :!= }.freeze
-
-
2
RESERVED_OPTIONS = CHECKS.keys + [:only_integer]
-
-
2
def check_validity!
-
keys = CHECKS.keys - [:odd, :even]
-
options.slice(*keys).each do |option, value|
-
unless value.is_a?(Numeric) || value.is_a?(Proc) || value.is_a?(Symbol)
-
raise ArgumentError, ":#{option} must be a number, a symbol or a proc"
-
end
-
end
-
end
-
-
2
def validate_each(record, attr_name, value)
-
before_type_cast = :"#{attr_name}_before_type_cast"
-
-
raw_value = record.send(before_type_cast) if record.respond_to?(before_type_cast)
-
raw_value ||= value
-
-
return if options[:allow_nil] && raw_value.nil?
-
-
unless value = parse_raw_value_as_a_number(raw_value)
-
record.errors.add(attr_name, :not_a_number, filtered_options(raw_value))
-
return
-
end
-
-
if options[:only_integer]
-
unless value = parse_raw_value_as_an_integer(raw_value)
-
record.errors.add(attr_name, :not_an_integer, filtered_options(raw_value))
-
return
-
end
-
end
-
-
options.slice(*CHECKS.keys).each do |option, option_value|
-
case option
-
when :odd, :even
-
unless value.to_i.send(CHECKS[option])
-
record.errors.add(attr_name, option, filtered_options(value))
-
end
-
else
-
case option_value
-
when Proc
-
option_value = option_value.call(record)
-
when Symbol
-
option_value = record.send(option_value)
-
end
-
-
unless value.send(CHECKS[option], option_value)
-
record.errors.add(attr_name, option, filtered_options(value).merge!(count: option_value))
-
end
-
end
-
end
-
end
-
-
2
protected
-
-
2
def parse_raw_value_as_a_number(raw_value)
-
Kernel.Float(raw_value) if raw_value !~ /\A0[xX]/
-
rescue ArgumentError, TypeError
-
nil
-
end
-
-
2
def parse_raw_value_as_an_integer(raw_value)
-
raw_value.to_i if raw_value.to_s =~ /\A[+-]?\d+\Z/
-
end
-
-
2
def filtered_options(value)
-
filtered = options.except(*RESERVED_OPTIONS)
-
filtered[:value] = value
-
filtered
-
end
-
end
-
-
2
module HelperMethods
-
# Validates whether the value of the specified attribute is numeric by
-
# trying to convert it to a float with Kernel.Float (if <tt>only_integer</tt>
-
# is +false+) or applying it to the regular expression <tt>/\A[\+\-]?\d+\Z/</tt>
-
# (if <tt>only_integer</tt> is set to +true+).
-
#
-
# class Person < ActiveRecord::Base
-
# validates_numericality_of :value, on: :create
-
# end
-
#
-
# Configuration options:
-
# * <tt>:message</tt> - A custom error message (default is: "is not a number").
-
# * <tt>:only_integer</tt> - Specifies whether the value has to be an
-
# integer, e.g. an integral value (default is +false+).
-
# * <tt>:allow_nil</tt> - Skip validation if attribute is +nil+ (default is
-
# +false+). Notice that for fixnum and float columns empty strings are
-
# converted to +nil+.
-
# * <tt>:greater_than</tt> - Specifies the value must be greater than the
-
# supplied value.
-
# * <tt>:greater_than_or_equal_to</tt> - Specifies the value must be
-
# greater than or equal the supplied value.
-
# * <tt>:equal_to</tt> - Specifies the value must be equal to the supplied
-
# value.
-
# * <tt>:less_than</tt> - Specifies the value must be less than the
-
# supplied value.
-
# * <tt>:less_than_or_equal_to</tt> - Specifies the value must be less
-
# than or equal the supplied value.
-
# * <tt>:other_than</tt> - Specifies the value must be other than the
-
# supplied value.
-
# * <tt>:odd</tt> - Specifies the value must be an odd number.
-
# * <tt>:even</tt> - Specifies the value must be an even number.
-
#
-
# There is also a list of default options supported by every validator:
-
# +:if+, +:unless+, +:on+, +:allow_nil+, +:allow_blank+, and +:strict+ .
-
# See <tt>ActiveModel::Validation#validates</tt> for more information
-
#
-
# The following checks can also be supplied with a proc or a symbol which
-
# corresponds to a method:
-
#
-
# * <tt>:greater_than</tt>
-
# * <tt>:greater_than_or_equal_to</tt>
-
# * <tt>:equal_to</tt>
-
# * <tt>:less_than</tt>
-
# * <tt>:less_than_or_equal_to</tt>
-
#
-
# For example:
-
#
-
# class Person < ActiveRecord::Base
-
# validates_numericality_of :width, less_than: ->(person) { person.height }
-
# validates_numericality_of :width, greater_than: :minimum_weight
-
# end
-
2
def validates_numericality_of(*attr_names)
-
validates_with NumericalityValidator, _merge_attributes(attr_names)
-
end
-
end
-
end
-
end
-
-
2
module ActiveModel
-
-
2
module Validations
-
2
class PresenceValidator < EachValidator # :nodoc:
-
2
def validate_each(record, attr_name, value)
-
585
record.errors.add(attr_name, :blank, options) if value.blank?
-
end
-
end
-
-
2
module HelperMethods
-
# Validates that the specified attributes are not blank (as defined by
-
# Object#blank?). Happens by default on save.
-
#
-
# class Person < ActiveRecord::Base
-
# validates_presence_of :first_name
-
# end
-
#
-
# The first_name attribute must be in the object and it cannot be blank.
-
#
-
# If you want to validate the presence of a boolean field (where the real
-
# values are +true+ and +false+), you will want to use
-
# <tt>validates_inclusion_of :field_name, in: [true, false]</tt>.
-
#
-
# This is due to the way Object#blank? handles boolean values:
-
# <tt>false.blank? # => true</tt>.
-
#
-
# Configuration options:
-
# * <tt>:message</tt> - A custom error message (default is: "can't be blank").
-
#
-
# There is also a list of default options supported by every validator:
-
# +:if+, +:unless+, +:on+, +:allow_nil+, +:allow_blank+, and +:strict+.
-
# See <tt>ActiveModel::Validation#validates</tt> for more information
-
2
def validates_presence_of(*attr_names)
-
validates_with PresenceValidator, _merge_attributes(attr_names)
-
end
-
end
-
end
-
end
-
2
require 'active_support/core_ext/hash/slice'
-
-
2
module ActiveModel
-
2
module Validations
-
2
module ClassMethods
-
# This method is a shortcut to all default validators and any custom
-
# validator classes ending in 'Validator'. Note that Rails default
-
# validators can be overridden inside specific classes by creating
-
# custom validator classes in their place such as PresenceValidator.
-
#
-
# Examples of using the default rails validators:
-
#
-
# validates :terms, acceptance: true
-
# validates :password, confirmation: true
-
# validates :username, exclusion: { in: %w(admin superuser) }
-
# validates :email, format: { with: /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i, on: :create }
-
# validates :age, inclusion: { in: 0..9 }
-
# validates :first_name, length: { maximum: 30 }
-
# validates :age, numericality: true
-
# validates :username, presence: true
-
# validates :username, uniqueness: true
-
#
-
# The power of the +validates+ method comes when using custom validators
-
# and default validators in one call for a given attribute.
-
#
-
# class EmailValidator < ActiveModel::EachValidator
-
# def validate_each(record, attribute, value)
-
# record.errors.add attribute, (options[:message] || "is not an email") unless
-
# value =~ /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i
-
# end
-
# end
-
#
-
# class Person
-
# include ActiveModel::Validations
-
# attr_accessor :name, :email
-
#
-
# validates :name, presence: true, uniqueness: true, length: { maximum: 100 }
-
# validates :email, presence: true, email: true
-
# end
-
#
-
# Validator classes may also exist within the class being validated
-
# allowing custom modules of validators to be included as needed.
-
#
-
# class Film
-
# include ActiveModel::Validations
-
#
-
# class TitleValidator < ActiveModel::EachValidator
-
# def validate_each(record, attribute, value)
-
# record.errors.add attribute, "must start with 'the'" unless value =~ /\Athe/i
-
# end
-
# end
-
#
-
# validates :name, title: true
-
# end
-
#
-
# Additionally validator classes may be in another namespace and still
-
# used within any class.
-
#
-
# validates :name, :'film/title' => true
-
#
-
# The validators hash can also handle regular expressions, ranges, arrays
-
# and strings in shortcut form.
-
#
-
# validates :email, format: /@/
-
# validates :gender, inclusion: %w(male female)
-
# validates :password, length: 6..20
-
#
-
# When using shortcut form, ranges and arrays are passed to your
-
# validator's initializer as <tt>options[:in]</tt> while other types
-
# including regular expressions and strings are passed as <tt>options[:with]</tt>.
-
#
-
# There is also a list of options that could be used along with validators:
-
#
-
# * <tt>:on</tt> - Specifies when this validation is active. Runs in all
-
# validation contexts by default (+nil+), other options are <tt>:create</tt>
-
# and <tt>:update</tt>.
-
# * <tt>:if</tt> - Specifies a method, proc or string to call to determine
-
# if the validation should occur (e.g. <tt>if: :allow_validation</tt>,
-
# or <tt>if: Proc.new { |user| user.signup_step > 2 }</tt>). The method,
-
# proc or string should return or evaluate to a +true+ or +false+ value.
-
# * <tt>:unless</tt> - Specifies a method, proc or string to call to determine
-
# if the validation should not occur (e.g. <tt>unless: :skip_validation</tt>,
-
# or <tt>unless: Proc.new { |user| user.signup_step <= 2 }</tt>). The
-
# method, proc or string should return or evaluate to a +true+ or
-
# +false+ value.
-
# * <tt>:allow_nil</tt> - Skip validation if the attribute is +nil+.
-
# * <tt>:allow_blank</tt> - Skip validation if the attribute is blank.
-
# * <tt>:strict</tt> - If the <tt>:strict</tt> option is set to true
-
# will raise ActiveModel::StrictValidationFailed instead of adding the error.
-
# <tt>:strict</tt> option can also be set to any other exception.
-
#
-
# Example:
-
#
-
# validates :password, presence: true, confirmation: true, if: :password_required?
-
# validates :token, uniqueness: true, strict: TokenGenerationException
-
#
-
#
-
# Finally, the options +:if+, +:unless+, +:on+, +:allow_blank+, +:allow_nil+, +:strict+
-
# and +:message+ can be given to one specific validator, as a hash:
-
#
-
# validates :password, presence: { if: :password_required?, message: 'is forgotten.' }, confirmation: true
-
2
def validates(*attributes)
-
18
defaults = attributes.extract_options!.dup
-
18
validations = defaults.slice!(*_validates_default_keys)
-
-
18
raise ArgumentError, "You need to supply at least one attribute" if attributes.empty?
-
18
raise ArgumentError, "You need to supply at least one validation" if validations.empty?
-
-
18
defaults[:attributes] = attributes
-
-
18
validations.each do |key, options|
-
48
next unless options
-
48
key = "#{key.to_s.camelize}Validator"
-
-
48
begin
-
48
validator = key.include?('::') ? key.constantize : const_get(key)
-
rescue NameError
-
raise ArgumentError, "Unknown validator: '#{key}'"
-
end
-
-
48
validates_with(validator, defaults.merge(_parse_validates_options(options)))
-
end
-
end
-
-
# This method is used to define validations that cannot be corrected by end
-
# users and are considered exceptional. So each validator defined with bang
-
# or <tt>:strict</tt> option set to <tt>true</tt> will always raise
-
# <tt>ActiveModel::StrictValidationFailed</tt> instead of adding error
-
# when validation fails. See <tt>validates</tt> for more information about
-
# the validation itself.
-
#
-
# class Person
-
# include ActiveModel::Validations
-
#
-
# attr_accessor :name
-
# validates! :name, presence: true
-
# end
-
#
-
# person = Person.new
-
# person.name = ''
-
# person.valid?
-
# # => ActiveModel::StrictValidationFailed: Name can't be blank
-
2
def validates!(*attributes)
-
options = attributes.extract_options!
-
options[:strict] = true
-
validates(*(attributes << options))
-
end
-
-
2
protected
-
-
# When creating custom validators, it might be useful to be able to specify
-
# additional default keys. This can be done by overwriting this method.
-
2
def _validates_default_keys # :nodoc:
-
18
[:if, :unless, :on, :allow_blank, :allow_nil , :strict]
-
end
-
-
2
def _parse_validates_options(options) # :nodoc:
-
48
case options
-
when TrueClass
-
24
{}
-
when Hash
-
24
options
-
when Range, Array
-
{ in: options }
-
else
-
{ with: options }
-
end
-
end
-
end
-
end
-
end
-
2
module ActiveModel
-
2
module Validations
-
2
module HelperMethods
-
2
private
-
2
def _merge_attributes(attr_names)
-
18
options = attr_names.extract_options!.symbolize_keys
-
18
attr_names.flatten!
-
18
options[:attributes] = attr_names
-
18
options
-
end
-
end
-
-
2
class WithValidator < EachValidator # :nodoc:
-
2
def validate_each(record, attr, val)
-
method_name = options[:with]
-
-
if record.method(method_name).arity == 0
-
record.send method_name
-
else
-
record.send method_name, attr
-
end
-
end
-
end
-
-
2
module ClassMethods
-
# Passes the record off to the class or classes specified and allows them
-
# to add errors based on more complex conditions.
-
#
-
# class Person
-
# include ActiveModel::Validations
-
# validates_with MyValidator
-
# end
-
#
-
# class MyValidator < ActiveModel::Validator
-
# def validate(record)
-
# if some_complex_logic
-
# record.errors.add :base, 'This record is invalid'
-
# end
-
# end
-
#
-
# private
-
# def some_complex_logic
-
# # ...
-
# end
-
# end
-
#
-
# You may also pass it multiple classes, like so:
-
#
-
# class Person
-
# include ActiveModel::Validations
-
# validates_with MyValidator, MyOtherValidator, on: :create
-
# end
-
#
-
# Configuration options:
-
# * <tt>:on</tt> - Specifies when this validation is active
-
# (<tt>:create</tt> or <tt>:update</tt>.
-
# * <tt>:if</tt> - Specifies a method, proc or string to call to determine
-
# if the validation should occur (e.g. <tt>if: :allow_validation</tt>,
-
# or <tt>if: Proc.new { |user| user.signup_step > 2 }</tt>).
-
# The method, proc or string should return or evaluate to a +true+ or
-
# +false+ value.
-
# * <tt>:unless</tt> - Specifies a method, proc or string to call to
-
# determine if the validation should not occur
-
# (e.g. <tt>unless: :skip_validation</tt>, or
-
# <tt>unless: Proc.new { |user| user.signup_step <= 2 }</tt>).
-
# The method, proc or string should return or evaluate to a +true+ or
-
# +false+ value.
-
# * <tt>:strict</tt> - Specifies whether validation should be strict.
-
# See <tt>ActiveModel::Validation#validates!</tt> for more information.
-
#
-
# If you pass any additional configuration options, they will be passed
-
# to the class and available as +options+:
-
#
-
# class Person
-
# include ActiveModel::Validations
-
# validates_with MyValidator, my_custom_key: 'my custom value'
-
# end
-
#
-
# class MyValidator < ActiveModel::Validator
-
# def validate(record)
-
# options[:my_custom_key] # => "my custom value"
-
# end
-
# end
-
2
def validates_with(*args, &block)
-
66
options = args.extract_options!
-
66
options[:class] = self
-
-
66
args.each do |klass|
-
66
validator = klass.new(options, &block)
-
-
66
if validator.respond_to?(:attributes) && !validator.attributes.empty?
-
66
validator.attributes.each do |attribute|
-
66
_validators[attribute.to_sym] << validator
-
end
-
else
-
_validators[nil] << validator
-
end
-
-
66
validate(validator, options)
-
end
-
end
-
end
-
-
# Passes the record off to the class or classes specified and allows them
-
# to add errors based on more complex conditions.
-
#
-
# class Person
-
# include ActiveModel::Validations
-
#
-
# validate :instance_validations
-
#
-
# def instance_validations
-
# validates_with MyValidator
-
# end
-
# end
-
#
-
# Please consult the class method documentation for more information on
-
# creating your own validator.
-
#
-
# You may also pass it multiple classes, like so:
-
#
-
# class Person
-
# include ActiveModel::Validations
-
#
-
# validate :instance_validations, on: :create
-
#
-
# def instance_validations
-
# validates_with MyValidator, MyOtherValidator
-
# end
-
# end
-
#
-
# Standard configuration options (<tt>:on</tt>, <tt>:if</tt> and
-
# <tt>:unless</tt>), which are available on the class version of
-
# +validates_with+, should instead be placed on the +validates+ method
-
# as these are applied and tested in the callback.
-
#
-
# If you pass any additional configuration options, they will be passed
-
# to the class and available as +options+, please refer to the
-
# class version of this method for more information.
-
2
def validates_with(*args, &block)
-
options = args.extract_options!
-
options[:class] = self.class
-
-
args.each do |klass|
-
validator = klass.new(options, &block)
-
validator.validate(self)
-
end
-
end
-
end
-
end
-
2
require "active_support/core_ext/module/anonymous"
-
-
2
module ActiveModel
-
-
# == Active \Model \Validator
-
#
-
# A simple base class that can be used along with
-
# ActiveModel::Validations::ClassMethods.validates_with
-
#
-
# class Person
-
# include ActiveModel::Validations
-
# validates_with MyValidator
-
# end
-
#
-
# class MyValidator < ActiveModel::Validator
-
# def validate(record)
-
# if some_complex_logic
-
# record.errors[:base] = "This record is invalid"
-
# end
-
# end
-
#
-
# private
-
# def some_complex_logic
-
# # ...
-
# end
-
# end
-
#
-
# Any class that inherits from ActiveModel::Validator must implement a method
-
# called +validate+ which accepts a +record+.
-
#
-
# class Person
-
# include ActiveModel::Validations
-
# validates_with MyValidator
-
# end
-
#
-
# class MyValidator < ActiveModel::Validator
-
# def validate(record)
-
# record # => The person instance being validated
-
# options # => Any non-standard options passed to validates_with
-
# end
-
# end
-
#
-
# To cause a validation error, you must add to the +record+'s errors directly
-
# from within the validators message.
-
#
-
# class MyValidator < ActiveModel::Validator
-
# def validate(record)
-
# record.errors.add :base, "This is some custom error message"
-
# record.errors.add :first_name, "This is some complex validation"
-
# # etc...
-
# end
-
# end
-
#
-
# To add behavior to the initialize method, use the following signature:
-
#
-
# class MyValidator < ActiveModel::Validator
-
# def initialize(options)
-
# super
-
# @my_custom_field = options[:field_name] || :first_name
-
# end
-
# end
-
#
-
# Note that the validator is initialized only once for the whole application
-
# life cycle, and not on each validation run.
-
#
-
# The easiest way to add custom validators for validating individual attributes
-
# is with the convenient <tt>ActiveModel::EachValidator</tt>.
-
#
-
# class TitleValidator < ActiveModel::EachValidator
-
# def validate_each(record, attribute, value)
-
# record.errors.add attribute, 'must be Mr., Mrs., or Dr.' unless %w(Mr. Mrs. Dr.).include?(value)
-
# end
-
# end
-
#
-
# This can now be used in combination with the +validates+ method
-
# (see <tt>ActiveModel::Validations::ClassMethods.validates</tt> for more on this).
-
#
-
# class Person
-
# include ActiveModel::Validations
-
# attr_accessor :title
-
#
-
# validates :title, presence: true, title: true
-
# end
-
#
-
# It can be useful to access the class that is using that validator when there are prerequisites such
-
# as an +attr_accessor+ being present. This class is accessible via +options[:class]+ in the constructor.
-
# To setup your validator override the constructor.
-
#
-
# class MyValidator < ActiveModel::Validator
-
# def initialize(options={})
-
# super
-
# options[:class].send :attr_accessor, :custom_attribute
-
# end
-
# end
-
2
class Validator
-
2
attr_reader :options
-
-
# Returns the kind of the validator.
-
#
-
# PresenceValidator.kind # => :presence
-
# UniquenessValidator.kind # => :uniqueness
-
2
def self.kind
-
@kind ||= name.split('::').last.underscore.sub(/_validator$/, '').to_sym unless anonymous?
-
end
-
-
# Accepts options that will be made available through the +options+ reader.
-
2
def initialize(options = {})
-
66
@options = options.except(:class).freeze
-
66
deprecated_setup(options)
-
end
-
-
# Returns the kind for this validator.
-
#
-
# PresenceValidator.new.kind # => :presence
-
# UniquenessValidator.new.kind # => :uniqueness
-
2
def kind
-
self.class.kind
-
end
-
-
# Override this method in subclasses with validation logic, adding errors
-
# to the records +errors+ array where necessary.
-
2
def validate(record)
-
raise NotImplementedError, "Subclasses must implement a validate(record) method."
-
end
-
-
2
private
-
2
def deprecated_setup(options) # TODO: remove me in 4.2.
-
66
return unless respond_to?(:setup)
-
ActiveSupport::Deprecation.warn "The `Validator#setup` instance method is deprecated and will be removed on Rails 4.2. Do your setup in the constructor instead:
-
-
class MyValidator < ActiveModel::Validator
-
def initialize(options={})
-
super
-
options[:class].send :attr_accessor, :custom_attribute
-
end
-
end
-
"
-
setup(options[:class])
-
end
-
end
-
-
# +EachValidator+ is a validator which iterates through the attributes given
-
# in the options hash invoking the <tt>validate_each</tt> method passing in the
-
# record, attribute and value.
-
#
-
# All Active Model validations are built on top of this validator.
-
2
class EachValidator < Validator #:nodoc:
-
2
attr_reader :attributes
-
-
# Returns a new validator instance. All options will be available via the
-
# +options+ reader, however the <tt>:attributes</tt> option will be removed
-
# and instead be made available through the +attributes+ reader.
-
2
def initialize(options)
-
66
@attributes = Array(options.delete(:attributes))
-
66
raise ArgumentError, ":attributes cannot be blank" if @attributes.empty?
-
66
super
-
66
check_validity!
-
end
-
-
# Performs validation on the supplied record. By default this will call
-
# +validates_each+ to determine validity therefore subclasses should
-
# override +validates_each+ with validation logic.
-
2
def validate(record)
-
2338
attributes.each do |attribute|
-
2338
value = record.read_attribute_for_validation(attribute)
-
2338
next if (value.nil? && options[:allow_nil]) || (value.blank? && options[:allow_blank])
-
2338
validate_each(record, attribute, value)
-
end
-
end
-
-
# Override this method in subclasses with the validation logic, adding
-
# errors to the records +errors+ array where necessary.
-
2
def validate_each(record, attribute, value)
-
raise NotImplementedError, "Subclasses must implement a validate_each(record, attribute, value) method"
-
end
-
-
# Hook method that gets called by the initializer allowing verification
-
# that the arguments supplied are valid. You could for example raise an
-
# +ArgumentError+ when invalid options are supplied.
-
2
def check_validity!
-
end
-
end
-
-
# +BlockValidator+ is a special +EachValidator+ which receives a block on initialization
-
# and call this block for each attribute being validated. +validates_each+ uses this validator.
-
2
class BlockValidator < EachValidator #:nodoc:
-
2
def initialize(options, &block)
-
@block = block
-
super
-
end
-
-
2
private
-
-
2
def validate_each(record, attribute, value)
-
@block.call(record, attribute, value)
-
end
-
end
-
end
-
2
require_relative 'gem_version'
-
-
2
module ActiveModel
-
# Returns the version of the currently loaded ActiveModel as a <tt>Gem::Version</tt>
-
2
def self.version
-
gem_version
-
end
-
end
-
#--
-
# Copyright (c) 2004-2014 David Heinemeier Hansson
-
#
-
# Permission is hereby granted, free of charge, to any person obtaining
-
# a copy of this software and associated documentation files (the
-
# "Software"), to deal in the Software without restriction, including
-
# without limitation the rights to use, copy, modify, merge, publish,
-
# distribute, sublicense, and/or sell copies of the Software, and to
-
# permit persons to whom the Software is furnished to do so, subject to
-
# the following conditions:
-
#
-
# The above copyright notice and this permission notice shall be
-
# included in all copies or substantial portions of the Software.
-
#
-
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
-
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
-
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
-
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-
#++
-
-
2
require 'active_support'
-
2
require 'active_support/rails'
-
2
require 'active_model'
-
2
require 'arel'
-
-
2
require 'active_record/version'
-
-
2
module ActiveRecord
-
2
extend ActiveSupport::Autoload
-
-
2
autoload :Base
-
2
autoload :Callbacks
-
2
autoload :Core
-
2
autoload :ConnectionHandling
-
2
autoload :CounterCache
-
2
autoload :DynamicMatchers
-
2
autoload :Enum
-
2
autoload :Explain
-
2
autoload :Inheritance
-
2
autoload :Integration
-
2
autoload :Migration
-
2
autoload :Migrator, 'active_record/migration'
-
2
autoload :ModelSchema
-
2
autoload :NestedAttributes
-
2
autoload :NoTouching
-
2
autoload :Persistence
-
2
autoload :QueryCache
-
2
autoload :Querying
-
2
autoload :ReadonlyAttributes
-
2
autoload :Reflection
-
2
autoload :RuntimeRegistry
-
2
autoload :Sanitization
-
2
autoload :Schema
-
2
autoload :SchemaDumper
-
2
autoload :SchemaMigration
-
2
autoload :Scoping
-
2
autoload :Serialization
-
2
autoload :StatementCache
-
2
autoload :Store
-
2
autoload :Timestamp
-
2
autoload :Transactions
-
2
autoload :Translation
-
2
autoload :Validations
-
-
2
eager_autoload do
-
2
autoload :ActiveRecordError, 'active_record/errors'
-
2
autoload :ConnectionNotEstablished, 'active_record/errors'
-
2
autoload :ConnectionAdapters, 'active_record/connection_adapters/abstract_adapter'
-
-
2
autoload :Aggregations
-
2
autoload :Associations
-
2
autoload :AttributeAssignment
-
2
autoload :AttributeMethods
-
2
autoload :AutosaveAssociation
-
-
2
autoload :Relation
-
2
autoload :AssociationRelation
-
2
autoload :NullRelation
-
-
2
autoload_under 'relation' do
-
2
autoload :QueryMethods
-
2
autoload :FinderMethods
-
2
autoload :Calculations
-
2
autoload :PredicateBuilder
-
2
autoload :SpawnMethods
-
2
autoload :Batches
-
2
autoload :Delegation
-
end
-
-
2
autoload :Result
-
end
-
-
2
module Coders
-
2
autoload :YAMLColumn, 'active_record/coders/yaml_column'
-
2
autoload :JSON, 'active_record/coders/json'
-
end
-
-
2
module AttributeMethods
-
2
extend ActiveSupport::Autoload
-
-
2
eager_autoload do
-
2
autoload :BeforeTypeCast
-
2
autoload :Dirty
-
2
autoload :PrimaryKey
-
2
autoload :Query
-
2
autoload :Read
-
2
autoload :TimeZoneConversion
-
2
autoload :Write
-
2
autoload :Serialization
-
end
-
end
-
-
2
module Locking
-
2
extend ActiveSupport::Autoload
-
-
2
eager_autoload do
-
2
autoload :Optimistic
-
2
autoload :Pessimistic
-
end
-
end
-
-
2
module ConnectionAdapters
-
2
extend ActiveSupport::Autoload
-
-
2
eager_autoload do
-
2
autoload :AbstractAdapter
-
2
autoload :ConnectionManagement, "active_record/connection_adapters/abstract/connection_pool"
-
end
-
end
-
-
2
module Scoping
-
2
extend ActiveSupport::Autoload
-
-
2
eager_autoload do
-
2
autoload :Named
-
2
autoload :Default
-
end
-
end
-
-
2
module Tasks
-
2
extend ActiveSupport::Autoload
-
-
2
autoload :DatabaseTasks
-
2
autoload :SQLiteDatabaseTasks, 'active_record/tasks/sqlite_database_tasks'
-
2
autoload :MySQLDatabaseTasks, 'active_record/tasks/mysql_database_tasks'
-
2
autoload :PostgreSQLDatabaseTasks,
-
'active_record/tasks/postgresql_database_tasks'
-
end
-
-
2
autoload :TestFixtures, 'active_record/fixtures'
-
-
2
def self.eager_load!
-
super
-
ActiveRecord::Locking.eager_load!
-
ActiveRecord::Scoping.eager_load!
-
ActiveRecord::Associations.eager_load!
-
ActiveRecord::AttributeMethods.eager_load!
-
ActiveRecord::ConnectionAdapters.eager_load!
-
end
-
end
-
-
2
ActiveSupport.on_load(:active_record) do
-
2
Arel::Table.engine = self
-
end
-
-
2
ActiveSupport.on_load(:i18n) do
-
2
I18n.load_path << File.dirname(__FILE__) + '/active_record/locale/en.yml'
-
end
-
2
module ActiveRecord
-
# = Active Record Aggregations
-
2
module Aggregations # :nodoc:
-
2
extend ActiveSupport::Concern
-
-
2
def clear_aggregation_cache #:nodoc:
-
@aggregation_cache.clear if persisted?
-
end
-
-
# Active Record implements aggregation through a macro-like class method called +composed_of+
-
# for representing attributes as value objects. It expresses relationships like "Account [is]
-
# composed of Money [among other things]" or "Person [is] composed of [an] address". Each call
-
# to the macro adds a description of how the value objects are created from the attributes of
-
# the entity object (when the entity is initialized either as a new object or from finding an
-
# existing object) and how it can be turned back into attributes (when the entity is saved to
-
# the database).
-
#
-
# class Customer < ActiveRecord::Base
-
# composed_of :balance, class_name: "Money", mapping: %w(balance amount)
-
# composed_of :address, mapping: [ %w(address_street street), %w(address_city city) ]
-
# end
-
#
-
# The customer class now has the following methods to manipulate the value objects:
-
# * <tt>Customer#balance, Customer#balance=(money)</tt>
-
# * <tt>Customer#address, Customer#address=(address)</tt>
-
#
-
# These methods will operate with value objects like the ones described below:
-
#
-
# class Money
-
# include Comparable
-
# attr_reader :amount, :currency
-
# EXCHANGE_RATES = { "USD_TO_DKK" => 6 }
-
#
-
# def initialize(amount, currency = "USD")
-
# @amount, @currency = amount, currency
-
# end
-
#
-
# def exchange_to(other_currency)
-
# exchanged_amount = (amount * EXCHANGE_RATES["#{currency}_TO_#{other_currency}"]).floor
-
# Money.new(exchanged_amount, other_currency)
-
# end
-
#
-
# def ==(other_money)
-
# amount == other_money.amount && currency == other_money.currency
-
# end
-
#
-
# def <=>(other_money)
-
# if currency == other_money.currency
-
# amount <=> other_money.amount
-
# else
-
# amount <=> other_money.exchange_to(currency).amount
-
# end
-
# end
-
# end
-
#
-
# class Address
-
# attr_reader :street, :city
-
# def initialize(street, city)
-
# @street, @city = street, city
-
# end
-
#
-
# def close_to?(other_address)
-
# city == other_address.city
-
# end
-
#
-
# def ==(other_address)
-
# city == other_address.city && street == other_address.street
-
# end
-
# end
-
#
-
# Now it's possible to access attributes from the database through the value objects instead. If
-
# you choose to name the composition the same as the attribute's name, it will be the only way to
-
# access that attribute. That's the case with our +balance+ attribute. You interact with the value
-
# objects just like you would with any other attribute:
-
#
-
# customer.balance = Money.new(20) # sets the Money value object and the attribute
-
# customer.balance # => Money value object
-
# customer.balance.exchange_to("DKK") # => Money.new(120, "DKK")
-
# customer.balance > Money.new(10) # => true
-
# customer.balance == Money.new(20) # => true
-
# customer.balance < Money.new(5) # => false
-
#
-
# Value objects can also be composed of multiple attributes, such as the case of Address. The order
-
# of the mappings will determine the order of the parameters.
-
#
-
# customer.address_street = "Hyancintvej"
-
# customer.address_city = "Copenhagen"
-
# customer.address # => Address.new("Hyancintvej", "Copenhagen")
-
#
-
# customer.address_street = "Vesterbrogade"
-
# customer.address # => Address.new("Hyancintvej", "Copenhagen")
-
# customer.clear_aggregation_cache
-
# customer.address # => Address.new("Vesterbrogade", "Copenhagen")
-
#
-
# customer.address = Address.new("May Street", "Chicago")
-
# customer.address_street # => "May Street"
-
# customer.address_city # => "Chicago"
-
#
-
# == Writing value objects
-
#
-
# Value objects are immutable and interchangeable objects that represent a given value, such as
-
# a Money object representing $5. Two Money objects both representing $5 should be equal (through
-
# methods such as <tt>==</tt> and <tt><=></tt> from Comparable if ranking makes sense). This is
-
# unlike entity objects where equality is determined by identity. An entity class such as Customer can
-
# easily have two different objects that both have an address on Hyancintvej. Entity identity is
-
# determined by object or relational unique identifiers (such as primary keys). Normal
-
# ActiveRecord::Base classes are entity objects.
-
#
-
# It's also important to treat the value objects as immutable. Don't allow the Money object to have
-
# its amount changed after creation. Create a new Money object with the new value instead. The
-
# Money#exchange_to method is an example of this. It returns a new value object instead of changing
-
# its own values. Active Record won't persist value objects that have been changed through means
-
# other than the writer method.
-
#
-
# The immutable requirement is enforced by Active Record by freezing any object assigned as a value
-
# object. Attempting to change it afterwards will result in a RuntimeError.
-
#
-
# Read more about value objects on http://c2.com/cgi/wiki?ValueObject and on the dangers of not
-
# keeping value objects immutable on http://c2.com/cgi/wiki?ValueObjectsShouldBeImmutable
-
#
-
# == Custom constructors and converters
-
#
-
# By default value objects are initialized by calling the <tt>new</tt> constructor of the value
-
# class passing each of the mapped attributes, in the order specified by the <tt>:mapping</tt>
-
# option, as arguments. If the value class doesn't support this convention then +composed_of+ allows
-
# a custom constructor to be specified.
-
#
-
# When a new value is assigned to the value object, the default assumption is that the new value
-
# is an instance of the value class. Specifying a custom converter allows the new value to be automatically
-
# converted to an instance of value class if necessary.
-
#
-
# For example, the NetworkResource model has +network_address+ and +cidr_range+ attributes that
-
# should be aggregated using the NetAddr::CIDR value class (http://netaddr.rubyforge.org). The constructor
-
# for the value class is called +create+ and it expects a CIDR address string as a parameter. New
-
# values can be assigned to the value object using either another NetAddr::CIDR object, a string
-
# or an array. The <tt>:constructor</tt> and <tt>:converter</tt> options can be used to meet
-
# these requirements:
-
#
-
# class NetworkResource < ActiveRecord::Base
-
# composed_of :cidr,
-
# class_name: 'NetAddr::CIDR',
-
# mapping: [ %w(network_address network), %w(cidr_range bits) ],
-
# allow_nil: true,
-
# constructor: Proc.new { |network_address, cidr_range| NetAddr::CIDR.create("#{network_address}/#{cidr_range}") },
-
# converter: Proc.new { |value| NetAddr::CIDR.create(value.is_a?(Array) ? value.join('/') : value) }
-
# end
-
#
-
# # This calls the :constructor
-
# network_resource = NetworkResource.new(network_address: '192.168.0.1', cidr_range: 24)
-
#
-
# # These assignments will both use the :converter
-
# network_resource.cidr = [ '192.168.2.1', 8 ]
-
# network_resource.cidr = '192.168.0.1/24'
-
#
-
# # This assignment won't use the :converter as the value is already an instance of the value class
-
# network_resource.cidr = NetAddr::CIDR.create('192.168.2.1/8')
-
#
-
# # Saving and then reloading will use the :constructor on reload
-
# network_resource.save
-
# network_resource.reload
-
#
-
# == Finding records by a value object
-
#
-
# Once a +composed_of+ relationship is specified for a model, records can be loaded from the database
-
# by specifying an instance of the value object in the conditions hash. The following example
-
# finds all customers with +balance_amount+ equal to 20 and +balance_currency+ equal to "USD":
-
#
-
# Customer.where(balance: Money.new(20, "USD"))
-
#
-
2
module ClassMethods
-
# Adds reader and writer methods for manipulating a value object:
-
# <tt>composed_of :address</tt> adds <tt>address</tt> and <tt>address=(new_address)</tt> methods.
-
#
-
# Options are:
-
# * <tt>:class_name</tt> - Specifies the class name of the association. Use it only if that name
-
# can't be inferred from the part id. So <tt>composed_of :address</tt> will by default be linked
-
# to the Address class, but if the real class name is CompanyAddress, you'll have to specify it
-
# with this option.
-
# * <tt>:mapping</tt> - Specifies the mapping of entity attributes to attributes of the value
-
# object. Each mapping is represented as an array where the first item is the name of the
-
# entity attribute and the second item is the name of the attribute in the value object. The
-
# order in which mappings are defined determines the order in which attributes are sent to the
-
# value class constructor.
-
# * <tt>:allow_nil</tt> - Specifies that the value object will not be instantiated when all mapped
-
# attributes are +nil+. Setting the value object to +nil+ has the effect of writing +nil+ to all
-
# mapped attributes.
-
# This defaults to +false+.
-
# * <tt>:constructor</tt> - A symbol specifying the name of the constructor method or a Proc that
-
# is called to initialize the value object. The constructor is passed all of the mapped attributes,
-
# in the order that they are defined in the <tt>:mapping option</tt>, as arguments and uses them
-
# to instantiate a <tt>:class_name</tt> object.
-
# The default is <tt>:new</tt>.
-
# * <tt>:converter</tt> - A symbol specifying the name of a class method of <tt>:class_name</tt>
-
# or a Proc that is called when a new value is assigned to the value object. The converter is
-
# passed the single value that is used in the assignment and is only called if the new value is
-
# not an instance of <tt>:class_name</tt>. If <tt>:allow_nil</tt> is set to true, the converter
-
# can return nil to skip the assignment.
-
#
-
# Option examples:
-
# composed_of :temperature, mapping: %w(reading celsius)
-
# composed_of :balance, class_name: "Money", mapping: %w(balance amount),
-
# converter: Proc.new { |balance| balance.to_money }
-
# composed_of :address, mapping: [ %w(address_street street), %w(address_city city) ]
-
# composed_of :gps_location
-
# composed_of :gps_location, allow_nil: true
-
# composed_of :ip_address,
-
# class_name: 'IPAddr',
-
# mapping: %w(ip to_i),
-
# constructor: Proc.new { |ip| IPAddr.new(ip, Socket::AF_INET) },
-
# converter: Proc.new { |ip| ip.is_a?(Integer) ? IPAddr.new(ip, Socket::AF_INET) : IPAddr.new(ip.to_s) }
-
#
-
2
def composed_of(part_id, options = {})
-
options.assert_valid_keys(:class_name, :mapping, :allow_nil, :constructor, :converter)
-
-
name = part_id.id2name
-
class_name = options[:class_name] || name.camelize
-
mapping = options[:mapping] || [ name, name ]
-
mapping = [ mapping ] unless mapping.first.is_a?(Array)
-
allow_nil = options[:allow_nil] || false
-
constructor = options[:constructor] || :new
-
converter = options[:converter]
-
-
reader_method(name, class_name, mapping, allow_nil, constructor)
-
writer_method(name, class_name, mapping, allow_nil, converter)
-
-
reflection = ActiveRecord::Reflection.create(:composed_of, part_id, nil, options, self)
-
Reflection.add_aggregate_reflection self, part_id, reflection
-
end
-
-
2
private
-
2
def reader_method(name, class_name, mapping, allow_nil, constructor)
-
define_method(name) do
-
if @aggregation_cache[name].nil? && (!allow_nil || mapping.any? {|pair| !read_attribute(pair.first).nil? })
-
attrs = mapping.collect {|pair| read_attribute(pair.first)}
-
object = constructor.respond_to?(:call) ?
-
constructor.call(*attrs) :
-
class_name.constantize.send(constructor, *attrs)
-
@aggregation_cache[name] = object
-
end
-
@aggregation_cache[name]
-
end
-
end
-
-
2
def writer_method(name, class_name, mapping, allow_nil, converter)
-
define_method("#{name}=") do |part|
-
klass = class_name.constantize
-
unless part.is_a?(klass) || converter.nil? || part.nil?
-
part = converter.respond_to?(:call) ? converter.call(part) : klass.send(converter, part)
-
end
-
-
if part.nil? && allow_nil
-
mapping.each { |pair| self[pair.first] = nil }
-
@aggregation_cache[name] = nil
-
else
-
mapping.each { |pair| self[pair.first] = part.send(pair.last) }
-
@aggregation_cache[name] = part.freeze
-
end
-
end
-
end
-
end
-
end
-
end
-
2
module ActiveRecord
-
2
class AssociationRelation < Relation
-
2
def initialize(klass, table, association)
-
144
super(klass, table)
-
144
@association = association
-
end
-
-
2
def proxy_association
-
@association
-
end
-
-
2
def ==(other)
-
other == to_a
-
end
-
-
2
private
-
-
2
def exec_queries
-
super.each { |r| @association.set_inverse_instance r }
-
end
-
end
-
end
-
2
require 'active_support/core_ext/enumerable'
-
2
require 'active_support/core_ext/string/conversions'
-
2
require 'active_support/core_ext/module/remove_method'
-
2
require 'active_record/errors'
-
-
2
module ActiveRecord
-
2
class AssociationNotFoundError < ConfigurationError #:nodoc:
-
2
def initialize(record, association_name)
-
super("Association named '#{association_name}' was not found on #{record.class.name}; perhaps you misspelled it?")
-
end
-
end
-
-
2
class InverseOfAssociationNotFoundError < ActiveRecordError #:nodoc:
-
2
def initialize(reflection, associated_class = nil)
-
super("Could not find the inverse association for #{reflection.name} (#{reflection.options[:inverse_of].inspect} in #{associated_class.nil? ? reflection.class_name : associated_class.name})")
-
end
-
end
-
-
2
class HasManyThroughAssociationNotFoundError < ActiveRecordError #:nodoc:
-
2
def initialize(owner_class_name, reflection)
-
super("Could not find the association #{reflection.options[:through].inspect} in model #{owner_class_name}")
-
end
-
end
-
-
2
class HasManyThroughAssociationPolymorphicSourceError < ActiveRecordError #:nodoc:
-
2
def initialize(owner_class_name, reflection, source_reflection)
-
super("Cannot have a has_many :through association '#{owner_class_name}##{reflection.name}' on the polymorphic object '#{source_reflection.class_name}##{source_reflection.name}' without 'source_type'. Try adding 'source_type: \"#{reflection.name.to_s.classify}\"' to 'has_many :through' definition.")
-
end
-
end
-
-
2
class HasManyThroughAssociationPolymorphicThroughError < ActiveRecordError #:nodoc:
-
2
def initialize(owner_class_name, reflection)
-
super("Cannot have a has_many :through association '#{owner_class_name}##{reflection.name}' which goes through the polymorphic association '#{owner_class_name}##{reflection.through_reflection.name}'.")
-
end
-
end
-
-
2
class HasManyThroughAssociationPointlessSourceTypeError < ActiveRecordError #:nodoc:
-
2
def initialize(owner_class_name, reflection, source_reflection)
-
super("Cannot have a has_many :through association '#{owner_class_name}##{reflection.name}' with a :source_type option if the '#{reflection.through_reflection.class_name}##{source_reflection.name}' is not polymorphic. Try removing :source_type on your association.")
-
end
-
end
-
-
2
class HasOneThroughCantAssociateThroughCollection < ActiveRecordError #:nodoc:
-
2
def initialize(owner_class_name, reflection, through_reflection)
-
super("Cannot have a has_one :through association '#{owner_class_name}##{reflection.name}' where the :through association '#{owner_class_name}##{through_reflection.name}' is a collection. Specify a has_one or belongs_to association in the :through option instead.")
-
end
-
end
-
-
2
class HasManyThroughSourceAssociationNotFoundError < ActiveRecordError #:nodoc:
-
2
def initialize(reflection)
-
through_reflection = reflection.through_reflection
-
source_reflection_names = reflection.source_reflection_names
-
source_associations = reflection.through_reflection.klass._reflections.keys
-
super("Could not find the source association(s) #{source_reflection_names.collect{ |a| a.inspect }.to_sentence(:two_words_connector => ' or ', :last_word_connector => ', or ', :locale => :en)} in model #{through_reflection.klass}. Try 'has_many #{reflection.name.inspect}, :through => #{through_reflection.name.inspect}, :source => <name>'. Is it one of #{source_associations.to_sentence(:two_words_connector => ' or ', :last_word_connector => ', or ', :locale => :en)}?")
-
end
-
end
-
-
2
class HasManyThroughCantAssociateThroughHasOneOrManyReflection < ActiveRecordError #:nodoc:
-
2
def initialize(owner, reflection)
-
super("Cannot modify association '#{owner.class.name}##{reflection.name}' because the source reflection class '#{reflection.source_reflection.class_name}' is associated to '#{reflection.through_reflection.class_name}' via :#{reflection.source_reflection.macro}.")
-
end
-
end
-
-
2
class HasManyThroughCantAssociateNewRecords < ActiveRecordError #:nodoc:
-
2
def initialize(owner, reflection)
-
super("Cannot associate new records through '#{owner.class.name}##{reflection.name}' on '#{reflection.source_reflection.class_name rescue nil}##{reflection.source_reflection.name rescue nil}'. Both records must have an id in order to create the has_many :through record associating them.")
-
end
-
end
-
-
2
class HasManyThroughCantDissociateNewRecords < ActiveRecordError #:nodoc:
-
2
def initialize(owner, reflection)
-
super("Cannot dissociate new records through '#{owner.class.name}##{reflection.name}' on '#{reflection.source_reflection.class_name rescue nil}##{reflection.source_reflection.name rescue nil}'. Both records must have an id in order to delete the has_many :through record associating them.")
-
end
-
end
-
-
2
class HasManyThroughNestedAssociationsAreReadonly < ActiveRecordError #:nodoc:
-
2
def initialize(owner, reflection)
-
super("Cannot modify association '#{owner.class.name}##{reflection.name}' because it goes through more than one other association.")
-
end
-
end
-
-
2
class EagerLoadPolymorphicError < ActiveRecordError #:nodoc:
-
2
def initialize(reflection)
-
super("Cannot eagerly load the polymorphic association #{reflection.name.inspect}")
-
end
-
end
-
-
2
class ReadOnlyAssociation < ActiveRecordError #:nodoc:
-
2
def initialize(reflection)
-
super("Cannot add to a has_many :through association. Try adding to #{reflection.through_reflection.name.inspect}.")
-
end
-
end
-
-
# This error is raised when trying to destroy a parent instance in N:1 or 1:1 associations
-
# (has_many, has_one) when there is at least 1 child associated instance.
-
# ex: if @project.tasks.size > 0, DeleteRestrictionError will be raised when trying to destroy @project
-
2
class DeleteRestrictionError < ActiveRecordError #:nodoc:
-
2
def initialize(name)
-
super("Cannot delete record because of dependent #{name}")
-
end
-
end
-
-
# See ActiveRecord::Associations::ClassMethods for documentation.
-
2
module Associations # :nodoc:
-
2
extend ActiveSupport::Autoload
-
2
extend ActiveSupport::Concern
-
-
# These classes will be loaded when associations are created.
-
# So there is no need to eager load them.
-
2
autoload :Association, 'active_record/associations/association'
-
2
autoload :SingularAssociation, 'active_record/associations/singular_association'
-
2
autoload :CollectionAssociation, 'active_record/associations/collection_association'
-
2
autoload :CollectionProxy, 'active_record/associations/collection_proxy'
-
-
2
autoload :BelongsToAssociation, 'active_record/associations/belongs_to_association'
-
2
autoload :BelongsToPolymorphicAssociation, 'active_record/associations/belongs_to_polymorphic_association'
-
2
autoload :HasManyAssociation, 'active_record/associations/has_many_association'
-
2
autoload :HasManyThroughAssociation, 'active_record/associations/has_many_through_association'
-
2
autoload :HasOneAssociation, 'active_record/associations/has_one_association'
-
2
autoload :HasOneThroughAssociation, 'active_record/associations/has_one_through_association'
-
2
autoload :ThroughAssociation, 'active_record/associations/through_association'
-
-
2
module Builder #:nodoc:
-
2
autoload :Association, 'active_record/associations/builder/association'
-
2
autoload :SingularAssociation, 'active_record/associations/builder/singular_association'
-
2
autoload :CollectionAssociation, 'active_record/associations/builder/collection_association'
-
-
2
autoload :BelongsTo, 'active_record/associations/builder/belongs_to'
-
2
autoload :HasOne, 'active_record/associations/builder/has_one'
-
2
autoload :HasMany, 'active_record/associations/builder/has_many'
-
2
autoload :HasAndBelongsToMany, 'active_record/associations/builder/has_and_belongs_to_many'
-
end
-
-
2
eager_autoload do
-
2
autoload :Preloader, 'active_record/associations/preloader'
-
2
autoload :JoinDependency, 'active_record/associations/join_dependency'
-
2
autoload :AssociationScope, 'active_record/associations/association_scope'
-
2
autoload :AliasTracker, 'active_record/associations/alias_tracker'
-
end
-
-
# Clears out the association cache.
-
2
def clear_association_cache #:nodoc:
-
@association_cache.clear if persisted?
-
end
-
-
# :nodoc:
-
2
attr_reader :association_cache
-
-
# Returns the association instance for the given name, instantiating it if it doesn't already exist
-
2
def association(name) #:nodoc:
-
216
association = association_instance_get(name)
-
-
216
if association.nil?
-
216
raise AssociationNotFoundError.new(self, name) unless reflection = self.class._reflect_on_association(name)
-
216
association = reflection.association_class.new(self, reflection)
-
216
association_instance_set(name, association)
-
end
-
-
216
association
-
end
-
-
2
private
-
# Returns the specified association instance if it responds to :loaded?, nil otherwise.
-
2
def association_instance_get(name)
-
2932
@association_cache[name]
-
end
-
-
# Set the specified association instance.
-
2
def association_instance_set(name, association)
-
216
@association_cache[name] = association
-
end
-
-
# \Associations are a set of macro-like class methods for tying objects together through
-
# foreign keys. They express relationships like "Project has one Project Manager"
-
# or "Project belongs to a Portfolio". Each macro adds a number of methods to the
-
# class which are specialized according to the collection or association symbol and the
-
# options hash. It works much the same way as Ruby's own <tt>attr*</tt>
-
# methods.
-
#
-
# class Project < ActiveRecord::Base
-
# belongs_to :portfolio
-
# has_one :project_manager
-
# has_many :milestones
-
# has_and_belongs_to_many :categories
-
# end
-
#
-
# The project class now has the following methods (and more) to ease the traversal and
-
# manipulation of its relationships:
-
# * <tt>Project#portfolio, Project#portfolio=(portfolio), Project#portfolio.nil?</tt>
-
# * <tt>Project#project_manager, Project#project_manager=(project_manager), Project#project_manager.nil?,</tt>
-
# * <tt>Project#milestones.empty?, Project#milestones.size, Project#milestones, Project#milestones<<(milestone),</tt>
-
# <tt>Project#milestones.delete(milestone), Project#milestones.destroy(milestone), Project#milestones.find(milestone_id),</tt>
-
# <tt>Project#milestones.build, Project#milestones.create</tt>
-
# * <tt>Project#categories.empty?, Project#categories.size, Project#categories, Project#categories<<(category1),</tt>
-
# <tt>Project#categories.delete(category1), Project#categories.destroy(category1)</tt>
-
#
-
# === A word of warning
-
#
-
# Don't create associations that have the same name as instance methods of
-
# <tt>ActiveRecord::Base</tt>. Since the association adds a method with that name to
-
# its model, it will override the inherited method and break things.
-
# For instance, +attributes+ and +connection+ would be bad choices for association names.
-
#
-
# == Auto-generated methods
-
#
-
# === Singular associations (one-to-one)
-
# | | belongs_to |
-
# generated methods | belongs_to | :polymorphic | has_one
-
# ----------------------------------+------------+--------------+---------
-
# other | X | X | X
-
# other=(other) | X | X | X
-
# build_other(attributes={}) | X | | X
-
# create_other(attributes={}) | X | | X
-
# create_other!(attributes={}) | X | | X
-
#
-
# ===Collection associations (one-to-many / many-to-many)
-
# | | | has_many
-
# generated methods | habtm | has_many | :through
-
# ----------------------------------+-------+----------+----------
-
# others | X | X | X
-
# others=(other,other,...) | X | X | X
-
# other_ids | X | X | X
-
# other_ids=(id,id,...) | X | X | X
-
# others<< | X | X | X
-
# others.push | X | X | X
-
# others.concat | X | X | X
-
# others.build(attributes={}) | X | X | X
-
# others.create(attributes={}) | X | X | X
-
# others.create!(attributes={}) | X | X | X
-
# others.size | X | X | X
-
# others.length | X | X | X
-
# others.count | X | X | X
-
# others.sum(*args) | X | X | X
-
# others.empty? | X | X | X
-
# others.clear | X | X | X
-
# others.delete(other,other,...) | X | X | X
-
# others.delete_all | X | X | X
-
# others.destroy(other,other,...) | X | X | X
-
# others.destroy_all | X | X | X
-
# others.find(*args) | X | X | X
-
# others.exists? | X | X | X
-
# others.distinct | X | X | X
-
# others.uniq | X | X | X
-
# others.reset | X | X | X
-
#
-
# === Overriding generated methods
-
#
-
# Association methods are generated in a module that is included into the model class,
-
# which allows you to easily override with your own methods and call the original
-
# generated method with +super+. For example:
-
#
-
# class Car < ActiveRecord::Base
-
# belongs_to :owner
-
# belongs_to :old_owner
-
# def owner=(new_owner)
-
# self.old_owner = self.owner
-
# super
-
# end
-
# end
-
#
-
# If your model class is <tt>Project</tt>, the module is
-
# named <tt>Project::GeneratedFeatureMethods</tt>. The GeneratedFeatureMethods module is
-
# included in the model class immediately after the (anonymous) generated attributes methods
-
# module, meaning an association will override the methods for an attribute with the same name.
-
#
-
# == Cardinality and associations
-
#
-
# Active Record associations can be used to describe one-to-one, one-to-many and many-to-many
-
# relationships between models. Each model uses an association to describe its role in
-
# the relation. The +belongs_to+ association is always used in the model that has
-
# the foreign key.
-
#
-
# === One-to-one
-
#
-
# Use +has_one+ in the base, and +belongs_to+ in the associated model.
-
#
-
# class Employee < ActiveRecord::Base
-
# has_one :office
-
# end
-
# class Office < ActiveRecord::Base
-
# belongs_to :employee # foreign key - employee_id
-
# end
-
#
-
# === One-to-many
-
#
-
# Use +has_many+ in the base, and +belongs_to+ in the associated model.
-
#
-
# class Manager < ActiveRecord::Base
-
# has_many :employees
-
# end
-
# class Employee < ActiveRecord::Base
-
# belongs_to :manager # foreign key - manager_id
-
# end
-
#
-
# === Many-to-many
-
#
-
# There are two ways to build a many-to-many relationship.
-
#
-
# The first way uses a +has_many+ association with the <tt>:through</tt> option and a join model, so
-
# there are two stages of associations.
-
#
-
# class Assignment < ActiveRecord::Base
-
# belongs_to :programmer # foreign key - programmer_id
-
# belongs_to :project # foreign key - project_id
-
# end
-
# class Programmer < ActiveRecord::Base
-
# has_many :assignments
-
# has_many :projects, through: :assignments
-
# end
-
# class Project < ActiveRecord::Base
-
# has_many :assignments
-
# has_many :programmers, through: :assignments
-
# end
-
#
-
# For the second way, use +has_and_belongs_to_many+ in both models. This requires a join table
-
# that has no corresponding model or primary key.
-
#
-
# class Programmer < ActiveRecord::Base
-
# has_and_belongs_to_many :projects # foreign keys in the join table
-
# end
-
# class Project < ActiveRecord::Base
-
# has_and_belongs_to_many :programmers # foreign keys in the join table
-
# end
-
#
-
# Choosing which way to build a many-to-many relationship is not always simple.
-
# If you need to work with the relationship model as its own entity,
-
# use <tt>has_many :through</tt>. Use +has_and_belongs_to_many+ when working with legacy schemas or when
-
# you never work directly with the relationship itself.
-
#
-
# == Is it a +belongs_to+ or +has_one+ association?
-
#
-
# Both express a 1-1 relationship. The difference is mostly where to place the foreign
-
# key, which goes on the table for the class declaring the +belongs_to+ relationship.
-
#
-
# class User < ActiveRecord::Base
-
# # I reference an account.
-
# belongs_to :account
-
# end
-
#
-
# class Account < ActiveRecord::Base
-
# # One user references me.
-
# has_one :user
-
# end
-
#
-
# The tables for these classes could look something like:
-
#
-
# CREATE TABLE users (
-
# id int(11) NOT NULL auto_increment,
-
# account_id int(11) default NULL,
-
# name varchar default NULL,
-
# PRIMARY KEY (id)
-
# )
-
#
-
# CREATE TABLE accounts (
-
# id int(11) NOT NULL auto_increment,
-
# name varchar default NULL,
-
# PRIMARY KEY (id)
-
# )
-
#
-
# == Unsaved objects and associations
-
#
-
# You can manipulate objects and associations before they are saved to the database, but
-
# there is some special behavior you should be aware of, mostly involving the saving of
-
# associated objects.
-
#
-
# You can set the <tt>:autosave</tt> option on a <tt>has_one</tt>, <tt>belongs_to</tt>,
-
# <tt>has_many</tt>, or <tt>has_and_belongs_to_many</tt> association. Setting it
-
# to +true+ will _always_ save the members, whereas setting it to +false+ will
-
# _never_ save the members. More details about <tt>:autosave</tt> option is available at
-
# AutosaveAssociation.
-
#
-
# === One-to-one associations
-
#
-
# * Assigning an object to a +has_one+ association automatically saves that object and
-
# the object being replaced (if there is one), in order to update their foreign
-
# keys - except if the parent object is unsaved (<tt>new_record? == true</tt>).
-
# * If either of these saves fail (due to one of the objects being invalid), an
-
# <tt>ActiveRecord::RecordNotSaved</tt> exception is raised and the assignment is
-
# cancelled.
-
# * If you wish to assign an object to a +has_one+ association without saving it,
-
# use the <tt>build_association</tt> method (documented below). The object being
-
# replaced will still be saved to update its foreign key.
-
# * Assigning an object to a +belongs_to+ association does not save the object, since
-
# the foreign key field belongs on the parent. It does not save the parent either.
-
#
-
# === Collections
-
#
-
# * Adding an object to a collection (+has_many+ or +has_and_belongs_to_many+) automatically
-
# saves that object, except if the parent object (the owner of the collection) is not yet
-
# stored in the database.
-
# * If saving any of the objects being added to a collection (via <tt>push</tt> or similar)
-
# fails, then <tt>push</tt> returns +false+.
-
# * If saving fails while replacing the collection (via <tt>association=</tt>), an
-
# <tt>ActiveRecord::RecordNotSaved</tt> exception is raised and the assignment is
-
# cancelled.
-
# * You can add an object to a collection without automatically saving it by using the
-
# <tt>collection.build</tt> method (documented below).
-
# * All unsaved (<tt>new_record? == true</tt>) members of the collection are automatically
-
# saved when the parent is saved.
-
#
-
# == Customizing the query
-
#
-
# \Associations are built from <tt>Relation</tt>s, and you can use the <tt>Relation</tt> syntax
-
# to customize them. For example, to add a condition:
-
#
-
# class Blog < ActiveRecord::Base
-
# has_many :published_posts, -> { where published: true }, class_name: 'Post'
-
# end
-
#
-
# Inside the <tt>-> { ... }</tt> block you can use all of the usual <tt>Relation</tt> methods.
-
#
-
# === Accessing the owner object
-
#
-
# Sometimes it is useful to have access to the owner object when building the query. The owner
-
# is passed as a parameter to the block. For example, the following association would find all
-
# events that occur on the user's birthday:
-
#
-
# class User < ActiveRecord::Base
-
# has_many :birthday_events, ->(user) { where starts_on: user.birthday }, class_name: 'Event'
-
# end
-
#
-
# == Association callbacks
-
#
-
# Similar to the normal callbacks that hook into the life cycle of an Active Record object,
-
# you can also define callbacks that get triggered when you add an object to or remove an
-
# object from an association collection.
-
#
-
# class Project
-
# has_and_belongs_to_many :developers, after_add: :evaluate_velocity
-
#
-
# def evaluate_velocity(developer)
-
# ...
-
# end
-
# end
-
#
-
# It's possible to stack callbacks by passing them as an array. Example:
-
#
-
# class Project
-
# has_and_belongs_to_many :developers,
-
# after_add: [:evaluate_velocity, Proc.new { |p, d| p.shipping_date = Time.now}]
-
# end
-
#
-
# Possible callbacks are: +before_add+, +after_add+, +before_remove+ and +after_remove+.
-
#
-
# Should any of the +before_add+ callbacks throw an exception, the object does not get
-
# added to the collection. Same with the +before_remove+ callbacks; if an exception is
-
# thrown the object doesn't get removed.
-
#
-
# == Association extensions
-
#
-
# The proxy objects that control the access to associations can be extended through anonymous
-
# modules. This is especially beneficial for adding new finders, creators, and other
-
# factory-type methods that are only used as part of this association.
-
#
-
# class Account < ActiveRecord::Base
-
# has_many :people do
-
# def find_or_create_by_name(name)
-
# first_name, last_name = name.split(" ", 2)
-
# find_or_create_by(first_name: first_name, last_name: last_name)
-
# end
-
# end
-
# end
-
#
-
# person = Account.first.people.find_or_create_by_name("David Heinemeier Hansson")
-
# person.first_name # => "David"
-
# person.last_name # => "Heinemeier Hansson"
-
#
-
# If you need to share the same extensions between many associations, you can use a named
-
# extension module.
-
#
-
# module FindOrCreateByNameExtension
-
# def find_or_create_by_name(name)
-
# first_name, last_name = name.split(" ", 2)
-
# find_or_create_by(first_name: first_name, last_name: last_name)
-
# end
-
# end
-
#
-
# class Account < ActiveRecord::Base
-
# has_many :people, -> { extending FindOrCreateByNameExtension }
-
# end
-
#
-
# class Company < ActiveRecord::Base
-
# has_many :people, -> { extending FindOrCreateByNameExtension }
-
# end
-
#
-
# Some extensions can only be made to work with knowledge of the association's internals.
-
# Extensions can access relevant state using the following methods (where +items+ is the
-
# name of the association):
-
#
-
# * <tt>record.association(:items).owner</tt> - Returns the object the association is part of.
-
# * <tt>record.association(:items).reflection</tt> - Returns the reflection object that describes the association.
-
# * <tt>record.association(:items).target</tt> - Returns the associated object for +belongs_to+ and +has_one+, or
-
# the collection of associated objects for +has_many+ and +has_and_belongs_to_many+.
-
#
-
# However, inside the actual extension code, you will not have access to the <tt>record</tt> as
-
# above. In this case, you can access <tt>proxy_association</tt>. For example,
-
# <tt>record.association(:items)</tt> and <tt>record.items.proxy_association</tt> will return
-
# the same object, allowing you to make calls like <tt>proxy_association.owner</tt> inside
-
# association extensions.
-
#
-
# == Association Join Models
-
#
-
# Has Many associations can be configured with the <tt>:through</tt> option to use an
-
# explicit join model to retrieve the data. This operates similarly to a
-
# +has_and_belongs_to_many+ association. The advantage is that you're able to add validations,
-
# callbacks, and extra attributes on the join model. Consider the following schema:
-
#
-
# class Author < ActiveRecord::Base
-
# has_many :authorships
-
# has_many :books, through: :authorships
-
# end
-
#
-
# class Authorship < ActiveRecord::Base
-
# belongs_to :author
-
# belongs_to :book
-
# end
-
#
-
# @author = Author.first
-
# @author.authorships.collect { |a| a.book } # selects all books that the author's authorships belong to
-
# @author.books # selects all books by using the Authorship join model
-
#
-
# You can also go through a +has_many+ association on the join model:
-
#
-
# class Firm < ActiveRecord::Base
-
# has_many :clients
-
# has_many :invoices, through: :clients
-
# end
-
#
-
# class Client < ActiveRecord::Base
-
# belongs_to :firm
-
# has_many :invoices
-
# end
-
#
-
# class Invoice < ActiveRecord::Base
-
# belongs_to :client
-
# end
-
#
-
# @firm = Firm.first
-
# @firm.clients.collect { |c| c.invoices }.flatten # select all invoices for all clients of the firm
-
# @firm.invoices # selects all invoices by going through the Client join model
-
#
-
# Similarly you can go through a +has_one+ association on the join model:
-
#
-
# class Group < ActiveRecord::Base
-
# has_many :users
-
# has_many :avatars, through: :users
-
# end
-
#
-
# class User < ActiveRecord::Base
-
# belongs_to :group
-
# has_one :avatar
-
# end
-
#
-
# class Avatar < ActiveRecord::Base
-
# belongs_to :user
-
# end
-
#
-
# @group = Group.first
-
# @group.users.collect { |u| u.avatar }.compact # select all avatars for all users in the group
-
# @group.avatars # selects all avatars by going through the User join model.
-
#
-
# An important caveat with going through +has_one+ or +has_many+ associations on the
-
# join model is that these associations are *read-only*. For example, the following
-
# would not work following the previous example:
-
#
-
# @group.avatars << Avatar.new # this would work if User belonged_to Avatar rather than the other way around
-
# @group.avatars.delete(@group.avatars.last) # so would this
-
#
-
# == Setting Inverses
-
#
-
# If you are using a +belongs_to+ on the join model, it is a good idea to set the
-
# <tt>:inverse_of</tt> option on the +belongs_to+, which will mean that the following example
-
# works correctly (where <tt>tags</tt> is a +has_many+ <tt>:through</tt> association):
-
#
-
# @post = Post.first
-
# @tag = @post.tags.build name: "ruby"
-
# @tag.save
-
#
-
# The last line ought to save the through record (a <tt>Taggable</tt>). This will only work if the
-
# <tt>:inverse_of</tt> is set:
-
#
-
# class Taggable < ActiveRecord::Base
-
# belongs_to :post
-
# belongs_to :tag, inverse_of: :taggings
-
# end
-
#
-
# If you do not set the <tt>:inverse_of</tt> record, the association will
-
# do its best to match itself up with the correct inverse. Automatic
-
# inverse detection only works on <tt>has_many</tt>, <tt>has_one</tt>, and
-
# <tt>belongs_to</tt> associations.
-
#
-
# Extra options on the associations, as defined in the
-
# <tt>AssociationReflection::INVALID_AUTOMATIC_INVERSE_OPTIONS</tt> constant, will
-
# also prevent the association's inverse from being found automatically.
-
#
-
# The automatic guessing of the inverse association uses a heuristic based
-
# on the name of the class, so it may not work for all associations,
-
# especially the ones with non-standard names.
-
#
-
# You can turn off the automatic detection of inverse associations by setting
-
# the <tt>:inverse_of</tt> option to <tt>false</tt> like so:
-
#
-
# class Taggable < ActiveRecord::Base
-
# belongs_to :tag, inverse_of: false
-
# end
-
#
-
# == Nested \Associations
-
#
-
# You can actually specify *any* association with the <tt>:through</tt> option, including an
-
# association which has a <tt>:through</tt> option itself. For example:
-
#
-
# class Author < ActiveRecord::Base
-
# has_many :posts
-
# has_many :comments, through: :posts
-
# has_many :commenters, through: :comments
-
# end
-
#
-
# class Post < ActiveRecord::Base
-
# has_many :comments
-
# end
-
#
-
# class Comment < ActiveRecord::Base
-
# belongs_to :commenter
-
# end
-
#
-
# @author = Author.first
-
# @author.commenters # => People who commented on posts written by the author
-
#
-
# An equivalent way of setting up this association this would be:
-
#
-
# class Author < ActiveRecord::Base
-
# has_many :posts
-
# has_many :commenters, through: :posts
-
# end
-
#
-
# class Post < ActiveRecord::Base
-
# has_many :comments
-
# has_many :commenters, through: :comments
-
# end
-
#
-
# class Comment < ActiveRecord::Base
-
# belongs_to :commenter
-
# end
-
#
-
# When using nested association, you will not be able to modify the association because there
-
# is not enough information to know what modification to make. For example, if you tried to
-
# add a <tt>Commenter</tt> in the example above, there would be no way to tell how to set up the
-
# intermediate <tt>Post</tt> and <tt>Comment</tt> objects.
-
#
-
# == Polymorphic \Associations
-
#
-
# Polymorphic associations on models are not restricted on what types of models they
-
# can be associated with. Rather, they specify an interface that a +has_many+ association
-
# must adhere to.
-
#
-
# class Asset < ActiveRecord::Base
-
# belongs_to :attachable, polymorphic: true
-
# end
-
#
-
# class Post < ActiveRecord::Base
-
# has_many :assets, as: :attachable # The :as option specifies the polymorphic interface to use.
-
# end
-
#
-
# @asset.attachable = @post
-
#
-
# This works by using a type column in addition to a foreign key to specify the associated
-
# record. In the Asset example, you'd need an +attachable_id+ integer column and an
-
# +attachable_type+ string column.
-
#
-
# Using polymorphic associations in combination with single table inheritance (STI) is
-
# a little tricky. In order for the associations to work as expected, ensure that you
-
# store the base model for the STI models in the type column of the polymorphic
-
# association. To continue with the asset example above, suppose there are guest posts
-
# and member posts that use the posts table for STI. In this case, there must be a +type+
-
# column in the posts table.
-
#
-
# Note: The <tt>attachable_type=</tt> method is being called when assigning an +attachable+.
-
# The +class_name+ of the +attachable+ is passed as a String.
-
#
-
# class Asset < ActiveRecord::Base
-
# belongs_to :attachable, polymorphic: true
-
#
-
# def attachable_type=(class_name)
-
# super(class_name.constantize.base_class.to_s)
-
# end
-
# end
-
#
-
# class Post < ActiveRecord::Base
-
# # because we store "Post" in attachable_type now dependent: :destroy will work
-
# has_many :assets, as: :attachable, dependent: :destroy
-
# end
-
#
-
# class GuestPost < Post
-
# end
-
#
-
# class MemberPost < Post
-
# end
-
#
-
# == Caching
-
#
-
# All of the methods are built on a simple caching principle that will keep the result
-
# of the last query around unless specifically instructed not to. The cache is even
-
# shared across methods to make it even cheaper to use the macro-added methods without
-
# worrying too much about performance at the first go.
-
#
-
# project.milestones # fetches milestones from the database
-
# project.milestones.size # uses the milestone cache
-
# project.milestones.empty? # uses the milestone cache
-
# project.milestones(true).size # fetches milestones from the database
-
# project.milestones # uses the milestone cache
-
#
-
# == Eager loading of associations
-
#
-
# Eager loading is a way to find objects of a certain class and a number of named associations.
-
# This is one of the easiest ways of to prevent the dreaded 1+N problem in which fetching 100
-
# posts that each need to display their author triggers 101 database queries. Through the
-
# use of eager loading, the 101 queries can be reduced to 2.
-
#
-
# class Post < ActiveRecord::Base
-
# belongs_to :author
-
# has_many :comments
-
# end
-
#
-
# Consider the following loop using the class above:
-
#
-
# Post.all.each do |post|
-
# puts "Post: " + post.title
-
# puts "Written by: " + post.author.name
-
# puts "Last comment on: " + post.comments.first.created_on
-
# end
-
#
-
# To iterate over these one hundred posts, we'll generate 201 database queries. Let's
-
# first just optimize it for retrieving the author:
-
#
-
# Post.includes(:author).each do |post|
-
#
-
# This references the name of the +belongs_to+ association that also used the <tt>:author</tt>
-
# symbol. After loading the posts, find will collect the +author_id+ from each one and load
-
# all the referenced authors with one query. Doing so will cut down the number of queries
-
# from 201 to 102.
-
#
-
# We can improve upon the situation further by referencing both associations in the finder with:
-
#
-
# Post.includes(:author, :comments).each do |post|
-
#
-
# This will load all comments with a single query. This reduces the total number of queries
-
# to 3. More generally the number of queries will be 1 plus the number of associations
-
# named (except if some of the associations are polymorphic +belongs_to+ - see below).
-
#
-
# To include a deep hierarchy of associations, use a hash:
-
#
-
# Post.includes(:author, {comments: {author: :gravatar}}).each do |post|
-
#
-
# That'll grab not only all the comments but all their authors and gravatar pictures.
-
# You can mix and match symbols, arrays and hashes in any combination to describe the
-
# associations you want to load.
-
#
-
# All of this power shouldn't fool you into thinking that you can pull out huge amounts
-
# of data with no performance penalty just because you've reduced the number of queries.
-
# The database still needs to send all the data to Active Record and it still needs to
-
# be processed. So it's no catch-all for performance problems, but it's a great way to
-
# cut down on the number of queries in a situation as the one described above.
-
#
-
# Since only one table is loaded at a time, conditions or orders cannot reference tables
-
# other than the main one. If this is the case Active Record falls back to the previously
-
# used LEFT OUTER JOIN based strategy. For example
-
#
-
# Post.includes([:author, :comments]).where(['comments.approved = ?', true])
-
#
-
# This will result in a single SQL query with joins along the lines of:
-
# <tt>LEFT OUTER JOIN comments ON comments.post_id = posts.id</tt> and
-
# <tt>LEFT OUTER JOIN authors ON authors.id = posts.author_id</tt>. Note that using conditions
-
# like this can have unintended consequences.
-
# In the above example posts with no approved comments are not returned at all, because
-
# the conditions apply to the SQL statement as a whole and not just to the association.
-
#
-
# If you want to load all posts (including posts with no approved comments) then write
-
# your own LEFT OUTER JOIN query using ON
-
#
-
# Post.joins('LEFT OUTER JOIN comments ON comments.post_id = posts.id AND comments.approved = true')
-
#
-
# You must disambiguate column references for this fallback to happen, for example
-
# <tt>order: "author.name DESC"</tt> will work but <tt>order: "name DESC"</tt> will not.
-
#
-
# If you do want eager load only some members of an association it is usually more natural
-
# to include an association which has conditions defined on it:
-
#
-
# class Post < ActiveRecord::Base
-
# has_many :approved_comments, -> { where approved: true }, class_name: 'Comment'
-
# end
-
#
-
# Post.includes(:approved_comments)
-
#
-
# This will load posts and eager load the +approved_comments+ association, which contains
-
# only those comments that have been approved.
-
#
-
# If you eager load an association with a specified <tt>:limit</tt> option, it will be ignored,
-
# returning all the associated objects:
-
#
-
# class Picture < ActiveRecord::Base
-
# has_many :most_recent_comments, -> { order('id DESC').limit(10) }, class_name: 'Comment'
-
# end
-
#
-
# Picture.includes(:most_recent_comments).first.most_recent_comments # => returns all associated comments.
-
#
-
# Eager loading is supported with polymorphic associations.
-
#
-
# class Address < ActiveRecord::Base
-
# belongs_to :addressable, polymorphic: true
-
# end
-
#
-
# A call that tries to eager load the addressable model
-
#
-
# Address.includes(:addressable)
-
#
-
# This will execute one query to load the addresses and load the addressables with one
-
# query per addressable type.
-
# For example if all the addressables are either of class Person or Company then a total
-
# of 3 queries will be executed. The list of addressable types to load is determined on
-
# the back of the addresses loaded. This is not supported if Active Record has to fallback
-
# to the previous implementation of eager loading and will raise <tt>ActiveRecord::EagerLoadPolymorphicError</tt>.
-
# The reason is that the parent model's type is a column value so its corresponding table
-
# name cannot be put in the +FROM+/+JOIN+ clauses of that query.
-
#
-
# == Table Aliasing
-
#
-
# Active Record uses table aliasing in the case that a table is referenced multiple times
-
# in a join. If a table is referenced only once, the standard table name is used. The
-
# second time, the table is aliased as <tt>#{reflection_name}_#{parent_table_name}</tt>.
-
# Indexes are appended for any more successive uses of the table name.
-
#
-
# Post.joins(:comments)
-
# # => SELECT ... FROM posts INNER JOIN comments ON ...
-
# Post.joins(:special_comments) # STI
-
# # => SELECT ... FROM posts INNER JOIN comments ON ... AND comments.type = 'SpecialComment'
-
# Post.joins(:comments, :special_comments) # special_comments is the reflection name, posts is the parent table name
-
# # => SELECT ... FROM posts INNER JOIN comments ON ... INNER JOIN comments special_comments_posts
-
#
-
# Acts as tree example:
-
#
-
# TreeMixin.joins(:children)
-
# # => SELECT ... FROM mixins INNER JOIN mixins childrens_mixins ...
-
# TreeMixin.joins(children: :parent)
-
# # => SELECT ... FROM mixins INNER JOIN mixins childrens_mixins ...
-
# INNER JOIN parents_mixins ...
-
# TreeMixin.joins(children: {parent: :children})
-
# # => SELECT ... FROM mixins INNER JOIN mixins childrens_mixins ...
-
# INNER JOIN parents_mixins ...
-
# INNER JOIN mixins childrens_mixins_2
-
#
-
# Has and Belongs to Many join tables use the same idea, but add a <tt>_join</tt> suffix:
-
#
-
# Post.joins(:categories)
-
# # => SELECT ... FROM posts INNER JOIN categories_posts ... INNER JOIN categories ...
-
# Post.joins(categories: :posts)
-
# # => SELECT ... FROM posts INNER JOIN categories_posts ... INNER JOIN categories ...
-
# INNER JOIN categories_posts posts_categories_join INNER JOIN posts posts_categories
-
# Post.joins(categories: {posts: :categories})
-
# # => SELECT ... FROM posts INNER JOIN categories_posts ... INNER JOIN categories ...
-
# INNER JOIN categories_posts posts_categories_join INNER JOIN posts posts_categories
-
# INNER JOIN categories_posts categories_posts_join INNER JOIN categories categories_posts_2
-
#
-
# If you wish to specify your own custom joins using <tt>joins</tt> method, those table
-
# names will take precedence over the eager associations:
-
#
-
# Post.joins(:comments).joins("inner join comments ...")
-
# # => SELECT ... FROM posts INNER JOIN comments_posts ON ... INNER JOIN comments ...
-
# Post.joins(:comments, :special_comments).joins("inner join comments ...")
-
# # => SELECT ... FROM posts INNER JOIN comments comments_posts ON ...
-
# INNER JOIN comments special_comments_posts ...
-
# INNER JOIN comments ...
-
#
-
# Table aliases are automatically truncated according to the maximum length of table identifiers
-
# according to the specific database.
-
#
-
# == Modules
-
#
-
# By default, associations will look for objects within the current module scope. Consider:
-
#
-
# module MyApplication
-
# module Business
-
# class Firm < ActiveRecord::Base
-
# has_many :clients
-
# end
-
#
-
# class Client < ActiveRecord::Base; end
-
# end
-
# end
-
#
-
# When <tt>Firm#clients</tt> is called, it will in turn call
-
# <tt>MyApplication::Business::Client.find_all_by_firm_id(firm.id)</tt>.
-
# If you want to associate with a class in another module scope, this can be done by
-
# specifying the complete class name.
-
#
-
# module MyApplication
-
# module Business
-
# class Firm < ActiveRecord::Base; end
-
# end
-
#
-
# module Billing
-
# class Account < ActiveRecord::Base
-
# belongs_to :firm, class_name: "MyApplication::Business::Firm"
-
# end
-
# end
-
# end
-
#
-
# == Bi-directional associations
-
#
-
# When you specify an association there is usually an association on the associated model
-
# that specifies the same relationship in reverse. For example, with the following models:
-
#
-
# class Dungeon < ActiveRecord::Base
-
# has_many :traps
-
# has_one :evil_wizard
-
# end
-
#
-
# class Trap < ActiveRecord::Base
-
# belongs_to :dungeon
-
# end
-
#
-
# class EvilWizard < ActiveRecord::Base
-
# belongs_to :dungeon
-
# end
-
#
-
# The +traps+ association on +Dungeon+ and the +dungeon+ association on +Trap+ are
-
# the inverse of each other and the inverse of the +dungeon+ association on +EvilWizard+
-
# is the +evil_wizard+ association on +Dungeon+ (and vice-versa). By default,
-
# Active Record doesn't know anything about these inverse relationships and so no object
-
# loading optimization is possible. For example:
-
#
-
# d = Dungeon.first
-
# t = d.traps.first
-
# d.level == t.dungeon.level # => true
-
# d.level = 10
-
# d.level == t.dungeon.level # => false
-
#
-
# The +Dungeon+ instances +d+ and <tt>t.dungeon</tt> in the above example refer to
-
# the same object data from the database, but are actually different in-memory copies
-
# of that data. Specifying the <tt>:inverse_of</tt> option on associations lets you tell
-
# Active Record about inverse relationships and it will optimise object loading. For
-
# example, if we changed our model definitions to:
-
#
-
# class Dungeon < ActiveRecord::Base
-
# has_many :traps, inverse_of: :dungeon
-
# has_one :evil_wizard, inverse_of: :dungeon
-
# end
-
#
-
# class Trap < ActiveRecord::Base
-
# belongs_to :dungeon, inverse_of: :traps
-
# end
-
#
-
# class EvilWizard < ActiveRecord::Base
-
# belongs_to :dungeon, inverse_of: :evil_wizard
-
# end
-
#
-
# Then, from our code snippet above, +d+ and <tt>t.dungeon</tt> are actually the same
-
# in-memory instance and our final <tt>d.level == t.dungeon.level</tt> will return +true+.
-
#
-
# There are limitations to <tt>:inverse_of</tt> support:
-
#
-
# * does not work with <tt>:through</tt> associations.
-
# * does not work with <tt>:polymorphic</tt> associations.
-
# * for +belongs_to+ associations +has_many+ inverse associations are ignored.
-
#
-
# == Deleting from associations
-
#
-
# === Dependent associations
-
#
-
# +has_many+, +has_one+ and +belongs_to+ associations support the <tt>:dependent</tt> option.
-
# This allows you to specify that associated records should be deleted when the owner is
-
# deleted.
-
#
-
# For example:
-
#
-
# class Author
-
# has_many :posts, dependent: :destroy
-
# end
-
# Author.find(1).destroy # => Will destroy all of the author's posts, too
-
#
-
# The <tt>:dependent</tt> option can have different values which specify how the deletion
-
# is done. For more information, see the documentation for this option on the different
-
# specific association types. When no option is given, the behavior is to do nothing
-
# with the associated records when destroying a record.
-
#
-
# Note that <tt>:dependent</tt> is implemented using Rails' callback
-
# system, which works by processing callbacks in order. Therefore, other
-
# callbacks declared either before or after the <tt>:dependent</tt> option
-
# can affect what it does.
-
#
-
# === Delete or destroy?
-
#
-
# +has_many+ and +has_and_belongs_to_many+ associations have the methods <tt>destroy</tt>,
-
# <tt>delete</tt>, <tt>destroy_all</tt> and <tt>delete_all</tt>.
-
#
-
# For +has_and_belongs_to_many+, <tt>delete</tt> and <tt>destroy</tt> are the same: they
-
# cause the records in the join table to be removed.
-
#
-
# For +has_many+, <tt>destroy</tt> and <tt>destroy_all</tt> will always call the <tt>destroy</tt> method of the
-
# record(s) being removed so that callbacks are run. However <tt>delete</tt> and <tt>delete_all</tt> will either
-
# do the deletion according to the strategy specified by the <tt>:dependent</tt> option, or
-
# if no <tt>:dependent</tt> option is given, then it will follow the default strategy.
-
# The default strategy is <tt>:nullify</tt> (set the foreign keys to <tt>nil</tt>), except for
-
# +has_many+ <tt>:through</tt>, where the default strategy is <tt>delete_all</tt> (delete
-
# the join records, without running their callbacks).
-
#
-
# There is also a <tt>clear</tt> method which is the same as <tt>delete_all</tt>, except that
-
# it returns the association rather than the records which have been deleted.
-
#
-
# === What gets deleted?
-
#
-
# There is a potential pitfall here: +has_and_belongs_to_many+ and +has_many+ <tt>:through</tt>
-
# associations have records in join tables, as well as the associated records. So when we
-
# call one of these deletion methods, what exactly should be deleted?
-
#
-
# The answer is that it is assumed that deletion on an association is about removing the
-
# <i>link</i> between the owner and the associated object(s), rather than necessarily the
-
# associated objects themselves. So with +has_and_belongs_to_many+ and +has_many+
-
# <tt>:through</tt>, the join records will be deleted, but the associated records won't.
-
#
-
# This makes sense if you think about it: if you were to call <tt>post.tags.delete(Tag.find_by(name: 'food'))</tt>
-
# you would want the 'food' tag to be unlinked from the post, rather than for the tag itself
-
# to be removed from the database.
-
#
-
# However, there are examples where this strategy doesn't make sense. For example, suppose
-
# a person has many projects, and each project has many tasks. If we deleted one of a person's
-
# tasks, we would probably not want the project to be deleted. In this scenario, the delete method
-
# won't actually work: it can only be used if the association on the join model is a
-
# +belongs_to+. In other situations you are expected to perform operations directly on
-
# either the associated records or the <tt>:through</tt> association.
-
#
-
# With a regular +has_many+ there is no distinction between the "associated records"
-
# and the "link", so there is only one choice for what gets deleted.
-
#
-
# With +has_and_belongs_to_many+ and +has_many+ <tt>:through</tt>, if you want to delete the
-
# associated records themselves, you can always do something along the lines of
-
# <tt>person.tasks.each(&:destroy)</tt>.
-
#
-
# == Type safety with <tt>ActiveRecord::AssociationTypeMismatch</tt>
-
#
-
# If you attempt to assign an object to an association that doesn't match the inferred
-
# or specified <tt>:class_name</tt>, you'll get an <tt>ActiveRecord::AssociationTypeMismatch</tt>.
-
#
-
# == Options
-
#
-
# All of the association macros can be specialized through options. This makes cases
-
# more complex than the simple and guessable ones possible.
-
2
module ClassMethods
-
# Specifies a one-to-many association. The following methods for retrieval and query of
-
# collections of associated objects will be added:
-
#
-
# [collection(force_reload = false)]
-
# Returns an array of all the associated objects.
-
# An empty array is returned if none are found.
-
# [collection<<(object, ...)]
-
# Adds one or more objects to the collection by setting their foreign keys to the collection's primary key.
-
# Note that this operation instantly fires update SQL without waiting for the save or update call on the
-
# parent object, unless the parent object is a new record.
-
# [collection.delete(object, ...)]
-
# Removes one or more objects from the collection by setting their foreign keys to +NULL+.
-
# Objects will be in addition destroyed if they're associated with <tt>dependent: :destroy</tt>,
-
# and deleted if they're associated with <tt>dependent: :delete_all</tt>.
-
#
-
# If the <tt>:through</tt> option is used, then the join records are deleted (rather than
-
# nullified) by default, but you can specify <tt>dependent: :destroy</tt> or
-
# <tt>dependent: :nullify</tt> to override this.
-
# [collection.destroy(object, ...)]
-
# Removes one or more objects from the collection by running <tt>destroy</tt> on
-
# each record, regardless of any dependent option, ensuring callbacks are run.
-
#
-
# If the <tt>:through</tt> option is used, then the join records are destroyed
-
# instead, not the objects themselves.
-
# [collection=objects]
-
# Replaces the collections content by deleting and adding objects as appropriate. If the <tt>:through</tt>
-
# option is true callbacks in the join models are triggered except destroy callbacks, since deletion is
-
# direct.
-
# [collection_singular_ids]
-
# Returns an array of the associated objects' ids
-
# [collection_singular_ids=ids]
-
# Replace the collection with the objects identified by the primary keys in +ids+. This
-
# method loads the models and calls <tt>collection=</tt>. See above.
-
# [collection.clear]
-
# Removes every object from the collection. This destroys the associated objects if they
-
# are associated with <tt>dependent: :destroy</tt>, deletes them directly from the
-
# database if <tt>dependent: :delete_all</tt>, otherwise sets their foreign keys to +NULL+.
-
# If the <tt>:through</tt> option is true no destroy callbacks are invoked on the join models.
-
# Join models are directly deleted.
-
# [collection.empty?]
-
# Returns +true+ if there are no associated objects.
-
# [collection.size]
-
# Returns the number of associated objects.
-
# [collection.find(...)]
-
# Finds an associated object according to the same rules as <tt>ActiveRecord::Base.find</tt>.
-
# [collection.exists?(...)]
-
# Checks whether an associated object with the given conditions exists.
-
# Uses the same rules as <tt>ActiveRecord::Base.exists?</tt>.
-
# [collection.build(attributes = {}, ...)]
-
# Returns one or more new objects of the collection type that have been instantiated
-
# with +attributes+ and linked to this object through a foreign key, but have not yet
-
# been saved.
-
# [collection.create(attributes = {})]
-
# Returns a new object of the collection type that has been instantiated
-
# with +attributes+, linked to this object through a foreign key, and that has already
-
# been saved (if it passed the validation). *Note*: This only works if the base model
-
# already exists in the DB, not if it is a new (unsaved) record!
-
# [collection.create!(attributes = {})]
-
# Does the same as <tt>collection.create</tt>, but raises <tt>ActiveRecord::RecordInvalid</tt>
-
# if the record is invalid.
-
#
-
# (*Note*: +collection+ is replaced with the symbol passed as the first argument, so
-
# <tt>has_many :clients</tt> would add among others <tt>clients.empty?</tt>.)
-
#
-
# === Example
-
#
-
# A <tt>Firm</tt> class declares <tt>has_many :clients</tt>, which will add:
-
# * <tt>Firm#clients</tt> (similar to <tt>Client.where(firm_id: id)</tt>)
-
# * <tt>Firm#clients<<</tt>
-
# * <tt>Firm#clients.delete</tt>
-
# * <tt>Firm#clients.destroy</tt>
-
# * <tt>Firm#clients=</tt>
-
# * <tt>Firm#client_ids</tt>
-
# * <tt>Firm#client_ids=</tt>
-
# * <tt>Firm#clients.clear</tt>
-
# * <tt>Firm#clients.empty?</tt> (similar to <tt>firm.clients.size == 0</tt>)
-
# * <tt>Firm#clients.size</tt> (similar to <tt>Client.count "firm_id = #{id}"</tt>)
-
# * <tt>Firm#clients.find</tt> (similar to <tt>Client.where(firm_id: id).find(id)</tt>)
-
# * <tt>Firm#clients.exists?(name: 'ACME')</tt> (similar to <tt>Client.exists?(name: 'ACME', firm_id: firm.id)</tt>)
-
# * <tt>Firm#clients.build</tt> (similar to <tt>Client.new("firm_id" => id)</tt>)
-
# * <tt>Firm#clients.create</tt> (similar to <tt>c = Client.new("firm_id" => id); c.save; c</tt>)
-
# * <tt>Firm#clients.create!</tt> (similar to <tt>c = Client.new("firm_id" => id); c.save!</tt>)
-
# The declaration can also include an options hash to specialize the behavior of the association.
-
#
-
# === Options
-
# [:class_name]
-
# Specify the class name of the association. Use it only if that name can't be inferred
-
# from the association name. So <tt>has_many :products</tt> will by default be linked
-
# to the Product class, but if the real class name is SpecialProduct, you'll have to
-
# specify it with this option.
-
# [:foreign_key]
-
# Specify the foreign key used for the association. By default this is guessed to be the name
-
# of this class in lower-case and "_id" suffixed. So a Person class that makes a +has_many+
-
# association will use "person_id" as the default <tt>:foreign_key</tt>.
-
# [:primary_key]
-
# Specify the method that returns the primary key used for the association. By default this is +id+.
-
# [:dependent]
-
# Controls what happens to the associated objects when
-
# their owner is destroyed. Note that these are implemented as
-
# callbacks, and Rails executes callbacks in order. Therefore, other
-
# similar callbacks may affect the <tt>:dependent</tt> behavior, and the
-
# <tt>:dependent</tt> behavior may affect other callbacks.
-
#
-
# * <tt>:destroy</tt> causes all the associated objects to also be destroyed.
-
# * <tt>:delete_all</tt> causes all the associated objects to be deleted directly from the database (so callbacks will not be executed).
-
# * <tt>:nullify</tt> causes the foreign keys to be set to +NULL+. Callbacks are not executed.
-
# * <tt>:restrict_with_exception</tt> causes an exception to be raised if there are any associated records.
-
# * <tt>:restrict_with_error</tt> causes an error to be added to the owner if there are any associated objects.
-
#
-
# If using with the <tt>:through</tt> option, the association on the join model must be
-
# a +belongs_to+, and the records which get deleted are the join records, rather than
-
# the associated records.
-
# [:counter_cache]
-
# This option can be used to configure a custom named <tt>:counter_cache.</tt> You only need this option,
-
# when you customized the name of your <tt>:counter_cache</tt> on the <tt>belongs_to</tt> association.
-
# [:as]
-
# Specifies a polymorphic interface (See <tt>belongs_to</tt>).
-
# [:through]
-
# Specifies an association through which to perform the query. This can be any other type
-
# of association, including other <tt>:through</tt> associations. Options for <tt>:class_name</tt>,
-
# <tt>:primary_key</tt> and <tt>:foreign_key</tt> are ignored, as the association uses the
-
# source reflection.
-
#
-
# If the association on the join model is a +belongs_to+, the collection can be modified
-
# and the records on the <tt>:through</tt> model will be automatically created and removed
-
# as appropriate. Otherwise, the collection is read-only, so you should manipulate the
-
# <tt>:through</tt> association directly.
-
#
-
# If you are going to modify the association (rather than just read from it), then it is
-
# a good idea to set the <tt>:inverse_of</tt> option on the source association on the
-
# join model. This allows associated records to be built which will automatically create
-
# the appropriate join model records when they are saved. (See the 'Association Join Models'
-
# section above.)
-
# [:source]
-
# Specifies the source association name used by <tt>has_many :through</tt> queries.
-
# Only use it if the name cannot be inferred from the association.
-
# <tt>has_many :subscribers, through: :subscriptions</tt> will look for either <tt>:subscribers</tt> or
-
# <tt>:subscriber</tt> on Subscription, unless a <tt>:source</tt> is given.
-
# [:source_type]
-
# Specifies type of the source association used by <tt>has_many :through</tt> queries where the source
-
# association is a polymorphic +belongs_to+.
-
# [:validate]
-
# If +false+, don't validate the associated objects when saving the parent object. true by default.
-
# [:autosave]
-
# If true, always save the associated objects or destroy them if marked for destruction,
-
# when saving the parent object. If false, never save or destroy the associated objects.
-
# By default, only save associated objects that are new records. This option is implemented as a
-
# +before_save+ callback. Because callbacks are run in the order they are defined, associated objects
-
# may need to be explicitly saved in any user-defined +before_save+ callbacks.
-
#
-
# Note that <tt>accepts_nested_attributes_for</tt> sets <tt>:autosave</tt> to <tt>true</tt>.
-
# [:inverse_of]
-
# Specifies the name of the <tt>belongs_to</tt> association on the associated object
-
# that is the inverse of this <tt>has_many</tt> association. Does not work in combination
-
# with <tt>:through</tt> or <tt>:as</tt> options.
-
# See ActiveRecord::Associations::ClassMethods's overview on Bi-directional associations for more detail.
-
#
-
# Option examples:
-
# has_many :comments, -> { order "posted_on" }
-
# has_many :comments, -> { includes :author }
-
# has_many :people, -> { where("deleted = 0").order("name") }, class_name: "Person"
-
# has_many :tracks, -> { order "position" }, dependent: :destroy
-
# has_many :comments, dependent: :nullify
-
# has_many :tags, as: :taggable
-
# has_many :reports, -> { readonly }
-
# has_many :subscribers, through: :subscriptions, source: :user
-
2
def has_many(name, scope = nil, options = {}, &extension)
-
27
reflection = Builder::HasMany.build(self, name, scope, options, &extension)
-
27
Reflection.add_reflection self, name, reflection
-
end
-
-
# Specifies a one-to-one association with another class. This method should only be used
-
# if the other class contains the foreign key. If the current class contains the foreign key,
-
# then you should use +belongs_to+ instead. See also ActiveRecord::Associations::ClassMethods's overview
-
# on when to use +has_one+ and when to use +belongs_to+.
-
#
-
# The following methods for retrieval and query of a single associated object will be added:
-
#
-
# [association(force_reload = false)]
-
# Returns the associated object. +nil+ is returned if none is found.
-
# [association=(associate)]
-
# Assigns the associate object, extracts the primary key, sets it as the foreign key,
-
# and saves the associate object. To avoid database inconsistencies, permanently deletes an existing
-
# associated object when assigning a new one, even if the new one isn't saved to database.
-
# [build_association(attributes = {})]
-
# Returns a new object of the associated type that has been instantiated
-
# with +attributes+ and linked to this object through a foreign key, but has not
-
# yet been saved.
-
# [create_association(attributes = {})]
-
# Returns a new object of the associated type that has been instantiated
-
# with +attributes+, linked to this object through a foreign key, and that
-
# has already been saved (if it passed the validation).
-
# [create_association!(attributes = {})]
-
# Does the same as <tt>create_association</tt>, but raises <tt>ActiveRecord::RecordInvalid</tt>
-
# if the record is invalid.
-
#
-
# (+association+ is replaced with the symbol passed as the first argument, so
-
# <tt>has_one :manager</tt> would add among others <tt>manager.nil?</tt>.)
-
#
-
# === Example
-
#
-
# An Account class declares <tt>has_one :beneficiary</tt>, which will add:
-
# * <tt>Account#beneficiary</tt> (similar to <tt>Beneficiary.where(account_id: id).first</tt>)
-
# * <tt>Account#beneficiary=(beneficiary)</tt> (similar to <tt>beneficiary.account_id = account.id; beneficiary.save</tt>)
-
# * <tt>Account#build_beneficiary</tt> (similar to <tt>Beneficiary.new("account_id" => id)</tt>)
-
# * <tt>Account#create_beneficiary</tt> (similar to <tt>b = Beneficiary.new("account_id" => id); b.save; b</tt>)
-
# * <tt>Account#create_beneficiary!</tt> (similar to <tt>b = Beneficiary.new("account_id" => id); b.save!; b</tt>)
-
#
-
# === Options
-
#
-
# The declaration can also include an options hash to specialize the behavior of the association.
-
#
-
# Options are:
-
# [:class_name]
-
# Specify the class name of the association. Use it only if that name can't be inferred
-
# from the association name. So <tt>has_one :manager</tt> will by default be linked to the Manager class, but
-
# if the real class name is Person, you'll have to specify it with this option.
-
# [:dependent]
-
# Controls what happens to the associated object when
-
# its owner is destroyed:
-
#
-
# * <tt>:destroy</tt> causes the associated object to also be destroyed
-
# * <tt>:delete</tt> causes the associated object to be deleted directly from the database (so callbacks will not execute)
-
# * <tt>:nullify</tt> causes the foreign key to be set to +NULL+. Callbacks are not executed.
-
# * <tt>:restrict_with_exception</tt> causes an exception to be raised if there is an associated record
-
# * <tt>:restrict_with_error</tt> causes an error to be added to the owner if there is an associated object
-
# [:foreign_key]
-
# Specify the foreign key used for the association. By default this is guessed to be the name
-
# of this class in lower-case and "_id" suffixed. So a Person class that makes a +has_one+ association
-
# will use "person_id" as the default <tt>:foreign_key</tt>.
-
# [:primary_key]
-
# Specify the method that returns the primary key used for the association. By default this is +id+.
-
# [:as]
-
# Specifies a polymorphic interface (See <tt>belongs_to</tt>).
-
# [:through]
-
# Specifies a Join Model through which to perform the query. Options for <tt>:class_name</tt>,
-
# <tt>:primary_key</tt>, and <tt>:foreign_key</tt> are ignored, as the association uses the
-
# source reflection. You can only use a <tt>:through</tt> query through a <tt>has_one</tt>
-
# or <tt>belongs_to</tt> association on the join model.
-
# [:source]
-
# Specifies the source association name used by <tt>has_one :through</tt> queries.
-
# Only use it if the name cannot be inferred from the association.
-
# <tt>has_one :favorite, through: :favorites</tt> will look for a
-
# <tt>:favorite</tt> on Favorite, unless a <tt>:source</tt> is given.
-
# [:source_type]
-
# Specifies type of the source association used by <tt>has_one :through</tt> queries where the source
-
# association is a polymorphic +belongs_to+.
-
# [:validate]
-
# If +false+, don't validate the associated object when saving the parent object. +false+ by default.
-
# [:autosave]
-
# If true, always save the associated object or destroy it if marked for destruction,
-
# when saving the parent object. If false, never save or destroy the associated object.
-
# By default, only save the associated object if it's a new record.
-
#
-
# Note that <tt>accepts_nested_attributes_for</tt> sets <tt>:autosave</tt> to <tt>true</tt>.
-
# [:inverse_of]
-
# Specifies the name of the <tt>belongs_to</tt> association on the associated object
-
# that is the inverse of this <tt>has_one</tt> association. Does not work in combination
-
# with <tt>:through</tt> or <tt>:as</tt> options.
-
# See ActiveRecord::Associations::ClassMethods's overview on Bi-directional associations for more detail.
-
#
-
# Option examples:
-
# has_one :credit_card, dependent: :destroy # destroys the associated credit card
-
# has_one :credit_card, dependent: :nullify # updates the associated records foreign
-
# # key value to NULL rather than destroying it
-
# has_one :last_comment, -> { order 'posted_on' }, class_name: "Comment"
-
# has_one :project_manager, -> { where role: 'project_manager' }, class_name: "Person"
-
# has_one :attachment, as: :attachable
-
# has_one :boss, readonly: :true
-
# has_one :club, through: :membership
-
# has_one :primary_address, -> { where primary: true }, through: :addressables, source: :addressable
-
2
def has_one(name, scope = nil, options = {})
-
2
reflection = Builder::HasOne.build(self, name, scope, options)
-
2
Reflection.add_reflection self, name, reflection
-
end
-
-
# Specifies a one-to-one association with another class. This method should only be used
-
# if this class contains the foreign key. If the other class contains the foreign key,
-
# then you should use +has_one+ instead. See also ActiveRecord::Associations::ClassMethods's overview
-
# on when to use +has_one+ and when to use +belongs_to+.
-
#
-
# Methods will be added for retrieval and query for a single associated object, for which
-
# this object holds an id:
-
#
-
# [association(force_reload = false)]
-
# Returns the associated object. +nil+ is returned if none is found.
-
# [association=(associate)]
-
# Assigns the associate object, extracts the primary key, and sets it as the foreign key.
-
# [build_association(attributes = {})]
-
# Returns a new object of the associated type that has been instantiated
-
# with +attributes+ and linked to this object through a foreign key, but has not yet been saved.
-
# [create_association(attributes = {})]
-
# Returns a new object of the associated type that has been instantiated
-
# with +attributes+, linked to this object through a foreign key, and that
-
# has already been saved (if it passed the validation).
-
# [create_association!(attributes = {})]
-
# Does the same as <tt>create_association</tt>, but raises <tt>ActiveRecord::RecordInvalid</tt>
-
# if the record is invalid.
-
#
-
# (+association+ is replaced with the symbol passed as the first argument, so
-
# <tt>belongs_to :author</tt> would add among others <tt>author.nil?</tt>.)
-
#
-
# === Example
-
#
-
# A Post class declares <tt>belongs_to :author</tt>, which will add:
-
# * <tt>Post#author</tt> (similar to <tt>Author.find(author_id)</tt>)
-
# * <tt>Post#author=(author)</tt> (similar to <tt>post.author_id = author.id</tt>)
-
# * <tt>Post#build_author</tt> (similar to <tt>post.author = Author.new</tt>)
-
# * <tt>Post#create_author</tt> (similar to <tt>post.author = Author.new; post.author.save; post.author</tt>)
-
# * <tt>Post#create_author!</tt> (similar to <tt>post.author = Author.new; post.author.save!; post.author</tt>)
-
# The declaration can also include an options hash to specialize the behavior of the association.
-
#
-
# === Options
-
#
-
# [:class_name]
-
# Specify the class name of the association. Use it only if that name can't be inferred
-
# from the association name. So <tt>belongs_to :author</tt> will by default be linked to the Author class, but
-
# if the real class name is Person, you'll have to specify it with this option.
-
# [:foreign_key]
-
# Specify the foreign key used for the association. By default this is guessed to be the name
-
# of the association with an "_id" suffix. So a class that defines a <tt>belongs_to :person</tt>
-
# association will use "person_id" as the default <tt>:foreign_key</tt>. Similarly,
-
# <tt>belongs_to :favorite_person, class_name: "Person"</tt> will use a foreign key
-
# of "favorite_person_id".
-
# [:foreign_type]
-
# Specify the column used to store the associated object's type, if this is a polymorphic
-
# association. By default this is guessed to be the name of the association with a "_type"
-
# suffix. So a class that defines a <tt>belongs_to :taggable, polymorphic: true</tt>
-
# association will use "taggable_type" as the default <tt>:foreign_type</tt>.
-
# [:primary_key]
-
# Specify the method that returns the primary key of associated object used for the association.
-
# By default this is id.
-
# [:dependent]
-
# If set to <tt>:destroy</tt>, the associated object is destroyed when this object is. If set to
-
# <tt>:delete</tt>, the associated object is deleted *without* calling its destroy method.
-
# This option should not be specified when <tt>belongs_to</tt> is used in conjunction with
-
# a <tt>has_many</tt> relationship on another class because of the potential to leave
-
# orphaned records behind.
-
# [:counter_cache]
-
# Caches the number of belonging objects on the associate class through the use of +increment_counter+
-
# and +decrement_counter+. The counter cache is incremented when an object of this
-
# class is created and decremented when it's destroyed. This requires that a column
-
# named <tt>#{table_name}_count</tt> (such as +comments_count+ for a belonging Comment class)
-
# is used on the associate class (such as a Post class) - that is the migration for
-
# <tt>#{table_name}_count</tt> is created on the associate class (such that <tt>Post.comments_count</tt> will
-
# return the count cached, see note below). You can also specify a custom counter
-
# cache column by providing a column name instead of a +true+/+false+ value to this
-
# option (e.g., <tt>counter_cache: :my_custom_counter</tt>.)
-
# Note: Specifying a counter cache will add it to that model's list of readonly attributes
-
# using +attr_readonly+.
-
# [:polymorphic]
-
# Specify this association is a polymorphic association by passing +true+.
-
# Note: If you've enabled the counter cache, then you may want to add the counter cache attribute
-
# to the +attr_readonly+ list in the associated classes (e.g. <tt>class Post; attr_readonly :comments_count; end</tt>).
-
# [:validate]
-
# If +false+, don't validate the associated objects when saving the parent object. +false+ by default.
-
# [:autosave]
-
# If true, always save the associated object or destroy it if marked for destruction, when
-
# saving the parent object.
-
# If false, never save or destroy the associated object.
-
# By default, only save the associated object if it's a new record.
-
#
-
# Note that <tt>accepts_nested_attributes_for</tt> sets <tt>:autosave</tt> to <tt>true</tt>.
-
# [:touch]
-
# If true, the associated object will be touched (the updated_at/on attributes set to now)
-
# when this record is either saved or destroyed. If you specify a symbol, that attribute
-
# will be updated with the current time in addition to the updated_at/on attribute.
-
# [:inverse_of]
-
# Specifies the name of the <tt>has_one</tt> or <tt>has_many</tt> association on the associated
-
# object that is the inverse of this <tt>belongs_to</tt> association. Does not work in
-
# combination with the <tt>:polymorphic</tt> options.
-
# See ActiveRecord::Associations::ClassMethods's overview on Bi-directional associations for more detail.
-
#
-
# Option examples:
-
# belongs_to :firm, foreign_key: "client_of"
-
# belongs_to :person, primary_key: "name", foreign_key: "person_name"
-
# belongs_to :author, class_name: "Person", foreign_key: "author_id"
-
# belongs_to :valid_coupon, ->(o) { where "discounts > ?", o.payments_count },
-
# class_name: "Coupon", foreign_key: "coupon_id"
-
# belongs_to :attachable, polymorphic: true
-
# belongs_to :project, readonly: true
-
# belongs_to :post, counter_cache: true
-
# belongs_to :company, touch: true
-
# belongs_to :company, touch: :employees_last_updated_at
-
2
def belongs_to(name, scope = nil, options = {})
-
12
reflection = Builder::BelongsTo.build(self, name, scope, options)
-
12
Reflection.add_reflection self, name, reflection
-
end
-
-
# Specifies a many-to-many relationship with another class. This associates two classes via an
-
# intermediate join table. Unless the join table is explicitly specified as an option, it is
-
# guessed using the lexical order of the class names. So a join between Developer and Project
-
# will give the default join table name of "developers_projects" because "D" precedes "P" alphabetically.
-
# Note that this precedence is calculated using the <tt><</tt> operator for String. This
-
# means that if the strings are of different lengths, and the strings are equal when compared
-
# up to the shortest length, then the longer string is considered of higher
-
# lexical precedence than the shorter one. For example, one would expect the tables "paper_boxes" and "papers"
-
# to generate a join table name of "papers_paper_boxes" because of the length of the name "paper_boxes",
-
# but it in fact generates a join table name of "paper_boxes_papers". Be aware of this caveat, and use the
-
# custom <tt>:join_table</tt> option if you need to.
-
# If your tables share a common prefix, it will only appear once at the beginning. For example,
-
# the tables "catalog_categories" and "catalog_products" generate a join table name of "catalog_categories_products".
-
#
-
# The join table should not have a primary key or a model associated with it. You must manually generate the
-
# join table with a migration such as this:
-
#
-
# class CreateDevelopersProjectsJoinTable < ActiveRecord::Migration
-
# def change
-
# create_table :developers_projects, id: false do |t|
-
# t.integer :developer_id
-
# t.integer :project_id
-
# end
-
# end
-
# end
-
#
-
# It's also a good idea to add indexes to each of those columns to speed up the joins process.
-
# However, in MySQL it is advised to add a compound index for both of the columns as MySQL only
-
# uses one index per table during the lookup.
-
#
-
# Adds the following methods for retrieval and query:
-
#
-
# [collection(force_reload = false)]
-
# Returns an array of all the associated objects.
-
# An empty array is returned if none are found.
-
# [collection<<(object, ...)]
-
# Adds one or more objects to the collection by creating associations in the join table
-
# (<tt>collection.push</tt> and <tt>collection.concat</tt> are aliases to this method).
-
# Note that this operation instantly fires update SQL without waiting for the save or update call on the
-
# parent object, unless the parent object is a new record.
-
# [collection.delete(object, ...)]
-
# Removes one or more objects from the collection by removing their associations from the join table.
-
# This does not destroy the objects.
-
# [collection.destroy(object, ...)]
-
# Removes one or more objects from the collection by running destroy on each association in the join table, overriding any dependent option.
-
# This does not destroy the objects.
-
# [collection=objects]
-
# Replaces the collection's content by deleting and adding objects as appropriate.
-
# [collection_singular_ids]
-
# Returns an array of the associated objects' ids.
-
# [collection_singular_ids=ids]
-
# Replace the collection by the objects identified by the primary keys in +ids+.
-
# [collection.clear]
-
# Removes every object from the collection. This does not destroy the objects.
-
# [collection.empty?]
-
# Returns +true+ if there are no associated objects.
-
# [collection.size]
-
# Returns the number of associated objects.
-
# [collection.find(id)]
-
# Finds an associated object responding to the +id+ and that
-
# meets the condition that it has to be associated with this object.
-
# Uses the same rules as <tt>ActiveRecord::Base.find</tt>.
-
# [collection.exists?(...)]
-
# Checks whether an associated object with the given conditions exists.
-
# Uses the same rules as <tt>ActiveRecord::Base.exists?</tt>.
-
# [collection.build(attributes = {})]
-
# Returns a new object of the collection type that has been instantiated
-
# with +attributes+ and linked to this object through the join table, but has not yet been saved.
-
# [collection.create(attributes = {})]
-
# Returns a new object of the collection type that has been instantiated
-
# with +attributes+, linked to this object through the join table, and that has already been
-
# saved (if it passed the validation).
-
#
-
# (+collection+ is replaced with the symbol passed as the first argument, so
-
# <tt>has_and_belongs_to_many :categories</tt> would add among others <tt>categories.empty?</tt>.)
-
#
-
# === Example
-
#
-
# A Developer class declares <tt>has_and_belongs_to_many :projects</tt>, which will add:
-
# * <tt>Developer#projects</tt>
-
# * <tt>Developer#projects<<</tt>
-
# * <tt>Developer#projects.delete</tt>
-
# * <tt>Developer#projects.destroy</tt>
-
# * <tt>Developer#projects=</tt>
-
# * <tt>Developer#project_ids</tt>
-
# * <tt>Developer#project_ids=</tt>
-
# * <tt>Developer#projects.clear</tt>
-
# * <tt>Developer#projects.empty?</tt>
-
# * <tt>Developer#projects.size</tt>
-
# * <tt>Developer#projects.find(id)</tt>
-
# * <tt>Developer#projects.exists?(...)</tt>
-
# * <tt>Developer#projects.build</tt> (similar to <tt>Project.new("developer_id" => id)</tt>)
-
# * <tt>Developer#projects.create</tt> (similar to <tt>c = Project.new("developer_id" => id); c.save; c</tt>)
-
# The declaration may include an options hash to specialize the behavior of the association.
-
#
-
# === Options
-
#
-
# [:class_name]
-
# Specify the class name of the association. Use it only if that name can't be inferred
-
# from the association name. So <tt>has_and_belongs_to_many :projects</tt> will by default be linked to the
-
# Project class, but if the real class name is SuperProject, you'll have to specify it with this option.
-
# [:join_table]
-
# Specify the name of the join table if the default based on lexical order isn't what you want.
-
# <b>WARNING:</b> If you're overwriting the table name of either class, the +table_name+ method
-
# MUST be declared underneath any +has_and_belongs_to_many+ declaration in order to work.
-
# [:foreign_key]
-
# Specify the foreign key used for the association. By default this is guessed to be the name
-
# of this class in lower-case and "_id" suffixed. So a Person class that makes
-
# a +has_and_belongs_to_many+ association to Project will use "person_id" as the
-
# default <tt>:foreign_key</tt>.
-
# [:association_foreign_key]
-
# Specify the foreign key used for the association on the receiving side of the association.
-
# By default this is guessed to be the name of the associated class in lower-case and "_id" suffixed.
-
# So if a Person class makes a +has_and_belongs_to_many+ association to Project,
-
# the association will use "project_id" as the default <tt>:association_foreign_key</tt>.
-
# [:readonly]
-
# If true, all the associated objects are readonly through the association.
-
# [:validate]
-
# If +false+, don't validate the associated objects when saving the parent object. +true+ by default.
-
# [:autosave]
-
# If true, always save the associated objects or destroy them if marked for destruction, when
-
# saving the parent object.
-
# If false, never save or destroy the associated objects.
-
# By default, only save associated objects that are new records.
-
#
-
# Note that <tt>accepts_nested_attributes_for</tt> sets <tt>:autosave</tt> to <tt>true</tt>.
-
#
-
# Option examples:
-
# has_and_belongs_to_many :projects
-
# has_and_belongs_to_many :projects, -> { includes :milestones, :manager }
-
# has_and_belongs_to_many :nations, class_name: "Country"
-
# has_and_belongs_to_many :categories, join_table: "prods_cats"
-
# has_and_belongs_to_many :categories, -> { readonly }
-
2
def has_and_belongs_to_many(name, scope = nil, options = {}, &extension)
-
if scope.is_a?(Hash)
-
options = scope
-
scope = nil
-
end
-
-
habtm_reflection = ActiveRecord::Reflection::AssociationReflection.new(:has_and_belongs_to_many, name, scope, options, self)
-
-
builder = Builder::HasAndBelongsToMany.new name, self, options
-
-
join_model = builder.through_model
-
-
# FIXME: we should move this to the internal constants. Also people
-
# should never directly access this constant so I'm not happy about
-
# setting it.
-
const_set join_model.name, join_model
-
-
middle_reflection = builder.middle_reflection join_model
-
-
Builder::HasMany.define_callbacks self, middle_reflection
-
Reflection.add_reflection self, middle_reflection.name, middle_reflection
-
middle_reflection.parent_reflection = [name.to_sym, habtm_reflection]
-
-
include Module.new {
-
class_eval <<-RUBY, __FILE__, __LINE__ + 1
-
def destroy_associations
-
association(:#{middle_reflection.name}).delete_all(:delete_all)
-
association(:#{name}).reset
-
super
-
end
-
RUBY
-
}
-
-
hm_options = {}
-
hm_options[:through] = middle_reflection.name
-
hm_options[:source] = join_model.right_reflection.name
-
-
[:before_add, :after_add, :before_remove, :after_remove, :autosave, :validate, :join_table].each do |k|
-
hm_options[k] = options[k] if options.key? k
-
end
-
-
has_many name, scope, hm_options, &extension
-
self._reflections[name.to_sym].parent_reflection = [name.to_sym, habtm_reflection]
-
end
-
end
-
end
-
end
-
2
require 'active_support/core_ext/string/conversions'
-
-
2
module ActiveRecord
-
2
module Associations
-
# Keeps track of table aliases for ActiveRecord::Associations::ClassMethods::JoinDependency and
-
# ActiveRecord::Associations::ThroughAssociationScope
-
2
class AliasTracker # :nodoc:
-
2
attr_reader :aliases, :connection
-
-
2
def self.empty(connection)
-
462
new connection, Hash.new(0)
-
end
-
-
2
def self.create(connection, table_joins)
-
390
if table_joins.empty?
-
390
empty connection
-
else
-
aliases = Hash.new { |h,k|
-
h[k] = initial_count_for(connection, k, table_joins)
-
}
-
new connection, aliases
-
end
-
end
-
-
2
def self.initial_count_for(connection, name, table_joins)
-
# quoted_name should be downcased as some database adapters (Oracle) return quoted name in uppercase
-
quoted_name = connection.quote_table_name(name).downcase
-
-
counts = table_joins.map do |join|
-
if join.is_a?(Arel::Nodes::StringJoin)
-
# Table names + table aliases
-
join.left.downcase.scan(
-
/join(?:\s+\w+)?\s+(\S+\s+)?#{quoted_name}\son/
-
).size
-
elsif join.respond_to? :left
-
join.left.table_name == name ? 1 : 0
-
else
-
# this branch is reached by two tests:
-
#
-
# activerecord/test/cases/associations/cascaded_eager_loading_test.rb:37
-
# with :posts
-
#
-
# activerecord/test/cases/associations/eager_test.rb:1133
-
# with :comments
-
#
-
0
-
end
-
end
-
-
counts.sum
-
end
-
-
# table_joins is an array of arel joins which might conflict with the aliases we assign here
-
2
def initialize(connection, aliases)
-
462
@aliases = aliases
-
462
@connection = connection
-
end
-
-
2
def aliased_table_for(table_name, aliased_name)
-
72
table_alias = aliased_name_for(table_name, aliased_name)
-
-
72
if table_alias == table_name
-
72
Arel::Table.new(table_name)
-
else
-
Arel::Table.new(table_name).alias(table_alias)
-
end
-
end
-
-
2
def aliased_name_for(table_name, aliased_name)
-
462
if aliases[table_name].zero?
-
# If it's zero, we can have our table_name
-
462
aliases[table_name] = 1
-
462
table_name
-
else
-
# Otherwise, we need to use an alias
-
aliased_name = connection.table_alias_for(aliased_name)
-
-
# Update the count
-
aliases[aliased_name] += 1
-
-
if aliases[aliased_name] > 1
-
"#{truncate(aliased_name)}_#{aliases[aliased_name]}"
-
else
-
aliased_name
-
end
-
end
-
end
-
-
2
private
-
-
2
def truncate(name)
-
name.slice(0, connection.table_alias_length - 2)
-
end
-
end
-
end
-
end
-
1
require 'active_support/core_ext/array/wrap'
-
-
1
module ActiveRecord
-
1
module Associations
-
# = Active Record Associations
-
#
-
# This is the root class of all associations ('+ Foo' signifies an included module Foo):
-
#
-
# Association
-
# SingularAssociation
-
# HasOneAssociation
-
# HasOneThroughAssociation + ThroughAssociation
-
# BelongsToAssociation
-
# BelongsToPolymorphicAssociation
-
# CollectionAssociation
-
# HasManyAssociation
-
# HasManyThroughAssociation + ThroughAssociation
-
1
class Association #:nodoc:
-
1
attr_reader :owner, :target, :reflection
-
1
attr_accessor :inversed
-
-
1
delegate :options, :to => :reflection
-
-
1
def initialize(owner, reflection)
-
216
reflection.check_validity!
-
-
216
@owner, @reflection = owner, reflection
-
-
216
reset
-
216
reset_scope
-
end
-
-
# Returns the name of the table of the associated class:
-
#
-
# post.comments.aliased_table_name # => "comments"
-
#
-
1
def aliased_table_name
-
klass.table_name
-
end
-
-
# Resets the \loaded flag to +false+ and sets the \target to +nil+.
-
1
def reset
-
216
@loaded = false
-
216
@target = nil
-
216
@stale_state = nil
-
216
@inversed = false
-
end
-
-
# Reloads the \target and returns +self+ on success.
-
1
def reload
-
reset
-
reset_scope
-
load_target
-
self unless target.nil?
-
end
-
-
# Has the \target been already \loaded?
-
1
def loaded?
-
360
@loaded
-
end
-
-
# Asserts the \target has been loaded setting the \loaded flag to +true+.
-
1
def loaded!
-
144
@loaded = true
-
144
@stale_state = stale_state
-
144
@inversed = false
-
end
-
-
# The target is stale if the target no longer points to the record(s) that the
-
# relevant foreign_key(s) refers to. If stale, the association accessor method
-
# on the owner will reload the target. It's up to subclasses to implement the
-
# stale_state method if relevant.
-
#
-
# Note that if the target has not been loaded, it is not considered stale.
-
1
def stale_target?
-
72
!inversed && loaded? && @stale_state != stale_state
-
end
-
-
# Sets the target of this association to <tt>\target</tt>, and the \loaded flag to +true+.
-
1
def target=(target)
-
144
@target = target
-
144
loaded!
-
end
-
-
1
def scope
-
144
target_scope.merge(association_scope)
-
end
-
-
# The scope for this association.
-
#
-
# Note that the association_scope is merged into the target_scope only when the
-
# scope method is called. This is because at that point the call may be surrounded
-
# by scope.scoping { ... } or with_scope { ... } etc, which affects the scope which
-
# actually gets built.
-
1
def association_scope
-
216
if klass
-
216
@association_scope ||= AssociationScope.scope(self, klass.connection)
-
end
-
end
-
-
1
def reset_scope
-
216
@association_scope = nil
-
end
-
-
# Set the inverse association, if possible
-
1
def set_inverse_instance(record)
-
216
if invertible_for?(record)
-
inverse = record.association(inverse_reflection_for(record).name)
-
inverse.target = owner
-
inverse.inversed = true
-
end
-
216
record
-
end
-
-
# Returns the class of the target. belongs_to polymorphic overrides this to look at the
-
# polymorphic_type field on the owner.
-
1
def klass
-
864
reflection.klass
-
end
-
-
# Can be overridden (i.e. in ThroughAssociation) to merge in other scopes (i.e. the
-
# through association's scope)
-
1
def target_scope
-
144
AssociationRelation.create(klass, klass.arel_table, self).merge!(klass.all)
-
end
-
-
# Loads the \target if needed and returns it.
-
#
-
# This method is abstract in the sense that it relies on +find_target+,
-
# which is expected to be provided by descendants.
-
#
-
# If the \target is already \loaded it is just returned. Thus, you can call
-
# +load_target+ unconditionally to get the \target.
-
#
-
# ActiveRecord::RecordNotFound is rescued within the method, and it is
-
# not reraised. The proxy is \reset and +nil+ is the return value.
-
1
def load_target
-
144
@target = find_target if (@stale_state && stale_target?) || find_target?
-
-
144
loaded! unless loaded?
-
144
target
-
rescue ActiveRecord::RecordNotFound
-
reset
-
end
-
-
1
def interpolate(sql, record = nil)
-
if sql.respond_to?(:to_proc)
-
owner.instance_exec(record, &sql)
-
else
-
sql
-
end
-
end
-
-
# We can't dump @reflection since it contains the scope proc
-
1
def marshal_dump
-
ivars = (instance_variables - [:@reflection]).map { |name| [name, instance_variable_get(name)] }
-
[@reflection.name, ivars]
-
end
-
-
1
def marshal_load(data)
-
reflection_name, ivars = data
-
ivars.each { |name, val| instance_variable_set(name, val) }
-
@reflection = @owner.class._reflect_on_association(reflection_name)
-
end
-
-
1
def initialize_attributes(record) #:nodoc:
-
72
skip_assign = [reflection.foreign_key, reflection.type].compact
-
72
attributes = create_scope.except(*(record.changed - skip_assign))
-
72
record.assign_attributes(attributes)
-
72
set_inverse_instance(record)
-
end
-
-
1
private
-
-
1
def find_target?
-
!loaded? && (!owner.new_record? || foreign_key_present?) && klass
-
end
-
-
1
def creation_attributes
-
72
attributes = {}
-
-
72
if (reflection.macro == :has_one || reflection.macro == :has_many) && !options[:through]
-
72
attributes[reflection.foreign_key] = owner[reflection.active_record_primary_key]
-
-
72
if reflection.options[:as]
-
72
attributes[reflection.type] = owner.class.base_class.name
-
end
-
end
-
-
72
attributes
-
end
-
-
# Sets the owner attributes on the given record
-
1
def set_owner_attributes(record)
-
216
creation_attributes.each { |key, value| record[key] = value }
-
end
-
-
# Returns true if there is a foreign key present on the owner which
-
# references the target. This is used to determine whether we can load
-
# the target if the owner is currently a new record (and therefore
-
# without a key). If the owner is a new record then foreign_key must
-
# be present in order to load target.
-
#
-
# Currently implemented by belongs_to (vanilla and polymorphic) and
-
# has_one/has_many :through associations which go through a belongs_to.
-
1
def foreign_key_present?
-
false
-
end
-
-
# Raises ActiveRecord::AssociationTypeMismatch unless +record+ is of
-
# the kind of the class of the associated objects. Meant to be used as
-
# a sanity check when you are about to assign an associated record.
-
1
def raise_on_type_mismatch!(record)
-
unless record.is_a?(reflection.klass) || record.is_a?(reflection.class_name.constantize)
-
message = "#{reflection.class_name}(##{reflection.klass.object_id}) expected, got #{record.class}(##{record.class.object_id})"
-
raise ActiveRecord::AssociationTypeMismatch, message
-
end
-
end
-
-
# Can be redefined by subclasses, notably polymorphic belongs_to
-
# The record parameter is necessary to support polymorphic inverses as we must check for
-
# the association in the specific class of the record.
-
1
def inverse_reflection_for(record)
-
216
reflection.inverse_of
-
end
-
-
# Returns true if inverse association on the given record needs to be set.
-
# This method is redefined by subclasses.
-
1
def invertible_for?(record)
-
216
foreign_key_for?(record) && inverse_reflection_for(record)
-
end
-
-
# Returns true if record contains the foreign_key
-
1
def foreign_key_for?(record)
-
216
record.has_attribute?(reflection.foreign_key)
-
end
-
-
# This should be implemented to return the values of the relevant key(s) on the owner,
-
# so that when stale_state is different from the value stored on the last find_target,
-
# the target is stale.
-
#
-
# This is only relevant to certain associations, which is why it returns nil by default.
-
1
def stale_state
-
end
-
-
1
def build_record(attributes)
-
72
reflection.build_association(attributes) do |record|
-
72
initialize_attributes(record)
-
end
-
end
-
end
-
end
-
end
-
1
module ActiveRecord
-
1
module Associations
-
1
class AssociationScope #:nodoc:
-
1
INSTANCE = new
-
-
1
def self.scope(association, connection)
-
72
INSTANCE.scope association, connection
-
end
-
-
1
def scope(association, connection)
-
72
klass = association.klass
-
72
reflection = association.reflection
-
72
scope = klass.unscoped
-
72
owner = association.owner
-
72
alias_tracker = AliasTracker.empty connection
-
-
72
scope.extending! Array(reflection.options[:extend])
-
72
add_constraints(scope, owner, klass, reflection, alias_tracker)
-
end
-
-
1
def join_type
-
Arel::Nodes::InnerJoin
-
end
-
-
1
private
-
-
1
def construct_tables(chain, klass, refl, alias_tracker)
-
72
chain.map do |reflection|
-
72
alias_tracker.aliased_table_for(
-
table_name_for(reflection, klass, refl),
-
table_alias_for(reflection, refl, reflection != refl)
-
)
-
end
-
end
-
-
1
def table_alias_for(reflection, refl, join = false)
-
72
name = "#{reflection.plural_name}_#{alias_suffix(refl)}"
-
72
name << "_join" if join
-
72
name
-
end
-
-
1
def join(table, constraint)
-
table.create_join(table, table.create_on(constraint), join_type)
-
end
-
-
1
def column_for(table_name, column_name, alias_tracker)
-
144
columns = alias_tracker.connection.schema_cache.columns_hash(table_name)
-
144
columns[column_name]
-
end
-
-
1
def bind_value(scope, column, value, alias_tracker)
-
144
substitute = alias_tracker.connection.substitute_at(
-
column, scope.bind_values.length)
-
144
scope.bind_values += [[column, value]]
-
144
substitute
-
end
-
-
1
def bind(scope, table_name, column_name, value, tracker)
-
144
column = column_for table_name, column_name, tracker
-
144
bind_value scope, column, value, tracker
-
end
-
-
1
def add_constraints(scope, owner, assoc_klass, refl, tracker)
-
72
chain = refl.chain
-
72
scope_chain = refl.scope_chain
-
-
72
tables = construct_tables(chain, assoc_klass, refl, tracker)
-
-
72
chain.each_with_index do |reflection, i|
-
72
table, foreign_table = tables.shift, tables.first
-
-
72
if reflection.source_macro == :belongs_to
-
if reflection.options[:polymorphic]
-
key = reflection.association_primary_key(assoc_klass)
-
else
-
key = reflection.association_primary_key
-
end
-
-
foreign_key = reflection.foreign_key
-
else
-
72
key = reflection.foreign_key
-
72
foreign_key = reflection.active_record_primary_key
-
end
-
-
72
if reflection == chain.last
-
72
bind_val = bind scope, table.table_name, key.to_s, owner[foreign_key], tracker
-
72
scope = scope.where(table[key].eq(bind_val))
-
-
72
if reflection.type
-
72
value = owner.class.base_class.name
-
72
bind_val = bind scope, table.table_name, reflection.type.to_s, value, tracker
-
72
scope = scope.where(table[reflection.type].eq(bind_val))
-
end
-
else
-
constraint = table[key].eq(foreign_table[foreign_key])
-
-
if reflection.type
-
value = chain[i + 1].klass.base_class.name
-
bind_val = bind scope, table.table_name, reflection.type.to_s, value, tracker
-
scope = scope.where(table[reflection.type].eq(bind_val))
-
end
-
-
scope = scope.joins(join(foreign_table, constraint))
-
end
-
-
72
is_first_chain = i == 0
-
72
klass = is_first_chain ? assoc_klass : reflection.klass
-
-
# Exclude the scope of the association itself, because that
-
# was already merged in the #scope method.
-
72
scope_chain[i].each do |scope_chain_item|
-
item = eval_scope(klass, scope_chain_item, owner)
-
-
if scope_chain_item == refl.scope
-
scope.merge! item.except(:where, :includes, :bind)
-
end
-
-
if is_first_chain
-
scope.includes! item.includes_values
-
end
-
-
scope.where_values += item.where_values
-
scope.order_values |= item.order_values
-
end
-
end
-
-
72
scope
-
end
-
-
1
def alias_suffix(refl)
-
72
refl.name
-
end
-
-
1
def table_name_for(reflection, klass, refl)
-
72
if reflection == refl
-
# If this is a polymorphic belongs_to, we want to get the klass from the
-
# association because it depends on the polymorphic_type attribute of
-
# the owner
-
72
klass.table_name
-
else
-
reflection.table_name
-
end
-
end
-
-
1
def eval_scope(klass, scope, owner)
-
if scope.is_a?(Relation)
-
scope
-
else
-
klass.unscoped.instance_exec(owner, &scope)
-
end
-
end
-
end
-
end
-
end
-
1
module ActiveRecord
-
# = Active Record Belongs To Polymorphic Association
-
1
module Associations
-
1
class BelongsToPolymorphicAssociation < BelongsToAssociation #:nodoc:
-
1
def klass
-
type = owner[reflection.foreign_type]
-
type.presence && type.constantize
-
end
-
-
1
private
-
-
1
def replace_keys(record)
-
super
-
owner[reflection.foreign_type] = record.class.base_class.name
-
end
-
-
1
def remove_keys
-
144
super
-
144
owner[reflection.foreign_type] = nil
-
end
-
-
1
def different_target?(record)
-
super || record.class != klass
-
end
-
-
1
def inverse_reflection_for(record)
-
reflection.polymorphic_inverse_of(record.class)
-
end
-
-
1
def raise_on_type_mismatch!(record)
-
# A polymorphic association cannot have a type mismatch, by definition
-
end
-
-
1
def stale_state
-
144
foreign_key = super
-
144
foreign_key && [foreign_key.to_s, owner[reflection.foreign_type].to_s]
-
end
-
end
-
end
-
end
-
2
require 'active_support/core_ext/module/attribute_accessors'
-
-
# This is the parent Association class which defines the variables
-
# used by all associations.
-
#
-
# The hierarchy is defined as follows:
-
# Association
-
# - SingularAssociation
-
# - BelongsToAssociation
-
# - HasOneAssociation
-
# - CollectionAssociation
-
# - HasManyAssociation
-
-
2
module ActiveRecord::Associations::Builder
-
2
class Association #:nodoc:
-
2
class << self
-
2
attr_accessor :extensions
-
# TODO: This class accessor is needed to make activerecord-deprecated_finders work.
-
# We can move it to a constant in 5.0.
-
2
attr_accessor :valid_options
-
end
-
2
self.extensions = []
-
-
2
self.valid_options = [:class_name, :class, :foreign_key, :validate]
-
-
2
attr_reader :name, :scope, :options
-
-
2
def self.build(model, name, scope, options, &block)
-
41
if model.dangerous_attribute_method?(name)
-
raise ArgumentError, "You tried to define an association named #{name} on the model #{model.name}, but " \
-
"this will conflict with a method #{name} already defined by Active Record. " \
-
"Please choose a different association name."
-
end
-
-
41
builder = create_builder model, name, scope, options, &block
-
41
reflection = builder.build(model)
-
41
define_accessors model, reflection
-
41
define_callbacks model, reflection
-
41
builder.define_extensions model
-
41
reflection
-
end
-
-
2
def self.create_builder(model, name, scope, options, &block)
-
41
raise ArgumentError, "association names must be a Symbol" unless name.kind_of?(Symbol)
-
-
41
new(model, name, scope, options, &block)
-
end
-
-
2
def initialize(model, name, scope, options)
-
# TODO: Move this to create_builder as soon we drop support to activerecord-deprecated_finders.
-
41
if scope.is_a?(Hash)
-
9
options = scope
-
9
scope = nil
-
end
-
-
# TODO: Remove this model argument as soon we drop support to activerecord-deprecated_finders.
-
41
@name = name
-
41
@scope = scope
-
41
@options = options
-
-
41
validate_options
-
-
41
if scope && scope.arity == 0
-
@scope = proc { instance_exec(&scope) }
-
end
-
end
-
-
2
def build(model)
-
41
ActiveRecord::Reflection.create(macro, name, scope, options, model)
-
end
-
-
2
def macro
-
raise NotImplementedError
-
end
-
-
2
def valid_options
-
41
Association.valid_options + Association.extensions.flat_map(&:valid_options)
-
end
-
-
2
def validate_options
-
41
options.assert_valid_keys(valid_options)
-
end
-
-
2
def define_extensions(model)
-
end
-
-
2
def self.define_callbacks(model, reflection)
-
41
add_before_destroy_callbacks(model, reflection) if reflection.options[:dependent]
-
41
Association.extensions.each do |extension|
-
41
extension.build model, reflection
-
end
-
end
-
-
# Defines the setter and getter methods for the association
-
# class Post < ActiveRecord::Base
-
# has_many :comments
-
# end
-
#
-
# Post.first.comments and Post.first.comments= methods are defined by this method...
-
2
def self.define_accessors(model, reflection)
-
41
mixin = model.generated_association_methods
-
41
name = reflection.name
-
41
define_readers(mixin, name)
-
41
define_writers(mixin, name)
-
end
-
-
2
def self.define_readers(mixin, name)
-
41
mixin.class_eval <<-CODE, __FILE__, __LINE__ + 1
-
def #{name}(*args)
-
association(:#{name}).reader(*args)
-
end
-
CODE
-
end
-
-
2
def self.define_writers(mixin, name)
-
41
mixin.class_eval <<-CODE, __FILE__, __LINE__ + 1
-
def #{name}=(value)
-
association(:#{name}).writer(value)
-
end
-
CODE
-
end
-
-
2
def self.valid_dependent_options
-
raise NotImplementedError
-
end
-
-
2
private
-
-
2
def self.add_before_destroy_callbacks(model, reflection)
-
unless valid_dependent_options.include? reflection.options[:dependent]
-
raise ArgumentError, "The :dependent option must be one of #{valid_dependent_options}, but is :#{reflection.options[:dependent]}"
-
end
-
-
name = reflection.name
-
model.before_destroy lambda { |o| o.association(name).handle_dependency }
-
end
-
end
-
end
-
2
module ActiveRecord::Associations::Builder
-
2
class BelongsTo < SingularAssociation #:nodoc:
-
2
def macro
-
12
:belongs_to
-
end
-
-
2
def valid_options
-
12
super + [:foreign_type, :polymorphic, :touch, :counter_cache]
-
end
-
-
2
def self.valid_dependent_options
-
[:destroy, :delete]
-
end
-
-
2
def self.define_callbacks(model, reflection)
-
12
super
-
12
add_counter_cache_callbacks(model, reflection) if reflection.options[:counter_cache]
-
12
add_touch_callbacks(model, reflection) if reflection.options[:touch]
-
end
-
-
2
def self.define_accessors(mixin, reflection)
-
12
super
-
12
add_counter_cache_methods mixin
-
end
-
-
2
private
-
-
2
def self.add_counter_cache_methods(mixin)
-
12
return if mixin.method_defined? :belongs_to_counter_cache_after_create
-
-
5
mixin.class_eval do
-
5
def belongs_to_counter_cache_after_create(reflection)
-
if record = send(reflection.name)
-
cache_column = reflection.counter_cache_column
-
record.class.increment_counter(cache_column, record.id)
-
@_after_create_counter_called = true
-
end
-
end
-
-
5
def belongs_to_counter_cache_before_destroy(reflection)
-
foreign_key = reflection.foreign_key.to_sym
-
unless destroyed_by_association && destroyed_by_association.foreign_key.to_sym == foreign_key
-
record = send reflection.name
-
if record && !self.destroyed?
-
cache_column = reflection.counter_cache_column
-
record.class.decrement_counter(cache_column, record.id)
-
end
-
end
-
end
-
-
5
def belongs_to_counter_cache_after_update(reflection)
-
foreign_key = reflection.foreign_key
-
cache_column = reflection.counter_cache_column
-
-
if (@_after_create_counter_called ||= false)
-
@_after_create_counter_called = false
-
elsif attribute_changed?(foreign_key) && !new_record? && reflection.constructable?
-
model = reflection.klass
-
foreign_key_was = attribute_was foreign_key
-
foreign_key = attribute foreign_key
-
-
if foreign_key && model.respond_to?(:increment_counter)
-
model.increment_counter(cache_column, foreign_key)
-
end
-
if foreign_key_was && model.respond_to?(:decrement_counter)
-
model.decrement_counter(cache_column, foreign_key_was)
-
end
-
end
-
end
-
end
-
end
-
-
2
def self.add_counter_cache_callbacks(model, reflection)
-
cache_column = reflection.counter_cache_column
-
-
model.after_create lambda { |record|
-
record.belongs_to_counter_cache_after_create(reflection)
-
}
-
-
model.before_destroy lambda { |record|
-
record.belongs_to_counter_cache_before_destroy(reflection)
-
}
-
-
model.after_update lambda { |record|
-
record.belongs_to_counter_cache_after_update(reflection)
-
}
-
-
klass = reflection.class_name.safe_constantize
-
klass.attr_readonly cache_column if klass && klass.respond_to?(:attr_readonly)
-
end
-
-
2
def self.touch_record(o, foreign_key, name, touch) # :nodoc:
-
old_foreign_id = o.changed_attributes[foreign_key]
-
-
if old_foreign_id
-
association = o.association(name)
-
reflection = association.reflection
-
if reflection.polymorphic?
-
klass = o.public_send("#{reflection.foreign_type}_was").constantize
-
else
-
klass = association.klass
-
end
-
old_record = klass.find_by(klass.primary_key => old_foreign_id)
-
-
if old_record
-
if touch != true
-
old_record.touch touch
-
else
-
old_record.touch
-
end
-
end
-
end
-
-
record = o.send name
-
if record && record.persisted?
-
if touch != true
-
record.touch touch
-
else
-
record.touch
-
end
-
end
-
end
-
-
2
def self.add_touch_callbacks(model, reflection)
-
foreign_key = reflection.foreign_key
-
n = reflection.name
-
touch = reflection.options[:touch]
-
-
callback = lambda { |record|
-
BelongsTo.touch_record(record, foreign_key, n, touch)
-
}
-
-
model.after_save callback
-
model.after_touch callback
-
model.after_destroy callback
-
end
-
end
-
end
-
# This class is inherited by the has_many and has_many_and_belongs_to_many association classes
-
-
2
require 'active_record/associations'
-
-
2
module ActiveRecord::Associations::Builder
-
2
class CollectionAssociation < Association #:nodoc:
-
-
2
CALLBACKS = [:before_add, :after_add, :before_remove, :after_remove]
-
-
2
def valid_options
-
super + [:table_name, :before_add,
-
27
:after_add, :before_remove, :after_remove, :extend]
-
end
-
-
2
attr_reader :block_extension
-
-
2
def initialize(model, name, scope, options)
-
27
super
-
27
@mod = nil
-
27
if block_given?
-
@mod = Module.new(&Proc.new)
-
@scope = wrap_scope @scope, @mod
-
end
-
end
-
-
2
def self.define_callbacks(model, reflection)
-
27
super
-
27
name = reflection.name
-
27
options = reflection.options
-
27
CALLBACKS.each { |callback_name|
-
108
define_callback(model, callback_name, name, options)
-
}
-
end
-
-
2
def define_extensions(model)
-
27
if @mod
-
extension_module_name = "#{model.name.demodulize}#{name.to_s.camelize}AssociationExtension"
-
model.parent.const_set(extension_module_name, @mod)
-
end
-
end
-
-
2
def self.define_callback(model, callback_name, name, options)
-
108
full_callback_name = "#{callback_name}_for_#{name}"
-
-
# TODO : why do i need method_defined? I think its because of the inheritance chain
-
108
model.class_attribute full_callback_name unless model.method_defined?(full_callback_name)
-
108
callbacks = Array(options[callback_name.to_sym]).map do |callback|
-
case callback
-
when Symbol
-
->(method, owner, record) { owner.send(callback, record) }
-
when Proc
-
->(method, owner, record) { callback.call(owner, record) }
-
else
-
->(method, owner, record) { callback.send(method, owner, record) }
-
end
-
end
-
108
model.send "#{full_callback_name}=", callbacks
-
end
-
-
# Defines the setter and getter methods for the collection_singular_ids.
-
2
def self.define_readers(mixin, name)
-
27
super
-
-
27
mixin.class_eval <<-CODE, __FILE__, __LINE__ + 1
-
def #{name.to_s.singularize}_ids
-
association(:#{name}).ids_reader
-
end
-
CODE
-
end
-
-
2
def self.define_writers(mixin, name)
-
27
super
-
-
27
mixin.class_eval <<-CODE, __FILE__, __LINE__ + 1
-
def #{name.to_s.singularize}_ids=(ids)
-
association(:#{name}).ids_writer(ids)
-
end
-
CODE
-
end
-
-
2
private
-
-
2
def wrap_scope(scope, mod)
-
if scope
-
proc { |owner| instance_exec(owner, &scope).extending(mod) }
-
else
-
proc { extending(mod) }
-
end
-
end
-
end
-
end
-
2
module ActiveRecord::Associations::Builder
-
2
class HasMany < CollectionAssociation #:nodoc:
-
2
def macro
-
27
:has_many
-
end
-
-
2
def valid_options
-
27
super + [:primary_key, :dependent, :as, :through, :source, :source_type, :inverse_of, :counter_cache, :join_table]
-
end
-
-
2
def self.valid_dependent_options
-
[:destroy, :delete_all, :nullify, :restrict_with_error, :restrict_with_exception]
-
end
-
end
-
end
-
2
module ActiveRecord::Associations::Builder
-
2
class HasOne < SingularAssociation #:nodoc:
-
2
def macro
-
2
:has_one
-
end
-
-
2
def valid_options
-
2
valid = super + [:order, :as]
-
2
valid += [:through, :source, :source_type] if options[:through]
-
2
valid
-
end
-
-
2
def self.valid_dependent_options
-
[:destroy, :delete, :nullify, :restrict_with_error, :restrict_with_exception]
-
end
-
-
2
private
-
-
2
def self.add_before_destroy_callbacks(model, reflection)
-
super unless reflection.options[:through]
-
end
-
end
-
end
-
# This class is inherited by the has_one and belongs_to association classes
-
-
2
module ActiveRecord::Associations::Builder
-
2
class SingularAssociation < Association #:nodoc:
-
2
def valid_options
-
14
super + [:remote, :dependent, :primary_key, :inverse_of]
-
end
-
-
2
def self.define_accessors(model, reflection)
-
14
super
-
14
define_constructors(model.generated_association_methods, reflection.name) if reflection.constructable?
-
end
-
-
# Defines the (build|create)_association methods for belongs_to or has_one association
-
2
def self.define_constructors(mixin, name)
-
8
mixin.class_eval <<-CODE, __FILE__, __LINE__ + 1
-
def build_#{name}(*args, &block)
-
association(:#{name}).build(*args, &block)
-
end
-
-
def create_#{name}(*args, &block)
-
association(:#{name}).create(*args, &block)
-
end
-
-
def create_#{name}!(*args, &block)
-
association(:#{name}).create!(*args, &block)
-
end
-
CODE
-
end
-
end
-
end
-
1
module ActiveRecord
-
1
module Associations
-
# = Active Record Association Collection
-
#
-
# CollectionAssociation is an abstract class that provides common stuff to
-
# ease the implementation of association proxies that represent
-
# collections. See the class hierarchy in Association.
-
#
-
# CollectionAssociation:
-
# HasManyAssociation => has_many
-
# HasManyThroughAssociation + ThroughAssociation => has_many :through
-
#
-
# CollectionAssociation class provides common methods to the collections
-
# defined by +has_and_belongs_to_many+, +has_many+ or +has_many+ with
-
# +:through association+ option.
-
#
-
# You need to be careful with assumptions regarding the target: The proxy
-
# does not fetch records from the database until it needs them, but new
-
# ones created with +build+ are added to the target. So, the target may be
-
# non-empty and still lack children waiting to be read from the database.
-
# If you look directly to the database you cannot assume that's the entire
-
# collection because new records may have been added to the target, etc.
-
#
-
# If you need to work on all current children, new and existing records,
-
# +load_target+ and the +loaded+ flag are your friends.
-
1
class CollectionAssociation < Association #:nodoc:
-
-
# Implements the reader method, e.g. foo.items for Foo.has_many :items
-
1
def reader(force_reload = false)
-
72
if force_reload
-
klass.uncached { reload }
-
elsif stale_target?
-
reload
-
end
-
-
72
@proxy ||= CollectionProxy.create(klass, self)
-
end
-
-
# Implements the writer method, e.g. foo.items= for Foo.has_many :items
-
1
def writer(records)
-
replace(records)
-
end
-
-
# Implements the ids reader method, e.g. foo.item_ids for Foo.has_many :items
-
1
def ids_reader
-
if loaded?
-
load_target.map do |record|
-
record.send(reflection.association_primary_key)
-
end
-
else
-
column = "#{reflection.quoted_table_name}.#{reflection.association_primary_key}"
-
scope.pluck(column)
-
end
-
end
-
-
# Implements the ids writer method, e.g. foo.item_ids= for Foo.has_many :items
-
1
def ids_writer(ids)
-
pk_column = reflection.primary_key_column
-
ids = Array(ids).reject { |id| id.blank? }
-
ids.map! { |i| pk_column.type_cast(i) }
-
replace(klass.find(ids).index_by { |r| r.id }.values_at(*ids))
-
end
-
-
1
def reset
-
72
super
-
72
@target = []
-
end
-
-
1
def select(*fields)
-
if block_given?
-
load_target.select.each { |e| yield e }
-
else
-
scope.select(*fields)
-
end
-
end
-
-
1
def find(*args)
-
if block_given?
-
load_target.find(*args) { |*block_args| yield(*block_args) }
-
else
-
if options[:inverse_of] && loaded?
-
args_flatten = args.flatten
-
raise RecordNotFound, "Couldn't find #{scope.klass.name} without an ID" if args_flatten.blank?
-
result = find_by_scan(*args)
-
-
result_size = Array(result).size
-
if !result || result_size != args_flatten.size
-
scope.raise_record_not_found_exception!(args_flatten, result_size, args_flatten.size)
-
else
-
result
-
end
-
else
-
scope.find(*args)
-
end
-
end
-
end
-
-
1
def first(*args)
-
first_nth_or_last(:first, *args)
-
end
-
-
1
def second(*args)
-
first_nth_or_last(:second, *args)
-
end
-
-
1
def third(*args)
-
first_nth_or_last(:third, *args)
-
end
-
-
1
def fourth(*args)
-
first_nth_or_last(:fourth, *args)
-
end
-
-
1
def fifth(*args)
-
first_nth_or_last(:fifth, *args)
-
end
-
-
1
def forty_two(*args)
-
first_nth_or_last(:forty_two, *args)
-
end
-
-
1
def last(*args)
-
first_nth_or_last(:last, *args)
-
end
-
-
1
def build(attributes = {}, &block)
-
if attributes.is_a?(Array)
-
attributes.collect { |attr| build(attr, &block) }
-
else
-
add_to_target(build_record(attributes)) do |record|
-
yield(record) if block_given?
-
end
-
end
-
end
-
-
1
def create(attributes = {}, &block)
-
72
_create_record(attributes, &block)
-
end
-
-
1
def create!(attributes = {}, &block)
-
_create_record(attributes, true, &block)
-
end
-
-
# Add +records+ to this association. Returns +self+ so method calls may
-
# be chained. Since << flattens its argument list and inserts each record,
-
# +push+ and +concat+ behave identically.
-
1
def concat(*records)
-
load_target if owner.new_record?
-
-
if owner.new_record?
-
concat_records(records)
-
else
-
transaction { concat_records(records) }
-
end
-
end
-
-
# Starts a transaction in the association class's database connection.
-
#
-
# class Author < ActiveRecord::Base
-
# has_many :books
-
# end
-
#
-
# Author.first.books.transaction do
-
# # same effect as calling Book.transaction
-
# end
-
1
def transaction(*args)
-
72
reflection.klass.transaction(*args) do
-
72
yield
-
end
-
end
-
-
# Removes all records from the association without calling callbacks
-
# on the associated records. It honors the `:dependent` option. However
-
# if the `:dependent` value is `:destroy` then in that case the `:delete_all`
-
# deletion strategy for the association is applied.
-
#
-
# You can force a particular deletion strategy by passing a parameter.
-
#
-
# Example:
-
#
-
# @author.books.delete_all(:nullify)
-
# @author.books.delete_all(:delete_all)
-
#
-
# See delete for more info.
-
1
def delete_all(dependent = nil)
-
if dependent.present? && ![:nullify, :delete_all].include?(dependent)
-
raise ArgumentError, "Valid values are :nullify or :delete_all"
-
end
-
-
dependent = if dependent.present?
-
dependent
-
elsif options[:dependent] == :destroy
-
:delete_all
-
else
-
options[:dependent]
-
end
-
-
delete(:all, dependent: dependent).tap do
-
reset
-
loaded!
-
end
-
end
-
-
# Destroy all the records from this association.
-
#
-
# See destroy for more info.
-
1
def destroy_all
-
destroy(load_target).tap do
-
reset
-
loaded!
-
end
-
end
-
-
# Count all records using SQL. Construct options and pass them with
-
# scope to the target class's +count+.
-
1
def count(column_name = nil, count_options = {})
-
# TODO: Remove count_options argument as soon we remove support to
-
# activerecord-deprecated_finders.
-
column_name, count_options = nil, column_name if column_name.is_a?(Hash)
-
-
relation = scope
-
if association_scope.distinct_value
-
# This is needed because 'SELECT count(DISTINCT *)..' is not valid SQL.
-
column_name ||= reflection.klass.primary_key
-
relation = relation.distinct
-
end
-
-
value = relation.count(column_name)
-
-
limit = options[:limit]
-
offset = options[:offset]
-
-
if limit || offset
-
[ [value - offset.to_i, 0].max, limit.to_i ].min
-
else
-
value
-
end
-
end
-
-
# Removes +records+ from this association calling +before_remove+ and
-
# +after_remove+ callbacks.
-
#
-
# This method is abstract in the sense that +delete_records+ has to be
-
# provided by descendants. Note this method does not imply the records
-
# are actually removed from the database, that depends precisely on
-
# +delete_records+. They are in any case removed from the collection.
-
1
def delete(*records)
-
_options = records.extract_options!
-
dependent = _options[:dependent] || options[:dependent]
-
-
if records.first == :all
-
if (loaded? || dependent == :destroy) && dependent != :delete_all
-
delete_or_destroy(load_target, dependent)
-
else
-
delete_records(:all, dependent)
-
end
-
else
-
records = find(records) if records.any? { |record| record.kind_of?(Fixnum) || record.kind_of?(String) }
-
delete_or_destroy(records, dependent)
-
end
-
end
-
-
# Deletes the +records+ and removes them from this association calling
-
# +before_remove+ , +after_remove+ , +before_destroy+ and +after_destroy+ callbacks.
-
#
-
# Note that this method removes records from the database ignoring the
-
# +:dependent+ option.
-
1
def destroy(*records)
-
records = find(records) if records.any? { |record| record.kind_of?(Fixnum) || record.kind_of?(String) }
-
delete_or_destroy(records, :destroy)
-
end
-
-
# Returns the size of the collection by executing a SELECT COUNT(*)
-
# query if the collection hasn't been loaded, and calling
-
# <tt>collection.size</tt> if it has.
-
#
-
# If the collection has been already loaded +size+ and +length+ are
-
# equivalent. If not and you are going to need the records anyway
-
# +length+ will take one less query. Otherwise +size+ is more efficient.
-
#
-
# This method is abstract in the sense that it relies on
-
# +count_records+, which is a method descendants have to provide.
-
1
def size
-
if !find_target? || loaded?
-
if association_scope.distinct_value
-
target.uniq.size
-
else
-
target.size
-
end
-
elsif !loaded? && !association_scope.group_values.empty?
-
load_target.size
-
elsif !loaded? && !association_scope.distinct_value && target.is_a?(Array)
-
unsaved_records = target.select { |r| r.new_record? }
-
unsaved_records.size + count_records
-
else
-
count_records
-
end
-
end
-
-
# Returns the size of the collection calling +size+ on the target.
-
#
-
# If the collection has been already loaded +length+ and +size+ are
-
# equivalent. If not and you are going to need the records anyway this
-
# method will take one less query. Otherwise +size+ is more efficient.
-
1
def length
-
load_target.size
-
end
-
-
# Returns true if the collection is empty.
-
#
-
# If the collection has been loaded
-
# it is equivalent to <tt>collection.size.zero?</tt>. If the
-
# collection has not been loaded, it is equivalent to
-
# <tt>collection.exists?</tt>. If the collection has not already been
-
# loaded and you are going to fetch the records anyway it is better to
-
# check <tt>collection.length.zero?</tt>.
-
1
def empty?
-
if loaded?
-
size.zero?
-
else
-
@target.blank? && !scope.exists?
-
end
-
end
-
-
# Returns true if the collections is not empty.
-
# Equivalent to +!collection.empty?+.
-
1
def any?
-
if block_given?
-
load_target.any? { |*block_args| yield(*block_args) }
-
else
-
!empty?
-
end
-
end
-
-
# Returns true if the collection has more than 1 record.
-
# Equivalent to +collection.size > 1+.
-
1
def many?
-
if block_given?
-
load_target.many? { |*block_args| yield(*block_args) }
-
else
-
size > 1
-
end
-
end
-
-
1
def distinct
-
seen = {}
-
load_target.find_all do |record|
-
seen[record.id] = true unless seen.key?(record.id)
-
end
-
end
-
1
alias uniq distinct
-
-
# Replace this collection with +other_array+. This will perform a diff
-
# and delete/add only records that have changed.
-
1
def replace(other_array)
-
other_array.each { |val| raise_on_type_mismatch!(val) }
-
original_target = load_target.dup
-
-
if owner.new_record?
-
replace_records(other_array, original_target)
-
else
-
transaction { replace_records(other_array, original_target) }
-
end
-
end
-
-
1
def include?(record)
-
if record.is_a?(reflection.klass)
-
if record.new_record?
-
include_in_memory?(record)
-
else
-
loaded? ? target.include?(record) : scope.exists?(record)
-
end
-
else
-
false
-
end
-
end
-
-
1
def load_target
-
if find_target?
-
@target = merge_target_lists(find_target, target)
-
end
-
-
loaded!
-
target
-
end
-
-
1
def add_to_target(record, skip_callbacks = false)
-
72
callback(:before_add, record) unless skip_callbacks
-
72
yield(record) if block_given?
-
-
72
if association_scope.distinct_value && index = @target.index(record)
-
@target[index] = record
-
else
-
72
@target << record
-
end
-
-
72
callback(:after_add, record) unless skip_callbacks
-
72
set_inverse_instance(record)
-
-
72
record
-
end
-
-
1
def scope(opts = {})
-
144
scope = super()
-
144
scope.none! if opts.fetch(:nullify, true) && null_scope?
-
144
scope
-
end
-
-
1
def null_scope?
-
72
owner.new_record? && !foreign_key_present?
-
end
-
-
1
private
-
-
1
def find_target
-
records = scope.to_a
-
records.each { |record| set_inverse_instance(record) }
-
records
-
end
-
-
# We have some records loaded from the database (persisted) and some that are
-
# in-memory (memory). The same record may be represented in the persisted array
-
# and in the memory array.
-
#
-
# So the task of this method is to merge them according to the following rules:
-
#
-
# * The final array must not have duplicates
-
# * The order of the persisted array is to be preserved
-
# * Any changes made to attributes on objects in the memory array are to be preserved
-
# * Otherwise, attributes should have the value found in the database
-
1
def merge_target_lists(persisted, memory)
-
return persisted if memory.empty?
-
return memory if persisted.empty?
-
-
persisted.map! do |record|
-
if mem_record = memory.delete(record)
-
-
((record.attribute_names & mem_record.attribute_names) - mem_record.changes.keys).each do |name|
-
mem_record[name] = record[name]
-
end
-
-
mem_record
-
else
-
record
-
end
-
end
-
-
persisted + memory
-
end
-
-
1
def _create_record(attributes, raise = false, &block)
-
72
unless owner.persisted?
-
raise ActiveRecord::RecordNotSaved, "You cannot call create unless the parent is saved"
-
end
-
-
72
if attributes.is_a?(Array)
-
attributes.collect { |attr| _create_record(attr, raise, &block) }
-
else
-
72
transaction do
-
72
add_to_target(build_record(attributes)) do |record|
-
72
yield(record) if block_given?
-
72
insert_record(record, true, raise)
-
end
-
end
-
end
-
end
-
-
# Do the relevant stuff to insert the given record into the association collection.
-
1
def insert_record(record, validate = true, raise = false)
-
raise NotImplementedError
-
end
-
-
1
def create_scope
-
72
scope.scope_for_create.stringify_keys
-
end
-
-
1
def delete_or_destroy(records, method)
-
records = records.flatten
-
records.each { |record| raise_on_type_mismatch!(record) }
-
existing_records = records.reject { |r| r.new_record? }
-
-
if existing_records.empty?
-
remove_records(existing_records, records, method)
-
else
-
transaction { remove_records(existing_records, records, method) }
-
end
-
end
-
-
1
def remove_records(existing_records, records, method)
-
records.each { |record| callback(:before_remove, record) }
-
-
delete_records(existing_records, method) if existing_records.any?
-
records.each { |record| target.delete(record) }
-
-
records.each { |record| callback(:after_remove, record) }
-
end
-
-
# Delete the given records from the association, using one of the methods :destroy,
-
# :delete_all or :nullify (or nil, in which case a default is used).
-
1
def delete_records(records, method)
-
raise NotImplementedError
-
end
-
-
1
def replace_records(new_target, original_target)
-
delete(target - new_target)
-
-
unless concat(new_target - target)
-
@target = original_target
-
raise RecordNotSaved, "Failed to replace #{reflection.name} because one or more of the " \
-
"new records could not be saved."
-
end
-
-
target
-
end
-
-
1
def concat_records(records, should_raise = false)
-
result = true
-
-
records.flatten.each do |record|
-
raise_on_type_mismatch!(record)
-
add_to_target(record) do |rec|
-
result &&= insert_record(rec, true, should_raise) unless owner.new_record?
-
end
-
end
-
-
result && records
-
end
-
-
1
def callback(method, record)
-
144
callbacks_for(method).each do |callback|
-
callback.call(method, owner, record)
-
end
-
end
-
-
1
def callbacks_for(callback_name)
-
144
full_callback_name = "#{callback_name}_for_#{reflection.name}"
-
144
owner.class.send(full_callback_name)
-
end
-
-
# Should we deal with assoc.first or assoc.last by issuing an independent query to
-
# the database, or by getting the target, and then taking the first/last item from that?
-
#
-
# If the args is just a non-empty options hash, go to the database.
-
#
-
# Otherwise, go to the database only if none of the following are true:
-
# * target already loaded
-
# * owner is new record
-
# * target contains new or changed record(s)
-
1
def fetch_first_nth_or_last_using_find?(args)
-
if args.first.is_a?(Hash)
-
true
-
else
-
!(loaded? ||
-
owner.new_record? ||
-
target.any? { |record| record.new_record? || record.changed? })
-
end
-
end
-
-
1
def include_in_memory?(record)
-
if reflection.is_a?(ActiveRecord::Reflection::ThroughReflection)
-
assoc = owner.association(reflection.through_reflection.name)
-
assoc.reader.any? { |source|
-
target = source.send(reflection.source_reflection.name)
-
target.respond_to?(:include?) ? target.include?(record) : target == record
-
} || target.include?(record)
-
else
-
target.include?(record)
-
end
-
end
-
-
# If the :inverse_of option has been
-
# specified, then #find scans the entire collection.
-
1
def find_by_scan(*args)
-
expects_array = args.first.kind_of?(Array)
-
ids = args.flatten.compact.map{ |arg| arg.to_s }.uniq
-
-
if ids.size == 1
-
id = ids.first
-
record = load_target.detect { |r| id == r.id.to_s }
-
expects_array ? [ record ] : record
-
else
-
load_target.select { |r| ids.include?(r.id.to_s) }
-
end
-
end
-
-
# Fetches the first/last using SQL if possible, otherwise from the target array.
-
1
def first_nth_or_last(type, *args)
-
args.shift if args.first.is_a?(Hash) && args.first.empty?
-
-
collection = fetch_first_nth_or_last_using_find?(args) ? scope : load_target
-
collection.send(type, *args).tap do |record|
-
set_inverse_instance record if record.is_a? ActiveRecord::Base
-
end
-
end
-
end
-
end
-
end
-
2
module ActiveRecord
-
2
module Associations
-
# Association proxies in Active Record are middlemen between the object that
-
# holds the association, known as the <tt>@owner</tt>, and the actual associated
-
# object, known as the <tt>@target</tt>. The kind of association any proxy is
-
# about is available in <tt>@reflection</tt>. That's an instance of the class
-
# ActiveRecord::Reflection::AssociationReflection.
-
#
-
# For example, given
-
#
-
# class Blog < ActiveRecord::Base
-
# has_many :posts
-
# end
-
#
-
# blog = Blog.first
-
#
-
# the association proxy in <tt>blog.posts</tt> has the object in +blog+ as
-
# <tt>@owner</tt>, the collection of its posts as <tt>@target</tt>, and
-
# the <tt>@reflection</tt> object represents a <tt>:has_many</tt> macro.
-
#
-
# This class delegates unknown methods to <tt>@target</tt> via
-
# <tt>method_missing</tt>.
-
#
-
# The <tt>@target</tt> object is not \loaded until needed. For example,
-
#
-
# blog.posts.count
-
#
-
# is computed directly through SQL and does not trigger by itself the
-
# instantiation of the actual post records.
-
2
class CollectionProxy < Relation
-
2
delegate(*(ActiveRecord::Calculations.public_instance_methods - [:count]), to: :scope)
-
-
2
def initialize(klass, association) #:nodoc:
-
72
@association = association
-
72
super klass, klass.arel_table
-
72
merge! association.scope(nullify: false)
-
end
-
-
2
def target
-
@association.target
-
end
-
-
2
def load_target
-
@association.load_target
-
end
-
-
# Returns +true+ if the association has been loaded, otherwise +false+.
-
#
-
# person.pets.loaded? # => false
-
# person.pets
-
# person.pets.loaded? # => true
-
2
def loaded?
-
@association.loaded?
-
end
-
-
# Works in two ways.
-
#
-
# *First:* Specify a subset of fields to be selected from the result set.
-
#
-
# class Person < ActiveRecord::Base
-
# has_many :pets
-
# end
-
#
-
# person.pets
-
# # => [
-
# # #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
-
# # #<Pet id: 2, name: "Spook", person_id: 1>,
-
# # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
-
# # ]
-
#
-
# person.pets.select(:name)
-
# # => [
-
# # #<Pet id: nil, name: "Fancy-Fancy">,
-
# # #<Pet id: nil, name: "Spook">,
-
# # #<Pet id: nil, name: "Choo-Choo">
-
# # ]
-
#
-
# person.pets.select(:id, :name )
-
# # => [
-
# # #<Pet id: 1, name: "Fancy-Fancy">,
-
# # #<Pet id: 2, name: "Spook">,
-
# # #<Pet id: 3, name: "Choo-Choo">
-
# # ]
-
#
-
# Be careful because this also means you're initializing a model
-
# object with only the fields that you've selected. If you attempt
-
# to access a field except +id+ that is not in the initialized record you'll
-
# receive:
-
#
-
# person.pets.select(:name).first.person_id
-
# # => ActiveModel::MissingAttributeError: missing attribute: person_id
-
#
-
# *Second:* You can pass a block so it can be used just like Array#select.
-
# This builds an array of objects from the database for the scope,
-
# converting them into an array and iterating through them using
-
# Array#select.
-
#
-
# person.pets.select { |pet| pet.name =~ /oo/ }
-
# # => [
-
# # #<Pet id: 2, name: "Spook", person_id: 1>,
-
# # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
-
# # ]
-
#
-
# person.pets.select(:name) { |pet| pet.name =~ /oo/ }
-
# # => [
-
# # #<Pet id: 2, name: "Spook">,
-
# # #<Pet id: 3, name: "Choo-Choo">
-
# # ]
-
2
def select(*fields, &block)
-
@association.select(*fields, &block)
-
end
-
-
# Finds an object in the collection responding to the +id+. Uses the same
-
# rules as <tt>ActiveRecord::Base.find</tt>. Returns <tt>ActiveRecord::RecordNotFound</tt>
-
# error if the object cannot be found.
-
#
-
# class Person < ActiveRecord::Base
-
# has_many :pets
-
# end
-
#
-
# person.pets
-
# # => [
-
# # #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
-
# # #<Pet id: 2, name: "Spook", person_id: 1>,
-
# # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
-
# # ]
-
#
-
# person.pets.find(1) # => #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>
-
# person.pets.find(4) # => ActiveRecord::RecordNotFound: Couldn't find Pet with id=4
-
#
-
# person.pets.find(2) { |pet| pet.name.downcase! }
-
# # => #<Pet id: 2, name: "fancy-fancy", person_id: 1>
-
#
-
# person.pets.find(2, 3)
-
# # => [
-
# # #<Pet id: 2, name: "Spook", person_id: 1>,
-
# # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
-
# # ]
-
2
def find(*args, &block)
-
@association.find(*args, &block)
-
end
-
-
# Returns the first record, or the first +n+ records, from the collection.
-
# If the collection is empty, the first form returns +nil+, and the second
-
# form returns an empty array.
-
#
-
# class Person < ActiveRecord::Base
-
# has_many :pets
-
# end
-
#
-
# person.pets
-
# # => [
-
# # #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
-
# # #<Pet id: 2, name: "Spook", person_id: 1>,
-
# # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
-
# # ]
-
#
-
# person.pets.first # => #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>
-
#
-
# person.pets.first(2)
-
# # => [
-
# # #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
-
# # #<Pet id: 2, name: "Spook", person_id: 1>
-
# # ]
-
#
-
# another_person_without.pets # => []
-
# another_person_without.pets.first # => nil
-
# another_person_without.pets.first(3) # => []
-
2
def first(*args)
-
@association.first(*args)
-
end
-
-
# Same as +first+ except returns only the second record.
-
2
def second(*args)
-
@association.second(*args)
-
end
-
-
# Same as +first+ except returns only the third record.
-
2
def third(*args)
-
@association.third(*args)
-
end
-
-
# Same as +first+ except returns only the fourth record.
-
2
def fourth(*args)
-
@association.fourth(*args)
-
end
-
-
# Same as +first+ except returns only the fifth record.
-
2
def fifth(*args)
-
@association.fifth(*args)
-
end
-
-
# Same as +first+ except returns only the forty second record.
-
# Also known as accessing "the reddit".
-
2
def forty_two(*args)
-
@association.forty_two(*args)
-
end
-
-
# Returns the last record, or the last +n+ records, from the collection.
-
# If the collection is empty, the first form returns +nil+, and the second
-
# form returns an empty array.
-
#
-
# class Person < ActiveRecord::Base
-
# has_many :pets
-
# end
-
#
-
# person.pets
-
# # => [
-
# # #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
-
# # #<Pet id: 2, name: "Spook", person_id: 1>,
-
# # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
-
# # ]
-
#
-
# person.pets.last # => #<Pet id: 3, name: "Choo-Choo", person_id: 1>
-
#
-
# person.pets.last(2)
-
# # => [
-
# # #<Pet id: 2, name: "Spook", person_id: 1>,
-
# # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
-
# # ]
-
#
-
# another_person_without.pets # => []
-
# another_person_without.pets.last # => nil
-
# another_person_without.pets.last(3) # => []
-
2
def last(*args)
-
@association.last(*args)
-
end
-
-
# Returns a new object of the collection type that has been instantiated
-
# with +attributes+ and linked to this object, but have not yet been saved.
-
# You can pass an array of attributes hashes, this will return an array
-
# with the new objects.
-
#
-
# class Person
-
# has_many :pets
-
# end
-
#
-
# person.pets.build
-
# # => #<Pet id: nil, name: nil, person_id: 1>
-
#
-
# person.pets.build(name: 'Fancy-Fancy')
-
# # => #<Pet id: nil, name: "Fancy-Fancy", person_id: 1>
-
#
-
# person.pets.build([{name: 'Spook'}, {name: 'Choo-Choo'}, {name: 'Brain'}])
-
# # => [
-
# # #<Pet id: nil, name: "Spook", person_id: 1>,
-
# # #<Pet id: nil, name: "Choo-Choo", person_id: 1>,
-
# # #<Pet id: nil, name: "Brain", person_id: 1>
-
# # ]
-
#
-
# person.pets.size # => 5 # size of the collection
-
# person.pets.count # => 0 # count from database
-
2
def build(attributes = {}, &block)
-
@association.build(attributes, &block)
-
end
-
2
alias_method :new, :build
-
-
# Returns a new object of the collection type that has been instantiated with
-
# attributes, linked to this object and that has already been saved (if it
-
# passes the validations).
-
#
-
# class Person
-
# has_many :pets
-
# end
-
#
-
# person.pets.create(name: 'Fancy-Fancy')
-
# # => #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>
-
#
-
# person.pets.create([{name: 'Spook'}, {name: 'Choo-Choo'}])
-
# # => [
-
# # #<Pet id: 2, name: "Spook", person_id: 1>,
-
# # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
-
# # ]
-
#
-
# person.pets.size # => 3
-
# person.pets.count # => 3
-
#
-
# person.pets.find(1, 2, 3)
-
# # => [
-
# # #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
-
# # #<Pet id: 2, name: "Spook", person_id: 1>,
-
# # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
-
# # ]
-
2
def create(attributes = {}, &block)
-
72
@association.create(attributes, &block)
-
end
-
-
# Like +create+, except that if the record is invalid, raises an exception.
-
#
-
# class Person
-
# has_many :pets
-
# end
-
#
-
# class Pet
-
# validates :name, presence: true
-
# end
-
#
-
# person.pets.create!(name: nil)
-
# # => ActiveRecord::RecordInvalid: Validation failed: Name can't be blank
-
2
def create!(attributes = {}, &block)
-
@association.create!(attributes, &block)
-
end
-
-
# Add one or more records to the collection by setting their foreign keys
-
# to the association's primary key. Since << flattens its argument list and
-
# inserts each record, +push+ and +concat+ behave identically. Returns +self+
-
# so method calls may be chained.
-
#
-
# class Person < ActiveRecord::Base
-
# has_many :pets
-
# end
-
#
-
# person.pets.size # => 0
-
# person.pets.concat(Pet.new(name: 'Fancy-Fancy'))
-
# person.pets.concat(Pet.new(name: 'Spook'), Pet.new(name: 'Choo-Choo'))
-
# person.pets.size # => 3
-
#
-
# person.id # => 1
-
# person.pets
-
# # => [
-
# # #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
-
# # #<Pet id: 2, name: "Spook", person_id: 1>,
-
# # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
-
# # ]
-
#
-
# person.pets.concat([Pet.new(name: 'Brain'), Pet.new(name: 'Benny')])
-
# person.pets.size # => 5
-
2
def concat(*records)
-
@association.concat(*records)
-
end
-
-
# Replaces this collection with +other_array+. This will perform a diff
-
# and delete/add only records that have changed.
-
#
-
# class Person < ActiveRecord::Base
-
# has_many :pets
-
# end
-
#
-
# person.pets
-
# # => [#<Pet id: 1, name: "Gorby", group: "cats", person_id: 1>]
-
#
-
# other_pets = [Pet.new(name: 'Puff', group: 'celebrities']
-
#
-
# person.pets.replace(other_pets)
-
#
-
# person.pets
-
# # => [#<Pet id: 2, name: "Puff", group: "celebrities", person_id: 1>]
-
#
-
# If the supplied array has an incorrect association type, it raises
-
# an <tt>ActiveRecord::AssociationTypeMismatch</tt> error:
-
#
-
# person.pets.replace(["doo", "ggie", "gaga"])
-
# # => ActiveRecord::AssociationTypeMismatch: Pet expected, got String
-
2
def replace(other_array)
-
@association.replace(other_array)
-
end
-
-
# Deletes all the records from the collection. For +has_many+ associations,
-
# the deletion is done according to the strategy specified by the <tt>:dependent</tt>
-
# option. Returns an array with the deleted records.
-
#
-
# If no <tt>:dependent</tt> option is given, then it will follow the
-
# default strategy. The default strategy is <tt>:nullify</tt>. This
-
# sets the foreign keys to <tt>NULL</tt>. For, +has_many+ <tt>:through</tt>,
-
# the default strategy is +delete_all+.
-
#
-
# class Person < ActiveRecord::Base
-
# has_many :pets # dependent: :nullify option by default
-
# end
-
#
-
# person.pets.size # => 3
-
# person.pets
-
# # => [
-
# # #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
-
# # #<Pet id: 2, name: "Spook", person_id: 1>,
-
# # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
-
# # ]
-
#
-
# person.pets.delete_all
-
# # => [
-
# # #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
-
# # #<Pet id: 2, name: "Spook", person_id: 1>,
-
# # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
-
# # ]
-
#
-
# person.pets.size # => 0
-
# person.pets # => []
-
#
-
# Pet.find(1, 2, 3)
-
# # => [
-
# # #<Pet id: 1, name: "Fancy-Fancy", person_id: nil>,
-
# # #<Pet id: 2, name: "Spook", person_id: nil>,
-
# # #<Pet id: 3, name: "Choo-Choo", person_id: nil>
-
# # ]
-
#
-
# If it is set to <tt>:destroy</tt> all the objects from the collection
-
# are removed by calling their +destroy+ method. See +destroy+ for more
-
# information.
-
#
-
# class Person < ActiveRecord::Base
-
# has_many :pets, dependent: :destroy
-
# end
-
#
-
# person.pets.size # => 3
-
# person.pets
-
# # => [
-
# # #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
-
# # #<Pet id: 2, name: "Spook", person_id: 1>,
-
# # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
-
# # ]
-
#
-
# person.pets.delete_all
-
# # => [
-
# # #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
-
# # #<Pet id: 2, name: "Spook", person_id: 1>,
-
# # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
-
# # ]
-
#
-
# Pet.find(1, 2, 3)
-
# # => ActiveRecord::RecordNotFound
-
#
-
# If it is set to <tt>:delete_all</tt>, all the objects are deleted
-
# *without* calling their +destroy+ method.
-
#
-
# class Person < ActiveRecord::Base
-
# has_many :pets, dependent: :delete_all
-
# end
-
#
-
# person.pets.size # => 3
-
# person.pets
-
# # => [
-
# # #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
-
# # #<Pet id: 2, name: "Spook", person_id: 1>,
-
# # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
-
# # ]
-
#
-
# person.pets.delete_all
-
# # => [
-
# # #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
-
# # #<Pet id: 2, name: "Spook", person_id: 1>,
-
# # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
-
# # ]
-
#
-
# Pet.find(1, 2, 3)
-
# # => ActiveRecord::RecordNotFound
-
2
def delete_all(dependent = nil)
-
@association.delete_all(dependent)
-
end
-
-
# Deletes the records of the collection directly from the database
-
# ignoring the +:dependent+ option. It invokes +before_remove+,
-
# +after_remove+ , +before_destroy+ and +after_destroy+ callbacks.
-
#
-
# class Person < ActiveRecord::Base
-
# has_many :pets
-
# end
-
#
-
# person.pets.size # => 3
-
# person.pets
-
# # => [
-
# # #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
-
# # #<Pet id: 2, name: "Spook", person_id: 1>,
-
# # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
-
# # ]
-
#
-
# person.pets.destroy_all
-
#
-
# person.pets.size # => 0
-
# person.pets # => []
-
#
-
# Pet.find(1) # => Couldn't find Pet with id=1
-
2
def destroy_all
-
@association.destroy_all
-
end
-
-
# Deletes the +records+ supplied and removes them from the collection. For
-
# +has_many+ associations, the deletion is done according to the strategy
-
# specified by the <tt>:dependent</tt> option. Returns an array with the
-
# deleted records.
-
#
-
# If no <tt>:dependent</tt> option is given, then it will follow the default
-
# strategy. The default strategy is <tt>:nullify</tt>. This sets the foreign
-
# keys to <tt>NULL</tt>. For, +has_many+ <tt>:through</tt>, the default
-
# strategy is +delete_all+.
-
#
-
# class Person < ActiveRecord::Base
-
# has_many :pets # dependent: :nullify option by default
-
# end
-
#
-
# person.pets.size # => 3
-
# person.pets
-
# # => [
-
# # #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
-
# # #<Pet id: 2, name: "Spook", person_id: 1>,
-
# # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
-
# # ]
-
#
-
# person.pets.delete(Pet.find(1))
-
# # => [#<Pet id: 1, name: "Fancy-Fancy", person_id: 1>]
-
#
-
# person.pets.size # => 2
-
# person.pets
-
# # => [
-
# # #<Pet id: 2, name: "Spook", person_id: 1>,
-
# # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
-
# # ]
-
#
-
# Pet.find(1)
-
# # => #<Pet id: 1, name: "Fancy-Fancy", person_id: nil>
-
#
-
# If it is set to <tt>:destroy</tt> all the +records+ are removed by calling
-
# their +destroy+ method. See +destroy+ for more information.
-
#
-
# class Person < ActiveRecord::Base
-
# has_many :pets, dependent: :destroy
-
# end
-
#
-
# person.pets.size # => 3
-
# person.pets
-
# # => [
-
# # #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
-
# # #<Pet id: 2, name: "Spook", person_id: 1>,
-
# # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
-
# # ]
-
#
-
# person.pets.delete(Pet.find(1), Pet.find(3))
-
# # => [
-
# # #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
-
# # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
-
# # ]
-
#
-
# person.pets.size # => 1
-
# person.pets
-
# # => [#<Pet id: 2, name: "Spook", person_id: 1>]
-
#
-
# Pet.find(1, 3)
-
# # => ActiveRecord::RecordNotFound: Couldn't find all Pets with IDs (1, 3)
-
#
-
# If it is set to <tt>:delete_all</tt>, all the +records+ are deleted
-
# *without* calling their +destroy+ method.
-
#
-
# class Person < ActiveRecord::Base
-
# has_many :pets, dependent: :delete_all
-
# end
-
#
-
# person.pets.size # => 3
-
# person.pets
-
# # => [
-
# # #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
-
# # #<Pet id: 2, name: "Spook", person_id: 1>,
-
# # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
-
# # ]
-
#
-
# person.pets.delete(Pet.find(1))
-
# # => [#<Pet id: 1, name: "Fancy-Fancy", person_id: 1>]
-
#
-
# person.pets.size # => 2
-
# person.pets
-
# # => [
-
# # #<Pet id: 2, name: "Spook", person_id: 1>,
-
# # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
-
# # ]
-
#
-
# Pet.find(1)
-
# # => ActiveRecord::RecordNotFound: Couldn't find Pet with id=1
-
#
-
# You can pass +Fixnum+ or +String+ values, it finds the records
-
# responding to the +id+ and executes delete on them.
-
#
-
# class Person < ActiveRecord::Base
-
# has_many :pets
-
# end
-
#
-
# person.pets.size # => 3
-
# person.pets
-
# # => [
-
# # #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
-
# # #<Pet id: 2, name: "Spook", person_id: 1>,
-
# # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
-
# # ]
-
#
-
# person.pets.delete("1")
-
# # => [#<Pet id: 1, name: "Fancy-Fancy", person_id: 1>]
-
#
-
# person.pets.delete(2, 3)
-
# # => [
-
# # #<Pet id: 2, name: "Spook", person_id: 1>,
-
# # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
-
# # ]
-
2
def delete(*records)
-
@association.delete(*records)
-
end
-
-
# Destroys the +records+ supplied and removes them from the collection.
-
# This method will _always_ remove record from the database ignoring
-
# the +:dependent+ option. Returns an array with the removed records.
-
#
-
# class Person < ActiveRecord::Base
-
# has_many :pets
-
# end
-
#
-
# person.pets.size # => 3
-
# person.pets
-
# # => [
-
# # #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
-
# # #<Pet id: 2, name: "Spook", person_id: 1>,
-
# # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
-
# # ]
-
#
-
# person.pets.destroy(Pet.find(1))
-
# # => [#<Pet id: 1, name: "Fancy-Fancy", person_id: 1>]
-
#
-
# person.pets.size # => 2
-
# person.pets
-
# # => [
-
# # #<Pet id: 2, name: "Spook", person_id: 1>,
-
# # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
-
# # ]
-
#
-
# person.pets.destroy(Pet.find(2), Pet.find(3))
-
# # => [
-
# # #<Pet id: 2, name: "Spook", person_id: 1>,
-
# # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
-
# # ]
-
#
-
# person.pets.size # => 0
-
# person.pets # => []
-
#
-
# Pet.find(1, 2, 3) # => ActiveRecord::RecordNotFound: Couldn't find all Pets with IDs (1, 2, 3)
-
#
-
# You can pass +Fixnum+ or +String+ values, it finds the records
-
# responding to the +id+ and then deletes them from the database.
-
#
-
# person.pets.size # => 3
-
# person.pets
-
# # => [
-
# # #<Pet id: 4, name: "Benny", person_id: 1>,
-
# # #<Pet id: 5, name: "Brain", person_id: 1>,
-
# # #<Pet id: 6, name: "Boss", person_id: 1>
-
# # ]
-
#
-
# person.pets.destroy("4")
-
# # => #<Pet id: 4, name: "Benny", person_id: 1>
-
#
-
# person.pets.size # => 2
-
# person.pets
-
# # => [
-
# # #<Pet id: 5, name: "Brain", person_id: 1>,
-
# # #<Pet id: 6, name: "Boss", person_id: 1>
-
# # ]
-
#
-
# person.pets.destroy(5, 6)
-
# # => [
-
# # #<Pet id: 5, name: "Brain", person_id: 1>,
-
# # #<Pet id: 6, name: "Boss", person_id: 1>
-
# # ]
-
#
-
# person.pets.size # => 0
-
# person.pets # => []
-
#
-
# Pet.find(4, 5, 6) # => ActiveRecord::RecordNotFound: Couldn't find all Pets with IDs (4, 5, 6)
-
2
def destroy(*records)
-
@association.destroy(*records)
-
end
-
-
# Specifies whether the records should be unique or not.
-
#
-
# class Person < ActiveRecord::Base
-
# has_many :pets
-
# end
-
#
-
# person.pets.select(:name)
-
# # => [
-
# # #<Pet name: "Fancy-Fancy">,
-
# # #<Pet name: "Fancy-Fancy">
-
# # ]
-
#
-
# person.pets.select(:name).distinct
-
# # => [#<Pet name: "Fancy-Fancy">]
-
2
def distinct
-
@association.distinct
-
end
-
2
alias uniq distinct
-
-
# Count all records using SQL.
-
#
-
# class Person < ActiveRecord::Base
-
# has_many :pets
-
# end
-
#
-
# person.pets.count # => 3
-
# person.pets
-
# # => [
-
# # #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
-
# # #<Pet id: 2, name: "Spook", person_id: 1>,
-
# # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
-
# # ]
-
2
def count(column_name = nil, options = {})
-
# TODO: Remove options argument as soon we remove support to
-
# activerecord-deprecated_finders.
-
@association.count(column_name, options)
-
end
-
-
# Returns the size of the collection. If the collection hasn't been loaded,
-
# it executes a <tt>SELECT COUNT(*)</tt> query. Else it calls <tt>collection.size</tt>.
-
#
-
# If the collection has been already loaded +size+ and +length+ are
-
# equivalent. If not and you are going to need the records anyway
-
# +length+ will take one less query. Otherwise +size+ is more efficient.
-
#
-
# class Person < ActiveRecord::Base
-
# has_many :pets
-
# end
-
#
-
# person.pets.size # => 3
-
# # executes something like SELECT COUNT(*) FROM "pets" WHERE "pets"."person_id" = 1
-
#
-
# person.pets # This will execute a SELECT * FROM query
-
# # => [
-
# # #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
-
# # #<Pet id: 2, name: "Spook", person_id: 1>,
-
# # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
-
# # ]
-
#
-
# person.pets.size # => 3
-
# # Because the collection is already loaded, this will behave like
-
# # collection.size and no SQL count query is executed.
-
2
def size
-
@association.size
-
end
-
-
# Returns the size of the collection calling +size+ on the target.
-
# If the collection has been already loaded, +length+ and +size+ are
-
# equivalent. If not and you are going to need the records anyway this
-
# method will take one less query. Otherwise +size+ is more efficient.
-
#
-
# class Person < ActiveRecord::Base
-
# has_many :pets
-
# end
-
#
-
# person.pets.length # => 3
-
# # executes something like SELECT "pets".* FROM "pets" WHERE "pets"."person_id" = 1
-
#
-
# # Because the collection is loaded, you can
-
# # call the collection with no additional queries:
-
# person.pets
-
# # => [
-
# # #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
-
# # #<Pet id: 2, name: "Spook", person_id: 1>,
-
# # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
-
# # ]
-
2
def length
-
@association.length
-
end
-
-
# Returns +true+ if the collection is empty. If the collection has been
-
# loaded it is equivalent
-
# to <tt>collection.size.zero?</tt>. If the collection has not been loaded,
-
# it is equivalent to <tt>collection.exists?</tt>. If the collection has
-
# not already been loaded and you are going to fetch the records anyway it
-
# is better to check <tt>collection.length.zero?</tt>.
-
#
-
# class Person < ActiveRecord::Base
-
# has_many :pets
-
# end
-
#
-
# person.pets.count # => 1
-
# person.pets.empty? # => false
-
#
-
# person.pets.delete_all
-
#
-
# person.pets.count # => 0
-
# person.pets.empty? # => true
-
2
def empty?
-
@association.empty?
-
end
-
-
# Returns +true+ if the collection is not empty.
-
#
-
# class Person < ActiveRecord::Base
-
# has_many :pets
-
# end
-
#
-
# person.pets.count # => 0
-
# person.pets.any? # => false
-
#
-
# person.pets << Pet.new(name: 'Snoop')
-
# person.pets.count # => 0
-
# person.pets.any? # => true
-
#
-
# You can also pass a block to define criteria. The behavior
-
# is the same, it returns true if the collection based on the
-
# criteria is not empty.
-
#
-
# person.pets
-
# # => [#<Pet name: "Snoop", group: "dogs">]
-
#
-
# person.pets.any? do |pet|
-
# pet.group == 'cats'
-
# end
-
# # => false
-
#
-
# person.pets.any? do |pet|
-
# pet.group == 'dogs'
-
# end
-
# # => true
-
2
def any?(&block)
-
@association.any?(&block)
-
end
-
-
# Returns true if the collection has more than one record.
-
# Equivalent to <tt>collection.size > 1</tt>.
-
#
-
# class Person < ActiveRecord::Base
-
# has_many :pets
-
# end
-
#
-
# person.pets.count # => 1
-
# person.pets.many? # => false
-
#
-
# person.pets << Pet.new(name: 'Snoopy')
-
# person.pets.count # => 2
-
# person.pets.many? # => true
-
#
-
# You can also pass a block to define criteria. The
-
# behavior is the same, it returns true if the collection
-
# based on the criteria has more than one record.
-
#
-
# person.pets
-
# # => [
-
# # #<Pet name: "Gorby", group: "cats">,
-
# # #<Pet name: "Puff", group: "cats">,
-
# # #<Pet name: "Snoop", group: "dogs">
-
# # ]
-
#
-
# person.pets.many? do |pet|
-
# pet.group == 'dogs'
-
# end
-
# # => false
-
#
-
# person.pets.many? do |pet|
-
# pet.group == 'cats'
-
# end
-
# # => true
-
2
def many?(&block)
-
@association.many?(&block)
-
end
-
-
# Returns +true+ if the given object is present in the collection.
-
#
-
# class Person < ActiveRecord::Base
-
# has_many :pets
-
# end
-
#
-
# person.pets # => [#<Pet id: 20, name: "Snoop">]
-
#
-
# person.pets.include?(Pet.find(20)) # => true
-
# person.pets.include?(Pet.find(21)) # => false
-
2
def include?(record)
-
!!@association.include?(record)
-
end
-
-
2
def arel
-
scope.arel
-
end
-
-
2
def proxy_association
-
@association
-
end
-
-
# We don't want this object to be put on the scoping stack, because
-
# that could create an infinite loop where we call an @association
-
# method, which gets the current scope, which is this object, which
-
# delegates to @association, and so on.
-
2
def scoping
-
@association.scope.scoping { yield }
-
end
-
-
# Returns a <tt>Relation</tt> object for the records in this association
-
2
def scope
-
@association.scope
-
end
-
2
alias spawn scope
-
-
# Equivalent to <tt>Array#==</tt>. Returns +true+ if the two arrays
-
# contain the same number of elements and if each element is equal
-
# to the corresponding element in the other array, otherwise returns
-
# +false+.
-
#
-
# class Person < ActiveRecord::Base
-
# has_many :pets
-
# end
-
#
-
# person.pets
-
# # => [
-
# # #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
-
# # #<Pet id: 2, name: "Spook", person_id: 1>
-
# # ]
-
#
-
# other = person.pets.to_ary
-
#
-
# person.pets == other
-
# # => true
-
#
-
# other = [Pet.new(id: 1), Pet.new(id: 2)]
-
#
-
# person.pets == other
-
# # => false
-
2
def ==(other)
-
load_target == other
-
end
-
-
# Returns a new array of objects from the collection. If the collection
-
# hasn't been loaded, it fetches the records from the database.
-
#
-
# class Person < ActiveRecord::Base
-
# has_many :pets
-
# end
-
#
-
# person.pets
-
# # => [
-
# # #<Pet id: 4, name: "Benny", person_id: 1>,
-
# # #<Pet id: 5, name: "Brain", person_id: 1>,
-
# # #<Pet id: 6, name: "Boss", person_id: 1>
-
# # ]
-
#
-
# other_pets = person.pets.to_ary
-
# # => [
-
# # #<Pet id: 4, name: "Benny", person_id: 1>,
-
# # #<Pet id: 5, name: "Brain", person_id: 1>,
-
# # #<Pet id: 6, name: "Boss", person_id: 1>
-
# # ]
-
#
-
# other_pets.replace([Pet.new(name: 'BooGoo')])
-
#
-
# other_pets
-
# # => [#<Pet id: nil, name: "BooGoo", person_id: 1>]
-
#
-
# person.pets
-
# # This is not affected by replace
-
# # => [
-
# # #<Pet id: 4, name: "Benny", person_id: 1>,
-
# # #<Pet id: 5, name: "Brain", person_id: 1>,
-
# # #<Pet id: 6, name: "Boss", person_id: 1>
-
# # ]
-
2
def to_ary
-
load_target.dup
-
end
-
2
alias_method :to_a, :to_ary
-
-
# Adds one or more +records+ to the collection by setting their foreign keys
-
# to the association's primary key. Returns +self+, so several appends may be
-
# chained together.
-
#
-
# class Person < ActiveRecord::Base
-
# has_many :pets
-
# end
-
#
-
# person.pets.size # => 0
-
# person.pets << Pet.new(name: 'Fancy-Fancy')
-
# person.pets << [Pet.new(name: 'Spook'), Pet.new(name: 'Choo-Choo')]
-
# person.pets.size # => 3
-
#
-
# person.id # => 1
-
# person.pets
-
# # => [
-
# # #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
-
# # #<Pet id: 2, name: "Spook", person_id: 1>,
-
# # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
-
# # ]
-
2
def <<(*records)
-
proxy_association.concat(records) && self
-
end
-
2
alias_method :push, :<<
-
2
alias_method :append, :<<
-
-
2
def prepend(*args)
-
raise NoMethodError, "prepend on association is not defined. Please use << or append"
-
end
-
-
# Equivalent to +delete_all+. The difference is that returns +self+, instead
-
# of an array with the deleted objects, so methods can be chained. See
-
# +delete_all+ for more information.
-
2
def clear
-
delete_all
-
self
-
end
-
-
# Reloads the collection from the database. Returns +self+.
-
# Equivalent to <tt>collection(true)</tt>.
-
#
-
# class Person < ActiveRecord::Base
-
# has_many :pets
-
# end
-
#
-
# person.pets # fetches pets from the database
-
# # => [#<Pet id: 1, name: "Snoop", group: "dogs", person_id: 1>]
-
#
-
# person.pets # uses the pets cache
-
# # => [#<Pet id: 1, name: "Snoop", group: "dogs", person_id: 1>]
-
#
-
# person.pets.reload # fetches pets from the database
-
# # => [#<Pet id: 1, name: "Snoop", group: "dogs", person_id: 1>]
-
#
-
# person.pets(true) # fetches pets from the database
-
# # => [#<Pet id: 1, name: "Snoop", group: "dogs", person_id: 1>]
-
2
def reload
-
proxy_association.reload
-
self
-
end
-
-
# Unloads the association. Returns +self+.
-
#
-
# class Person < ActiveRecord::Base
-
# has_many :pets
-
# end
-
#
-
# person.pets # fetches pets from the database
-
# # => [#<Pet id: 1, name: "Snoop", group: "dogs", person_id: 1>]
-
#
-
# person.pets # uses the pets cache
-
# # => [#<Pet id: 1, name: "Snoop", group: "dogs", person_id: 1>]
-
#
-
# person.pets.reset # clears the pets cache
-
#
-
# person.pets # fetches pets from the database
-
# # => [#<Pet id: 1, name: "Snoop", group: "dogs", person_id: 1>]
-
2
def reset
-
proxy_association.reset
-
proxy_association.reset_scope
-
self
-
end
-
end
-
end
-
end
-
1
module ActiveRecord
-
# = Active Record Has Many Association
-
1
module Associations
-
# This is the proxy that handles a has many association.
-
#
-
# If the association has a <tt>:through</tt> option further specialization
-
# is provided by its child HasManyThroughAssociation.
-
1
class HasManyAssociation < CollectionAssociation #:nodoc:
-
-
1
def handle_dependency
-
case options[:dependent]
-
when :restrict_with_exception
-
raise ActiveRecord::DeleteRestrictionError.new(reflection.name) unless empty?
-
-
when :restrict_with_error
-
unless empty?
-
record = klass.human_attribute_name(reflection.name).downcase
-
owner.errors.add(:base, :"restrict_dependent_destroy.many", record: record)
-
false
-
end
-
-
else
-
if options[:dependent] == :destroy
-
# No point in executing the counter update since we're going to destroy the parent anyway
-
load_target.each { |t| t.destroyed_by_association = reflection }
-
destroy_all
-
else
-
delete_all
-
end
-
end
-
end
-
-
1
def insert_record(record, validate = true, raise = false)
-
72
set_owner_attributes(record)
-
72
set_inverse_instance(record)
-
-
72
if raise
-
record.save!(:validate => validate)
-
else
-
72
record.save(:validate => validate)
-
end
-
end
-
-
1
private
-
-
# Returns the number of records in this collection.
-
#
-
# If the association has a counter cache it gets that value. Otherwise
-
# it will attempt to do a count via SQL, bounded to <tt>:limit</tt> if
-
# there's one. Some configuration options like :group make it impossible
-
# to do an SQL count, in those cases the array count will be used.
-
#
-
# That does not depend on whether the collection has already been loaded
-
# or not. The +size+ method is the one that takes the loaded flag into
-
# account and delegates to +count_records+ if needed.
-
#
-
# If the collection is empty the target is set to an empty array and
-
# the loaded flag is set to true as well.
-
1
def count_records
-
count = if has_cached_counter?
-
owner.send(:read_attribute, cached_counter_attribute_name)
-
else
-
scope.count
-
end
-
-
# If there's nothing in the database and @target has no new records
-
# we are certain the current target is an empty array. This is a
-
# documented side-effect of the method that may avoid an extra SELECT.
-
@target ||= [] and loaded! if count == 0
-
-
[association_scope.limit_value, count].compact.min
-
end
-
-
1
def has_cached_counter?(reflection = reflection())
-
owner.attribute_present?(cached_counter_attribute_name(reflection))
-
end
-
-
1
def cached_counter_attribute_name(reflection = reflection())
-
options[:counter_cache] || "#{reflection.name}_count"
-
end
-
-
1
def update_counter(difference, reflection = reflection())
-
if has_cached_counter?(reflection)
-
counter = cached_counter_attribute_name(reflection)
-
owner.class.update_counters(owner.id, counter => difference)
-
owner[counter] += difference
-
owner.changed_attributes.delete(counter) # eww
-
end
-
end
-
-
# This shit is nasty. We need to avoid the following situation:
-
#
-
# * An associated record is deleted via record.destroy
-
# * Hence the callbacks run, and they find a belongs_to on the record with a
-
# :counter_cache options which points back at our owner. So they update the
-
# counter cache.
-
# * In which case, we must make sure to *not* update the counter cache, or else
-
# it will be decremented twice.
-
#
-
# Hence this method.
-
1
def inverse_updates_counter_cache?(reflection = reflection())
-
counter_name = cached_counter_attribute_name(reflection)
-
reflection.klass._reflections.values.any? { |inverse_reflection|
-
:belongs_to == inverse_reflection.macro &&
-
inverse_reflection.counter_cache_column == counter_name
-
}
-
end
-
-
# Deletes the records according to the <tt>:dependent</tt> option.
-
1
def delete_records(records, method)
-
if method == :destroy
-
records.each(&:destroy!)
-
update_counter(-records.length) unless inverse_updates_counter_cache?
-
else
-
if records == :all || !reflection.klass.primary_key
-
scope = self.scope
-
else
-
scope = self.scope.where(reflection.klass.primary_key => records)
-
end
-
-
if method == :delete_all
-
update_counter(-scope.delete_all)
-
else
-
update_counter(-scope.update_all(reflection.foreign_key => nil))
-
end
-
end
-
end
-
-
1
def foreign_key_present?
-
if reflection.klass.primary_key
-
owner.attribute_present?(reflection.association_primary_key)
-
else
-
false
-
end
-
end
-
end
-
end
-
end
-
2
module ActiveRecord
-
2
module Associations
-
2
class JoinDependency # :nodoc:
-
2
autoload :JoinBase, 'active_record/associations/join_dependency/join_base'
-
2
autoload :JoinAssociation, 'active_record/associations/join_dependency/join_association'
-
-
2
class Aliases # :nodoc:
-
2
def initialize(tables)
-
@tables = tables
-
@alias_cache = tables.each_with_object({}) { |table,h|
-
h[table.node] = table.columns.each_with_object({}) { |column,i|
-
i[column.name] = column.alias
-
}
-
}
-
@name_and_alias_cache = tables.each_with_object({}) { |table,h|
-
h[table.node] = table.columns.map { |column|
-
[column.name, column.alias]
-
}
-
}
-
end
-
-
2
def columns
-
@tables.flat_map { |t| t.column_aliases }
-
end
-
-
# An array of [column_name, alias] pairs for the table
-
2
def column_aliases(node)
-
@name_and_alias_cache[node]
-
end
-
-
2
def column_alias(node, column)
-
@alias_cache[node][column]
-
end
-
-
2
class Table < Struct.new(:node, :columns)
-
2
def table
-
Arel::Nodes::TableAlias.new node.table, node.aliased_table_name
-
end
-
-
2
def column_aliases
-
t = table
-
columns.map { |column| t[column.name].as Arel.sql column.alias }
-
end
-
end
-
2
Column = Struct.new(:name, :alias)
-
end
-
-
2
attr_reader :alias_tracker, :base_klass, :join_root
-
-
2
def self.make_tree(associations)
-
390
hash = {}
-
390
walk_tree associations, hash
-
390
hash
-
end
-
-
2
def self.walk_tree(associations, hash)
-
390
case associations
-
when Symbol, String
-
hash[associations.to_sym] ||= {}
-
when Array
-
390
associations.each do |assoc|
-
walk_tree assoc, hash
-
end
-
when Hash
-
associations.each do |k,v|
-
cache = hash[k] ||= {}
-
walk_tree v, cache
-
end
-
else
-
raise ConfigurationError, associations.inspect
-
end
-
end
-
-
# base is the base class on which operation is taking place.
-
# associations is the list of associations which are joined using hash, symbol or array.
-
# joins is the list of all string join commands and arel nodes.
-
#
-
# Example :
-
#
-
# class Physician < ActiveRecord::Base
-
# has_many :appointments
-
# has_many :patients, through: :appointments
-
# end
-
#
-
# If I execute `@physician.patients.to_a` then
-
# base # => Physician
-
# associations # => []
-
# joins # => [#<Arel::Nodes::InnerJoin: ...]
-
#
-
# However if I execute `Physician.joins(:appointments).to_a` then
-
# base # => Physician
-
# associations # => [:appointments]
-
# joins # => []
-
#
-
2
def initialize(base, associations, joins)
-
390
@alias_tracker = AliasTracker.create(base.connection, joins)
-
390
@alias_tracker.aliased_name_for(base.table_name, base.table_name) # Updates the count for base.table_name to 1
-
390
tree = self.class.make_tree associations
-
390
@join_root = JoinBase.new base, build(tree, base)
-
390
@join_root.children.each { |child| construct_tables! @join_root, child }
-
end
-
-
2
def reflections
-
195
join_root.drop(1).map!(&:reflection)
-
end
-
-
2
def join_constraints(outer_joins)
-
195
joins = join_root.children.flat_map { |child|
-
make_inner_joins join_root, child
-
}
-
-
195
joins.concat outer_joins.flat_map { |oj|
-
195
if join_root.match? oj.join_root
-
195
walk join_root, oj.join_root
-
else
-
oj.join_root.children.flat_map { |child|
-
make_outer_joins oj.join_root, child
-
}
-
end
-
}
-
end
-
-
2
def aliases
-
Aliases.new join_root.each_with_index.map { |join_part,i|
-
columns = join_part.column_names.each_with_index.map { |column_name,j|
-
Aliases::Column.new column_name, "t#{i}_r#{j}"
-
}
-
Aliases::Table.new(join_part, columns)
-
}
-
end
-
-
2
def instantiate(result_set, aliases)
-
primary_key = aliases.column_alias(join_root, join_root.primary_key)
-
type_caster = result_set.column_type primary_key
-
-
seen = Hash.new { |h,parent_klass|
-
h[parent_klass] = Hash.new { |i,parent_id|
-
i[parent_id] = Hash.new { |j,child_klass| j[child_klass] = {} }
-
}
-
}
-
-
model_cache = Hash.new { |h,klass| h[klass] = {} }
-
parents = model_cache[join_root]
-
column_aliases = aliases.column_aliases join_root
-
-
result_set.each { |row_hash|
-
primary_id = type_caster.type_cast row_hash[primary_key]
-
parent = parents[primary_id] ||= join_root.instantiate(row_hash, column_aliases)
-
construct(parent, join_root, row_hash, result_set, seen, model_cache, aliases)
-
}
-
-
parents.values
-
end
-
-
2
private
-
-
2
def make_constraints(parent, child, tables, join_type)
-
chain = child.reflection.chain
-
foreign_table = parent.table
-
foreign_klass = parent.base_klass
-
child.join_constraints(foreign_table, foreign_klass, child, join_type, tables, child.reflection.scope_chain, chain)
-
end
-
-
2
def make_outer_joins(parent, child)
-
tables = table_aliases_for(parent, child)
-
join_type = Arel::Nodes::OuterJoin
-
joins = make_constraints parent, child, tables, join_type
-
-
joins.concat child.children.flat_map { |c| make_outer_joins(child, c) }
-
end
-
-
2
def make_inner_joins(parent, child)
-
tables = child.tables
-
join_type = Arel::Nodes::InnerJoin
-
joins = make_constraints parent, child, tables, join_type
-
-
joins.concat child.children.flat_map { |c| make_inner_joins(child, c) }
-
end
-
-
2
def table_aliases_for(parent, node)
-
node.reflection.chain.map { |reflection|
-
alias_tracker.aliased_table_for(
-
reflection.table_name,
-
table_alias_for(reflection, parent, reflection != node.reflection)
-
)
-
}
-
end
-
-
2
def construct_tables!(parent, node)
-
node.tables = table_aliases_for(parent, node)
-
node.children.each { |child| construct_tables! node, child }
-
end
-
-
2
def table_alias_for(reflection, parent, join)
-
name = "#{reflection.plural_name}_#{parent.table_name}"
-
name << "_join" if join
-
name
-
end
-
-
2
def walk(left, right)
-
195
intersection, missing = right.children.map { |node1|
-
[left.children.find { |node2| node1.match? node2 }, node1]
-
}.partition(&:first)
-
-
195
ojs = missing.flat_map { |_,n| make_outer_joins left, n }
-
195
intersection.flat_map { |l,r| walk l, r }.concat ojs
-
end
-
-
2
def find_reflection(klass, name)
-
klass._reflect_on_association(name) or
-
raise ConfigurationError, "Association named '#{ name }' was not found on #{ klass.name }; perhaps you misspelled it?"
-
end
-
-
2
def build(associations, base_klass)
-
390
associations.map do |name, right|
-
reflection = find_reflection base_klass, name
-
reflection.check_validity!
-
-
if reflection.options[:polymorphic]
-
raise EagerLoadPolymorphicError.new(reflection)
-
end
-
-
JoinAssociation.new reflection, build(right, reflection.klass)
-
end
-
end
-
-
2
def construct(ar_parent, parent, row, rs, seen, model_cache, aliases)
-
primary_id = ar_parent.id
-
-
parent.children.each do |node|
-
if node.reflection.collection?
-
other = ar_parent.association(node.reflection.name)
-
other.loaded!
-
else
-
if ar_parent.association_cache.key?(node.reflection.name)
-
model = ar_parent.association(node.reflection.name).target
-
construct(model, node, row, rs, seen, model_cache, aliases)
-
next
-
end
-
end
-
-
key = aliases.column_alias(node, node.primary_key)
-
id = row[key]
-
next if id.nil?
-
-
model = seen[parent.base_klass][primary_id][node.base_klass][id]
-
-
if model
-
construct(model, node, row, rs, seen, model_cache, aliases)
-
else
-
model = construct_model(ar_parent, node, row, model_cache, id, aliases)
-
seen[parent.base_klass][primary_id][node.base_klass][id] = model
-
construct(model, node, row, rs, seen, model_cache, aliases)
-
end
-
end
-
end
-
-
2
def construct_model(record, node, row, model_cache, id, aliases)
-
model = model_cache[node][id] ||= node.instantiate(row,
-
aliases.column_aliases(node))
-
other = record.association(node.reflection.name)
-
-
if node.reflection.collection?
-
other.target.push(model)
-
else
-
other.target = model
-
end
-
-
other.set_inverse_instance(model)
-
model
-
end
-
end
-
end
-
end
-
2
require 'active_record/associations/join_dependency/join_part'
-
-
2
module ActiveRecord
-
2
module Associations
-
2
class JoinDependency # :nodoc:
-
2
class JoinBase < JoinPart # :nodoc:
-
2
def match?(other)
-
195
return true if self == other
-
195
super && base_klass == other.base_klass
-
end
-
-
2
def table
-
base_klass.arel_table
-
end
-
-
2
def aliased_table_name
-
base_klass.table_name
-
end
-
end
-
end
-
end
-
end
-
2
module ActiveRecord
-
2
module Associations
-
2
class JoinDependency # :nodoc:
-
# A JoinPart represents a part of a JoinDependency. It is inherited
-
# by JoinBase and JoinAssociation. A JoinBase represents the Active Record which
-
# everything else is being joined onto. A JoinAssociation represents an association which
-
# is joining to the base. A JoinAssociation may result in more than one actual join
-
# operations (for example a has_and_belongs_to_many JoinAssociation would result in
-
# two; one for the join table and one for the target table).
-
2
class JoinPart # :nodoc:
-
2
include Enumerable
-
-
# The Active Record class which this join part is associated 'about'; for a JoinBase
-
# this is the actual base model, for a JoinAssociation this is the target model of the
-
# association.
-
2
attr_reader :base_klass, :children
-
-
2
delegate :table_name, :column_names, :primary_key, :to => :base_klass
-
-
2
def initialize(base_klass, children)
-
390
@base_klass = base_klass
-
390
@column_names_with_alias = nil
-
390
@children = children
-
end
-
-
2
def name
-
reflection.name
-
end
-
-
2
def match?(other)
-
195
self.class == other.class
-
end
-
-
2
def each(&block)
-
195
yield self
-
195
children.each { |child| child.each(&block) }
-
end
-
-
# An Arel::Table for the active_record
-
2
def table
-
raise NotImplementedError
-
end
-
-
# The alias for the active_record's table
-
2
def aliased_table_name
-
raise NotImplementedError
-
end
-
-
2
def extract_record(row, column_names_with_alias)
-
# This code is performance critical as it is called per row.
-
# see: https://github.com/rails/rails/pull/12185
-
hash = {}
-
-
index = 0
-
length = column_names_with_alias.length
-
-
while index < length
-
column_name, alias_name = column_names_with_alias[index]
-
hash[column_name] = row[alias_name]
-
index += 1
-
end
-
-
hash
-
end
-
-
2
def instantiate(row, aliases)
-
base_klass.instantiate(extract_record(row, aliases))
-
end
-
end
-
end
-
end
-
end
-
1
module ActiveRecord
-
1
module Associations
-
# Implements the details of eager loading of Active Record associations.
-
#
-
# Note that 'eager loading' and 'preloading' are actually the same thing.
-
# However, there are two different eager loading strategies.
-
#
-
# The first one is by using table joins. This was only strategy available
-
# prior to Rails 2.1. Suppose that you have an Author model with columns
-
# 'name' and 'age', and a Book model with columns 'name' and 'sales'. Using
-
# this strategy, Active Record would try to retrieve all data for an author
-
# and all of its books via a single query:
-
#
-
# SELECT * FROM authors
-
# LEFT OUTER JOIN books ON authors.id = books.author_id
-
# WHERE authors.name = 'Ken Akamatsu'
-
#
-
# However, this could result in many rows that contain redundant data. After
-
# having received the first row, we already have enough data to instantiate
-
# the Author object. In all subsequent rows, only the data for the joined
-
# 'books' table is useful; the joined 'authors' data is just redundant, and
-
# processing this redundant data takes memory and CPU time. The problem
-
# quickly becomes worse and worse as the level of eager loading increases
-
# (i.e. if Active Record is to eager load the associations' associations as
-
# well).
-
#
-
# The second strategy is to use multiple database queries, one for each
-
# level of association. Since Rails 2.1, this is the default strategy. In
-
# situations where a table join is necessary (e.g. when the +:conditions+
-
# option references an association's column), it will fallback to the table
-
# join strategy.
-
1
class Preloader #:nodoc:
-
1
extend ActiveSupport::Autoload
-
-
1
eager_autoload do
-
1
autoload :Association, 'active_record/associations/preloader/association'
-
1
autoload :SingularAssociation, 'active_record/associations/preloader/singular_association'
-
1
autoload :CollectionAssociation, 'active_record/associations/preloader/collection_association'
-
1
autoload :ThroughAssociation, 'active_record/associations/preloader/through_association'
-
-
1
autoload :HasMany, 'active_record/associations/preloader/has_many'
-
1
autoload :HasManyThrough, 'active_record/associations/preloader/has_many_through'
-
1
autoload :HasOne, 'active_record/associations/preloader/has_one'
-
1
autoload :HasOneThrough, 'active_record/associations/preloader/has_one_through'
-
1
autoload :BelongsTo, 'active_record/associations/preloader/belongs_to'
-
end
-
-
# Eager loads the named associations for the given Active Record record(s).
-
#
-
# In this description, 'association name' shall refer to the name passed
-
# to an association creation method. For example, a model that specifies
-
# <tt>belongs_to :author</tt>, <tt>has_many :buyers</tt> has association
-
# names +:author+ and +:buyers+.
-
#
-
# == Parameters
-
# +records+ is an array of ActiveRecord::Base. This array needs not be flat,
-
# i.e. +records+ itself may also contain arrays of records. In any case,
-
# +preload_associations+ will preload the all associations records by
-
# flattening +records+.
-
#
-
# +associations+ specifies one or more associations that you want to
-
# preload. It may be:
-
# - a Symbol or a String which specifies a single association name. For
-
# example, specifying +:books+ allows this method to preload all books
-
# for an Author.
-
# - an Array which specifies multiple association names. This array
-
# is processed recursively. For example, specifying <tt>[:avatar, :books]</tt>
-
# allows this method to preload an author's avatar as well as all of his
-
# books.
-
# - a Hash which specifies multiple association names, as well as
-
# association names for the to-be-preloaded association objects. For
-
# example, specifying <tt>{ author: :avatar }</tt> will preload a
-
# book's author, as well as that author's avatar.
-
#
-
# +:associations+ has the same format as the +:include+ option for
-
# <tt>ActiveRecord::Base.find</tt>. So +associations+ could look like this:
-
#
-
# :books
-
# [ :books, :author ]
-
# { author: :avatar }
-
# [ :books, { author: :avatar } ]
-
-
1
NULL_RELATION = Struct.new(:values).new({})
-
-
1
def preload(records, associations, preload_scope = nil)
-
records = Array.wrap(records).compact.uniq
-
associations = Array.wrap(associations)
-
preload_scope = preload_scope || NULL_RELATION
-
-
if records.empty?
-
[]
-
else
-
associations.flat_map { |association|
-
preloaders_on association, records, preload_scope
-
}
-
end
-
end
-
-
1
private
-
-
1
def preloaders_on(association, records, scope)
-
case association
-
when Hash
-
preloaders_for_hash(association, records, scope)
-
when Symbol
-
preloaders_for_one(association, records, scope)
-
when String
-
preloaders_for_one(association.to_sym, records, scope)
-
else
-
raise ArgumentError, "#{association.inspect} was not recognised for preload"
-
end
-
end
-
-
1
def preloaders_for_hash(association, records, scope)
-
association.flat_map { |parent, child|
-
loaders = preloaders_for_one parent, records, scope
-
-
recs = loaders.flat_map(&:preloaded_records).uniq
-
loaders.concat Array.wrap(child).flat_map { |assoc|
-
preloaders_on assoc, recs, scope
-
}
-
loaders
-
}
-
end
-
-
# Not all records have the same class, so group then preload group on the reflection
-
# itself so that if various subclass share the same association then we do not split
-
# them unnecessarily
-
#
-
# Additionally, polymorphic belongs_to associations can have multiple associated
-
# classes, depending on the polymorphic_type field. So we group by the classes as
-
# well.
-
1
def preloaders_for_one(association, records, scope)
-
grouped_records(association, records).flat_map do |reflection, klasses|
-
klasses.map do |rhs_klass, rs|
-
loader = preloader_for(reflection, rs, rhs_klass).new(rhs_klass, rs, reflection, scope)
-
loader.run self
-
loader
-
end
-
end
-
end
-
-
1
def grouped_records(association, records)
-
h = {}
-
records.each do |record|
-
next unless record
-
assoc = record.association(association)
-
klasses = h[assoc.reflection] ||= {}
-
(klasses[assoc.klass] ||= []) << record
-
end
-
h
-
end
-
-
1
class AlreadyLoaded
-
1
attr_reader :owners, :reflection
-
-
1
def initialize(klass, owners, reflection, preload_scope)
-
@owners = owners
-
@reflection = reflection
-
end
-
-
1
def run(preloader); end
-
-
1
def preloaded_records
-
owners.flat_map { |owner| owner.association(reflection.name).target }
-
end
-
end
-
-
1
class NullPreloader
-
1
def self.new(klass, owners, reflection, preload_scope); self; end
-
1
def self.run(preloader); end
-
end
-
-
1
def preloader_for(reflection, owners, rhs_klass)
-
return NullPreloader unless rhs_klass
-
-
if owners.first.association(reflection.name).loaded?
-
return AlreadyLoaded
-
end
-
-
case reflection.macro
-
when :has_many
-
reflection.options[:through] ? HasManyThrough : HasMany
-
when :has_one
-
reflection.options[:through] ? HasOneThrough : HasOne
-
when :belongs_to
-
BelongsTo
-
end
-
end
-
end
-
end
-
end
-
1
module ActiveRecord
-
1
module Associations
-
1
class SingularAssociation < Association #:nodoc:
-
# Implements the reader method, e.g. foo.bar for Foo.has_one :bar
-
1
def reader(force_reload = false)
-
if force_reload
-
klass.uncached { reload }
-
elsif !loaded? || stale_target?
-
reload
-
end
-
-
target
-
end
-
-
# Implements the writer method, e.g. foo.bar= for Foo.belongs_to :bar
-
1
def writer(record)
-
144
replace(record)
-
end
-
-
1
def create(attributes = {}, &block)
-
_create_record(attributes, &block)
-
end
-
-
1
def create!(attributes = {}, &block)
-
_create_record(attributes, true, &block)
-
end
-
-
1
def build(attributes = {})
-
record = build_record(attributes)
-
yield(record) if block_given?
-
set_new_record(record)
-
record
-
end
-
-
1
private
-
-
1
def create_scope
-
scope.scope_for_create.stringify_keys.except(klass.primary_key)
-
end
-
-
1
def find_target
-
if record = scope.take
-
set_inverse_instance record
-
end
-
end
-
-
1
def replace(record)
-
raise NotImplementedError, "Subclasses must implement a replace(record) method"
-
end
-
-
1
def set_new_record(record)
-
replace(record)
-
end
-
-
1
def _create_record(attributes, raise_error = false)
-
record = build_record(attributes)
-
yield(record) if block_given?
-
saved = record.save
-
set_new_record(record)
-
raise RecordInvalid.new(record) if !saved && raise_error
-
record
-
end
-
end
-
end
-
end
-
2
require 'active_model/forbidden_attributes_protection'
-
-
2
module ActiveRecord
-
2
module AttributeAssignment
-
2
extend ActiveSupport::Concern
-
2
include ActiveModel::ForbiddenAttributesProtection
-
-
# Allows you to set all the attributes by passing in a hash of attributes with
-
# keys matching the attribute names (which again matches the column names).
-
#
-
# If the passed hash responds to <tt>permitted?</tt> method and the return value
-
# of this method is +false+ an <tt>ActiveModel::ForbiddenAttributesError</tt>
-
# exception is raised.
-
2
def assign_attributes(new_attributes)
-
347
if !new_attributes.respond_to?(:stringify_keys)
-
raise ArgumentError, "When assigning attributes, you must pass a hash as an argument."
-
end
-
347
return if new_attributes.blank?
-
-
347
attributes = new_attributes.stringify_keys
-
347
multi_parameter_attributes = []
-
347
nested_parameter_attributes = []
-
-
347
attributes = sanitize_for_mass_assignment(attributes)
-
-
347
attributes.each do |k, v|
-
1039
if k.include?("(")
-
multi_parameter_attributes << [ k, v ]
-
elsif v.is_a?(Hash)
-
72
nested_parameter_attributes << [ k, v ]
-
else
-
967
_assign_attribute(k, v)
-
end
-
end
-
-
347
assign_nested_parameter_attributes(nested_parameter_attributes) unless nested_parameter_attributes.empty?
-
347
assign_multiparameter_attributes(multi_parameter_attributes) unless multi_parameter_attributes.empty?
-
end
-
-
2
alias attributes= assign_attributes
-
-
2
private
-
-
2
def _assign_attribute(k, v)
-
1039
public_send("#{k}=", v)
-
rescue NoMethodError
-
if respond_to?("#{k}=")
-
raise
-
else
-
raise UnknownAttributeError.new(self, k)
-
end
-
end
-
-
# Assign any deferred nested attributes after the base attributes have been set.
-
2
def assign_nested_parameter_attributes(pairs)
-
144
pairs.each { |k, v| _assign_attribute(k, v) }
-
end
-
-
# Instantiates objects for all attribute classes that needs more than one constructor parameter. This is done
-
# by calling new on the column type or aggregation type (through composed_of) object with these parameters.
-
# So having the pairs written_on(1) = "2004", written_on(2) = "6", written_on(3) = "24", will instantiate
-
# written_on (a date type) with Date.new("2004", "6", "24"). You can also specify a typecast character in the
-
# parentheses to have the parameters typecasted before they're used in the constructor. Use i for Fixnum and
-
# f for Float. If all the values for a given attribute are empty, the attribute will be set to +nil+.
-
2
def assign_multiparameter_attributes(pairs)
-
execute_callstack_for_multiparameter_attributes(
-
extract_callstack_for_multiparameter_attributes(pairs)
-
)
-
end
-
-
2
def execute_callstack_for_multiparameter_attributes(callstack)
-
errors = []
-
callstack.each do |name, values_with_empty_parameters|
-
begin
-
send("#{name}=", MultiparameterAttribute.new(self, name, values_with_empty_parameters).read_value)
-
rescue => ex
-
errors << AttributeAssignmentError.new("error on assignment #{values_with_empty_parameters.values.inspect} to #{name} (#{ex.message})", ex, name)
-
end
-
end
-
unless errors.empty?
-
error_descriptions = errors.map { |ex| ex.message }.join(",")
-
raise MultiparameterAssignmentErrors.new(errors), "#{errors.size} error(s) on assignment of multiparameter attributes [#{error_descriptions}]"
-
end
-
end
-
-
2
def extract_callstack_for_multiparameter_attributes(pairs)
-
attributes = {}
-
-
pairs.each do |(multiparameter_name, value)|
-
attribute_name = multiparameter_name.split("(").first
-
attributes[attribute_name] ||= {}
-
-
parameter_value = value.empty? ? nil : type_cast_attribute_value(multiparameter_name, value)
-
attributes[attribute_name][find_parameter_position(multiparameter_name)] ||= parameter_value
-
end
-
-
attributes
-
end
-
-
2
def type_cast_attribute_value(multiparameter_name, value)
-
multiparameter_name =~ /\([0-9]*([if])\)/ ? value.send("to_" + $1) : value
-
end
-
-
2
def find_parameter_position(multiparameter_name)
-
multiparameter_name.scan(/\(([0-9]*).*\)/).first.first.to_i
-
end
-
-
2
class MultiparameterAttribute #:nodoc:
-
2
attr_reader :object, :name, :values, :column
-
-
2
def initialize(object, name, values)
-
@object = object
-
@name = name
-
@values = values
-
end
-
-
2
def read_value
-
return if values.values.compact.empty?
-
-
@column = object.class.reflect_on_aggregation(name.to_sym) || object.column_for_attribute(name)
-
klass = column.klass
-
-
if klass == Time
-
read_time
-
elsif klass == Date
-
read_date
-
else
-
read_other(klass)
-
end
-
end
-
-
2
private
-
-
2
def instantiate_time_object(set_values)
-
if object.class.send(:create_time_zone_conversion_attribute?, name, column)
-
Time.zone.local(*set_values)
-
else
-
Time.send(object.class.default_timezone, *set_values)
-
end
-
end
-
-
2
def read_time
-
# If column is a :time (and not :date or :timestamp) there is no need to validate if
-
# there are year/month/day fields
-
if column.type == :time
-
# if the column is a time set the values to their defaults as January 1, 1970, but only if they're nil
-
{ 1 => 1970, 2 => 1, 3 => 1 }.each do |key,value|
-
values[key] ||= value
-
end
-
else
-
# else column is a timestamp, so if Date bits were not provided, error
-
validate_required_parameters!([1,2,3])
-
-
# If Date bits were provided but blank, then return nil
-
return if blank_date_parameter?
-
end
-
-
max_position = extract_max_param(6)
-
set_values = values.values_at(*(1..max_position))
-
# If Time bits are not there, then default to 0
-
(3..5).each { |i| set_values[i] = set_values[i].presence || 0 }
-
instantiate_time_object(set_values)
-
end
-
-
2
def read_date
-
return if blank_date_parameter?
-
set_values = values.values_at(1,2,3)
-
begin
-
Date.new(*set_values)
-
rescue ArgumentError # if Date.new raises an exception on an invalid date
-
instantiate_time_object(set_values).to_date # we instantiate Time object and convert it back to a date thus using Time's logic in handling invalid dates
-
end
-
end
-
-
2
def read_other(klass)
-
max_position = extract_max_param
-
positions = (1..max_position)
-
validate_required_parameters!(positions)
-
-
set_values = values.values_at(*positions)
-
klass.new(*set_values)
-
end
-
-
# Checks whether some blank date parameter exists. Note that this is different
-
# than the validate_required_parameters! method, since it just checks for blank
-
# positions instead of missing ones, and does not raise in case one blank position
-
# exists. The caller is responsible to handle the case of this returning true.
-
2
def blank_date_parameter?
-
(1..3).any? { |position| values[position].blank? }
-
end
-
-
# If some position is not provided, it errors out a missing parameter exception.
-
2
def validate_required_parameters!(positions)
-
if missing_parameter = positions.detect { |position| !values.key?(position) }
-
raise ArgumentError.new("Missing Parameter - #{name}(#{missing_parameter})")
-
end
-
end
-
-
2
def extract_max_param(upper_cap = 100)
-
[values.keys.max, upper_cap].min
-
end
-
end
-
end
-
end
-
2
require 'active_support/core_ext/enumerable'
-
2
require 'mutex_m'
-
2
require 'thread_safe'
-
-
2
module ActiveRecord
-
# = Active Record Attribute Methods
-
2
module AttributeMethods
-
2
extend ActiveSupport::Concern
-
2
include ActiveModel::AttributeMethods
-
-
2
included do
-
2
initialize_generated_modules
-
2
include Read
-
2
include Write
-
2
include BeforeTypeCast
-
2
include Query
-
2
include PrimaryKey
-
2
include TimeZoneConversion
-
2
include Dirty
-
2
include Serialization
-
end
-
-
2
AttrNames = Module.new {
-
2
def self.set_name_cache(name, value)
-
106
const_name = "ATTR_#{name}"
-
106
unless const_defined? const_name
-
57
const_set const_name, value.dup.freeze
-
end
-
end
-
}
-
-
2
BLACKLISTED_CLASS_METHODS = %w(private public protected allocate new name parent superclass)
-
-
2
class AttributeMethodCache
-
2
def initialize
-
4
@module = Module.new
-
4
@method_cache = ThreadSafe::Cache.new
-
end
-
-
2
def [](name)
-
198
@method_cache.compute_if_absent(name) do
-
106
safe_name = name.unpack('h*').first
-
106
temp_method = "__temp__#{safe_name}"
-
106
ActiveRecord::AttributeMethods::AttrNames.set_name_cache safe_name, name
-
106
@module.module_eval method_body(temp_method, safe_name), __FILE__, __LINE__
-
106
@module.instance_method temp_method
-
end
-
end
-
-
2
private
-
2
def method_body; raise NotImplementedError; end
-
end
-
-
2
class GeneratedAttributeMethods < Module; end # :nodoc:
-
-
2
module ClassMethods
-
2
def inherited(child_class) #:nodoc:
-
13
child_class.initialize_generated_modules
-
13
super
-
end
-
-
2
def initialize_generated_modules # :nodoc:
-
30
@generated_attribute_methods = GeneratedAttributeMethods.new { extend Mutex_m }
-
15
@attribute_methods_generated = false
-
15
include @generated_attribute_methods
-
-
15
super
-
end
-
-
# Generates all the attribute related methods for columns in the database
-
# accessors, mutators and query methods.
-
2
def define_attribute_methods # :nodoc:
-
1720
return false if @attribute_methods_generated
-
# Use a mutex; we don't want two thread simultaneously trying to define
-
# attribute methods.
-
11
generated_attribute_methods.synchronize do
-
11
return false if @attribute_methods_generated
-
11
superclass.define_attribute_methods unless self == base_class
-
11
super(column_names)
-
11
@attribute_methods_generated = true
-
end
-
11
true
-
end
-
-
2
def undefine_attribute_methods # :nodoc:
-
10
generated_attribute_methods.synchronize do
-
10
super if @attribute_methods_generated
-
10
@attribute_methods_generated = false
-
end
-
end
-
-
# Raises a <tt>ActiveRecord::DangerousAttributeError</tt> exception when an
-
# \Active \Record method is defined in the model, otherwise +false+.
-
#
-
# class Person < ActiveRecord::Base
-
# def save
-
# 'already defined by Active Record'
-
# end
-
# end
-
#
-
# Person.instance_method_already_implemented?(:save)
-
# # => ActiveRecord::DangerousAttributeError: save is defined by ActiveRecord
-
#
-
# Person.instance_method_already_implemented?(:name)
-
# # => false
-
2
def instance_method_already_implemented?(method_name)
-
999
if dangerous_attribute_method?(method_name)
-
raise DangerousAttributeError, "#{method_name} is defined by Active Record. Check to make sure that you don't have an attribute or method with the same name."
-
end
-
-
999
if superclass == Base
-
900
super
-
else
-
# If ThisClass < ... < SomeSuperClass < ... < Base and SomeSuperClass
-
# defines its own attribute method, then we don't want to overwrite that.
-
99
defined = method_defined_within?(method_name, superclass, Base) &&
-
! superclass.instance_method(method_name).owner.is_a?(GeneratedAttributeMethods)
-
99
defined || super
-
end
-
end
-
-
# A method name is 'dangerous' if it is already (re)defined by Active Record, but
-
# not by any ancestors. (So 'puts' is not dangerous but 'save' is.)
-
2
def dangerous_attribute_method?(name) # :nodoc:
-
1040
method_defined_within?(name, Base)
-
end
-
-
2
def method_defined_within?(name, klass, superklass = klass.superclass) # :nodoc:
-
1148
if klass.method_defined?(name) || klass.private_method_defined?(name)
-
158
if superklass.method_defined?(name) || superklass.private_method_defined?(name)
-
5
klass.instance_method(name).owner != superklass.instance_method(name).owner
-
else
-
153
true
-
end
-
else
-
990
false
-
end
-
end
-
-
# A class method is 'dangerous' if it is already (re)defined by Active Record, but
-
# not by any ancestors. (So 'puts' is not dangerous but 'new' is.)
-
2
def dangerous_class_method?(method_name)
-
BLACKLISTED_CLASS_METHODS.include?(method_name.to_s) || class_method_defined_within?(method_name, Base)
-
end
-
-
2
def class_method_defined_within?(name, klass, superklass = klass.superclass) # :nodoc
-
if klass.respond_to?(name, true)
-
if superklass.respond_to?(name, true)
-
klass.method(name).owner != superklass.method(name).owner
-
else
-
true
-
end
-
else
-
false
-
end
-
end
-
-
2
def find_generated_attribute_method(method_name) # :nodoc:
-
9
klass = self
-
9
until klass == Base
-
9
gen_methods = klass.generated_attribute_methods
-
9
return gen_methods.instance_method(method_name) if method_defined_within?(method_name, gen_methods, Object)
-
klass = klass.superclass
-
end
-
nil
-
end
-
-
# Returns +true+ if +attribute+ is an attribute method and table exists,
-
# +false+ otherwise.
-
#
-
# class Person < ActiveRecord::Base
-
# end
-
#
-
# Person.attribute_method?('name') # => true
-
# Person.attribute_method?(:age=) # => true
-
# Person.attribute_method?(:nothing) # => false
-
2
def attribute_method?(attribute)
-
super || (table_exists? && column_names.include?(attribute.to_s.sub(/=$/, '')))
-
end
-
-
# Returns an array of column names as strings if it's not an abstract class and
-
# table exists. Otherwise it returns an empty array.
-
#
-
# class Person < ActiveRecord::Base
-
# end
-
#
-
# Person.attribute_names
-
# # => ["id", "created_at", "updated_at", "name", "age"]
-
2
def attribute_names
-
@attribute_names ||= if !abstract_class? && table_exists?
-
column_names
-
else
-
[]
-
end
-
end
-
end
-
-
# If we haven't generated any methods yet, generate them, then
-
# see if we've created the method we're looking for.
-
2
def method_missing(method, *args, &block) # :nodoc:
-
9
self.class.define_attribute_methods
-
9
if respond_to_without_attributes?(method)
-
# make sure to invoke the correct attribute method, as we might have gotten here via a `super`
-
# call in a overwritten attribute method
-
9
if attribute_method = self.class.find_generated_attribute_method(method)
-
# this is probably horribly slow, but should only happen at most once for a given AR class
-
9
attribute_method.bind(self).call(*args, &block)
-
else
-
return super unless respond_to_missing?(method, true)
-
send(method, *args, &block)
-
end
-
else
-
super
-
end
-
end
-
-
# A Person object with a name attribute can ask <tt>person.respond_to?(:name)</tt>,
-
# <tt>person.respond_to?(:name=)</tt>, and <tt>person.respond_to?(:name?)</tt>
-
# which will all return +true+. It also define the attribute methods if they have
-
# not been generated.
-
#
-
# class Person < ActiveRecord::Base
-
# end
-
#
-
# person = Person.new
-
# person.respond_to(:name) # => true
-
# person.respond_to(:name=) # => true
-
# person.respond_to(:name?) # => true
-
# person.respond_to('age') # => true
-
# person.respond_to('age=') # => true
-
# person.respond_to('age?') # => true
-
# person.respond_to(:nothing) # => false
-
2
def respond_to?(name, include_private = false)
-
1678
name = name.to_s
-
1678
self.class.define_attribute_methods
-
1678
result = super
-
-
# If the result is false the answer is false.
-
1678
return false unless result
-
-
# If the result is true then check for the select case.
-
# For queries selecting a subset of columns, return false for unselected columns.
-
# We check defined?(@attributes) not to issue warnings if called on objects that
-
# have been allocated but not yet initialized.
-
1144
if defined?(@attributes) && @attributes.any? && self.class.column_names.include?(name)
-
534
return has_attribute?(name)
-
end
-
-
610
return true
-
end
-
-
# Returns +true+ if the given attribute is in the attributes hash, otherwise +false+.
-
#
-
# class Person < ActiveRecord::Base
-
# end
-
#
-
# person = Person.new
-
# person.has_attribute?(:name) # => true
-
# person.has_attribute?('age') # => true
-
# person.has_attribute?(:nothing) # => false
-
2
def has_attribute?(attr_name)
-
1093
@attributes.has_key?(attr_name.to_s)
-
end
-
-
# Returns an array of names for the attributes available on this object.
-
#
-
# class Person < ActiveRecord::Base
-
# end
-
#
-
# person = Person.new
-
# person.attribute_names
-
# # => ["id", "created_at", "updated_at", "name", "age"]
-
2
def attribute_names
-
72
@attributes.keys
-
end
-
-
# Returns a hash of all the attributes with their names as keys and the values of the attributes as values.
-
#
-
# class Person < ActiveRecord::Base
-
# end
-
#
-
# person = Person.create(name: 'Francesco', age: 22)
-
# person.attributes
-
# # => {"id"=>3, "created_at"=>Sun, 21 Oct 2012 04:53:04, "updated_at"=>Sun, 21 Oct 2012 04:53:04, "name"=>"Francesco", "age"=>22}
-
2
def attributes
-
72
attribute_names.each_with_object({}) { |name, attrs|
-
792
attrs[name] = read_attribute(name)
-
}
-
end
-
-
# Placeholder so it can be overriden when needed by serialization
-
2
def attributes_for_coder # :nodoc:
-
attributes
-
end
-
-
# Returns an <tt>#inspect</tt>-like string for the value of the
-
# attribute +attr_name+. String attributes are truncated upto 50
-
# characters, Date and Time attributes are returned in the
-
# <tt>:db</tt> format, Array attributes are truncated upto 10 values.
-
# Other attributes return the value of <tt>#inspect</tt> without
-
# modification.
-
#
-
# person = Person.create!(name: 'David Heinemeier Hansson ' * 3)
-
#
-
# person.attribute_for_inspect(:name)
-
# # => "\"David Heinemeier Hansson David Heinemeier Hansson ...\""
-
#
-
# person.attribute_for_inspect(:created_at)
-
# # => "\"2012-10-22 00:15:07\""
-
#
-
# person.attribute_for_inspect(:tag_ids)
-
# # => "[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, ...]"
-
2
def attribute_for_inspect(attr_name)
-
value = read_attribute(attr_name)
-
-
if value.is_a?(String) && value.length > 50
-
"#{value[0, 50]}...".inspect
-
elsif value.is_a?(Date) || value.is_a?(Time)
-
%("#{value.to_s(:db)}")
-
elsif value.is_a?(Array) && value.size > 10
-
inspected = value.first(10).inspect
-
%(#{inspected[0...-1]}, ...])
-
else
-
value.inspect
-
end
-
end
-
-
# Returns +true+ if the specified +attribute+ has been set by the user or by a
-
# database load and is neither +nil+ nor <tt>empty?</tt> (the latter only applies
-
# to objects that respond to <tt>empty?</tt>, most notably Strings). Otherwise, +false+.
-
# Note that it always returns +true+ with boolean attributes.
-
#
-
# class Task < ActiveRecord::Base
-
# end
-
#
-
# person = Task.new(title: '', is_done: false)
-
# person.attribute_present?(:title) # => false
-
# person.attribute_present?(:is_done) # => true
-
# person.name = 'Francesco'
-
# person.is_done = true
-
# person.attribute_present?(:title) # => true
-
# person.attribute_present?(:is_done) # => true
-
2
def attribute_present?(attribute)
-
value = read_attribute(attribute)
-
!value.nil? && !(value.respond_to?(:empty?) && value.empty?)
-
end
-
-
# Returns the column object for the named attribute. Returns +nil+ if the
-
# named attribute not exists.
-
#
-
# class Person < ActiveRecord::Base
-
# end
-
#
-
# person = Person.new
-
# person.column_for_attribute(:name) # the result depends on the ConnectionAdapter
-
# # => #<ActiveRecord::ConnectionAdapters::SQLite3Column:0x007ff4ab083980 @name="name", @sql_type="varchar(255)", @null=true, ...>
-
#
-
# person.column_for_attribute(:nothing)
-
# # => nil
-
2
def column_for_attribute(name)
-
# FIXME: should this return a null object for columns that don't exist?
-
11538
self.class.columns_hash[name.to_s]
-
end
-
-
# Returns the value of the attribute identified by <tt>attr_name</tt> after it has been typecast (for example,
-
# "2004-12-12" in a date column is cast to a date object, like Date.new(2004, 12, 12)). It raises
-
# <tt>ActiveModel::MissingAttributeError</tt> if the identified attribute is missing.
-
#
-
# Alias for the <tt>read_attribute</tt> method.
-
#
-
# class Person < ActiveRecord::Base
-
# belongs_to :organization
-
# end
-
#
-
# person = Person.new(name: 'Francesco', age: '22')
-
# person[:name] # => "Francesco"
-
# person[:age] # => 22
-
#
-
# person = Person.select('id').first
-
# person[:name] # => ActiveModel::MissingAttributeError: missing attribute: name
-
# person[:organization_id] # => ActiveModel::MissingAttributeError: missing attribute: organization_id
-
2
def [](attr_name)
-
288
read_attribute(attr_name) { |n| missing_attribute(n, caller) }
-
end
-
-
# Updates the attribute identified by <tt>attr_name</tt> with the specified +value+.
-
# (Alias for the protected <tt>write_attribute</tt> method).
-
#
-
# class Person < ActiveRecord::Base
-
# end
-
#
-
# person = Person.new
-
# person[:age] = '22'
-
# person[:age] # => 22
-
# person[:age] # => Fixnum
-
2
def []=(attr_name, value)
-
432
write_attribute(attr_name, value)
-
end
-
-
2
protected
-
-
2
def clone_attributes(reader_method = :read_attribute, attributes = {}) # :nodoc:
-
attribute_names.each do |name|
-
attributes[name] = clone_attribute_value(reader_method, name)
-
end
-
attributes
-
end
-
-
2
def clone_attribute_value(reader_method, attribute_name) # :nodoc:
-
2101
value = send(reader_method, attribute_name)
-
2101
value.duplicable? ? value.clone : value
-
rescue TypeError, NoMethodError
-
value
-
end
-
-
2
def arel_attributes_with_values_for_create(attribute_names) # :nodoc:
-
267
arel_attributes_with_values(attributes_for_create(attribute_names))
-
end
-
-
2
def arel_attributes_with_values_for_update(attribute_names) # :nodoc:
-
arel_attributes_with_values(attributes_for_update(attribute_names))
-
end
-
-
2
def attribute_method?(attr_name) # :nodoc:
-
# We check defined? because Syck calls respond_to? before actually calling initialize.
-
534
defined?(@attributes) && @attributes.include?(attr_name)
-
end
-
-
2
private
-
-
# Returns a Hash of the Arel::Attributes and attribute values that have been
-
# typecasted for use in an Arel insert/update method.
-
2
def arel_attributes_with_values(attribute_names)
-
267
attrs = {}
-
267
arel_table = self.class.arel_table
-
-
267
attribute_names.each do |name|
-
1405
attrs[arel_table[name]] = typecasted_attribute_value(name)
-
end
-
267
attrs
-
end
-
-
# Filters the primary keys and readonly attributes from the attribute names.
-
2
def attributes_for_update(attribute_names)
-
attribute_names.select do |name|
-
column_for_attribute(name) && !readonly_attribute?(name)
-
end
-
end
-
-
# Filters out the primary keys, from the attribute names, when the primary
-
# key is to be generated (e.g. the id attribute has no value).
-
2
def attributes_for_create(attribute_names)
-
267
attribute_names.select do |name|
-
1405
column_for_attribute(name) && !(pk_attribute?(name) && id.nil?)
-
end
-
end
-
-
2
def readonly_attribute?(name)
-
self.class.readonly_attributes.include?(name)
-
end
-
-
2
def pk_attribute?(name)
-
1405
column_for_attribute(name).primary
-
end
-
-
2
def typecasted_attribute_value(name)
-
# FIXME: we need @attributes to be used consistently.
-
# If the values stored in @attributes were already typecasted, this code
-
# could be simplified
-
1333
read_attribute(name)
-
end
-
end
-
end
-
2
module ActiveRecord
-
2
module AttributeMethods
-
# = Active Record Attribute Methods Before Type Cast
-
#
-
# <tt>ActiveRecord::AttributeMethods::BeforeTypeCast</tt> provides a way to
-
# read the value of the attributes before typecasting and deserialization.
-
#
-
# class Task < ActiveRecord::Base
-
# end
-
#
-
# task = Task.new(id: '1', completed_on: '2012-10-21')
-
# task.id # => 1
-
# task.completed_on # => Sun, 21 Oct 2012
-
#
-
# task.attributes_before_type_cast
-
# # => {"id"=>"1", "completed_on"=>"2012-10-21", ... }
-
# task.read_attribute_before_type_cast('id') # => "1"
-
# task.read_attribute_before_type_cast('completed_on') # => "2012-10-21"
-
#
-
# In addition to #read_attribute_before_type_cast and #attributes_before_type_cast,
-
# it declares a method for all attributes with the <tt>*_before_type_cast</tt>
-
# suffix.
-
#
-
# task.id_before_type_cast # => "1"
-
# task.completed_on_before_type_cast # => "2012-10-21"
-
2
module BeforeTypeCast
-
2
extend ActiveSupport::Concern
-
-
2
included do
-
2
attribute_method_suffix "_before_type_cast"
-
end
-
-
# Returns the value of the attribute identified by +attr_name+ before
-
# typecasting and deserialization.
-
#
-
# class Task < ActiveRecord::Base
-
# end
-
#
-
# task = Task.new(id: '1', completed_on: '2012-10-21')
-
# task.read_attribute('id') # => 1
-
# task.read_attribute_before_type_cast('id') # => '1'
-
# task.read_attribute('completed_on') # => Sun, 21 Oct 2012
-
# task.read_attribute_before_type_cast('completed_on') # => "2012-10-21"
-
# task.read_attribute_before_type_cast(:completed_on) # => "2012-10-21"
-
2
def read_attribute_before_type_cast(attr_name)
-
12
@attributes[attr_name.to_s]
-
end
-
-
# Returns a hash of attributes before typecasting and deserialization.
-
#
-
# class Task < ActiveRecord::Base
-
# end
-
#
-
# task = Task.new(title: nil, is_done: true, completed_on: '2012-10-21')
-
# task.attributes
-
# # => {"id"=>nil, "title"=>nil, "is_done"=>true, "completed_on"=>Sun, 21 Oct 2012, "created_at"=>nil, "updated_at"=>nil}
-
# task.attributes_before_type_cast
-
# # => {"id"=>nil, "title"=>nil, "is_done"=>true, "completed_on"=>"2012-10-21", "created_at"=>nil, "updated_at"=>nil}
-
2
def attributes_before_type_cast
-
@attributes
-
end
-
-
2
private
-
-
# Handle *_before_type_cast for method_missing.
-
2
def attribute_before_type_cast(attribute_name)
-
12
read_attribute_before_type_cast(attribute_name)
-
end
-
end
-
end
-
end
-
2
require 'active_support/core_ext/module/attribute_accessors'
-
-
2
module ActiveRecord
-
2
module AttributeMethods
-
2
module Dirty # :nodoc:
-
2
extend ActiveSupport::Concern
-
-
2
include ActiveModel::Dirty
-
-
2
included do
-
2
if self < ::ActiveRecord::Timestamp
-
raise "You cannot include Dirty after Timestamp"
-
end
-
-
2
class_attribute :partial_writes, instance_writer: false
-
2
self.partial_writes = true
-
end
-
-
# Attempts to +save+ the record and clears changed attributes if successful.
-
2
def save(*)
-
74
if status = super
-
72
changes_applied
-
end
-
74
status
-
end
-
-
# Attempts to <tt>save!</tt> the record and clears changed attributes if successful.
-
2
def save!(*)
-
195
super.tap do
-
195
changes_applied
-
end
-
end
-
-
# <tt>reload</tt> the record and clears changed attributes.
-
2
def reload(*)
-
super.tap do
-
reset_changes
-
end
-
end
-
-
2
def initialize_dup(other) # :nodoc:
-
super
-
init_changed_attributes
-
end
-
-
2
private
-
2
def initialize_internals_callback
-
279
super
-
279
init_changed_attributes
-
end
-
-
2
def init_changed_attributes
-
279
@changed_attributes = nil
-
# Intentionally avoid using #column_defaults since overridden defaults (as is done in
-
# optimistic locking) won't get written unless they get marked as changed
-
279
self.class.columns.each do |c|
-
3852
attr, orig_value = c.name, c.default
-
3852
changed_attributes[attr] = orig_value if _field_changed?(attr, orig_value, @attributes[attr])
-
end
-
end
-
-
# Wrap write_attribute to remember original attribute value.
-
2
def write_attribute(attr, value)
-
2510
attr = attr.to_s
-
-
2510
save_changed_attribute(attr, value)
-
-
2510
super(attr, value)
-
end
-
-
2
def save_changed_attribute(attr, value)
-
# The attribute already has an unsaved change.
-
2510
if attribute_changed?(attr)
-
409
old = changed_attributes[attr]
-
409
changed_attributes.delete(attr) unless _field_changed?(attr, old, value)
-
else
-
2101
old = clone_attribute_value(:read_attribute, attr)
-
2101
changed_attributes[attr] = old if _field_changed?(attr, old, value)
-
end
-
end
-
-
2
def _update_record(*)
-
partial_writes? ? super(keys_for_partial_write) : super
-
end
-
-
2
def _create_record(*)
-
267
partial_writes? ? super(keys_for_partial_write) : super
-
end
-
-
# Serialized attributes should always be written in case they've been
-
# changed in place.
-
2
def keys_for_partial_write
-
267
changed
-
end
-
-
2
def _field_changed?(attr, old, value)
-
6218
if column = column_for_attribute(attr)
-
if column.number? && (changes_from_nil_to_empty_string?(column, old, value) ||
-
6218
changes_from_zero_to_string?(old, value))
-
832
value = nil
-
else
-
5386
value = column.type_cast(value)
-
end
-
end
-
-
6218
old != value
-
end
-
-
2
def changes_from_nil_to_empty_string?(column, old, value)
-
# For nullable numeric columns, NULL gets stored in database for blank (i.e. '') values.
-
# Hence we don't record it as a change if the value changes from nil to ''.
-
# If an old value of 0 is set to '' we want this to get changed to nil as otherwise it'll
-
# be typecast back to 0 (''.to_i => 0)
-
1720
column.null && (old.nil? || old == 0) && value.blank?
-
end
-
-
2
def changes_from_zero_to_string?(old, value)
-
# For columns with old 0 and value non-empty string
-
888
old == 0 && value.is_a?(String) && value.present? && non_zero?(value)
-
end
-
-
2
def non_zero?(value)
-
value !~ /\A0+(\.0+)?\z/
-
end
-
end
-
end
-
end
-
2
module ActiveRecord
-
2
module AttributeMethods
-
2
module Query
-
2
extend ActiveSupport::Concern
-
-
2
included do
-
2
attribute_method_suffix "?"
-
end
-
-
2
def query_attribute(attr_name)
-
value = read_attribute(attr_name) { |n| missing_attribute(n, caller) }
-
-
case value
-
when true then true
-
when false, nil then false
-
else
-
column = self.class.columns_hash[attr_name]
-
if column.nil?
-
if Numeric === value || value !~ /[^0-9]/
-
!value.to_i.zero?
-
else
-
return false if ActiveRecord::ConnectionAdapters::Column::FALSE_VALUES.include?(value)
-
!value.blank?
-
end
-
elsif column.number?
-
!value.zero?
-
else
-
!value.blank?
-
end
-
end
-
end
-
-
2
private
-
# Handle *? for method_missing.
-
2
def attribute?(attribute_name)
-
query_attribute(attribute_name)
-
end
-
end
-
end
-
end
-
2
require 'active_support/core_ext/module/method_transplanting'
-
-
2
module ActiveRecord
-
2
module AttributeMethods
-
2
module Read
-
2
ReaderMethodCache = Class.new(AttributeMethodCache) {
-
2
private
-
# We want to generate the methods via module_eval rather than
-
# define_method, because define_method is slower on dispatch.
-
# Evaluating many similar methods may use more memory as the instruction
-
# sequences are duplicated and cached (in MRI). define_method may
-
# be slower on dispatch, but if you're careful about the closure
-
# created, then define_method will consume much less memory.
-
#
-
# But sometimes the database might return columns with
-
# characters that are not allowed in normal method names (like
-
# 'my_column(omg)'. So to work around this we first define with
-
# the __temp__ identifier, and then use alias method to rename
-
# it to what we want.
-
#
-
# We are also defining a constant to hold the frozen string of
-
# the attribute name. Using a constant means that we do not have
-
# to allocate an object on each call to the attribute method.
-
# Making it frozen means that it doesn't get duped when used to
-
# key the @attributes_cache in read_attribute.
-
2
def method_body(method_name, const_name)
-
<<-EOMETHOD
-
57
def #{method_name}
-
name = ::ActiveRecord::AttributeMethods::AttrNames::ATTR_#{const_name}
-
read_attribute(name) { |n| missing_attribute(n, caller) }
-
end
-
EOMETHOD
-
end
-
}.new
-
-
2
extend ActiveSupport::Concern
-
-
2
ATTRIBUTE_TYPES_CACHED_BY_DEFAULT = [:datetime, :timestamp, :time, :date]
-
-
2
included do
-
2
class_attribute :attribute_types_cached_by_default, instance_writer: false
-
2
self.attribute_types_cached_by_default = ATTRIBUTE_TYPES_CACHED_BY_DEFAULT
-
end
-
-
2
module ClassMethods
-
# +cache_attributes+ allows you to declare which converted attribute
-
# values should be cached. Usually caching only pays off for attributes
-
# with expensive conversion methods, like time related columns (e.g.
-
# +created_at+, +updated_at+).
-
2
def cache_attributes(*attribute_names)
-
cached_attributes.merge attribute_names.map { |attr| attr.to_s }
-
end
-
-
# Returns the attributes which are cached. By default time related columns
-
# with datatype <tt>:datetime, :timestamp, :time, :date</tt> are cached.
-
2
def cached_attributes
-
4573
@cached_attributes ||= columns.select { |c| cacheable_column?(c) }.map { |col| col.name }.to_set
-
end
-
-
# Returns +true+ if the provided attribute is being cached.
-
2
def cache_attribute?(attr_name)
-
4374
cached_attributes.include?(attr_name)
-
end
-
-
2
protected
-
-
2
if Module.methods_transplantable?
-
2
def define_method_attribute(name)
-
111
method = ReaderMethodCache[name]
-
222
generated_attribute_methods.module_eval { define_method name, method }
-
end
-
else
-
def define_method_attribute(name)
-
safe_name = name.unpack('h*').first
-
temp_method = "__temp__#{safe_name}"
-
-
ActiveRecord::AttributeMethods::AttrNames.set_name_cache safe_name, name
-
-
generated_attribute_methods.module_eval <<-STR, __FILE__, __LINE__ + 1
-
def #{temp_method}
-
name = ::ActiveRecord::AttributeMethods::AttrNames::ATTR_#{safe_name}
-
read_attribute(name) { |n| missing_attribute(n, caller) }
-
end
-
STR
-
-
generated_attribute_methods.module_eval do
-
alias_method name, temp_method
-
undef_method temp_method
-
end
-
end
-
end
-
-
2
private
-
-
2
def cacheable_column?(column)
-
100
if attribute_types_cached_by_default == ATTRIBUTE_TYPES_CACHED_BY_DEFAULT
-
100
! serialized_attributes.include? column.name
-
else
-
attribute_types_cached_by_default.include?(column.type)
-
end
-
end
-
end
-
-
# Returns the value of the attribute identified by <tt>attr_name</tt> after
-
# it has been typecast (for example, "2004-12-12" in a date column is cast
-
# to a date object, like Date.new(2004, 12, 12)).
-
2
def read_attribute(attr_name)
-
# If it's cached, just return it
-
# We use #[] first as a perf optimization for non-nil values. See https://gist.github.com/jonleighton/3552829.
-
10554
name = attr_name.to_s
-
@attributes_cache[name] || @attributes_cache.fetch(name) {
-
4374
column = @column_types_override[name] if @column_types_override
-
4374
column ||= @column_types[name]
-
-
return @attributes.fetch(name) {
-
if name == 'id' && self.class.primary_key != name
-
read_attribute(self.class.primary_key)
-
end
-
4374
} unless column
-
-
4374
value = @attributes.fetch(name) {
-
return block_given? ? yield(name) : nil
-
}
-
-
4374
if self.class.cache_attribute?(name)
-
4230
@attributes_cache[name] = column.type_cast(value)
-
else
-
144
column.type_cast value
-
end
-
10554
}
-
end
-
-
2
private
-
-
2
def attribute(attribute_name)
-
read_attribute(attribute_name)
-
end
-
end
-
end
-
end
-
2
module ActiveRecord
-
2
module AttributeMethods
-
2
module Serialization
-
2
extend ActiveSupport::Concern
-
-
2
included do
-
# Returns a hash of all the attributes that have been specified for
-
# serialization as keys and their class restriction as values.
-
2
class_attribute :serialized_attributes, instance_accessor: false
-
2
self.serialized_attributes = {}
-
end
-
-
2
module ClassMethods
-
##
-
# :method: serialized_attributes
-
#
-
# Returns a hash of all the attributes that have been specified for
-
# serialization as keys and their class restriction as values.
-
-
# If you have an attribute that needs to be saved to the database as an
-
# object, and retrieved as the same object, then specify the name of that
-
# attribute using this method and it will be handled automatically. The
-
# serialization is done through YAML. If +class_name+ is specified, the
-
# serialized object must be of that class on retrieval or
-
# <tt>SerializationTypeMismatch</tt> will be raised.
-
#
-
# A notable side effect of serialized attributes is that the model will
-
# be updated on every save, even if it is not dirty.
-
#
-
# ==== Parameters
-
#
-
# * +attr_name+ - The field name that should be serialized.
-
# * +class_name_or_coder+ - Optional, a coder object, which responds to `.load` / `.dump`
-
# or a class name that the object type should be equal to.
-
#
-
# ==== Example
-
#
-
# # Serialize a preferences attribute.
-
# class User < ActiveRecord::Base
-
# serialize :preferences
-
# end
-
#
-
# # Serialize preferences using JSON as coder.
-
# class User < ActiveRecord::Base
-
# serialize :preferences, JSON
-
# end
-
#
-
# # Serialize preferences as Hash using YAML coder.
-
# class User < ActiveRecord::Base
-
# serialize :preferences, Hash
-
# end
-
2
def serialize(attr_name, class_name_or_coder = Object)
-
2
include Behavior
-
-
# When ::JSON is used, force it to go through the Active Support JSON encoder
-
# to ensure special objects (e.g. Active Record models) are dumped correctly
-
# using the #as_json hook.
-
2
coder = if class_name_or_coder == ::JSON
-
Coders::JSON
-
4
elsif [:load, :dump].all? { |x| class_name_or_coder.respond_to?(x) }
-
class_name_or_coder
-
else
-
2
Coders::YAMLColumn.new(class_name_or_coder)
-
end
-
-
# merge new serialized attribute and create new hash to ensure that each class in inheritance hierarchy
-
# has its own hash of own serialized attributes
-
2
self.serialized_attributes = serialized_attributes.merge(attr_name.to_s => coder)
-
end
-
end
-
-
2
class Type # :nodoc:
-
2
def initialize(column)
-
1
@column = column
-
end
-
-
2
def type_cast(value)
-
144
if value.state == :serialized
-
72
value.unserialized_value @column.type_cast value.value
-
else
-
72
value.unserialized_value
-
end
-
end
-
-
2
def type
-
@column.type
-
end
-
-
2
def accessor
-
ActiveRecord::Store::IndifferentHashAccessor
-
end
-
end
-
-
2
class Attribute < Struct.new(:coder, :value, :state) # :nodoc:
-
2
def unserialized_value(v = value)
-
144
state == :serialized ? unserialize(v) : value
-
end
-
-
2
def serialized_value
-
72
state == :unserialized ? serialize : value
-
end
-
-
2
def unserialize(v)
-
72
self.state = :unserialized
-
72
self.value = coder.load(v)
-
end
-
-
2
def serialize
-
72
self.state = :serialized
-
72
self.value = coder.dump(value)
-
end
-
end
-
-
# This is only added to the model when serialize is called, which
-
# ensures we do not make things slower when serialization is not used.
-
2
module Behavior # :nodoc:
-
2
extend ActiveSupport::Concern
-
-
2
module ClassMethods # :nodoc:
-
2
def initialize_attributes(attributes, options = {})
-
144
serialized = (options.delete(:serialized) { true }) ? :serialized : :unserialized
-
72
super(attributes, options)
-
-
72
serialized_attributes.each do |key, coder|
-
72
if attributes.key?(key)
-
72
attributes[key] = Attribute.new(coder, attributes[key], serialized)
-
end
-
end
-
-
72
attributes
-
end
-
end
-
-
2
def should_record_timestamps?
-
super || (self.record_timestamps && (attributes.keys & self.class.serialized_attributes.keys).present?)
-
end
-
-
2
def keys_for_partial_write
-
72
super | (attributes.keys & self.class.serialized_attributes.keys)
-
end
-
-
2
def type_cast_attribute_for_write(column, value)
-
936
if column && coder = self.class.serialized_attributes[column.name]
-
72
Attribute.new(coder, value, :unserialized)
-
else
-
864
super
-
end
-
end
-
-
2
def raw_type_cast_attribute_for_write(column, value)
-
if column && coder = self.class.serialized_attributes[column.name]
-
Attribute.new(coder, value, :serialized)
-
else
-
super
-
end
-
end
-
-
2
def _field_changed?(attr, old, value)
-
1728
if self.class.serialized_attributes.include?(attr)
-
144
old != value
-
else
-
1584
super
-
end
-
end
-
-
2
def read_attribute_before_type_cast(attr_name)
-
if self.class.serialized_attributes.include?(attr_name)
-
super.unserialized_value
-
else
-
super
-
end
-
end
-
-
2
def attributes_before_type_cast
-
super.dup.tap do |attributes|
-
self.class.serialized_attributes.each_key do |key|
-
if attributes.key?(key)
-
attributes[key] = attributes[key].unserialized_value
-
end
-
end
-
end
-
end
-
-
2
def typecasted_attribute_value(name)
-
432
if self.class.serialized_attributes.include?(name)
-
72
@attributes[name].serialized_value
-
else
-
360
super
-
end
-
end
-
-
2
def attributes_for_coder
-
attribute_names.each_with_object({}) do |name, attrs|
-
attrs[name] = if self.class.serialized_attributes.include?(name)
-
@attributes[name].serialized_value
-
else
-
read_attribute(name)
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
2
module ActiveRecord
-
2
module AttributeMethods
-
2
module TimeZoneConversion
-
2
class Type # :nodoc:
-
2
def initialize(column)
-
22
@column = column
-
end
-
-
2
def type_cast(value)
-
1068
value = @column.type_cast(value)
-
1068
value.acts_like?(:time) ? value.in_time_zone : value
-
end
-
-
2
def type
-
@column.type
-
end
-
end
-
-
2
extend ActiveSupport::Concern
-
-
2
included do
-
2
mattr_accessor :time_zone_aware_attributes, instance_writer: false
-
2
self.time_zone_aware_attributes = false
-
-
2
class_attribute :skip_time_zone_conversion_for_attributes, instance_writer: false
-
2
self.skip_time_zone_conversion_for_attributes = []
-
end
-
-
2
module ClassMethods
-
2
protected
-
# Defined for all +datetime+ and +timestamp+ attributes when +time_zone_aware_attributes+ are enabled.
-
# This enhanced write method will automatically convert the time passed to it to the zone stored in Time.zone.
-
2
def define_method_attribute=(attr_name)
-
111
if create_time_zone_conversion_attribute?(attr_name, columns_hash[attr_name])
-
24
method_body, line = <<-EOV, __LINE__ + 1
-
def #{attr_name}=(time)
-
time_with_zone = time.respond_to?(:in_time_zone) ? time.in_time_zone : nil
-
previous_time = attribute_changed?("#{attr_name}") ? changed_attributes["#{attr_name}"] : read_attribute(:#{attr_name})
-
write_attribute(:#{attr_name}, time)
-
#{attr_name}_will_change! if previous_time != time_with_zone
-
@attributes_cache["#{attr_name}"] = time_with_zone
-
end
-
EOV
-
24
generated_attribute_methods.module_eval(method_body, __FILE__, line)
-
else
-
87
super
-
end
-
end
-
-
2
private
-
2
def create_time_zone_conversion_attribute?(name, column)
-
time_zone_aware_attributes &&
-
211
!self.skip_time_zone_conversion_for_attributes.include?(name.to_sym) &&
-
211
(:datetime == column.type || :timestamp == column.type)
-
end
-
end
-
end
-
end
-
end
-
2
require 'active_support/core_ext/module/method_transplanting'
-
-
2
module ActiveRecord
-
2
module AttributeMethods
-
2
module Write
-
2
WriterMethodCache = Class.new(AttributeMethodCache) {
-
2
private
-
-
2
def method_body(method_name, const_name)
-
<<-EOMETHOD
-
49
def #{method_name}(value)
-
name = ::ActiveRecord::AttributeMethods::AttrNames::ATTR_#{const_name}
-
write_attribute(name, value)
-
end
-
EOMETHOD
-
end
-
}.new
-
-
2
extend ActiveSupport::Concern
-
-
2
included do
-
2
attribute_method_suffix "="
-
end
-
-
2
module ClassMethods
-
2
protected
-
-
2
if Module.methods_transplantable?
-
# See define_method_attribute in read.rb for an explanation of
-
# this code.
-
2
def define_method_attribute=(name)
-
87
method = WriterMethodCache[name]
-
87
generated_attribute_methods.module_eval {
-
87
define_method "#{name}=", method
-
}
-
end
-
else
-
def define_method_attribute=(name)
-
safe_name = name.unpack('h*').first
-
ActiveRecord::AttributeMethods::AttrNames.set_name_cache safe_name, name
-
-
generated_attribute_methods.module_eval <<-STR, __FILE__, __LINE__ + 1
-
def __temp__#{safe_name}=(value)
-
name = ::ActiveRecord::AttributeMethods::AttrNames::ATTR_#{safe_name}
-
write_attribute(name, value)
-
end
-
alias_method #{(name + '=').inspect}, :__temp__#{safe_name}=
-
undef_method :__temp__#{safe_name}=
-
STR
-
end
-
end
-
end
-
-
# Updates the attribute identified by <tt>attr_name</tt> with the
-
# specified +value+. Empty strings for fixnum and float columns are
-
# turned into +nil+.
-
2
def write_attribute(attr_name, value)
-
2510
write_attribute_with_type_cast(attr_name, value, :type_cast_attribute_for_write)
-
end
-
-
2
def raw_write_attribute(attr_name, value)
-
write_attribute_with_type_cast(attr_name, value, :raw_type_cast_attribute_for_write)
-
end
-
-
2
private
-
# Handle *= for method_missing.
-
2
def attribute=(attribute_name, value)
-
write_attribute(attribute_name, value)
-
end
-
-
2
def type_cast_attribute_for_write(column, value)
-
2438
return value unless column
-
-
2438
column.type_cast_for_write value
-
end
-
2
alias_method :raw_type_cast_attribute_for_write, :type_cast_attribute_for_write
-
-
2
def write_attribute_with_type_cast(attr_name, value, type_cast_method)
-
2510
attr_name = attr_name.to_s
-
2510
attr_name = self.class.primary_key if attr_name == 'id' && self.class.primary_key
-
2510
@attributes_cache.delete(attr_name)
-
2510
column = column_for_attribute(attr_name)
-
-
# If we're dealing with a binary column, write the data to the cache
-
# so we don't attempt to typecast multiple times.
-
2510
if column && column.binary?
-
@attributes_cache[attr_name] = value
-
end
-
-
2510
if column || @attributes.has_key?(attr_name)
-
2510
@attributes[attr_name] = send(type_cast_method, column, value)
-
else
-
raise ActiveModel::MissingAttributeError, "can't write unknown attribute `#{attr_name}'"
-
end
-
end
-
end
-
end
-
end
-
2
module ActiveRecord
-
# = Active Record Autosave Association
-
#
-
# +AutosaveAssociation+ is a module that takes care of automatically saving
-
# associated records when their parent is saved. In addition to saving, it
-
# also destroys any associated records that were marked for destruction.
-
# (See +mark_for_destruction+ and <tt>marked_for_destruction?</tt>).
-
#
-
# Saving of the parent, its associations, and the destruction of marked
-
# associations, all happen inside a transaction. This should never leave the
-
# database in an inconsistent state.
-
#
-
# If validations for any of the associations fail, their error messages will
-
# be applied to the parent.
-
#
-
# Note that it also means that associations marked for destruction won't
-
# be destroyed directly. They will however still be marked for destruction.
-
#
-
# Note that <tt>autosave: false</tt> is not same as not declaring <tt>:autosave</tt>.
-
# When the <tt>:autosave</tt> option is not present then new association records are
-
# saved but the updated association records are not saved.
-
#
-
# == Validation
-
#
-
# Children records are validated unless <tt>:validate</tt> is +false+.
-
#
-
# == Callbacks
-
#
-
# Association with autosave option defines several callbacks on your
-
# model (before_save, after_create, after_update). Please note that
-
# callbacks are executed in the order they were defined in
-
# model. You should avoid modifying the association content, before
-
# autosave callbacks are executed. Placing your callbacks after
-
# associations is usually a good practice.
-
#
-
# === One-to-one Example
-
#
-
# class Post < ActiveRecord::Base
-
# has_one :author, autosave: true
-
# end
-
#
-
# Saving changes to the parent and its associated model can now be performed
-
# automatically _and_ atomically:
-
#
-
# post = Post.find(1)
-
# post.title # => "The current global position of migrating ducks"
-
# post.author.name # => "alloy"
-
#
-
# post.title = "On the migration of ducks"
-
# post.author.name = "Eloy Duran"
-
#
-
# post.save
-
# post.reload
-
# post.title # => "On the migration of ducks"
-
# post.author.name # => "Eloy Duran"
-
#
-
# Destroying an associated model, as part of the parent's save action, is as
-
# simple as marking it for destruction:
-
#
-
# post.author.mark_for_destruction
-
# post.author.marked_for_destruction? # => true
-
#
-
# Note that the model is _not_ yet removed from the database:
-
#
-
# id = post.author.id
-
# Author.find_by(id: id).nil? # => false
-
#
-
# post.save
-
# post.reload.author # => nil
-
#
-
# Now it _is_ removed from the database:
-
#
-
# Author.find_by(id: id).nil? # => true
-
#
-
# === One-to-many Example
-
#
-
# When <tt>:autosave</tt> is not declared new children are saved when their parent is saved:
-
#
-
# class Post < ActiveRecord::Base
-
# has_many :comments # :autosave option is not declared
-
# end
-
#
-
# post = Post.new(title: 'ruby rocks')
-
# post.comments.build(body: 'hello world')
-
# post.save # => saves both post and comment
-
#
-
# post = Post.create(title: 'ruby rocks')
-
# post.comments.build(body: 'hello world')
-
# post.save # => saves both post and comment
-
#
-
# post = Post.create(title: 'ruby rocks')
-
# post.comments.create(body: 'hello world')
-
# post.save # => saves both post and comment
-
#
-
# When <tt>:autosave</tt> is true all children are saved, no matter whether they
-
# are new records or not:
-
#
-
# class Post < ActiveRecord::Base
-
# has_many :comments, autosave: true
-
# end
-
#
-
# post = Post.create(title: 'ruby rocks')
-
# post.comments.create(body: 'hello world')
-
# post.comments[0].body = 'hi everyone'
-
# post.comments.build(body: "good morning.")
-
# post.title += "!"
-
# post.save # => saves both post and comments.
-
#
-
# Destroying one of the associated models as part of the parent's save action
-
# is as simple as marking it for destruction:
-
#
-
# post.comments # => [#<Comment id: 1, ...>, #<Comment id: 2, ...]>
-
# post.comments[1].mark_for_destruction
-
# post.comments[1].marked_for_destruction? # => true
-
# post.comments.length # => 2
-
#
-
# Note that the model is _not_ yet removed from the database:
-
#
-
# id = post.comments.last.id
-
# Comment.find_by(id: id).nil? # => false
-
#
-
# post.save
-
# post.reload.comments.length # => 1
-
#
-
# Now it _is_ removed from the database:
-
#
-
# Comment.find_by(id: id).nil? # => true
-
-
2
module AutosaveAssociation
-
2
extend ActiveSupport::Concern
-
-
2
module AssociationBuilderExtension #:nodoc:
-
2
def self.build(model, reflection)
-
41
model.send(:add_autosave_association_callbacks, reflection)
-
end
-
-
2
def self.valid_options
-
41
[ :autosave ]
-
end
-
end
-
-
2
included do
-
2
Associations::Builder::Association.extensions << AssociationBuilderExtension
-
end
-
-
2
module ClassMethods
-
2
private
-
-
2
def define_non_cyclic_method(name, &block)
-
66
return if method_defined?(name)
-
66
define_method(name) do |*args|
-
2595
result = true; @_already_called ||= {}
-
# Loop prevention for validation of associations
-
2595
unless @_already_called[name]
-
2595
begin
-
2595
@_already_called[name]=true
-
2595
result = instance_eval(&block)
-
ensure
-
2595
@_already_called[name]=false
-
end
-
end
-
-
2595
result
-
end
-
end
-
-
# Adds validation and save callbacks for the association as specified by
-
# the +reflection+.
-
#
-
# For performance reasons, we don't check whether to validate at runtime.
-
# However the validation and callback methods are lazy and those methods
-
# get created when they are invoked for the very first time. However,
-
# this can change, for instance, when using nested attributes, which is
-
# called _after_ the association has been defined. Since we don't want
-
# the callbacks to get defined multiple times, there are guards that
-
# check if the save or validation methods have already been defined
-
# before actually defining them.
-
2
def add_autosave_association_callbacks(reflection)
-
41
save_method = :"autosave_associated_records_for_#{reflection.name}"
-
41
validation_method = :"validate_associated_records_for_#{reflection.name}"
-
41
collection = reflection.collection?
-
-
41
if collection
-
27
before_save :before_save_collection_association
-
-
1208
define_non_cyclic_method(save_method) { save_collection_association(reflection) }
-
# Doesn't use after_save as that would save associations added in after_create/after_update twice
-
27
after_create save_method
-
27
after_update save_method
-
elsif reflection.macro == :has_one
-
123
define_method(save_method) { save_has_one_association(reflection) } unless method_defined?(save_method)
-
# Configures two callbacks instead of a single after_save so that
-
# the model may rely on their execution order relative to its
-
# own callbacks.
-
#
-
# For example, given that after_creates run before after_saves, if
-
# we configured instead an after_save there would be no way to fire
-
# a custom after_create callback after the child association gets
-
# created.
-
2
after_create save_method
-
2
after_update save_method
-
else
-
232
define_non_cyclic_method(save_method) { save_belongs_to_association(reflection) }
-
12
before_save save_method
-
end
-
-
41
if reflection.validate? && !method_defined?(validation_method)
-
27
method = (collection ? :validate_collection_association : :validate_single_association)
-
1221
define_non_cyclic_method(validation_method) { send(method, reflection) }
-
27
validate validation_method
-
end
-
end
-
end
-
-
# Reloads the attributes of the object as usual and clears <tt>marked_for_destruction</tt> flag.
-
2
def reload(options = nil)
-
@marked_for_destruction = false
-
@destroyed_by_association = nil
-
super
-
end
-
-
# Marks this record to be destroyed as part of the parents save transaction.
-
# This does _not_ actually destroy the record instantly, rather child record will be destroyed
-
# when <tt>parent.save</tt> is called.
-
#
-
# Only useful if the <tt>:autosave</tt> option on the parent is enabled for this associated model.
-
2
def mark_for_destruction
-
@marked_for_destruction = true
-
end
-
-
# Returns whether or not this record will be destroyed as part of the parents save transaction.
-
#
-
# Only useful if the <tt>:autosave</tt> option on the parent is enabled for this associated model.
-
2
def marked_for_destruction?
-
@marked_for_destruction
-
end
-
-
# Records the association that is being destroyed and destroying this
-
# record in the process.
-
2
def destroyed_by_association=(reflection)
-
@destroyed_by_association = reflection
-
end
-
-
# Returns the association for the parent being destroyed.
-
#
-
# Used to avoid updating the counter cache unnecessarily.
-
2
def destroyed_by_association
-
@destroyed_by_association
-
end
-
-
# Returns whether or not this record has been changed in any way (including whether
-
# any of its nested autosave associations are likewise changed)
-
2
def changed_for_autosave?
-
new_record? || changed? || marked_for_destruction? || nested_records_changed_for_autosave?
-
end
-
-
2
private
-
-
# Returns the record for an association collection that should be validated
-
# or saved. If +autosave+ is +false+ only new records will be returned,
-
# unless the parent is/was a new record itself.
-
2
def associated_records_to_validate_or_save(association, new_record, autosave)
-
if new_record
-
association && association.target
-
elsif autosave
-
association.target.find_all { |record| record.changed_for_autosave? }
-
else
-
association.target.find_all { |record| record.new_record? }
-
end
-
end
-
-
# go through nested autosave associations that are loaded in memory (without loading
-
# any new ones), and return true if is changed for autosave
-
2
def nested_records_changed_for_autosave?
-
self.class._reflections.values.any? do |reflection|
-
if reflection.options[:autosave]
-
association = association_instance_get(reflection.name)
-
association && Array.wrap(association.target).any? { |a| a.changed_for_autosave? }
-
end
-
end
-
end
-
-
# Validate the association if <tt>:validate</tt> or <tt>:autosave</tt> is
-
# turned on for the association.
-
2
def validate_single_association(reflection)
-
association = association_instance_get(reflection.name)
-
record = association && association.reader
-
association_valid?(reflection, record) if record
-
end
-
-
# Validate the associated records if <tt>:validate</tt> or
-
# <tt>:autosave</tt> is turned on for the association specified by
-
# +reflection+.
-
2
def validate_collection_association(reflection)
-
1194
if association = association_instance_get(reflection.name)
-
if records = associated_records_to_validate_or_save(association, new_record?, reflection.options[:autosave])
-
records.each { |record| association_valid?(reflection, record) }
-
end
-
end
-
end
-
-
# Returns whether or not the association is valid and applies any errors to
-
# the parent, <tt>self</tt>, if it wasn't. Skips any <tt>:autosave</tt>
-
# enabled records if they're marked_for_destruction? or destroyed.
-
2
def association_valid?(reflection, record)
-
return true if record.destroyed? || record.marked_for_destruction?
-
-
unless valid = record.valid?
-
if reflection.options[:autosave]
-
record.errors.each do |attribute, message|
-
attribute = "#{reflection.name}.#{attribute}"
-
errors[attribute] << message
-
errors[attribute].uniq!
-
end
-
else
-
errors.add(reflection.name)
-
end
-
end
-
valid
-
end
-
-
# Is used as a before_save callback to check while saving a collection
-
# association whether or not the parent was a new record before saving.
-
2
def before_save_collection_association
-
193
@new_record_before_save = new_record?
-
193
true
-
end
-
-
# Saves any new associated records, or all loaded autosave associations if
-
# <tt>:autosave</tt> is enabled on the association.
-
#
-
# In addition, it destroys all children that were marked for destruction
-
# with mark_for_destruction.
-
#
-
# This all happens inside a transaction, _if_ the Transactions module is included into
-
# ActiveRecord::Base after the AutosaveAssociation module, which it does by default.
-
2
def save_collection_association(reflection)
-
1181
if association = association_instance_get(reflection.name)
-
autosave = reflection.options[:autosave]
-
-
if records = associated_records_to_validate_or_save(association, @new_record_before_save, autosave)
-
if autosave
-
records_to_destroy = records.select(&:marked_for_destruction?)
-
records_to_destroy.each { |record| association.destroy(record) }
-
records -= records_to_destroy
-
end
-
-
records.each do |record|
-
next if record.destroyed?
-
-
saved = true
-
-
if autosave != false && (@new_record_before_save || record.new_record?)
-
if autosave
-
saved = association.insert_record(record, false)
-
else
-
association.insert_record(record) unless reflection.nested?
-
end
-
elsif autosave
-
saved = record.save(:validate => false)
-
end
-
-
raise ActiveRecord::Rollback unless saved
-
end
-
end
-
-
# reconstruct the scope now that we know the owner's id
-
association.reset_scope if association.respond_to?(:reset_scope)
-
end
-
end
-
-
# Saves the associated record if it's new or <tt>:autosave</tt> is enabled
-
# on the association.
-
#
-
# In addition, it will destroy the association if it was marked for
-
# destruction with mark_for_destruction.
-
#
-
# This all happens inside a transaction, _if_ the Transactions module is included into
-
# ActiveRecord::Base after the AutosaveAssociation module, which it does by default.
-
2
def save_has_one_association(reflection)
-
121
association = association_instance_get(reflection.name)
-
121
record = association && association.load_target
-
-
121
if record && !record.destroyed?
-
autosave = reflection.options[:autosave]
-
-
if autosave && record.marked_for_destruction?
-
record.destroy
-
elsif autosave != false
-
key = reflection.options[:primary_key] ? send(reflection.options[:primary_key]) : id
-
-
if (autosave && record.changed_for_autosave?) || new_record? || record_changed?(reflection, record, key)
-
unless reflection.through_reflection
-
record[reflection.foreign_key] = key
-
end
-
-
saved = record.save(:validate => !autosave)
-
raise ActiveRecord::Rollback if !saved && autosave
-
saved
-
end
-
end
-
end
-
end
-
-
# If the record is new or it has changed, returns true.
-
2
def record_changed?(reflection, record, key)
-
record.new_record? || record[reflection.foreign_key] != key || record.attribute_changed?(reflection.foreign_key)
-
end
-
-
# Saves the associated record if it's new or <tt>:autosave</tt> is enabled.
-
#
-
# In addition, it will destroy the association if it was marked for destruction.
-
2
def save_belongs_to_association(reflection)
-
220
association = association_instance_get(reflection.name)
-
220
record = association && association.load_target
-
220
if record && !record.destroyed?
-
autosave = reflection.options[:autosave]
-
-
if autosave && record.marked_for_destruction?
-
self[reflection.foreign_key] = nil
-
record.destroy
-
elsif autosave != false
-
saved = record.save(:validate => !autosave) if record.new_record? || (autosave && record.changed_for_autosave?)
-
-
if association.updated?
-
association_id = record.send(reflection.options[:primary_key] || :id)
-
self[reflection.foreign_key] = association_id
-
association.loaded!
-
end
-
-
saved if autosave
-
end
-
end
-
end
-
end
-
end
-
2
require 'yaml'
-
2
require 'set'
-
2
require 'active_support/benchmarkable'
-
2
require 'active_support/dependencies'
-
2
require 'active_support/descendants_tracker'
-
2
require 'active_support/time'
-
2
require 'active_support/core_ext/module/attribute_accessors'
-
2
require 'active_support/core_ext/class/delegating_attributes'
-
2
require 'active_support/core_ext/array/extract_options'
-
2
require 'active_support/core_ext/hash/deep_merge'
-
2
require 'active_support/core_ext/hash/slice'
-
2
require 'active_support/core_ext/string/behavior'
-
2
require 'active_support/core_ext/kernel/singleton_class'
-
2
require 'active_support/core_ext/module/introspection'
-
2
require 'active_support/core_ext/object/duplicable'
-
2
require 'active_support/core_ext/class/subclasses'
-
2
require 'arel'
-
2
require 'active_record/errors'
-
2
require 'active_record/log_subscriber'
-
2
require 'active_record/explain_subscriber'
-
2
require 'active_record/relation/delegation'
-
-
2
module ActiveRecord #:nodoc:
-
# = Active Record
-
#
-
# Active Record objects don't specify their attributes directly, but rather infer them from
-
# the table definition with which they're linked. Adding, removing, and changing attributes
-
# and their type is done directly in the database. Any change is instantly reflected in the
-
# Active Record objects. The mapping that binds a given Active Record class to a certain
-
# database table will happen automatically in most common cases, but can be overwritten for the uncommon ones.
-
#
-
# See the mapping rules in table_name and the full example in link:files/activerecord/README_rdoc.html for more insight.
-
#
-
# == Creation
-
#
-
# Active Records accept constructor parameters either in a hash or as a block. The hash
-
# method is especially useful when you're receiving the data from somewhere else, like an
-
# HTTP request. It works like this:
-
#
-
# user = User.new(name: "David", occupation: "Code Artist")
-
# user.name # => "David"
-
#
-
# You can also use block initialization:
-
#
-
# user = User.new do |u|
-
# u.name = "David"
-
# u.occupation = "Code Artist"
-
# end
-
#
-
# And of course you can just create a bare object and specify the attributes after the fact:
-
#
-
# user = User.new
-
# user.name = "David"
-
# user.occupation = "Code Artist"
-
#
-
# == Conditions
-
#
-
# Conditions can either be specified as a string, array, or hash representing the WHERE-part of an SQL statement.
-
# The array form is to be used when the condition input is tainted and requires sanitization. The string form can
-
# be used for statements that don't involve tainted data. The hash form works much like the array form, except
-
# only equality and range is possible. Examples:
-
#
-
# class User < ActiveRecord::Base
-
# def self.authenticate_unsafely(user_name, password)
-
# where("user_name = '#{user_name}' AND password = '#{password}'").first
-
# end
-
#
-
# def self.authenticate_safely(user_name, password)
-
# where("user_name = ? AND password = ?", user_name, password).first
-
# end
-
#
-
# def self.authenticate_safely_simply(user_name, password)
-
# where(user_name: user_name, password: password).first
-
# end
-
# end
-
#
-
# The <tt>authenticate_unsafely</tt> method inserts the parameters directly into the query
-
# and is thus susceptible to SQL-injection attacks if the <tt>user_name</tt> and +password+
-
# parameters come directly from an HTTP request. The <tt>authenticate_safely</tt> and
-
# <tt>authenticate_safely_simply</tt> both will sanitize the <tt>user_name</tt> and +password+
-
# before inserting them in the query, which will ensure that an attacker can't escape the
-
# query and fake the login (or worse).
-
#
-
# When using multiple parameters in the conditions, it can easily become hard to read exactly
-
# what the fourth or fifth question mark is supposed to represent. In those cases, you can
-
# resort to named bind variables instead. That's done by replacing the question marks with
-
# symbols and supplying a hash with values for the matching symbol keys:
-
#
-
# Company.where(
-
# "id = :id AND name = :name AND division = :division AND created_at > :accounting_date",
-
# { id: 3, name: "37signals", division: "First", accounting_date: '2005-01-01' }
-
# ).first
-
#
-
# Similarly, a simple hash without a statement will generate conditions based on equality with the SQL AND
-
# operator. For instance:
-
#
-
# Student.where(first_name: "Harvey", status: 1)
-
# Student.where(params[:student])
-
#
-
# A range may be used in the hash to use the SQL BETWEEN operator:
-
#
-
# Student.where(grade: 9..12)
-
#
-
# An array may be used in the hash to use the SQL IN operator:
-
#
-
# Student.where(grade: [9,11,12])
-
#
-
# When joining tables, nested hashes or keys written in the form 'table_name.column_name'
-
# can be used to qualify the table name of a particular condition. For instance:
-
#
-
# Student.joins(:schools).where(schools: { category: 'public' })
-
# Student.joins(:schools).where('schools.category' => 'public' )
-
#
-
# == Overwriting default accessors
-
#
-
# All column values are automatically available through basic accessors on the Active Record
-
# object, but sometimes you want to specialize this behavior. This can be done by overwriting
-
# the default accessors (using the same name as the attribute) and calling
-
# <tt>read_attribute(attr_name)</tt> and <tt>write_attribute(attr_name, value)</tt> to actually
-
# change things.
-
#
-
# class Song < ActiveRecord::Base
-
# # Uses an integer of seconds to hold the length of the song
-
#
-
# def length=(minutes)
-
# write_attribute(:length, minutes.to_i * 60)
-
# end
-
#
-
# def length
-
# read_attribute(:length) / 60
-
# end
-
# end
-
#
-
# You can alternatively use <tt>self[:attribute]=(value)</tt> and <tt>self[:attribute]</tt>
-
# instead of <tt>write_attribute(:attribute, value)</tt> and <tt>read_attribute(:attribute)</tt>.
-
#
-
# == Attribute query methods
-
#
-
# In addition to the basic accessors, query methods are also automatically available on the Active Record object.
-
# Query methods allow you to test whether an attribute value is present.
-
#
-
# For example, an Active Record User with the <tt>name</tt> attribute has a <tt>name?</tt> method that you can call
-
# to determine whether the user has a name:
-
#
-
# user = User.new(name: "David")
-
# user.name? # => true
-
#
-
# anonymous = User.new(name: "")
-
# anonymous.name? # => false
-
#
-
# == Accessing attributes before they have been typecasted
-
#
-
# Sometimes you want to be able to read the raw attribute data without having the column-determined
-
# typecast run its course first. That can be done by using the <tt><attribute>_before_type_cast</tt>
-
# accessors that all attributes have. For example, if your Account model has a <tt>balance</tt> attribute,
-
# you can call <tt>account.balance_before_type_cast</tt> or <tt>account.id_before_type_cast</tt>.
-
#
-
# This is especially useful in validation situations where the user might supply a string for an
-
# integer field and you want to display the original string back in an error message. Accessing the
-
# attribute normally would typecast the string to 0, which isn't what you want.
-
#
-
# == Dynamic attribute-based finders
-
#
-
# Dynamic attribute-based finders are a mildly deprecated way of getting (and/or creating) objects
-
# by simple queries without turning to SQL. They work by appending the name of an attribute
-
# to <tt>find_by_</tt> like <tt>Person.find_by_user_name</tt>.
-
# Instead of writing <tt>Person.find_by(user_name: user_name)</tt>, you can use
-
# <tt>Person.find_by_user_name(user_name)</tt>.
-
#
-
# It's possible to add an exclamation point (!) on the end of the dynamic finders to get them to raise an
-
# <tt>ActiveRecord::RecordNotFound</tt> error if they do not return any records,
-
# like <tt>Person.find_by_last_name!</tt>.
-
#
-
# It's also possible to use multiple attributes in the same find by separating them with "_and_".
-
#
-
# Person.find_by(user_name: user_name, password: password)
-
# Person.find_by_user_name_and_password(user_name, password) # with dynamic finder
-
#
-
# It's even possible to call these dynamic finder methods on relations and named scopes.
-
#
-
# Payment.order("created_on").find_by_amount(50)
-
#
-
# == Saving arrays, hashes, and other non-mappable objects in text columns
-
#
-
# Active Record can serialize any object in text columns using YAML. To do so, you must
-
# specify this with a call to the class method +serialize+.
-
# This makes it possible to store arrays, hashes, and other non-mappable objects without doing
-
# any additional work.
-
#
-
# class User < ActiveRecord::Base
-
# serialize :preferences
-
# end
-
#
-
# user = User.create(preferences: { "background" => "black", "display" => large })
-
# User.find(user.id).preferences # => { "background" => "black", "display" => large }
-
#
-
# You can also specify a class option as the second parameter that'll raise an exception
-
# if a serialized object is retrieved as a descendant of a class not in the hierarchy.
-
#
-
# class User < ActiveRecord::Base
-
# serialize :preferences, Hash
-
# end
-
#
-
# user = User.create(preferences: %w( one two three ))
-
# User.find(user.id).preferences # raises SerializationTypeMismatch
-
#
-
# When you specify a class option, the default value for that attribute will be a new
-
# instance of that class.
-
#
-
# class User < ActiveRecord::Base
-
# serialize :preferences, OpenStruct
-
# end
-
#
-
# user = User.new
-
# user.preferences.theme_color = "red"
-
#
-
#
-
# == Single table inheritance
-
#
-
# Active Record allows inheritance by storing the name of the class in a column that by
-
# default is named "type" (can be changed by overwriting <tt>Base.inheritance_column</tt>).
-
# This means that an inheritance looking like this:
-
#
-
# class Company < ActiveRecord::Base; end
-
# class Firm < Company; end
-
# class Client < Company; end
-
# class PriorityClient < Client; end
-
#
-
# When you do <tt>Firm.create(name: "37signals")</tt>, this record will be saved in
-
# the companies table with type = "Firm". You can then fetch this row again using
-
# <tt>Company.where(name: '37signals').first</tt> and it will return a Firm object.
-
#
-
# If you don't have a type column defined in your table, single-table inheritance won't
-
# be triggered. In that case, it'll work just like normal subclasses with no special magic
-
# for differentiating between them or reloading the right type with find.
-
#
-
# Note, all the attributes for all the cases are kept in the same table. Read more:
-
# http://www.martinfowler.com/eaaCatalog/singleTableInheritance.html
-
#
-
# == Connection to multiple databases in different models
-
#
-
# Connections are usually created through ActiveRecord::Base.establish_connection and retrieved
-
# by ActiveRecord::Base.connection. All classes inheriting from ActiveRecord::Base will use this
-
# connection. But you can also set a class-specific connection. For example, if Course is an
-
# ActiveRecord::Base, but resides in a different database, you can just say <tt>Course.establish_connection</tt>
-
# and Course and all of its subclasses will use this connection instead.
-
#
-
# This feature is implemented by keeping a connection pool in ActiveRecord::Base that is
-
# a Hash indexed by the class. If a connection is requested, the retrieve_connection method
-
# will go up the class-hierarchy until a connection is found in the connection pool.
-
#
-
# == Exceptions
-
#
-
# * ActiveRecordError - Generic error class and superclass of all other errors raised by Active Record.
-
# * AdapterNotSpecified - The configuration hash used in <tt>establish_connection</tt> didn't include an
-
# <tt>:adapter</tt> key.
-
# * AdapterNotFound - The <tt>:adapter</tt> key used in <tt>establish_connection</tt> specified a
-
# non-existent adapter
-
# (or a bad spelling of an existing one).
-
# * AssociationTypeMismatch - The object assigned to the association wasn't of the type
-
# specified in the association definition.
-
# * AttributeAssignmentError - An error occurred while doing a mass assignment through the
-
# <tt>attributes=</tt> method.
-
# You can inspect the +attribute+ property of the exception object to determine which attribute
-
# triggered the error.
-
# * ConnectionNotEstablished - No connection has been established. Use <tt>establish_connection</tt>
-
# before querying.
-
# * MultiparameterAssignmentErrors - Collection of errors that occurred during a mass assignment using the
-
# <tt>attributes=</tt> method. The +errors+ property of this exception contains an array of
-
# AttributeAssignmentError
-
# objects that should be inspected to determine which attributes triggered the errors.
-
# * RecordInvalid - raised by save! and create! when the record is invalid.
-
# * RecordNotFound - No record responded to the +find+ method. Either the row with the given ID doesn't exist
-
# or the row didn't meet the additional restrictions. Some +find+ calls do not raise this exception to signal
-
# nothing was found, please check its documentation for further details.
-
# * SerializationTypeMismatch - The serialized object wasn't of the class specified as the second parameter.
-
# * StatementInvalid - The database server rejected the SQL statement. The precise error is added in the message.
-
#
-
# *Note*: The attributes listed are class-level attributes (accessible from both the class and instance level).
-
# So it's possible to assign a logger to the class through <tt>Base.logger=</tt> which will then be used by all
-
# instances in the current object space.
-
2
class Base
-
2
extend ActiveModel::Naming
-
-
2
extend ActiveSupport::Benchmarkable
-
2
extend ActiveSupport::DescendantsTracker
-
-
2
extend ConnectionHandling
-
2
extend QueryCache::ClassMethods
-
2
extend Querying
-
2
extend Translation
-
2
extend DynamicMatchers
-
2
extend Explain
-
2
extend Enum
-
2
extend Delegation::DelegateCache
-
-
2
include Core
-
2
include Persistence
-
2
include ReadonlyAttributes
-
2
include ModelSchema
-
2
include Inheritance
-
2
include Scoping
-
2
include Sanitization
-
2
include AttributeAssignment
-
2
include ActiveModel::Conversion
-
2
include Integration
-
2
include Validations
-
2
include CounterCache
-
2
include Locking::Optimistic
-
2
include Locking::Pessimistic
-
2
include AttributeMethods
-
2
include Callbacks
-
2
include Timestamp
-
2
include Associations
-
2
include ActiveModel::SecurePassword
-
2
include AutosaveAssociation
-
2
include NestedAttributes
-
2
include Aggregations
-
2
include Transactions
-
2
include NoTouching
-
2
include Reflection
-
2
include Serialization
-
2
include Store
-
end
-
-
2
ActiveSupport.run_load_hooks(:active_record, Base)
-
end
-
2
module ActiveRecord
-
# = Active Record Callbacks
-
#
-
# Callbacks are hooks into the life cycle of an Active Record object that allow you to trigger logic
-
# before or after an alteration of the object state. This can be used to make sure that associated and
-
# dependent objects are deleted when +destroy+ is called (by overwriting +before_destroy+) or to massage attributes
-
# before they're validated (by overwriting +before_validation+). As an example of the callbacks initiated, consider
-
# the <tt>Base#save</tt> call for a new record:
-
#
-
# * (-) <tt>save</tt>
-
# * (-) <tt>valid</tt>
-
# * (1) <tt>before_validation</tt>
-
# * (-) <tt>validate</tt>
-
# * (2) <tt>after_validation</tt>
-
# * (3) <tt>before_save</tt>
-
# * (4) <tt>before_create</tt>
-
# * (-) <tt>create</tt>
-
# * (5) <tt>after_create</tt>
-
# * (6) <tt>after_save</tt>
-
# * (7) <tt>after_commit</tt>
-
#
-
# Also, an <tt>after_rollback</tt> callback can be configured to be triggered whenever a rollback is issued.
-
# Check out <tt>ActiveRecord::Transactions</tt> for more details about <tt>after_commit</tt> and
-
# <tt>after_rollback</tt>.
-
#
-
# Additionally, an <tt>after_touch</tt> callback is triggered whenever an
-
# object is touched.
-
#
-
# Lastly an <tt>after_find</tt> and <tt>after_initialize</tt> callback is triggered for each object that
-
# is found and instantiated by a finder, with <tt>after_initialize</tt> being triggered after new objects
-
# are instantiated as well.
-
#
-
# There are nineteen callbacks in total, which give you immense power to react and prepare for each state in the
-
# Active Record life cycle. The sequence for calling <tt>Base#save</tt> for an existing record is similar,
-
# except that each <tt>_create</tt> callback is replaced by the corresponding <tt>_update</tt> callback.
-
#
-
# Examples:
-
# class CreditCard < ActiveRecord::Base
-
# # Strip everything but digits, so the user can specify "555 234 34" or
-
# # "5552-3434" and both will mean "55523434"
-
# before_validation(on: :create) do
-
# self.number = number.gsub(/[^0-9]/, "") if attribute_present?("number")
-
# end
-
# end
-
#
-
# class Subscription < ActiveRecord::Base
-
# before_create :record_signup
-
#
-
# private
-
# def record_signup
-
# self.signed_up_on = Date.today
-
# end
-
# end
-
#
-
# class Firm < ActiveRecord::Base
-
# # Destroys the associated clients and people when the firm is destroyed
-
# before_destroy { |record| Person.destroy_all "firm_id = #{record.id}" }
-
# before_destroy { |record| Client.destroy_all "client_of = #{record.id}" }
-
# end
-
#
-
# == Inheritable callback queues
-
#
-
# Besides the overwritable callback methods, it's also possible to register callbacks through the
-
# use of the callback macros. Their main advantage is that the macros add behavior into a callback
-
# queue that is kept intact down through an inheritance hierarchy.
-
#
-
# class Topic < ActiveRecord::Base
-
# before_destroy :destroy_author
-
# end
-
#
-
# class Reply < Topic
-
# before_destroy :destroy_readers
-
# end
-
#
-
# Now, when <tt>Topic#destroy</tt> is run only +destroy_author+ is called. When <tt>Reply#destroy</tt> is
-
# run, both +destroy_author+ and +destroy_readers+ are called. Contrast this to the following situation
-
# where the +before_destroy+ method is overridden:
-
#
-
# class Topic < ActiveRecord::Base
-
# def before_destroy() destroy_author end
-
# end
-
#
-
# class Reply < Topic
-
# def before_destroy() destroy_readers end
-
# end
-
#
-
# In that case, <tt>Reply#destroy</tt> would only run +destroy_readers+ and _not_ +destroy_author+.
-
# So, use the callback macros when you want to ensure that a certain callback is called for the entire
-
# hierarchy, and use the regular overwritable methods when you want to leave it up to each descendant
-
# to decide whether they want to call +super+ and trigger the inherited callbacks.
-
#
-
# *IMPORTANT:* In order for inheritance to work for the callback queues, you must specify the
-
# callbacks before specifying the associations. Otherwise, you might trigger the loading of a
-
# child before the parent has registered the callbacks and they won't be inherited.
-
#
-
# == Types of callbacks
-
#
-
# There are four types of callbacks accepted by the callback macros: Method references (symbol), callback objects,
-
# inline methods (using a proc), and inline eval methods (using a string). Method references and callback objects
-
# are the recommended approaches, inline methods using a proc are sometimes appropriate (such as for
-
# creating mix-ins), and inline eval methods are deprecated.
-
#
-
# The method reference callbacks work by specifying a protected or private method available in the object, like this:
-
#
-
# class Topic < ActiveRecord::Base
-
# before_destroy :delete_parents
-
#
-
# private
-
# def delete_parents
-
# self.class.delete_all "parent_id = #{id}"
-
# end
-
# end
-
#
-
# The callback objects have methods named after the callback called with the record as the only parameter, such as:
-
#
-
# class BankAccount < ActiveRecord::Base
-
# before_save EncryptionWrapper.new
-
# after_save EncryptionWrapper.new
-
# after_initialize EncryptionWrapper.new
-
# end
-
#
-
# class EncryptionWrapper
-
# def before_save(record)
-
# record.credit_card_number = encrypt(record.credit_card_number)
-
# end
-
#
-
# def after_save(record)
-
# record.credit_card_number = decrypt(record.credit_card_number)
-
# end
-
#
-
# alias_method :after_initialize, :after_save
-
#
-
# private
-
# def encrypt(value)
-
# # Secrecy is committed
-
# end
-
#
-
# def decrypt(value)
-
# # Secrecy is unveiled
-
# end
-
# end
-
#
-
# So you specify the object you want messaged on a given callback. When that callback is triggered, the object has
-
# a method by the name of the callback messaged. You can make these callbacks more flexible by passing in other
-
# initialization data such as the name of the attribute to work with:
-
#
-
# class BankAccount < ActiveRecord::Base
-
# before_save EncryptionWrapper.new("credit_card_number")
-
# after_save EncryptionWrapper.new("credit_card_number")
-
# after_initialize EncryptionWrapper.new("credit_card_number")
-
# end
-
#
-
# class EncryptionWrapper
-
# def initialize(attribute)
-
# @attribute = attribute
-
# end
-
#
-
# def before_save(record)
-
# record.send("#{@attribute}=", encrypt(record.send("#{@attribute}")))
-
# end
-
#
-
# def after_save(record)
-
# record.send("#{@attribute}=", decrypt(record.send("#{@attribute}")))
-
# end
-
#
-
# alias_method :after_initialize, :after_save
-
#
-
# private
-
# def encrypt(value)
-
# # Secrecy is committed
-
# end
-
#
-
# def decrypt(value)
-
# # Secrecy is unveiled
-
# end
-
# end
-
#
-
# The callback macros usually accept a symbol for the method they're supposed to run, but you can also
-
# pass a "method string", which will then be evaluated within the binding of the callback. Example:
-
#
-
# class Topic < ActiveRecord::Base
-
# before_destroy 'self.class.delete_all "parent_id = #{id}"'
-
# end
-
#
-
# Notice that single quotes (') are used so the <tt>#{id}</tt> part isn't evaluated until the callback
-
# is triggered. Also note that these inline callbacks can be stacked just like the regular ones:
-
#
-
# class Topic < ActiveRecord::Base
-
# before_destroy 'self.class.delete_all "parent_id = #{id}"',
-
# 'puts "Evaluated after parents are destroyed"'
-
# end
-
#
-
# == <tt>before_validation*</tt> returning statements
-
#
-
# If the returning value of a +before_validation+ callback can be evaluated to +false+, the process will be
-
# aborted and <tt>Base#save</tt> will return +false+. If Base#save! is called it will raise a
-
# ActiveRecord::RecordInvalid exception. Nothing will be appended to the errors object.
-
#
-
# == Canceling callbacks
-
#
-
# If a <tt>before_*</tt> callback returns +false+, all the later callbacks and the associated action are
-
# cancelled. If an <tt>after_*</tt> callback returns +false+, all the later callbacks are cancelled.
-
# Callbacks are generally run in the order they are defined, with the exception of callbacks defined as
-
# methods on the model, which are called last.
-
#
-
# == Ordering callbacks
-
#
-
# Sometimes the code needs that the callbacks execute in a specific order. For example, a +before_destroy+
-
# callback (+log_children+ in this case) should be executed before the children get destroyed by the +dependent: destroy+ option.
-
#
-
# Let's look at the code below:
-
#
-
# class Topic < ActiveRecord::Base
-
# has_many :children, dependent: destroy
-
#
-
# before_destroy :log_children
-
#
-
# private
-
# def log_children
-
# # Child processing
-
# end
-
# end
-
#
-
# In this case, the problem is that when the +before_destroy+ callback is executed, the children are not available
-
# because the +destroy+ callback gets executed first. You can use the +prepend+ option on the +before_destroy+ callback to avoid this.
-
#
-
# class Topic < ActiveRecord::Base
-
# has_many :children, dependent: destroy
-
#
-
# before_destroy :log_children, prepend: true
-
#
-
# private
-
# def log_children
-
# # Child processing
-
# end
-
# end
-
#
-
# This way, the +before_destroy+ gets executed before the <tt>dependent: destroy</tt> is called, and the data is still available.
-
#
-
# == Transactions
-
#
-
# The entire callback chain of a +save+, <tt>save!</tt>, or +destroy+ call runs
-
# within a transaction. That includes <tt>after_*</tt> hooks. If everything
-
# goes fine a COMMIT is executed once the chain has been completed.
-
#
-
# If a <tt>before_*</tt> callback cancels the action a ROLLBACK is issued. You
-
# can also trigger a ROLLBACK raising an exception in any of the callbacks,
-
# including <tt>after_*</tt> hooks. Note, however, that in that case the client
-
# needs to be aware of it because an ordinary +save+ will raise such exception
-
# instead of quietly returning +false+.
-
#
-
# == Debugging callbacks
-
#
-
# The callback chain is accessible via the <tt>_*_callbacks</tt> method on an object. ActiveModel Callbacks support
-
# <tt>:before</tt>, <tt>:after</tt> and <tt>:around</tt> as values for the <tt>kind</tt> property. The <tt>kind</tt> property
-
# defines what part of the chain the callback runs in.
-
#
-
# To find all callbacks in the before_save callback chain:
-
#
-
# Topic._save_callbacks.select { |cb| cb.kind.eql?(:before) }
-
#
-
# Returns an array of callback objects that form the before_save chain.
-
#
-
# To further check if the before_save chain contains a proc defined as <tt>rest_when_dead</tt> use the <tt>filter</tt> property of the callback object:
-
#
-
# Topic._save_callbacks.select { |cb| cb.kind.eql?(:before) }.collect(&:filter).include?(:rest_when_dead)
-
#
-
# Returns true or false depending on whether the proc is contained in the before_save callback chain on a Topic model.
-
#
-
2
module Callbacks
-
2
extend ActiveSupport::Concern
-
-
2
CALLBACKS = [
-
:after_initialize, :after_find, :after_touch, :before_validation, :after_validation,
-
:before_save, :around_save, :after_save, :before_create, :around_create,
-
:after_create, :before_update, :around_update, :after_update,
-
:before_destroy, :around_destroy, :after_destroy, :after_commit, :after_rollback
-
]
-
-
2
module ClassMethods
-
2
include ActiveModel::Callbacks
-
end
-
-
2
included do
-
2
include ActiveModel::Validations::Callbacks
-
-
2
define_model_callbacks :initialize, :find, :touch, :only => :after
-
2
define_model_callbacks :save, :create, :update, :destroy
-
end
-
-
2
def destroy #:nodoc:
-
run_callbacks(:destroy) { super }
-
end
-
-
2
def touch(*) #:nodoc:
-
run_callbacks(:touch) { super }
-
end
-
-
2
private
-
-
2
def create_or_update #:nodoc:
-
534
run_callbacks(:save) { super }
-
end
-
-
2
def _create_record #:nodoc:
-
534
run_callbacks(:create) { super }
-
end
-
-
2
def _update_record(*) #:nodoc:
-
run_callbacks(:update) { super }
-
end
-
end
-
end
-
2
require 'yaml'
-
-
2
module ActiveRecord
-
2
module Coders # :nodoc:
-
2
class YAMLColumn # :nodoc:
-
-
2
attr_accessor :object_class
-
-
2
def initialize(object_class = Object)
-
2
@object_class = object_class
-
end
-
-
2
def dump(obj)
-
72
return if obj.nil?
-
-
72
unless obj.is_a?(object_class)
-
raise SerializationTypeMismatch,
-
"Attribute was supposed to be a #{object_class}, but was a #{obj.class}. -- #{obj.inspect}"
-
end
-
72
YAML.dump obj
-
end
-
-
2
def load(yaml)
-
72
return object_class.new if object_class != Object && yaml.nil?
-
72
return yaml unless yaml.is_a?(String) && yaml =~ /^---/
-
72
obj = YAML.load(yaml)
-
-
72
unless obj.is_a?(object_class) || obj.nil?
-
raise SerializationTypeMismatch,
-
"Attribute was supposed to be a #{object_class}, but was a #{obj.class}"
-
end
-
72
obj ||= object_class.new if object_class != Object
-
-
72
obj
-
end
-
end
-
end
-
end
-
2
require 'thread'
-
2
require 'thread_safe'
-
2
require 'monitor'
-
2
require 'set'
-
-
2
module ActiveRecord
-
# Raised when a connection could not be obtained within the connection
-
# acquisition timeout period: because max connections in pool
-
# are in use.
-
2
class ConnectionTimeoutError < ConnectionNotEstablished
-
end
-
-
2
module ConnectionAdapters
-
# Connection pool base class for managing Active Record database
-
# connections.
-
#
-
# == Introduction
-
#
-
# A connection pool synchronizes thread access to a limited number of
-
# database connections. The basic idea is that each thread checks out a
-
# database connection from the pool, uses that connection, and checks the
-
# connection back in. ConnectionPool is completely thread-safe, and will
-
# ensure that a connection cannot be used by two threads at the same time,
-
# as long as ConnectionPool's contract is correctly followed. It will also
-
# handle cases in which there are more threads than connections: if all
-
# connections have been checked out, and a thread tries to checkout a
-
# connection anyway, then ConnectionPool will wait until some other thread
-
# has checked in a connection.
-
#
-
# == Obtaining (checking out) a connection
-
#
-
# Connections can be obtained and used from a connection pool in several
-
# ways:
-
#
-
# 1. Simply use ActiveRecord::Base.connection as with Active Record 2.1 and
-
# earlier (pre-connection-pooling). Eventually, when you're done with
-
# the connection(s) and wish it to be returned to the pool, you call
-
# ActiveRecord::Base.clear_active_connections!. This will be the
-
# default behavior for Active Record when used in conjunction with
-
# Action Pack's request handling cycle.
-
# 2. Manually check out a connection from the pool with
-
# ActiveRecord::Base.connection_pool.checkout. You are responsible for
-
# returning this connection to the pool when finished by calling
-
# ActiveRecord::Base.connection_pool.checkin(connection).
-
# 3. Use ActiveRecord::Base.connection_pool.with_connection(&block), which
-
# obtains a connection, yields it as the sole argument to the block,
-
# and returns it to the pool after the block completes.
-
#
-
# Connections in the pool are actually AbstractAdapter objects (or objects
-
# compatible with AbstractAdapter's interface).
-
#
-
# == Options
-
#
-
# There are several connection-pooling-related options that you can add to
-
# your database connection configuration:
-
#
-
# * +pool+: number indicating size of connection pool (default 5)
-
# * +checkout_timeout+: number of seconds to block and wait for a connection
-
# before giving up and raising a timeout error (default 5 seconds).
-
# * +reaping_frequency+: frequency in seconds to periodically run the
-
# Reaper, which attempts to find and close dead connections, which can
-
# occur if a programmer forgets to close a connection at the end of a
-
# thread or a thread dies unexpectedly. (Default nil, which means don't
-
# run the Reaper).
-
# * +dead_connection_timeout+: number of seconds from last checkout
-
# after which the Reaper will consider a connection reapable. (default
-
# 5 seconds).
-
2
class ConnectionPool
-
# Threadsafe, fair, FIFO queue. Meant to be used by ConnectionPool
-
# with which it shares a Monitor. But could be a generic Queue.
-
#
-
# The Queue in stdlib's 'thread' could replace this class except
-
# stdlib's doesn't support waiting with a timeout.
-
2
class Queue
-
2
def initialize(lock = Monitor.new)
-
2
@lock = lock
-
2
@cond = @lock.new_cond
-
2
@num_waiting = 0
-
2
@queue = []
-
end
-
-
# Test if any threads are currently waiting on the queue.
-
2
def any_waiting?
-
synchronize do
-
@num_waiting > 0
-
end
-
end
-
-
# Returns the number of threads currently waiting on this
-
# queue.
-
2
def num_waiting
-
synchronize do
-
@num_waiting
-
end
-
end
-
-
# Add +element+ to the queue. Never blocks.
-
2
def add(element)
-
21
synchronize do
-
21
@queue.push element
-
21
@cond.signal
-
end
-
end
-
-
# If +element+ is in the queue, remove and return it, or nil.
-
2
def delete(element)
-
synchronize do
-
@queue.delete(element)
-
end
-
end
-
-
# Remove all elements from the queue.
-
2
def clear
-
synchronize do
-
@queue.clear
-
end
-
end
-
-
# Remove the head of the queue.
-
#
-
# If +timeout+ is not given, remove and return the head the
-
# queue if the number of available elements is strictly
-
# greater than the number of threads currently waiting (that
-
# is, don't jump ahead in line). Otherwise, return nil.
-
#
-
# If +timeout+ is given, block if it there is no element
-
# available, waiting up to +timeout+ seconds for an element to
-
# become available.
-
#
-
# Raises:
-
# - ConnectionTimeoutError if +timeout+ is given and no element
-
# becomes available after +timeout+ seconds,
-
2
def poll(timeout = nil)
-
22
synchronize do
-
22
if timeout
-
no_wait_poll || wait_poll(timeout)
-
else
-
22
no_wait_poll
-
end
-
end
-
end
-
-
2
private
-
-
2
def synchronize(&block)
-
43
@lock.synchronize(&block)
-
end
-
-
# Test if the queue currently contains any elements.
-
2
def any?
-
!@queue.empty?
-
end
-
-
# A thread can remove an element from the queue without
-
# waiting if an only if the number of currently available
-
# connections is strictly greater than the number of waiting
-
# threads.
-
2
def can_remove_no_wait?
-
22
@queue.size > @num_waiting
-
end
-
-
# Removes and returns the head of the queue if possible, or nil.
-
2
def remove
-
20
@queue.shift
-
end
-
-
# Remove and return the head the queue if the number of
-
# available elements is strictly greater than the number of
-
# threads currently waiting. Otherwise, return nil.
-
2
def no_wait_poll
-
22
remove if can_remove_no_wait?
-
end
-
-
# Waits on the queue up to +timeout+ seconds, then removes and
-
# returns the head of the queue.
-
2
def wait_poll(timeout)
-
@num_waiting += 1
-
-
t0 = Time.now
-
elapsed = 0
-
loop do
-
@cond.wait(timeout - elapsed)
-
-
return remove if any?
-
-
elapsed = Time.now - t0
-
if elapsed >= timeout
-
msg = 'could not obtain a database connection within %0.3f seconds (waited %0.3f seconds)' %
-
[timeout, elapsed]
-
raise ConnectionTimeoutError, msg
-
end
-
end
-
ensure
-
@num_waiting -= 1
-
end
-
end
-
-
# Every +frequency+ seconds, the reaper will call +reap+ on +pool+.
-
# A reaper instantiated with a nil frequency will never reap the
-
# connection pool.
-
#
-
# Configure the frequency by setting "reaping_frequency" in your
-
# database yaml file.
-
2
class Reaper
-
2
attr_reader :pool, :frequency
-
-
2
def initialize(pool, frequency)
-
2
@pool = pool
-
2
@frequency = frequency
-
end
-
-
2
def run
-
2
return unless frequency
-
Thread.new(frequency, pool) { |t, p|
-
while true
-
sleep t
-
p.reap
-
end
-
}
-
end
-
end
-
-
2
include MonitorMixin
-
-
2
attr_accessor :automatic_reconnect, :checkout_timeout, :dead_connection_timeout
-
2
attr_reader :spec, :connections, :size, :reaper
-
-
# Creates a new ConnectionPool object. +spec+ is a ConnectionSpecification
-
# object which describes database connection information (e.g. adapter,
-
# host name, username, password, etc), as well as the maximum size for
-
# this ConnectionPool.
-
#
-
# The default ConnectionPool maximum size is 5.
-
2
def initialize(spec)
-
2
super()
-
-
2
@spec = spec
-
-
2
@checkout_timeout = (spec.config[:checkout_timeout] && spec.config[:checkout_timeout].to_f) || 5
-
2
@dead_connection_timeout = (spec.config[:dead_connection_timeout] && spec.config[:dead_connection_timeout].to_f) || 5
-
2
@reaper = Reaper.new self, spec.config[:reaping_frequency]
-
2
@reaper.run
-
-
# default max pool size to 5
-
2
@size = (spec.config[:pool] && spec.config[:pool].to_i) || 5
-
-
# The cache of reserved connections mapped to threads
-
2
@reserved_connections = ThreadSafe::Cache.new(:initial_capacity => @size)
-
-
2
@connections = []
-
2
@automatic_reconnect = true
-
-
2
@available = Queue.new self
-
end
-
-
# Retrieve the connection associated with the current thread, or call
-
# #checkout to obtain one if necessary.
-
#
-
# #connection can be called any number of times; the connection is
-
# held in a hash keyed by the thread id.
-
2
def connection
-
# this is correctly done double-checked locking
-
# (ThreadSafe::Cache's lookups have volatile semantics)
-
@reserved_connections[current_connection_id] || synchronize do
-
22
@reserved_connections[current_connection_id] ||= checkout
-
4324
end
-
end
-
-
# Is there an open connection that is being used for the current thread?
-
2
def active_connection?
-
synchronize do
-
@reserved_connections.fetch(current_connection_id) {
-
return false
-
}.in_use?
-
end
-
end
-
-
# Signal that the thread is finished with the current connection.
-
# #release_connection releases the connection-thread association
-
# and returns the connection to the pool.
-
2
def release_connection(with_id = current_connection_id)
-
21
synchronize do
-
21
conn = @reserved_connections.delete(with_id)
-
21
checkin conn if conn
-
end
-
end
-
-
# If a connection already exists yield it to the block. If no connection
-
# exists checkout a connection, yield it to the block, and checkin the
-
# connection when finished.
-
2
def with_connection
-
connection_id = current_connection_id
-
fresh_connection = true unless active_connection?
-
yield connection
-
ensure
-
release_connection(connection_id) if fresh_connection
-
end
-
-
# Returns true if a connection has already been opened.
-
2
def connected?
-
100
synchronize { @connections.any? }
-
end
-
-
# Disconnects all connections in the pool, and clears the pool.
-
2
def disconnect!
-
synchronize do
-
@reserved_connections.clear
-
@connections.each do |conn|
-
checkin conn
-
conn.disconnect!
-
end
-
@connections = []
-
@available.clear
-
end
-
end
-
-
# Clears the cache which maps classes.
-
2
def clear_reloadable_connections!
-
synchronize do
-
@reserved_connections.clear
-
@connections.each do |conn|
-
checkin conn
-
conn.disconnect! if conn.requires_reloading?
-
end
-
@connections.delete_if do |conn|
-
conn.requires_reloading?
-
end
-
@available.clear
-
@connections.each do |conn|
-
@available.add conn
-
end
-
end
-
end
-
-
# Check-out a database connection from the pool, indicating that you want
-
# to use it. You should call #checkin when you no longer need this.
-
#
-
# This is done by either returning and leasing existing connection, or by
-
# creating a new connection and leasing it.
-
#
-
# If all connections are leased and the pool is at capacity (meaning the
-
# number of currently leased connections is greater than or equal to the
-
# size limit set), an ActiveRecord::ConnectionTimeoutError exception will be raised.
-
#
-
# Returns: an AbstractAdapter object.
-
#
-
# Raises:
-
# - ConnectionTimeoutError: no connection can be obtained from the pool.
-
2
def checkout
-
22
synchronize do
-
22
conn = acquire_connection
-
22
conn.lease
-
22
checkout_and_verify(conn)
-
end
-
end
-
-
# Check-in a database connection back into the pool, indicating that you
-
# no longer need this connection.
-
#
-
# +conn+: an AbstractAdapter object, which was obtained by earlier by
-
# calling +checkout+ on this pool.
-
2
def checkin(conn)
-
21
synchronize do
-
21
conn.run_callbacks :checkin do
-
21
conn.expire
-
end
-
-
21
release conn
-
-
21
@available.add conn
-
end
-
end
-
-
# Remove a connection from the connection pool. The connection will
-
# remain open and active but will no longer be managed by this pool.
-
2
def remove(conn)
-
synchronize do
-
@connections.delete conn
-
@available.delete conn
-
-
# FIXME: we might want to store the key on the connection so that removing
-
# from the reserved hash will be a little easier.
-
release conn
-
-
@available.add checkout_new_connection if @available.any_waiting?
-
end
-
end
-
-
# Removes dead connections from the pool. A dead connection can occur
-
# if a programmer forgets to close a connection at the end of a thread
-
# or a thread dies unexpectedly.
-
2
def reap
-
synchronize do
-
stale = Time.now - @dead_connection_timeout
-
connections.dup.each do |conn|
-
if conn.in_use? && stale > conn.last_use && !conn.active_threadsafe?
-
remove conn
-
end
-
end
-
end
-
end
-
-
2
private
-
-
# Acquire a connection by one of 1) immediately removing one
-
# from the queue of available connections, 2) creating a new
-
# connection if the pool is not at capacity, 3) waiting on the
-
# queue for a connection to become available.
-
#
-
# Raises:
-
# - ConnectionTimeoutError if a connection could not be acquired
-
2
def acquire_connection
-
22
if conn = @available.poll
-
20
conn
-
2
elsif @connections.size < @size
-
2
checkout_new_connection
-
else
-
@available.poll(@checkout_timeout)
-
end
-
end
-
-
2
def release(conn)
-
21
thread_id = if @reserved_connections[current_connection_id] == conn
-
current_connection_id
-
else
-
21
@reserved_connections.keys.find { |k|
-
@reserved_connections[k] == conn
-
}
-
end
-
-
21
@reserved_connections.delete thread_id if thread_id
-
end
-
-
2
def new_connection
-
2
Base.send(spec.adapter_method, spec.config)
-
end
-
-
2
def current_connection_id #:nodoc:
-
4388
Base.connection_id ||= Thread.current.object_id
-
end
-
-
2
def checkout_new_connection
-
2
raise ConnectionNotEstablished unless @automatic_reconnect
-
-
2
c = new_connection
-
2
c.pool = self
-
2
@connections << c
-
2
c
-
end
-
-
2
def checkout_and_verify(c)
-
22
c.run_callbacks :checkout do
-
22
c.verify!
-
end
-
22
c
-
end
-
end
-
-
# ConnectionHandler is a collection of ConnectionPool objects. It is used
-
# for keeping separate connection pools for Active Record models that connect
-
# to different databases.
-
#
-
# For example, suppose that you have 5 models, with the following hierarchy:
-
#
-
# |
-
# +-- Book
-
# | |
-
# | +-- ScaryBook
-
# | +-- GoodBook
-
# +-- Author
-
# +-- BankAccount
-
#
-
# Suppose that Book is to connect to a separate database (i.e. one other
-
# than the default database). Then Book, ScaryBook and GoodBook will all use
-
# the same connection pool. Likewise, Author and BankAccount will use the
-
# same connection pool. However, the connection pool used by Author/BankAccount
-
# is not the same as the one used by Book/ScaryBook/GoodBook.
-
#
-
# Normally there is only a single ConnectionHandler instance, accessible via
-
# ActiveRecord::Base.connection_handler. Active Record models use this to
-
# determine the connection pool that they should use.
-
2
class ConnectionHandler
-
2
def initialize
-
# These caches are keyed by klass.name, NOT klass. Keying them by klass
-
# alone would lead to memory leaks in development mode as all previous
-
# instances of the class would stay in memory.
-
2
@owner_to_pool = ThreadSafe::Cache.new(:initial_capacity => 2) do |h,k|
-
2
h[k] = ThreadSafe::Cache.new(:initial_capacity => 2)
-
end
-
2
@class_to_pool = ThreadSafe::Cache.new(:initial_capacity => 2) do |h,k|
-
2
h[k] = ThreadSafe::Cache.new
-
end
-
end
-
-
2
def connection_pool_list
-
42
owner_to_pool.values.compact
-
end
-
-
2
def connection_pools
-
ActiveSupport::Deprecation.warn(
-
"In the next release, this will return the same as #connection_pool_list. " \
-
"(An array of pools, rather than a hash mapping specs to pools.)"
-
)
-
Hash[connection_pool_list.map { |pool| [pool.spec, pool] }]
-
end
-
-
2
def establish_connection(owner, spec)
-
2
@class_to_pool.clear
-
2
raise RuntimeError, "Anonymous class is not allowed." unless owner.name
-
2
owner_to_pool[owner.name] = ConnectionAdapters::ConnectionPool.new(spec)
-
end
-
-
# Returns true if there are any active connections among the connection
-
# pools that the ConnectionHandler is managing.
-
2
def active_connections?
-
connection_pool_list.any?(&:active_connection?)
-
end
-
-
# Returns any connections in use by the current thread back to the pool,
-
# and also returns connections to the pool cached by threads that are no
-
# longer alive.
-
2
def clear_active_connections!
-
21
connection_pool_list.each(&:release_connection)
-
end
-
-
# Clears the cache which maps classes.
-
2
def clear_reloadable_connections!
-
connection_pool_list.each(&:clear_reloadable_connections!)
-
end
-
-
2
def clear_all_connections!
-
connection_pool_list.each(&:disconnect!)
-
end
-
-
# Locate the connection of the nearest super class. This can be an
-
# active or defined connection: if it is the latter, it will be
-
# opened and set as the active connection for the class it was defined
-
# for (not necessarily the current class).
-
2
def retrieve_connection(klass) #:nodoc:
-
4303
pool = retrieve_connection_pool(klass)
-
4303
(pool && pool.connection) or raise ConnectionNotEstablished
-
end
-
-
# Returns true if a connection that's accessible to this class has
-
# already been opened.
-
2
def connected?(klass)
-
50
conn = retrieve_connection_pool(klass)
-
50
conn && conn.connected?
-
end
-
-
# Remove the connection for this class. This will close the active
-
# connection and the defined connection (if they exist). The result
-
# can be used as an argument for establish_connection, for easily
-
# re-establishing the connection.
-
2
def remove_connection(owner)
-
2
if pool = owner_to_pool.delete(owner.name)
-
@class_to_pool.clear
-
pool.automatic_reconnect = false
-
pool.disconnect!
-
pool.spec.config
-
end
-
end
-
-
# Retrieving the connection pool happens a lot so we cache it in @class_to_pool.
-
# This makes retrieving the connection pool O(1) once the process is warm.
-
# When a connection is established or removed, we invalidate the cache.
-
#
-
# Ideally we would use #fetch here, as class_to_pool[klass] may sometimes be nil.
-
# However, benchmarking (https://gist.github.com/jonleighton/3552829) showed that
-
# #fetch is significantly slower than #[]. So in the nil case, no caching will
-
# take place, but that's ok since the nil case is not the common one that we wish
-
# to optimise for.
-
2
def retrieve_connection_pool(klass)
-
4371
class_to_pool[klass.name] ||= begin
-
14
until pool = pool_for(klass)
-
13
klass = klass.superclass
-
13
break unless klass <= Base
-
end
-
-
14
class_to_pool[klass.name] = pool
-
end
-
end
-
-
2
private
-
-
2
def owner_to_pool
-
85
@owner_to_pool[Process.pid]
-
end
-
-
2
def class_to_pool
-
4385
@class_to_pool[Process.pid]
-
end
-
-
2
def pool_for(owner)
-
27
owner_to_pool.fetch(owner.name) {
-
12
if ancestor_pool = pool_from_any_process_for(owner)
-
# A connection was established in an ancestor process that must have
-
# subsequently forked. We can't reuse the connection, but we can copy
-
# the specification and establish a new connection with it.
-
establish_connection owner, ancestor_pool.spec
-
else
-
12
owner_to_pool[owner.name] = nil
-
end
-
}
-
end
-
-
2
def pool_from_any_process_for(owner)
-
24
owner_to_pool = @owner_to_pool.values.find { |v| v[owner.name] }
-
12
owner_to_pool && owner_to_pool[owner.name]
-
end
-
end
-
-
2
class ConnectionManagement
-
2
def initialize(app)
-
2
@app = app
-
end
-
-
2
def call(env)
-
13
testing = env.key?('rack.test')
-
-
13
response = @app.call(env)
-
13
response[2] = ::Rack::BodyProxy.new(response[2]) do
-
13
ActiveRecord::Base.clear_active_connections! unless testing
-
end
-
-
13
response
-
rescue Exception
-
ActiveRecord::Base.clear_active_connections! unless testing
-
raise
-
end
-
end
-
end
-
end
-
2
module ActiveRecord
-
2
module ConnectionAdapters # :nodoc:
-
2
module DatabaseLimits
-
-
# Returns the maximum length of a table alias.
-
2
def table_alias_length
-
255
-
end
-
-
# Returns the maximum length of a column name.
-
2
def column_name_length
-
64
-
end
-
-
# Returns the maximum length of a table name.
-
2
def table_name_length
-
64
-
end
-
-
# Returns the maximum allowed length for an index name. This
-
# limit is enforced by rails and Is less than or equal to
-
# <tt>index_name_length</tt>. The gap between
-
# <tt>index_name_length</tt> is to allow internal rails
-
# operations to use prefixes in temporary operations.
-
2
def allowed_index_name_length
-
index_name_length
-
end
-
-
# Returns the maximum length of an index name.
-
2
def index_name_length
-
64
-
end
-
-
# Returns the maximum number of columns per table.
-
2
def columns_per_table
-
1024
-
end
-
-
# Returns the maximum number of indexes per table.
-
2
def indexes_per_table
-
16
-
end
-
-
# Returns the maximum number of columns in a multicolumn index.
-
2
def columns_per_multicolumn_index
-
16
-
end
-
-
# Returns the maximum number of elements in an IN (x,y,z) clause.
-
# nil means no limit.
-
2
def in_clause_length
-
nil
-
end
-
-
# Returns the maximum length of an SQL query.
-
2
def sql_query_length
-
1048575
-
end
-
-
# Returns maximum number of joins in a single query.
-
2
def joins_per_query
-
256
-
end
-
-
end
-
end
-
end
-
2
module ActiveRecord
-
2
module ConnectionAdapters # :nodoc:
-
2
module DatabaseStatements
-
2
def initialize
-
2
super
-
2
reset_transaction
-
end
-
-
# Converts an arel AST to SQL
-
2
def to_sql(arel, binds = [])
-
495
if arel.respond_to?(:ast)
-
478
binds = binds.dup
-
478
visitor.accept(arel.ast) do
-
quote(*binds.shift.reverse)
-
end
-
else
-
17
arel
-
end
-
end
-
-
# Returns an ActiveRecord::Result instance.
-
2
def select_all(arel, name = nil, binds = [])
-
211
arel, binds = binds_from_relation arel, binds
-
211
select(to_sql(arel, binds), name, binds)
-
end
-
-
# Returns a record hash with the column names as keys and column values
-
# as values.
-
2
def select_one(arel, name = nil, binds = [])
-
195
select_all(arel, name, binds).first
-
end
-
-
# Returns a single value from a record
-
2
def select_value(arel, name = nil, binds = [])
-
195
if result = select_one(arel, name, binds)
-
result.values.first
-
end
-
end
-
-
# Returns an array of the values of the first column in a select:
-
# select_values("SELECT id FROM companies LIMIT 3") => [1,2,3]
-
2
def select_values(arel, name = nil)
-
arel, binds = binds_from_relation arel, []
-
select_rows(to_sql(arel, binds), name, binds).map(&:first)
-
end
-
-
# Returns an array of arrays containing the field values.
-
# Order is the same as that returned by +columns+.
-
2
def select_rows(sql, name = nil, binds = [])
-
end
-
2
undef_method :select_rows
-
-
# Executes the SQL statement in the context of this connection.
-
2
def execute(sql, name = nil)
-
end
-
2
undef_method :execute
-
-
# Executes +sql+ statement in the context of this connection using
-
# +binds+ as the bind substitutes. +name+ is logged along with
-
# the executed +sql+ statement.
-
2
def exec_query(sql, name = 'SQL', binds = [])
-
end
-
-
# Executes insert +sql+ statement in the context of this connection using
-
# +binds+ as the bind substitutes. +name+ is logged along with
-
# the executed +sql+ statement.
-
2
def exec_insert(sql, name, binds, pk = nil, sequence_name = nil)
-
267
exec_query(sql, name, binds)
-
end
-
-
# Executes delete +sql+ statement in the context of this connection using
-
# +binds+ as the bind substitutes. +name+ is logged along with
-
# the executed +sql+ statement.
-
2
def exec_delete(sql, name, binds)
-
exec_query(sql, name, binds)
-
end
-
-
# Executes update +sql+ statement in the context of this connection using
-
# +binds+ as the bind substitutes. +name+ is logged along with
-
# the executed +sql+ statement.
-
2
def exec_update(sql, name, binds)
-
exec_query(sql, name, binds)
-
end
-
-
# Returns the last auto-generated ID from the affected table.
-
#
-
# +id_value+ will be returned unless the value is nil, in
-
# which case the database will attempt to calculate the last inserted
-
# id and return that value.
-
#
-
# If the next id was calculated in advance (as in Oracle), it should be
-
# passed in as +id_value+.
-
2
def insert(arel, name = nil, pk = nil, id_value = nil, sequence_name = nil, binds = [])
-
267
sql, binds = sql_for_insert(to_sql(arel, binds), pk, id_value, sequence_name, binds)
-
267
value = exec_insert(sql, name, binds, pk, sequence_name)
-
267
id_value || last_inserted_id(value)
-
end
-
-
# Executes the update statement and returns the number of rows affected.
-
2
def update(arel, name = nil, binds = [])
-
exec_update(to_sql(arel, binds), name, binds)
-
end
-
-
# Executes the delete statement and returns the number of rows affected.
-
2
def delete(arel, name = nil, binds = [])
-
exec_delete(to_sql(arel, binds), name, binds)
-
end
-
-
# Returns +true+ when the connection adapter supports prepared statement
-
# caching, otherwise returns +false+
-
2
def supports_statement_cache?
-
false
-
end
-
-
# Runs the given block in a database transaction, and returns the result
-
# of the block.
-
#
-
# == Nested transactions support
-
#
-
# Most databases don't support true nested transactions. At the time of
-
# writing, the only database that supports true nested transactions that
-
# we're aware of, is MS-SQL.
-
#
-
# In order to get around this problem, #transaction will emulate the effect
-
# of nested transactions, by using savepoints:
-
# http://dev.mysql.com/doc/refman/5.0/en/savepoint.html
-
# Savepoints are supported by MySQL and PostgreSQL. SQLite3 version >= '3.6.8'
-
# supports savepoints.
-
#
-
# It is safe to call this method if a database transaction is already open,
-
# i.e. if #transaction is called within another #transaction block. In case
-
# of a nested call, #transaction will behave as follows:
-
#
-
# - The block will be run without doing anything. All database statements
-
# that happen within the block are effectively appended to the already
-
# open database transaction.
-
# - However, if +:requires_new+ is set, the block will be wrapped in a
-
# database savepoint acting as a sub-transaction.
-
#
-
# === Caveats
-
#
-
# MySQL doesn't support DDL transactions. If you perform a DDL operation,
-
# then any created savepoints will be automatically released. For example,
-
# if you've created a savepoint, then you execute a CREATE TABLE statement,
-
# then the savepoint that was created will be automatically released.
-
#
-
# This means that, on MySQL, you shouldn't execute DDL operations inside
-
# a #transaction call that you know might create a savepoint. Otherwise,
-
# #transaction will raise exceptions when it tries to release the
-
# already-automatically-released savepoints:
-
#
-
# Model.connection.transaction do # BEGIN
-
# Model.connection.transaction(requires_new: true) do # CREATE SAVEPOINT active_record_1
-
# Model.connection.create_table(...)
-
# # active_record_1 now automatically released
-
# end # RELEASE SAVEPOINT active_record_1 <--- BOOM! database error!
-
# end
-
#
-
# == Transaction isolation
-
#
-
# If your database supports setting the isolation level for a transaction, you can set
-
# it like so:
-
#
-
# Post.transaction(isolation: :serializable) do
-
# # ...
-
# end
-
#
-
# Valid isolation levels are:
-
#
-
# * <tt>:read_uncommitted</tt>
-
# * <tt>:read_committed</tt>
-
# * <tt>:repeatable_read</tt>
-
# * <tt>:serializable</tt>
-
#
-
# You should consult the documentation for your database to understand the
-
# semantics of these different levels:
-
#
-
# * http://www.postgresql.org/docs/9.1/static/transaction-iso.html
-
# * https://dev.mysql.com/doc/refman/5.0/en/set-transaction.html
-
#
-
# An <tt>ActiveRecord::TransactionIsolationError</tt> will be raised if:
-
#
-
# * The adapter does not support setting the isolation level
-
# * You are joining an existing open transaction
-
# * You are creating a nested (savepoint) transaction
-
#
-
# The mysql, mysql2 and postgresql adapters support setting the transaction
-
# isolation level. However, support is disabled for mysql versions below 5,
-
# because they are affected by a bug[http://bugs.mysql.com/bug.php?id=39170]
-
# which means the isolation level gets persisted outside the transaction.
-
2
def transaction(options = {})
-
347
options.assert_valid_keys :requires_new, :joinable, :isolation
-
-
347
if !options[:requires_new] && current_transaction.joinable?
-
144
if options[:isolation]
-
raise ActiveRecord::TransactionIsolationError, "cannot set isolation when joining a transaction"
-
end
-
-
144
yield
-
else
-
406
within_new_transaction(options) { yield }
-
end
-
rescue ActiveRecord::Rollback
-
# rollbacks are silently swallowed
-
end
-
-
2
def within_new_transaction(options = {}) #:nodoc:
-
203
transaction = begin_transaction(options)
-
203
yield
-
rescue Exception => error
-
2
rollback_transaction if transaction
-
2
raise
-
ensure
-
203
begin
-
203
commit_transaction unless error
-
rescue Exception
-
rollback_transaction
-
raise
-
end
-
end
-
-
2
def current_transaction #:nodoc:
-
347
@transaction
-
end
-
-
2
def transaction_open?
-
21
@transaction.open?
-
end
-
-
2
def begin_transaction(options = {}) #:nodoc:
-
230
@transaction = @transaction.begin(options)
-
end
-
-
2
def commit_transaction #:nodoc:
-
201
@transaction = @transaction.commit
-
end
-
-
2
def rollback_transaction #:nodoc:
-
29
@transaction = @transaction.rollback
-
end
-
-
2
def reset_transaction #:nodoc:
-
2
@transaction = ClosedTransaction.new(self)
-
end
-
-
# Register a record with the current transaction so that its after_commit and after_rollback callbacks
-
# can be called.
-
2
def add_transaction_record(record)
-
269
@transaction.add_record(record)
-
end
-
-
# Begins the transaction (and turns off auto-committing).
-
2
def begin_db_transaction() end
-
-
2
def transaction_isolation_levels
-
{
-
read_uncommitted: "READ UNCOMMITTED",
-
read_committed: "READ COMMITTED",
-
repeatable_read: "REPEATABLE READ",
-
serializable: "SERIALIZABLE"
-
}
-
end
-
-
# Begins the transaction with the isolation level set. Raises an error by
-
# default; adapters that support setting the isolation level should implement
-
# this method.
-
2
def begin_isolated_db_transaction(isolation)
-
raise ActiveRecord::TransactionIsolationError, "adapter does not support setting transaction isolation"
-
end
-
-
# Commits the transaction (and turns on auto-committing).
-
2
def commit_db_transaction() end
-
-
# Rolls back the transaction (and turns on auto-committing). Must be
-
# done if the transaction block raises an exception or returns false.
-
2
def rollback_db_transaction() end
-
-
2
def default_sequence_name(table, column)
-
nil
-
end
-
-
# Set the sequence to the max value of the table's column.
-
2
def reset_sequence!(table, column, sequence = nil)
-
# Do nothing by default. Implement for PostgreSQL, Oracle, ...
-
end
-
-
# Inserts the given fixture into the table. Overridden in adapters that require
-
# something beyond a simple insert (eg. Oracle).
-
2
def insert_fixture(fixture, table_name)
-
columns = schema_cache.columns_hash(table_name)
-
-
key_list = []
-
value_list = fixture.map do |name, value|
-
key_list << quote_column_name(name)
-
quote(value, columns[name])
-
end
-
-
execute "INSERT INTO #{quote_table_name(table_name)} (#{key_list.join(', ')}) VALUES (#{value_list.join(', ')})", 'Fixture Insert'
-
end
-
-
2
def empty_insert_statement_value
-
"DEFAULT VALUES"
-
end
-
-
2
def limited_update_conditions(where_sql, quoted_table_name, quoted_primary_key)
-
"WHERE #{quoted_primary_key} IN (SELECT #{quoted_primary_key} FROM #{quoted_table_name} #{where_sql})"
-
end
-
-
# Sanitizes the given LIMIT parameter in order to prevent SQL injection.
-
#
-
# The +limit+ may be anything that can evaluate to a string via #to_s. It
-
# should look like an integer, or a comma-delimited list of integers, or
-
# an Arel SQL literal.
-
#
-
# Returns Integer and Arel::Nodes::SqlLiteral limits as is.
-
# Returns the sanitized limit parameter, either as an integer, or as a
-
# string which contains a comma-delimited list of integers.
-
2
def sanitize_limit(limit)
-
210
if limit.is_a?(Integer) || limit.is_a?(Arel::Nodes::SqlLiteral)
-
210
limit
-
elsif limit.to_s.include?(',')
-
Arel.sql limit.to_s.split(',').map{ |i| Integer(i) }.join(',')
-
else
-
Integer(limit)
-
end
-
end
-
-
# The default strategy for an UPDATE with joins is to use a subquery. This doesn't work
-
# on mysql (even when aliasing the tables), but mysql allows using JOIN directly in
-
# an UPDATE statement, so in the mysql adapters we redefine this to do that.
-
2
def join_to_update(update, select) #:nodoc:
-
key = update.key
-
subselect = subquery_for(key, select)
-
-
update.where key.in(subselect)
-
end
-
-
2
def join_to_delete(delete, select, key) #:nodoc:
-
subselect = subquery_for(key, select)
-
-
delete.where key.in(subselect)
-
end
-
-
2
protected
-
-
# Returns a subquery for the given key using the join information.
-
2
def subquery_for(key, select)
-
subselect = select.clone
-
subselect.projections = [key]
-
subselect
-
end
-
-
# Returns an ActiveRecord::Result instance.
-
2
def select(sql, name = nil, binds = [])
-
end
-
2
undef_method :select
-
-
# Returns the last auto-generated ID from the affected table.
-
2
def insert_sql(sql, name = nil, pk = nil, id_value = nil, sequence_name = nil)
-
execute(sql, name)
-
id_value
-
end
-
-
# Executes the update statement and returns the number of rows affected.
-
2
def update_sql(sql, name = nil)
-
execute(sql, name)
-
end
-
-
# Executes the delete statement and returns the number of rows affected.
-
2
def delete_sql(sql, name = nil)
-
update_sql(sql, name)
-
end
-
-
2
def sql_for_insert(sql, pk, id_value, sequence_name, binds)
-
267
[sql, binds]
-
end
-
-
2
def last_inserted_id(result)
-
row = result.rows.first
-
row && row.first
-
end
-
-
2
def binds_from_relation(relation, binds)
-
228
if relation.is_a?(Relation) && binds.blank?
-
195
relation, binds = relation.arel, relation.bind_values
-
end
-
228
[relation, binds]
-
end
-
end
-
end
-
end
-
2
module ActiveRecord
-
2
module ConnectionAdapters # :nodoc:
-
2
module QueryCache
-
2
class << self
-
2
def included(base) #:nodoc:
-
2
dirties_query_cache base, :insert, :update, :delete
-
end
-
-
2
def dirties_query_cache(base, *method_names)
-
2
method_names.each do |method_name|
-
6
base.class_eval <<-end_code, __FILE__, __LINE__ + 1
-
def #{method_name}(*)
-
clear_query_cache if @query_cache_enabled
-
super
-
end
-
end_code
-
end
-
end
-
end
-
-
2
attr_reader :query_cache, :query_cache_enabled
-
-
2
def initialize(*)
-
2
super
-
19
@query_cache = Hash.new { |h,sql| h[sql] = {} }
-
2
@query_cache_enabled = false
-
end
-
-
# Enable the query cache within the block.
-
2
def cache
-
old, @query_cache_enabled = @query_cache_enabled, true
-
yield
-
ensure
-
@query_cache_enabled = old
-
clear_query_cache unless @query_cache_enabled
-
end
-
-
2
def enable_query_cache!
-
13
@query_cache_enabled = true
-
end
-
-
2
def disable_query_cache!
-
13
@query_cache_enabled = false
-
end
-
-
# Disable the query cache within the block.
-
2
def uncached
-
old, @query_cache_enabled = @query_cache_enabled, false
-
yield
-
ensure
-
@query_cache_enabled = old
-
end
-
-
# Clears the query cache.
-
#
-
# One reason you may wish to call this method explicitly is between queries
-
# that ask the database to randomize results. Otherwise the cache would see
-
# the same SQL query and repeatedly return the same result each time, silently
-
# undermining the randomness you were expecting.
-
2
def clear_query_cache
-
13
@query_cache.clear
-
end
-
-
2
def select_all(arel, name = nil, binds = [])
-
211
if @query_cache_enabled && !locked?(arel)
-
17
arel, binds = binds_from_relation arel, binds
-
17
sql = to_sql(arel, binds)
-
34
cache_sql(sql, binds) { super(sql, name, binds) }
-
else
-
194
super
-
end
-
end
-
-
2
private
-
-
2
def cache_sql(sql, binds)
-
17
result =
-
if @query_cache[sql].key?(binds)
-
ActiveSupport::Notifications.instrument("sql.active_record",
-
:sql => sql, :binds => binds, :name => "CACHE", :connection_id => object_id)
-
@query_cache[sql][binds]
-
else
-
17
@query_cache[sql][binds] = yield
-
end
-
17
result.dup
-
end
-
-
# If arel is locked this is a SELECT ... FOR UPDATE or somesuch. Such
-
# queries should not be cached.
-
2
def locked?(arel)
-
17
arel.respond_to?(:locked) && arel.locked
-
end
-
end
-
end
-
end
-
2
require 'active_support/core_ext/big_decimal/conversions'
-
-
2
module ActiveRecord
-
2
module ConnectionAdapters # :nodoc:
-
2
module Quoting
-
# Quotes the column value to help prevent
-
# {SQL injection attacks}[http://en.wikipedia.org/wiki/SQL_injection].
-
2
def quote(value, column = nil)
-
# records are quoted as their primary key
-
197
return value.quoted_id if value.respond_to?(:quoted_id)
-
-
197
case value
-
when String, ActiveSupport::Multibyte::Chars
-
197
value = value.to_s
-
197
return "'#{quote_string(value)}'" unless column
-
-
197
case column.type
-
when :integer then value.to_i.to_s
-
when :float then value.to_f.to_s
-
else
-
197
"'#{quote_string(value)}'"
-
end
-
-
when true, false
-
if column && column.type == :integer
-
value ? '1' : '0'
-
else
-
value ? quoted_true : quoted_false
-
end
-
# BigDecimals need to be put in a non-normalized form and quoted.
-
when nil then "NULL"
-
when BigDecimal then value.to_s('F')
-
when Numeric, ActiveSupport::Duration
-
if column.try(:type) == :string
-
quote(value.to_s, column)
-
else
-
value.to_s
-
end
-
when Date, Time then "'#{quoted_date(value)}'"
-
when Symbol then "'#{quote_string(value.to_s)}'"
-
when Class then "'#{value.to_s}'"
-
else
-
"'#{quote_string(YAML.dump(value))}'"
-
end
-
end
-
-
# Cast a +value+ to a type that the database understands. For example,
-
# SQLite does not understand dates, so this method will convert a Date
-
# to a String.
-
2
def type_cast(value, column)
-
1600
if value.respond_to?(:quoted_id) && value.respond_to?(:id)
-
return value.id
-
end
-
-
1600
case value
-
when String, ActiveSupport::Multibyte::Chars
-
990
value = value.to_s
-
990
return value unless column
-
-
990
case column.type
-
when :integer then value.to_i
-
when :float then value.to_f
-
else
-
990
value
-
end
-
-
when true, false
-
if column && column.type == :integer
-
value ? 1 : 0
-
else
-
value ? 't' : 'f'
-
end
-
# BigDecimals need to be put in a non-normalized form and quoted.
-
when nil then nil
-
when BigDecimal then value.to_s('F')
-
76
when Numeric then value
-
534
when Date, Time then quoted_date(value)
-
when Symbol then value.to_s
-
else
-
to_type = column ? " to #{column.type}" : ""
-
raise TypeError, "can't cast #{value.class}#{to_type}"
-
end
-
end
-
-
# Quotes a string, escaping any ' (single quote) and \ (backslash)
-
# characters.
-
2
def quote_string(s)
-
s.gsub(/\\/, '\&\&').gsub(/'/, "''") # ' (for ruby-mode)
-
end
-
-
# Quotes the column name. Defaults to no quoting.
-
2
def quote_column_name(column_name)
-
column_name
-
end
-
-
# Quotes the table name. Defaults to column name quoting.
-
2
def quote_table_name(table_name)
-
35
quote_column_name(table_name)
-
end
-
-
# Override to return the quoted table name for assignment. Defaults to
-
# table quoting.
-
#
-
# This works for mysql and mysql2 where table.column can be used to
-
# resolve ambiguity.
-
#
-
# We override this in the sqlite and postgresql adapters to use only
-
# the column name (as per syntax requirements).
-
2
def quote_table_name_for_assignment(table, attr)
-
quote_table_name("#{table}.#{attr}")
-
end
-
-
2
def quoted_true
-
"'t'"
-
end
-
-
2
def quoted_false
-
"'f'"
-
end
-
-
2
def quoted_date(value)
-
534
if value.acts_like?(:time)
-
534
zone_conversion_method = ActiveRecord::Base.default_timezone == :utc ? :getutc : :getlocal
-
-
534
if value.respond_to?(zone_conversion_method)
-
534
value = value.send(zone_conversion_method)
-
end
-
end
-
-
534
value.to_s(:db)
-
end
-
end
-
end
-
end
-
2
module ActiveRecord
-
2
module ConnectionAdapters
-
2
module Savepoints #:nodoc:
-
2
def supports_savepoints?
-
true
-
end
-
-
2
def create_savepoint(name = current_savepoint_name)
-
197
execute("SAVEPOINT #{name}")
-
end
-
-
2
def rollback_to_savepoint(name = current_savepoint_name)
-
2
execute("ROLLBACK TO SAVEPOINT #{name}")
-
end
-
-
2
def release_savepoint(name = current_savepoint_name)
-
195
execute("RELEASE SAVEPOINT #{name}")
-
end
-
end
-
end
-
end
-
2
module ActiveRecord
-
2
module ConnectionAdapters
-
2
class AbstractAdapter
-
2
class SchemaCreation # :nodoc:
-
2
def initialize(conn)
-
@conn = conn
-
@cache = {}
-
end
-
-
2
def accept(o)
-
m = @cache[o.class] ||= "visit_#{o.class.name.split('::').last}"
-
send m, o
-
end
-
-
2
def visit_AddColumn(o)
-
sql_type = type_to_sql(o.type.to_sym, o.limit, o.precision, o.scale)
-
sql = "ADD #{quote_column_name(o.name)} #{sql_type}"
-
add_column_options!(sql, column_options(o))
-
end
-
-
2
private
-
-
2
def visit_AlterTable(o)
-
sql = "ALTER TABLE #{quote_table_name(o.name)} "
-
sql << o.adds.map { |col| visit_AddColumn col }.join(' ')
-
end
-
-
2
def visit_ColumnDefinition(o)
-
sql_type = type_to_sql(o.type.to_sym, o.limit, o.precision, o.scale)
-
column_sql = "#{quote_column_name(o.name)} #{sql_type}"
-
add_column_options!(column_sql, column_options(o)) unless o.primary_key?
-
column_sql
-
end
-
-
2
def visit_TableDefinition(o)
-
create_sql = "CREATE#{' TEMPORARY' if o.temporary} TABLE "
-
create_sql << "#{quote_table_name(o.name)} "
-
create_sql << "(#{o.columns.map { |c| accept c }.join(', ')}) " unless o.as
-
create_sql << "#{o.options}"
-
create_sql << " AS #{@conn.to_sql(o.as)}" if o.as
-
create_sql
-
end
-
-
2
def column_options(o)
-
column_options = {}
-
column_options[:null] = o.null unless o.null.nil?
-
column_options[:default] = o.default unless o.default.nil?
-
column_options[:column] = o
-
column_options[:first] = o.first
-
column_options[:after] = o.after
-
column_options
-
end
-
-
2
def quote_column_name(name)
-
@conn.quote_column_name name
-
end
-
-
2
def quote_table_name(name)
-
@conn.quote_table_name name
-
end
-
-
2
def type_to_sql(type, limit, precision, scale)
-
@conn.type_to_sql type.to_sym, limit, precision, scale
-
end
-
-
2
def add_column_options!(sql, options)
-
sql << " DEFAULT #{quote_value(options[:default], options[:column])}" if options_include_default?(options)
-
# must explicitly check for :null to allow change_column to work on migrations
-
if options[:null] == false
-
sql << " NOT NULL"
-
end
-
if options[:auto_increment] == true
-
sql << " AUTO_INCREMENT"
-
end
-
sql
-
end
-
-
2
def quote_value(value, column)
-
column.sql_type ||= type_to_sql(column.type, column.limit, column.precision, column.scale)
-
-
@conn.quote(value, column)
-
end
-
-
2
def options_include_default?(options)
-
options.include?(:default) && !(options[:null] == false && options[:default].nil?)
-
end
-
end
-
end
-
end
-
end
-
2
require 'date'
-
2
require 'set'
-
2
require 'bigdecimal'
-
2
require 'bigdecimal/util'
-
-
2
module ActiveRecord
-
2
module ConnectionAdapters #:nodoc:
-
# Abstract representation of an index definition on a table. Instances of
-
# this type are typically created and returned by methods in database
-
# adapters. e.g. ActiveRecord::ConnectionAdapters::AbstractMysqlAdapter#indexes
-
2
class IndexDefinition < Struct.new(:table, :name, :unique, :columns, :lengths, :orders, :where, :type, :using) #:nodoc:
-
end
-
-
# Abstract representation of a column definition. Instances of this type
-
# are typically created by methods in TableDefinition, and added to the
-
# +columns+ attribute of said TableDefinition object, in order to be used
-
# for generating a number of table creation or table changing SQL statements.
-
2
class ColumnDefinition < Struct.new(:name, :type, :limit, :precision, :scale, :default, :null, :first, :after, :primary_key, :sql_type) #:nodoc:
-
-
2
def primary_key?
-
primary_key || type.to_sym == :primary_key
-
end
-
end
-
-
2
class ChangeColumnDefinition < Struct.new(:column, :type, :options) #:nodoc:
-
end
-
-
# Represents the schema of an SQL table in an abstract way. This class
-
# provides methods for manipulating the schema representation.
-
#
-
# Inside migration files, the +t+ object in +create_table+
-
# is actually of this type:
-
#
-
# class SomeMigration < ActiveRecord::Migration
-
# def up
-
# create_table :foo do |t|
-
# puts t.class # => "ActiveRecord::ConnectionAdapters::TableDefinition"
-
# end
-
# end
-
#
-
# def down
-
# ...
-
# end
-
# end
-
#
-
# The table definitions
-
# The Columns are stored as a ColumnDefinition in the +columns+ attribute.
-
2
class TableDefinition
-
# An array of ColumnDefinition objects, representing the column changes
-
# that have been defined.
-
2
attr_accessor :indexes
-
2
attr_reader :name, :temporary, :options, :as
-
-
2
def initialize(types, name, temporary, options, as = nil)
-
@columns_hash = {}
-
@indexes = {}
-
@native = types
-
@temporary = temporary
-
@options = options
-
@as = as
-
@name = name
-
end
-
-
2
def columns; @columns_hash.values; end
-
-
# Appends a primary key definition to the table definition.
-
# Can be called multiple times, but this is probably not a good idea.
-
2
def primary_key(name, type = :primary_key, options = {})
-
column(name, type, options.merge(:primary_key => true))
-
end
-
-
# Returns a ColumnDefinition for the column with name +name+.
-
2
def [](name)
-
@columns_hash[name.to_s]
-
end
-
-
# Instantiates a new column for the table.
-
# The +type+ parameter is normally one of the migrations native types,
-
# which is one of the following:
-
# <tt>:primary_key</tt>, <tt>:string</tt>, <tt>:text</tt>,
-
# <tt>:integer</tt>, <tt>:float</tt>, <tt>:decimal</tt>,
-
# <tt>:datetime</tt>, <tt>:timestamp</tt>, <tt>:time</tt>,
-
# <tt>:date</tt>, <tt>:binary</tt>, <tt>:boolean</tt>.
-
#
-
# You may use a type not in this list as long as it is supported by your
-
# database (for example, "polygon" in MySQL), but this will not be database
-
# agnostic and should usually be avoided.
-
#
-
# Available options are (none of these exists by default):
-
# * <tt>:limit</tt> -
-
# Requests a maximum column length. This is number of characters for <tt>:string</tt> and
-
# <tt>:text</tt> columns and number of bytes for <tt>:binary</tt> and <tt>:integer</tt> columns.
-
# * <tt>:default</tt> -
-
# The column's default value. Use nil for NULL.
-
# * <tt>:null</tt> -
-
# Allows or disallows +NULL+ values in the column. This option could
-
# have been named <tt>:null_allowed</tt>.
-
# * <tt>:precision</tt> -
-
# Specifies the precision for a <tt>:decimal</tt> column.
-
# * <tt>:scale</tt> -
-
# Specifies the scale for a <tt>:decimal</tt> column.
-
#
-
# For clarity's sake: the precision is the number of significant digits,
-
# while the scale is the number of digits that can be stored following
-
# the decimal point. For example, the number 123.45 has a precision of 5
-
# and a scale of 2. A decimal with a precision of 5 and a scale of 2 can
-
# range from -999.99 to 999.99.
-
#
-
# Please be aware of different RDBMS implementations behavior with
-
# <tt>:decimal</tt> columns:
-
# * The SQL standard says the default scale should be 0, <tt>:scale</tt> <=
-
# <tt>:precision</tt>, and makes no comments about the requirements of
-
# <tt>:precision</tt>.
-
# * MySQL: <tt>:precision</tt> [1..63], <tt>:scale</tt> [0..30].
-
# Default is (10,0).
-
# * PostgreSQL: <tt>:precision</tt> [1..infinity],
-
# <tt>:scale</tt> [0..infinity]. No default.
-
# * SQLite2: Any <tt>:precision</tt> and <tt>:scale</tt> may be used.
-
# Internal storage as strings. No default.
-
# * SQLite3: No restrictions on <tt>:precision</tt> and <tt>:scale</tt>,
-
# but the maximum supported <tt>:precision</tt> is 16. No default.
-
# * Oracle: <tt>:precision</tt> [1..38], <tt>:scale</tt> [-84..127].
-
# Default is (38,0).
-
# * DB2: <tt>:precision</tt> [1..63], <tt>:scale</tt> [0..62].
-
# Default unknown.
-
# * Firebird: <tt>:precision</tt> [1..18], <tt>:scale</tt> [0..18].
-
# Default (9,0). Internal types NUMERIC and DECIMAL have different
-
# storage rules, decimal being better.
-
# * FrontBase?: <tt>:precision</tt> [1..38], <tt>:scale</tt> [0..38].
-
# Default (38,0). WARNING Max <tt>:precision</tt>/<tt>:scale</tt> for
-
# NUMERIC is 19, and DECIMAL is 38.
-
# * SqlServer?: <tt>:precision</tt> [1..38], <tt>:scale</tt> [0..38].
-
# Default (38,0).
-
# * Sybase: <tt>:precision</tt> [1..38], <tt>:scale</tt> [0..38].
-
# Default (38,0).
-
# * OpenBase?: Documentation unclear. Claims storage in <tt>double</tt>.
-
#
-
# This method returns <tt>self</tt>.
-
#
-
# == Examples
-
# # Assuming +td+ is an instance of TableDefinition
-
# td.column(:granted, :boolean)
-
# # granted BOOLEAN
-
#
-
# td.column(:picture, :binary, limit: 2.megabytes)
-
# # => picture BLOB(2097152)
-
#
-
# td.column(:sales_stage, :string, limit: 20, default: 'new', null: false)
-
# # => sales_stage VARCHAR(20) DEFAULT 'new' NOT NULL
-
#
-
# td.column(:bill_gates_money, :decimal, precision: 15, scale: 2)
-
# # => bill_gates_money DECIMAL(15,2)
-
#
-
# td.column(:sensor_reading, :decimal, precision: 30, scale: 20)
-
# # => sensor_reading DECIMAL(30,20)
-
#
-
# # While <tt>:scale</tt> defaults to zero on most databases, it
-
# # probably wouldn't hurt to include it.
-
# td.column(:huge_integer, :decimal, precision: 30)
-
# # => huge_integer DECIMAL(30)
-
#
-
# # Defines a column with a database-specific type.
-
# td.column(:foo, 'polygon')
-
# # => foo polygon
-
#
-
# == Short-hand examples
-
#
-
# Instead of calling +column+ directly, you can also work with the short-hand definitions for the default types.
-
# They use the type as the method name instead of as a parameter and allow for multiple columns to be defined
-
# in a single statement.
-
#
-
# What can be written like this with the regular calls to column:
-
#
-
# create_table :products do |t|
-
# t.column :shop_id, :integer
-
# t.column :creator_id, :integer
-
# t.column :name, :string, default: "Untitled"
-
# t.column :value, :string, default: "Untitled"
-
# t.column :created_at, :datetime
-
# t.column :updated_at, :datetime
-
# end
-
#
-
# can also be written as follows using the short-hand:
-
#
-
# create_table :products do |t|
-
# t.integer :shop_id, :creator_id
-
# t.string :name, :value, default: "Untitled"
-
# t.timestamps
-
# end
-
#
-
# There's a short-hand method for each of the type values declared at the top. And then there's
-
# TableDefinition#timestamps that'll add +created_at+ and +updated_at+ as datetimes.
-
#
-
# TableDefinition#references will add an appropriately-named _id column, plus a corresponding _type
-
# column if the <tt>:polymorphic</tt> option is supplied. If <tt>:polymorphic</tt> is a hash of
-
# options, these will be used when creating the <tt>_type</tt> column. The <tt>:index</tt> option
-
# will also create an index, similar to calling <tt>add_index</tt>. So what can be written like this:
-
#
-
# create_table :taggings do |t|
-
# t.integer :tag_id, :tagger_id, :taggable_id
-
# t.string :tagger_type
-
# t.string :taggable_type, default: 'Photo'
-
# end
-
# add_index :taggings, :tag_id, name: 'index_taggings_on_tag_id'
-
# add_index :taggings, [:tagger_id, :tagger_type]
-
#
-
# Can also be written as follows using references:
-
#
-
# create_table :taggings do |t|
-
# t.references :tag, index: { name: 'index_taggings_on_tag_id' }
-
# t.references :tagger, polymorphic: true, index: true
-
# t.references :taggable, polymorphic: { default: 'Photo' }
-
# end
-
2
def column(name, type, options = {})
-
name = name.to_s
-
type = type.to_sym
-
-
if primary_key_column_name == name
-
raise ArgumentError, "you can't redefine the primary key column '#{name}'. To define a custom primary key, pass { id: false } to create_table."
-
end
-
-
@columns_hash[name] = new_column_definition(name, type, options)
-
self
-
end
-
-
2
def remove_column(name)
-
@columns_hash.delete name.to_s
-
end
-
-
2
[:string, :text, :integer, :float, :decimal, :datetime, :timestamp, :time, :date, :binary, :boolean].each do |column_type|
-
22
define_method column_type do |*args|
-
options = args.extract_options!
-
column_names = args
-
column_names.each { |name| column(name, column_type, options) }
-
end
-
end
-
-
# Adds index options to the indexes hash, keyed by column name
-
# This is primarily used to track indexes that need to be created after the table
-
#
-
# index(:account_id, name: 'index_projects_on_account_id')
-
2
def index(column_name, options = {})
-
indexes[column_name] = options
-
end
-
-
# Appends <tt>:datetime</tt> columns <tt>:created_at</tt> and
-
# <tt>:updated_at</tt> to the table.
-
2
def timestamps(*args)
-
options = args.extract_options!
-
column(:created_at, :datetime, options)
-
column(:updated_at, :datetime, options)
-
end
-
-
2
def references(*args)
-
options = args.extract_options!
-
polymorphic = options.delete(:polymorphic)
-
index_options = options.delete(:index)
-
args.each do |col|
-
column("#{col}_id", :integer, options)
-
column("#{col}_type", :string, polymorphic.is_a?(Hash) ? polymorphic : options) if polymorphic
-
index(polymorphic ? %w(id type).map { |t| "#{col}_#{t}" } : "#{col}_id", index_options.is_a?(Hash) ? index_options : {}) if index_options
-
end
-
end
-
2
alias :belongs_to :references
-
-
2
def new_column_definition(name, type, options) # :nodoc:
-
column = create_column_definition name, type
-
limit = options.fetch(:limit) do
-
native[type][:limit] if native[type].is_a?(Hash)
-
end
-
-
column.limit = limit
-
column.array = options[:array] if column.respond_to?(:array)
-
column.precision = options[:precision]
-
column.scale = options[:scale]
-
column.default = options[:default]
-
column.null = options[:null]
-
column.first = options[:first]
-
column.after = options[:after]
-
column.primary_key = type == :primary_key || options[:primary_key]
-
column
-
end
-
-
2
private
-
2
def create_column_definition(name, type)
-
ColumnDefinition.new name, type
-
end
-
-
2
def primary_key_column_name
-
primary_key_column = columns.detect { |c| c.primary_key? }
-
primary_key_column && primary_key_column.name
-
end
-
-
2
def native
-
@native
-
end
-
end
-
-
2
class AlterTable # :nodoc:
-
2
attr_reader :adds
-
-
2
def initialize(td)
-
@td = td
-
@adds = []
-
end
-
-
2
def name; @td.name; end
-
-
2
def add_column(name, type, options)
-
name = name.to_s
-
type = type.to_sym
-
@adds << @td.new_column_definition(name, type, options)
-
end
-
end
-
-
# Represents an SQL table in an abstract way for updating a table.
-
# Also see TableDefinition and SchemaStatements#create_table
-
#
-
# Available transformations are:
-
#
-
# change_table :table do |t|
-
# t.column
-
# t.index
-
# t.rename_index
-
# t.timestamps
-
# t.change
-
# t.change_default
-
# t.rename
-
# t.references
-
# t.belongs_to
-
# t.string
-
# t.text
-
# t.integer
-
# t.float
-
# t.decimal
-
# t.datetime
-
# t.timestamp
-
# t.time
-
# t.date
-
# t.binary
-
# t.boolean
-
# t.remove
-
# t.remove_references
-
# t.remove_belongs_to
-
# t.remove_index
-
# t.remove_timestamps
-
# end
-
#
-
2
class Table
-
2
def initialize(table_name, base)
-
@table_name = table_name
-
@base = base
-
end
-
-
# Adds a new column to the named table.
-
# See TableDefinition#column for details of the options you can use.
-
#
-
# ====== Creating a simple column
-
# t.column(:name, :string)
-
2
def column(column_name, type, options = {})
-
@base.add_column(@table_name, column_name, type, options)
-
end
-
-
# Checks to see if a column exists. See SchemaStatements#column_exists?
-
2
def column_exists?(column_name, type = nil, options = {})
-
@base.column_exists?(@table_name, column_name, type, options)
-
end
-
-
# Adds a new index to the table. +column_name+ can be a single Symbol, or
-
# an Array of Symbols. See SchemaStatements#add_index
-
#
-
# ====== Creating a simple index
-
# t.index(:name)
-
# ====== Creating a unique index
-
# t.index([:branch_id, :party_id], unique: true)
-
# ====== Creating a named index
-
# t.index([:branch_id, :party_id], unique: true, name: 'by_branch_party')
-
2
def index(column_name, options = {})
-
@base.add_index(@table_name, column_name, options)
-
end
-
-
# Checks to see if an index exists. See SchemaStatements#index_exists?
-
2
def index_exists?(column_name, options = {})
-
@base.index_exists?(@table_name, column_name, options)
-
end
-
-
# Renames the given index on the table.
-
#
-
# t.rename_index(:user_id, :account_id)
-
2
def rename_index(index_name, new_index_name)
-
@base.rename_index(@table_name, index_name, new_index_name)
-
end
-
-
# Adds timestamps (+created_at+ and +updated_at+) columns to the table. See SchemaStatements#add_timestamps
-
#
-
# t.timestamps
-
2
def timestamps
-
@base.add_timestamps(@table_name)
-
end
-
-
# Changes the column's definition according to the new options.
-
# See TableDefinition#column for details of the options you can use.
-
#
-
# t.change(:name, :string, limit: 80)
-
# t.change(:description, :text)
-
2
def change(column_name, type, options = {})
-
@base.change_column(@table_name, column_name, type, options)
-
end
-
-
# Sets a new default value for a column. See SchemaStatements#change_column_default
-
#
-
# t.change_default(:qualification, 'new')
-
# t.change_default(:authorized, 1)
-
2
def change_default(column_name, default)
-
@base.change_column_default(@table_name, column_name, default)
-
end
-
-
# Removes the column(s) from the table definition.
-
#
-
# t.remove(:qualification)
-
# t.remove(:qualification, :experience)
-
2
def remove(*column_names)
-
@base.remove_columns(@table_name, *column_names)
-
end
-
-
# Removes the given index from the table.
-
#
-
# ====== Remove the index_table_name_on_column in the table_name table
-
# t.remove_index :column
-
# ====== Remove the index named index_table_name_on_branch_id in the table_name table
-
# t.remove_index column: :branch_id
-
# ====== Remove the index named index_table_name_on_branch_id_and_party_id in the table_name table
-
# t.remove_index column: [:branch_id, :party_id]
-
# ====== Remove the index named by_branch_party in the table_name table
-
# t.remove_index name: :by_branch_party
-
2
def remove_index(options = {})
-
@base.remove_index(@table_name, options)
-
end
-
-
# Removes the timestamp columns (+created_at+ and +updated_at+) from the table.
-
#
-
# t.remove_timestamps
-
2
def remove_timestamps
-
@base.remove_timestamps(@table_name)
-
end
-
-
# Renames a column.
-
#
-
# t.rename(:description, :name)
-
2
def rename(column_name, new_column_name)
-
@base.rename_column(@table_name, column_name, new_column_name)
-
end
-
-
# Adds a reference. Optionally adds a +type+ column, if <tt>:polymorphic</tt> option is provided.
-
# <tt>references</tt> and <tt>belongs_to</tt> are acceptable.
-
#
-
# t.references(:user)
-
# t.belongs_to(:supplier, polymorphic: true)
-
#
-
2
def references(*args)
-
options = args.extract_options!
-
args.each do |ref_name|
-
@base.add_reference(@table_name, ref_name, options)
-
end
-
end
-
2
alias :belongs_to :references
-
-
# Removes a reference. Optionally removes a +type+ column.
-
# <tt>remove_references</tt> and <tt>remove_belongs_to</tt> are acceptable.
-
#
-
# t.remove_references(:user)
-
# t.remove_belongs_to(:supplier, polymorphic: true)
-
#
-
2
def remove_references(*args)
-
options = args.extract_options!
-
args.each do |ref_name|
-
@base.remove_reference(@table_name, ref_name, options)
-
end
-
end
-
2
alias :remove_belongs_to :remove_references
-
-
# Adds a column or columns of a specified type
-
#
-
# t.string(:goat)
-
# t.string(:goat, :sheep)
-
2
[:string, :text, :integer, :float, :decimal, :datetime, :timestamp, :time, :date, :binary, :boolean].each do |column_type|
-
22
define_method column_type do |*args|
-
options = args.extract_options!
-
args.each do |name|
-
@base.add_column(@table_name, name, column_type, options)
-
end
-
end
-
end
-
-
2
private
-
2
def native
-
@base.native_database_types
-
end
-
end
-
-
end
-
end
-
2
require 'ipaddr'
-
-
2
module ActiveRecord
-
2
module ConnectionAdapters # :nodoc:
-
# The goal of this module is to move Adapter specific column
-
# definitions to the Adapter instead of having it in the schema
-
# dumper itself. This code represents the normal case.
-
# We can then redefine how certain data types may be handled in the schema dumper on the
-
# Adapter level by over-writing this code inside the database specific adapters
-
2
module ColumnDumper
-
2
def column_spec(column, types)
-
spec = prepare_column_options(column, types)
-
(spec.keys - [:name, :type]).each{ |k| spec[k].insert(0, "#{k.to_s}: ")}
-
spec
-
end
-
-
# This can be overridden on a Adapter level basis to support other
-
# extended datatypes (Example: Adding an array option in the
-
# PostgreSQLAdapter)
-
2
def prepare_column_options(column, types)
-
spec = {}
-
spec[:name] = column.name.inspect
-
-
# AR has an optimization which handles zero-scale decimals as integers. This
-
# code ensures that the dumper still dumps the column as a decimal.
-
spec[:type] = if column.type == :integer && /^(numeric|decimal)/ =~ column.sql_type
-
'decimal'
-
else
-
column.type.to_s
-
end
-
spec[:limit] = column.limit.inspect if column.limit != types[column.type][:limit] && spec[:type] != 'decimal'
-
spec[:precision] = column.precision.inspect if column.precision
-
spec[:scale] = column.scale.inspect if column.scale
-
spec[:null] = 'false' unless column.null
-
spec[:default] = default_string(column.default) if column.has_default?
-
spec
-
end
-
-
# Lists the valid migration options
-
2
def migration_keys
-
[:name, :limit, :precision, :scale, :default, :null]
-
end
-
-
2
private
-
-
2
def default_string(value)
-
case value
-
when BigDecimal
-
value.to_s
-
when Date, DateTime, Time
-
"'#{value.to_s(:db)}'"
-
when Range
-
# infinity dumps as Infinity, which causes uninitialized constant error
-
value.inspect.gsub('Infinity', '::Float::INFINITY')
-
when IPAddr
-
subnet_mask = value.instance_variable_get(:@mask_addr)
-
-
# If the subnet mask is equal to /32, don't output it
-
if subnet_mask == (2**32 - 1)
-
"\"#{value.to_s}\""
-
else
-
"\"#{value.to_s}/#{subnet_mask.to_s(2).count('1')}\""
-
end
-
else
-
value.inspect
-
end
-
end
-
end
-
end
-
end
-
2
require 'active_record/migration/join_table'
-
-
2
module ActiveRecord
-
2
module ConnectionAdapters # :nodoc:
-
2
module SchemaStatements
-
2
include ActiveRecord::Migration::JoinTable
-
-
# Returns a hash of mappings from the abstract data types to the native
-
# database types. See TableDefinition#column for details on the recognized
-
# abstract data types.
-
2
def native_database_types
-
{}
-
end
-
-
# Truncates a table alias according to the limits of the current adapter.
-
2
def table_alias_for(table_name)
-
table_name[0...table_alias_length].tr('.', '_')
-
end
-
-
# Checks to see if the table +table_name+ exists on the database.
-
#
-
# table_exists?(:developers)
-
#
-
2
def table_exists?(table_name)
-
tables.include?(table_name.to_s)
-
end
-
-
# Returns an array of indexes for the given table.
-
# def indexes(table_name, name = nil) end
-
-
# Checks to see if an index exists on a table for a given index definition.
-
#
-
# # Check an index exists
-
# index_exists?(:suppliers, :company_id)
-
#
-
# # Check an index on multiple columns exists
-
# index_exists?(:suppliers, [:company_id, :company_type])
-
#
-
# # Check a unique index exists
-
# index_exists?(:suppliers, :company_id, unique: true)
-
#
-
# # Check an index with a custom name exists
-
# index_exists?(:suppliers, :company_id, name: "idx_company_id")
-
#
-
2
def index_exists?(table_name, column_name, options = {})
-
column_names = Array(column_name)
-
index_name = options.key?(:name) ? options[:name].to_s : index_name(table_name, :column => column_names)
-
if options[:unique]
-
indexes(table_name).any?{ |i| i.unique && i.name == index_name }
-
else
-
indexes(table_name).any?{ |i| i.name == index_name }
-
end
-
end
-
-
# Returns an array of Column objects for the table specified by +table_name+.
-
# See the concrete implementation for details on the expected parameter values.
-
2
def columns(table_name) end
-
-
# Checks to see if a column exists in a given table.
-
#
-
# # Check a column exists
-
# column_exists?(:suppliers, :name)
-
#
-
# # Check a column exists of a particular type
-
# column_exists?(:suppliers, :name, :string)
-
#
-
# # Check a column exists with a specific definition
-
# column_exists?(:suppliers, :name, :string, limit: 100)
-
# column_exists?(:suppliers, :name, :string, default: 'default')
-
# column_exists?(:suppliers, :name, :string, null: false)
-
# column_exists?(:suppliers, :tax, :decimal, precision: 8, scale: 2)
-
#
-
2
def column_exists?(table_name, column_name, type = nil, options = {})
-
columns(table_name).any?{ |c| c.name == column_name.to_s &&
-
(!type || c.type == type) &&
-
(!options.key?(:limit) || c.limit == options[:limit]) &&
-
(!options.key?(:precision) || c.precision == options[:precision]) &&
-
(!options.key?(:scale) || c.scale == options[:scale]) &&
-
(!options.key?(:default) || c.default == options[:default]) &&
-
(!options.key?(:null) || c.null == options[:null]) }
-
end
-
-
# Creates a new table with the name +table_name+. +table_name+ may either
-
# be a String or a Symbol.
-
#
-
# There are two ways to work with +create_table+. You can use the block
-
# form or the regular form, like this:
-
#
-
# === Block form
-
#
-
# # create_table() passes a TableDefinition object to the block.
-
# # This form will not only create the table, but also columns for the
-
# # table.
-
#
-
# create_table(:suppliers) do |t|
-
# t.column :name, :string, limit: 60
-
# # Other fields here
-
# end
-
#
-
# === Block form, with shorthand
-
#
-
# # You can also use the column types as method calls, rather than calling the column method.
-
# create_table(:suppliers) do |t|
-
# t.string :name, limit: 60
-
# # Other fields here
-
# end
-
#
-
# === Regular form
-
#
-
# # Creates a table called 'suppliers' with no columns.
-
# create_table(:suppliers)
-
# # Add a column to 'suppliers'.
-
# add_column(:suppliers, :name, :string, {limit: 60})
-
#
-
# The +options+ hash can include the following keys:
-
# [<tt>:id</tt>]
-
# Whether to automatically add a primary key column. Defaults to true.
-
# Join tables for +has_and_belongs_to_many+ should set it to false.
-
# [<tt>:primary_key</tt>]
-
# The name of the primary key, if one is to be added automatically.
-
# Defaults to +id+. If <tt>:id</tt> is false this option is ignored.
-
#
-
# Note that Active Record models will automatically detect their
-
# primary key. This can be avoided by using +self.primary_key=+ on the model
-
# to define the key explicitly.
-
#
-
# [<tt>:options</tt>]
-
# Any extra options you want appended to the table definition.
-
# [<tt>:temporary</tt>]
-
# Make a temporary table.
-
# [<tt>:force</tt>]
-
# Set to true to drop the table before creating it.
-
# Defaults to false.
-
# [<tt>:as</tt>]
-
# SQL to use to generate the table. When this option is used, the block is
-
# ignored, as are the <tt>:id</tt> and <tt>:primary_key</tt> options.
-
#
-
# ====== Add a backend specific option to the generated SQL (MySQL)
-
#
-
# create_table(:suppliers, options: 'ENGINE=InnoDB DEFAULT CHARSET=utf8')
-
#
-
# generates:
-
#
-
# CREATE TABLE suppliers (
-
# id int(11) DEFAULT NULL auto_increment PRIMARY KEY
-
# ) ENGINE=InnoDB DEFAULT CHARSET=utf8
-
#
-
# ====== Rename the primary key column
-
#
-
# create_table(:objects, primary_key: 'guid') do |t|
-
# t.column :name, :string, limit: 80
-
# end
-
#
-
# generates:
-
#
-
# CREATE TABLE objects (
-
# guid int(11) DEFAULT NULL auto_increment PRIMARY KEY,
-
# name varchar(80)
-
# )
-
#
-
# ====== Do not add a primary key column
-
#
-
# create_table(:categories_suppliers, id: false) do |t|
-
# t.column :category_id, :integer
-
# t.column :supplier_id, :integer
-
# end
-
#
-
# generates:
-
#
-
# CREATE TABLE categories_suppliers (
-
# category_id int,
-
# supplier_id int
-
# )
-
#
-
# ====== Create a temporary table based on a query
-
#
-
# create_table(:long_query, temporary: true,
-
# as: "SELECT * FROM orders INNER JOIN line_items ON order_id=orders.id")
-
#
-
# generates:
-
#
-
# CREATE TEMPORARY TABLE long_query AS
-
# SELECT * FROM orders INNER JOIN line_items ON order_id=orders.id
-
#
-
# See also TableDefinition#column for details on how to create columns.
-
2
def create_table(table_name, options = {})
-
td = create_table_definition table_name, options[:temporary], options[:options], options[:as]
-
-
if !options[:as]
-
unless options[:id] == false
-
pk = options.fetch(:primary_key) {
-
Base.get_primary_key table_name.to_s.singularize
-
}
-
-
td.primary_key pk, options.fetch(:id, :primary_key), options
-
end
-
-
yield td if block_given?
-
end
-
-
if options[:force] && table_exists?(table_name)
-
drop_table(table_name, options)
-
end
-
-
execute schema_creation.accept td
-
td.indexes.each_pair { |c,o| add_index table_name, c, o }
-
end
-
-
# Creates a new join table with the name created using the lexical order of the first two
-
# arguments. These arguments can be a String or a Symbol.
-
#
-
# # Creates a table called 'assemblies_parts' with no id.
-
# create_join_table(:assemblies, :parts)
-
#
-
# You can pass a +options+ hash can include the following keys:
-
# [<tt>:table_name</tt>]
-
# Sets the table name overriding the default
-
# [<tt>:column_options</tt>]
-
# Any extra options you want appended to the columns definition.
-
# [<tt>:options</tt>]
-
# Any extra options you want appended to the table definition.
-
# [<tt>:temporary</tt>]
-
# Make a temporary table.
-
# [<tt>:force</tt>]
-
# Set to true to drop the table before creating it.
-
# Defaults to false.
-
#
-
# Note that +create_join_table+ does not create any indices by default; you can use
-
# its block form to do so yourself:
-
#
-
# create_join_table :products, :categories do |t|
-
# t.index :product_id
-
# t.index :category_id
-
# end
-
#
-
# ====== Add a backend specific option to the generated SQL (MySQL)
-
#
-
# create_join_table(:assemblies, :parts, options: 'ENGINE=InnoDB DEFAULT CHARSET=utf8')
-
#
-
# generates:
-
#
-
# CREATE TABLE assemblies_parts (
-
# assembly_id int NOT NULL,
-
# part_id int NOT NULL,
-
# ) ENGINE=InnoDB DEFAULT CHARSET=utf8
-
#
-
2
def create_join_table(table_1, table_2, options = {})
-
join_table_name = find_join_table_name(table_1, table_2, options)
-
-
column_options = options.delete(:column_options) || {}
-
column_options.reverse_merge!(null: false)
-
-
t1_column, t2_column = [table_1, table_2].map{ |t| t.to_s.singularize.foreign_key }
-
-
create_table(join_table_name, options.merge!(id: false)) do |td|
-
td.integer t1_column, column_options
-
td.integer t2_column, column_options
-
yield td if block_given?
-
end
-
end
-
-
# Drops the join table specified by the given arguments.
-
# See +create_join_table+ for details.
-
#
-
# Although this command ignores the block if one is given, it can be helpful
-
# to provide one in a migration's +change+ method so it can be reverted.
-
# In that case, the block will be used by create_join_table.
-
2
def drop_join_table(table_1, table_2, options = {})
-
join_table_name = find_join_table_name(table_1, table_2, options)
-
drop_table(join_table_name)
-
end
-
-
# A block for changing columns in +table+.
-
#
-
# # change_table() yields a Table instance
-
# change_table(:suppliers) do |t|
-
# t.column :name, :string, limit: 60
-
# # Other column alterations here
-
# end
-
#
-
# The +options+ hash can include the following keys:
-
# [<tt>:bulk</tt>]
-
# Set this to true to make this a bulk alter query, such as
-
#
-
# ALTER TABLE `users` ADD COLUMN age INT(11), ADD COLUMN birthdate DATETIME ...
-
#
-
# Defaults to false.
-
#
-
# ====== Add a column
-
#
-
# change_table(:suppliers) do |t|
-
# t.column :name, :string, limit: 60
-
# end
-
#
-
# ====== Add 2 integer columns
-
#
-
# change_table(:suppliers) do |t|
-
# t.integer :width, :height, null: false, default: 0
-
# end
-
#
-
# ====== Add created_at/updated_at columns
-
#
-
# change_table(:suppliers) do |t|
-
# t.timestamps
-
# end
-
#
-
# ====== Add a foreign key column
-
#
-
# change_table(:suppliers) do |t|
-
# t.references :company
-
# end
-
#
-
# Creates a <tt>company_id(integer)</tt> column.
-
#
-
# ====== Add a polymorphic foreign key column
-
#
-
# change_table(:suppliers) do |t|
-
# t.belongs_to :company, polymorphic: true
-
# end
-
#
-
# Creates <tt>company_type(varchar)</tt> and <tt>company_id(integer)</tt> columns.
-
#
-
# ====== Remove a column
-
#
-
# change_table(:suppliers) do |t|
-
# t.remove :company
-
# end
-
#
-
# ====== Remove several columns
-
#
-
# change_table(:suppliers) do |t|
-
# t.remove :company_id
-
# t.remove :width, :height
-
# end
-
#
-
# ====== Remove an index
-
#
-
# change_table(:suppliers) do |t|
-
# t.remove_index :company_id
-
# end
-
#
-
# See also Table for details on all of the various column transformation.
-
2
def change_table(table_name, options = {})
-
if supports_bulk_alter? && options[:bulk]
-
recorder = ActiveRecord::Migration::CommandRecorder.new(self)
-
yield update_table_definition(table_name, recorder)
-
bulk_change_table(table_name, recorder.commands)
-
else
-
yield update_table_definition(table_name, self)
-
end
-
end
-
-
# Renames a table.
-
#
-
# rename_table('octopuses', 'octopi')
-
#
-
2
def rename_table(table_name, new_name)
-
raise NotImplementedError, "rename_table is not implemented"
-
end
-
-
# Drops a table from the database.
-
#
-
# Although this command ignores +options+ and the block if one is given, it can be helpful
-
# to provide these in a migration's +change+ method so it can be reverted.
-
# In that case, +options+ and the block will be used by create_table.
-
2
def drop_table(table_name, options = {})
-
execute "DROP TABLE #{quote_table_name(table_name)}"
-
end
-
-
# Adds a new column to the named table.
-
# See TableDefinition#column for details of the options you can use.
-
2
def add_column(table_name, column_name, type, options = {})
-
at = create_alter_table table_name
-
at.add_column(column_name, type, options)
-
execute schema_creation.accept at
-
end
-
-
# Removes the given columns from the table definition.
-
#
-
# remove_columns(:suppliers, :qualification, :experience)
-
#
-
2
def remove_columns(table_name, *column_names)
-
raise ArgumentError.new("You must specify at least one column name. Example: remove_columns(:people, :first_name)") if column_names.empty?
-
column_names.each do |column_name|
-
remove_column(table_name, column_name)
-
end
-
end
-
-
# Removes the column from the table definition.
-
#
-
# remove_column(:suppliers, :qualification)
-
#
-
# The +type+ and +options+ parameters will be ignored if present. It can be helpful
-
# to provide these in a migration's +change+ method so it can be reverted.
-
# In that case, +type+ and +options+ will be used by add_column.
-
2
def remove_column(table_name, column_name, type = nil, options = {})
-
execute "ALTER TABLE #{quote_table_name(table_name)} DROP #{quote_column_name(column_name)}"
-
end
-
-
# Changes the column's definition according to the new options.
-
# See TableDefinition#column for details of the options you can use.
-
#
-
# change_column(:suppliers, :name, :string, limit: 80)
-
# change_column(:accounts, :description, :text)
-
#
-
2
def change_column(table_name, column_name, type, options = {})
-
raise NotImplementedError, "change_column is not implemented"
-
end
-
-
# Sets a new default value for a column:
-
#
-
# change_column_default(:suppliers, :qualification, 'new')
-
# change_column_default(:accounts, :authorized, 1)
-
#
-
# Setting the default to +nil+ effectively drops the default:
-
#
-
# change_column_default(:users, :email, nil)
-
#
-
2
def change_column_default(table_name, column_name, default)
-
raise NotImplementedError, "change_column_default is not implemented"
-
end
-
-
# Sets or removes a +NOT NULL+ constraint on a column. The +null+ flag
-
# indicates whether the value can be +NULL+. For example
-
#
-
# change_column_null(:users, :nickname, false)
-
#
-
# says nicknames cannot be +NULL+ (adds the constraint), whereas
-
#
-
# change_column_null(:users, :nickname, true)
-
#
-
# allows them to be +NULL+ (drops the constraint).
-
#
-
# The method accepts an optional fourth argument to replace existing
-
# +NULL+s with some other value. Use that one when enabling the
-
# constraint if needed, since otherwise those rows would not be valid.
-
#
-
# Please note the fourth argument does not set a column's default.
-
2
def change_column_null(table_name, column_name, null, default = nil)
-
raise NotImplementedError, "change_column_null is not implemented"
-
end
-
-
# Renames a column.
-
#
-
# rename_column(:suppliers, :description, :name)
-
#
-
2
def rename_column(table_name, column_name, new_column_name)
-
raise NotImplementedError, "rename_column is not implemented"
-
end
-
-
# Adds a new index to the table. +column_name+ can be a single Symbol, or
-
# an Array of Symbols.
-
#
-
# The index will be named after the table and the column name(s), unless
-
# you pass <tt>:name</tt> as an option.
-
#
-
# ====== Creating a simple index
-
#
-
# add_index(:suppliers, :name)
-
#
-
# generates:
-
#
-
# CREATE INDEX suppliers_name_index ON suppliers(name)
-
#
-
# ====== Creating a unique index
-
#
-
# add_index(:accounts, [:branch_id, :party_id], unique: true)
-
#
-
# generates:
-
#
-
# CREATE UNIQUE INDEX accounts_branch_id_party_id_index ON accounts(branch_id, party_id)
-
#
-
# ====== Creating a named index
-
#
-
# add_index(:accounts, [:branch_id, :party_id], unique: true, name: 'by_branch_party')
-
#
-
# generates:
-
#
-
# CREATE UNIQUE INDEX by_branch_party ON accounts(branch_id, party_id)
-
#
-
# ====== Creating an index with specific key length
-
#
-
# add_index(:accounts, :name, name: 'by_name', length: 10)
-
#
-
# generates:
-
#
-
# CREATE INDEX by_name ON accounts(name(10))
-
#
-
# add_index(:accounts, [:name, :surname], name: 'by_name_surname', length: {name: 10, surname: 15})
-
#
-
# generates:
-
#
-
# CREATE INDEX by_name_surname ON accounts(name(10), surname(15))
-
#
-
# Note: SQLite doesn't support index length.
-
#
-
# ====== Creating an index with a sort order (desc or asc, asc is the default)
-
#
-
# add_index(:accounts, [:branch_id, :party_id, :surname], order: {branch_id: :desc, party_id: :asc})
-
#
-
# generates:
-
#
-
# CREATE INDEX by_branch_desc_party ON accounts(branch_id DESC, party_id ASC, surname)
-
#
-
# Note: MySQL doesn't yet support index order (it accepts the syntax but ignores it).
-
#
-
# ====== Creating a partial index
-
#
-
# add_index(:accounts, [:branch_id, :party_id], unique: true, where: "active")
-
#
-
# generates:
-
#
-
# CREATE UNIQUE INDEX index_accounts_on_branch_id_and_party_id ON accounts(branch_id, party_id) WHERE active
-
#
-
# ====== Creating an index with a specific method
-
#
-
# add_index(:developers, :name, using: 'btree')
-
#
-
# generates:
-
#
-
# CREATE INDEX index_developers_on_name ON developers USING btree (name) -- PostgreSQL
-
# CREATE INDEX index_developers_on_name USING btree ON developers (name) -- MySQL
-
#
-
# Note: only supported by PostgreSQL and MySQL
-
#
-
# ====== Creating an index with a specific type
-
#
-
# add_index(:developers, :name, type: :fulltext)
-
#
-
# generates:
-
#
-
# CREATE FULLTEXT INDEX index_developers_on_name ON developers (name) -- MySQL
-
#
-
# Note: only supported by MySQL. Supported: <tt>:fulltext</tt> and <tt>:spatial</tt> on MyISAM tables.
-
2
def add_index(table_name, column_name, options = {})
-
index_name, index_type, index_columns, index_options = add_index_options(table_name, column_name, options)
-
execute "CREATE #{index_type} INDEX #{quote_column_name(index_name)} ON #{quote_table_name(table_name)} (#{index_columns})#{index_options}"
-
end
-
-
# Removes the given index from the table.
-
#
-
# Removes the +index_accounts_on_column+ in the +accounts+ table.
-
#
-
# remove_index :accounts, :column
-
#
-
# Removes the index named +index_accounts_on_branch_id+ in the +accounts+ table.
-
#
-
# remove_index :accounts, column: :branch_id
-
#
-
# Removes the index named +index_accounts_on_branch_id_and_party_id+ in the +accounts+ table.
-
#
-
# remove_index :accounts, column: [:branch_id, :party_id]
-
#
-
# Removes the index named +by_branch_party+ in the +accounts+ table.
-
#
-
# remove_index :accounts, name: :by_branch_party
-
#
-
2
def remove_index(table_name, options = {})
-
remove_index!(table_name, index_name_for_remove(table_name, options))
-
end
-
-
2
def remove_index!(table_name, index_name) #:nodoc:
-
execute "DROP INDEX #{quote_column_name(index_name)} ON #{quote_table_name(table_name)}"
-
end
-
-
# Renames an index.
-
#
-
# Rename the +index_people_on_last_name+ index to +index_users_on_last_name+:
-
#
-
# rename_index :people, 'index_people_on_last_name', 'index_users_on_last_name'
-
#
-
2
def rename_index(table_name, old_name, new_name)
-
# this is a naive implementation; some DBs may support this more efficiently (Postgres, for instance)
-
old_index_def = indexes(table_name).detect { |i| i.name == old_name }
-
return unless old_index_def
-
add_index(table_name, old_index_def.columns, name: new_name, unique: old_index_def.unique)
-
remove_index(table_name, name: old_name)
-
end
-
-
2
def index_name(table_name, options) #:nodoc:
-
if Hash === options
-
if options[:column]
-
"index_#{table_name}_on_#{Array(options[:column]) * '_and_'}"
-
elsif options[:name]
-
options[:name]
-
else
-
raise ArgumentError, "You must specify the index name"
-
end
-
else
-
index_name(table_name, :column => options)
-
end
-
end
-
-
# Verifies the existence of an index with a given name.
-
#
-
# The default argument is returned if the underlying implementation does not define the indexes method,
-
# as there's no way to determine the correct answer in that case.
-
2
def index_name_exists?(table_name, index_name, default)
-
return default unless respond_to?(:indexes)
-
index_name = index_name.to_s
-
indexes(table_name).detect { |i| i.name == index_name }
-
end
-
-
# Adds a reference. Optionally adds a +type+ column, if <tt>:polymorphic</tt> option is provided.
-
# <tt>add_reference</tt> and <tt>add_belongs_to</tt> are acceptable.
-
#
-
# ====== Create a user_id column
-
#
-
# add_reference(:products, :user)
-
#
-
# ====== Create a supplier_id and supplier_type columns
-
#
-
# add_belongs_to(:products, :supplier, polymorphic: true)
-
#
-
# ====== Create a supplier_id, supplier_type columns and appropriate index
-
#
-
# add_reference(:products, :supplier, polymorphic: true, index: true)
-
#
-
2
def add_reference(table_name, ref_name, options = {})
-
polymorphic = options.delete(:polymorphic)
-
index_options = options.delete(:index)
-
add_column(table_name, "#{ref_name}_id", :integer, options)
-
add_column(table_name, "#{ref_name}_type", :string, polymorphic.is_a?(Hash) ? polymorphic : options) if polymorphic
-
add_index(table_name, polymorphic ? %w[id type].map{ |t| "#{ref_name}_#{t}" } : "#{ref_name}_id", index_options.is_a?(Hash) ? index_options : {}) if index_options
-
end
-
2
alias :add_belongs_to :add_reference
-
-
# Removes the reference(s). Also removes a +type+ column if one exists.
-
# <tt>remove_reference</tt>, <tt>remove_references</tt> and <tt>remove_belongs_to</tt> are acceptable.
-
#
-
# ====== Remove the reference
-
#
-
# remove_reference(:products, :user, index: true)
-
#
-
# ====== Remove polymorphic reference
-
#
-
# remove_reference(:products, :supplier, polymorphic: true)
-
#
-
2
def remove_reference(table_name, ref_name, options = {})
-
remove_column(table_name, "#{ref_name}_id")
-
remove_column(table_name, "#{ref_name}_type") if options[:polymorphic]
-
end
-
2
alias :remove_belongs_to :remove_reference
-
-
2
def dump_schema_information #:nodoc:
-
sm_table = ActiveRecord::Migrator.schema_migrations_table_name
-
-
ActiveRecord::SchemaMigration.order('version').map { |sm|
-
"INSERT INTO #{sm_table} (version) VALUES ('#{sm.version}');"
-
}.join "\n\n"
-
end
-
-
# Should not be called normally, but this operation is non-destructive.
-
# The migrations module handles this automatically.
-
2
def initialize_schema_migrations_table
-
ActiveRecord::SchemaMigration.create_table
-
end
-
-
2
def assume_migrated_upto_version(version, migrations_paths = ActiveRecord::Migrator.migrations_paths)
-
migrations_paths = Array(migrations_paths)
-
version = version.to_i
-
sm_table = quote_table_name(ActiveRecord::Migrator.schema_migrations_table_name)
-
-
migrated = select_values("SELECT version FROM #{sm_table}").map { |v| v.to_i }
-
paths = migrations_paths.map {|p| "#{p}/[0-9]*_*.rb" }
-
versions = Dir[*paths].map do |filename|
-
filename.split('/').last.split('_').first.to_i
-
end
-
-
unless migrated.include?(version)
-
execute "INSERT INTO #{sm_table} (version) VALUES ('#{version}')"
-
end
-
-
inserted = Set.new
-
(versions - migrated).each do |v|
-
if inserted.include?(v)
-
raise "Duplicate migration #{v}. Please renumber your migrations to resolve the conflict."
-
elsif v < version
-
execute "INSERT INTO #{sm_table} (version) VALUES ('#{v}')"
-
inserted << v
-
end
-
end
-
end
-
-
2
def type_to_sql(type, limit = nil, precision = nil, scale = nil) #:nodoc:
-
if native = native_database_types[type.to_sym]
-
column_type_sql = (native.is_a?(Hash) ? native[:name] : native).dup
-
-
if type == :decimal # ignore limit, use precision and scale
-
scale ||= native[:scale]
-
-
if precision ||= native[:precision]
-
if scale
-
column_type_sql << "(#{precision},#{scale})"
-
else
-
column_type_sql << "(#{precision})"
-
end
-
elsif scale
-
raise ArgumentError, "Error adding decimal column: precision cannot be empty if scale is specified"
-
end
-
-
elsif (type != :primary_key) && (limit ||= native.is_a?(Hash) && native[:limit])
-
column_type_sql << "(#{limit})"
-
end
-
-
column_type_sql
-
else
-
type.to_s
-
end
-
end
-
-
# Given a set of columns and an ORDER BY clause, returns the columns for a SELECT DISTINCT.
-
# Both PostgreSQL and Oracle overrides this for custom DISTINCT syntax - they
-
# require the order columns appear in the SELECT.
-
#
-
# columns_for_distinct("posts.id", ["posts.created_at desc"])
-
2
def columns_for_distinct(columns, orders) #:nodoc:
-
columns
-
end
-
-
# Adds timestamps (+created_at+ and +updated_at+) columns to the named table.
-
#
-
# add_timestamps(:suppliers)
-
#
-
2
def add_timestamps(table_name)
-
add_column table_name, :created_at, :datetime
-
add_column table_name, :updated_at, :datetime
-
end
-
-
# Removes the timestamp columns (+created_at+ and +updated_at+) from the table definition.
-
#
-
# remove_timestamps(:suppliers)
-
#
-
2
def remove_timestamps(table_name)
-
remove_column table_name, :updated_at
-
remove_column table_name, :created_at
-
end
-
-
2
def update_table_definition(table_name, base) #:nodoc:
-
Table.new(table_name, base)
-
end
-
-
2
protected
-
2
def add_index_sort_order(option_strings, column_names, options = {})
-
if options.is_a?(Hash) && order = options[:order]
-
case order
-
when Hash
-
column_names.each {|name| option_strings[name] += " #{order[name].upcase}" if order.has_key?(name)}
-
when String
-
column_names.each {|name| option_strings[name] += " #{order.upcase}"}
-
end
-
end
-
-
return option_strings
-
end
-
-
# Overridden by the mysql adapter for supporting index lengths
-
2
def quoted_columns_for_index(column_names, options = {})
-
option_strings = Hash[column_names.map {|name| [name, '']}]
-
-
# add index sort order if supported
-
if supports_index_sort_order?
-
option_strings = add_index_sort_order(option_strings, column_names, options)
-
end
-
-
column_names.map {|name| quote_column_name(name) + option_strings[name]}
-
end
-
-
2
def options_include_default?(options)
-
options.include?(:default) && !(options[:null] == false && options[:default].nil?)
-
end
-
-
2
def add_index_options(table_name, column_name, options = {})
-
column_names = Array(column_name)
-
index_name = index_name(table_name, column: column_names)
-
-
options.assert_valid_keys(:unique, :order, :name, :where, :length, :internal, :using, :algorithm, :type)
-
-
index_type = options[:unique] ? "UNIQUE" : ""
-
index_type = options[:type].to_s if options.key?(:type)
-
index_name = options[:name].to_s if options.key?(:name)
-
max_index_length = options.fetch(:internal, false) ? index_name_length : allowed_index_name_length
-
-
if options.key?(:algorithm)
-
algorithm = index_algorithms.fetch(options[:algorithm]) {
-
raise ArgumentError.new("Algorithm must be one of the following: #{index_algorithms.keys.map(&:inspect).join(', ')}")
-
}
-
end
-
-
using = "USING #{options[:using]}" if options[:using].present?
-
-
if supports_partial_index?
-
index_options = options[:where] ? " WHERE #{options[:where]}" : ""
-
end
-
-
if index_name.length > max_index_length
-
raise ArgumentError, "Index name '#{index_name}' on table '#{table_name}' is too long; the limit is #{max_index_length} characters"
-
end
-
if index_name_exists?(table_name, index_name, false)
-
raise ArgumentError, "Index name '#{index_name}' on table '#{table_name}' already exists"
-
end
-
index_columns = quoted_columns_for_index(column_names, options).join(", ")
-
-
[index_name, index_type, index_columns, index_options, algorithm, using]
-
end
-
-
2
def index_name_for_remove(table_name, options = {})
-
index_name = index_name(table_name, options)
-
-
unless index_name_exists?(table_name, index_name, true)
-
if options.is_a?(Hash) && options.has_key?(:name)
-
options_without_column = options.dup
-
options_without_column.delete :column
-
index_name_without_column = index_name(table_name, options_without_column)
-
-
return index_name_without_column if index_name_exists?(table_name, index_name_without_column, false)
-
end
-
-
raise ArgumentError, "Index name '#{index_name}' on table '#{table_name}' does not exist"
-
end
-
-
index_name
-
end
-
-
2
def rename_table_indexes(table_name, new_name)
-
indexes(new_name).each do |index|
-
generated_index_name = index_name(table_name, column: index.columns)
-
if generated_index_name == index.name
-
rename_index new_name, generated_index_name, index_name(new_name, column: index.columns)
-
end
-
end
-
end
-
-
2
def rename_column_indexes(table_name, column_name, new_column_name)
-
column_name, new_column_name = column_name.to_s, new_column_name.to_s
-
indexes(table_name).each do |index|
-
next unless index.columns.include?(new_column_name)
-
old_columns = index.columns.dup
-
old_columns[old_columns.index(new_column_name)] = column_name
-
generated_index_name = index_name(table_name, column: old_columns)
-
if generated_index_name == index.name
-
rename_index table_name, generated_index_name, index_name(table_name, column: index.columns)
-
end
-
end
-
end
-
-
2
private
-
2
def create_table_definition(name, temporary, options, as = nil)
-
TableDefinition.new native_database_types, name, temporary, options, as
-
end
-
-
2
def create_alter_table(name)
-
AlterTable.new create_table_definition(name, false, {})
-
end
-
end
-
end
-
end
-
2
module ActiveRecord
-
2
module ConnectionAdapters
-
2
class Transaction #:nodoc:
-
2
attr_reader :connection
-
-
2
def initialize(connection)
-
232
@connection = connection
-
232
@state = TransactionState.new
-
end
-
-
2
def state
-
195
@state
-
end
-
end
-
-
2
class TransactionState
-
2
attr_accessor :parent
-
-
2
VALID_STATES = Set.new([:committed, :rolledback, nil])
-
-
2
def initialize(state = nil)
-
232
@state = state
-
232
@parent = nil
-
end
-
-
2
def finalized?
-
148
@state
-
end
-
-
2
def committed?
-
@state == :committed
-
end
-
-
2
def rolledback?
-
@state == :rolledback
-
end
-
-
2
def set_state(state)
-
230
if !VALID_STATES.include?(state)
-
raise ArgumentError, "Invalid transaction state: #{state}"
-
end
-
230
@state = state
-
end
-
end
-
-
2
class ClosedTransaction < Transaction #:nodoc:
-
2
def number
-
400
0
-
end
-
-
2
def begin(options = {})
-
33
RealTransaction.new(connection, self, options)
-
end
-
-
2
def closed?
-
193
true
-
end
-
-
2
def open?
-
false
-
end
-
-
2
def joinable?
-
6
false
-
end
-
-
# This is a noop when there are no open transactions
-
2
def add_record(record)
-
end
-
end
-
-
2
class OpenTransaction < Transaction #:nodoc:
-
2
attr_reader :parent, :records
-
2
attr_writer :joinable
-
-
2
def initialize(connection, parent, options = {})
-
230
super connection
-
-
230
@parent = parent
-
230
@records = []
-
230
@finishing = false
-
230
@joinable = options.fetch(:joinable, true)
-
end
-
-
# This state is necessary so that we correctly handle stuff that might
-
# happen in a commit/rollback. But it's kinda distasteful. Maybe we can
-
# find a better way to structure it in the future.
-
2
def finishing?
-
938
@finishing
-
end
-
-
2
def joinable?
-
341
@joinable && !finishing?
-
end
-
-
2
def number
-
597
if finishing?
-
197
parent.number
-
else
-
400
parent.number + 1
-
end
-
end
-
-
2
def begin(options = {})
-
197
if finishing?
-
parent.begin
-
else
-
197
SavepointTransaction.new(connection, self, options)
-
end
-
end
-
-
2
def rollback
-
29
@finishing = true
-
29
perform_rollback
-
29
parent
-
end
-
-
2
def commit
-
201
@finishing = true
-
201
perform_commit
-
201
parent
-
end
-
-
2
def add_record(record)
-
462
if record.has_transactional_callbacks?
-
388
records << record
-
else
-
74
record.set_transaction_state(@state)
-
end
-
end
-
-
2
def rollback_records
-
29
@state.set_state(:rolledback)
-
29
records.uniq.each do |record|
-
195
begin
-
195
record.rolledback!(parent.closed?)
-
rescue => e
-
record.logger.error(e) if record.respond_to?(:logger) && record.logger
-
end
-
end
-
end
-
-
2
def commit_records
-
6
@state.set_state(:committed)
-
6
records.uniq.each do |record|
-
begin
-
record.committed!
-
rescue => e
-
record.logger.error(e) if record.respond_to?(:logger) && record.logger
-
end
-
end
-
end
-
-
2
def closed?
-
2
false
-
end
-
-
2
def open?
-
21
true
-
end
-
end
-
-
2
class RealTransaction < OpenTransaction #:nodoc:
-
2
def initialize(connection, parent, options = {})
-
33
super
-
-
33
if options[:isolation]
-
connection.begin_isolated_db_transaction(options[:isolation])
-
else
-
33
connection.begin_db_transaction
-
end
-
end
-
-
2
def perform_rollback
-
27
connection.rollback_db_transaction
-
27
rollback_records
-
end
-
-
2
def perform_commit
-
6
connection.commit_db_transaction
-
6
commit_records
-
end
-
end
-
-
2
class SavepointTransaction < OpenTransaction #:nodoc:
-
2
def initialize(connection, parent, options = {})
-
197
if options[:isolation]
-
raise ActiveRecord::TransactionIsolationError, "cannot set transaction isolation in a nested transaction"
-
end
-
-
197
super
-
197
connection.create_savepoint
-
end
-
-
2
def perform_rollback
-
2
connection.rollback_to_savepoint
-
2
rollback_records
-
end
-
-
2
def perform_commit
-
195
@state.set_state(:committed)
-
195
@state.parent = parent.state
-
195
connection.release_savepoint
-
388
records.each { |r| parent.add_record(r) }
-
end
-
end
-
end
-
end
-
2
require 'date'
-
2
require 'bigdecimal'
-
2
require 'bigdecimal/util'
-
2
require 'active_support/core_ext/benchmark'
-
2
require 'active_record/connection_adapters/schema_cache'
-
2
require 'active_record/connection_adapters/abstract/schema_dumper'
-
2
require 'active_record/connection_adapters/abstract/schema_creation'
-
2
require 'monitor'
-
-
2
module ActiveRecord
-
2
module ConnectionAdapters # :nodoc:
-
2
extend ActiveSupport::Autoload
-
-
2
autoload :Column
-
2
autoload :ConnectionSpecification
-
-
2
autoload_at 'active_record/connection_adapters/abstract/schema_definitions' do
-
2
autoload :IndexDefinition
-
2
autoload :ColumnDefinition
-
2
autoload :ChangeColumnDefinition
-
2
autoload :TableDefinition
-
2
autoload :Table
-
2
autoload :AlterTable
-
end
-
-
2
autoload_at 'active_record/connection_adapters/abstract/connection_pool' do
-
2
autoload :ConnectionHandler
-
2
autoload :ConnectionManagement
-
end
-
-
2
autoload_under 'abstract' do
-
2
autoload :SchemaStatements
-
2
autoload :DatabaseStatements
-
2
autoload :DatabaseLimits
-
2
autoload :Quoting
-
2
autoload :ConnectionPool
-
2
autoload :QueryCache
-
2
autoload :Savepoints
-
end
-
-
2
autoload_at 'active_record/connection_adapters/abstract/transaction' do
-
2
autoload :ClosedTransaction
-
2
autoload :RealTransaction
-
2
autoload :SavepointTransaction
-
2
autoload :TransactionState
-
end
-
-
# Active Record supports multiple database systems. AbstractAdapter and
-
# related classes form the abstraction layer which makes this possible.
-
# An AbstractAdapter represents a connection to a database, and provides an
-
# abstract interface for database-specific functionality such as establishing
-
# a connection, escaping values, building the right SQL fragments for ':offset'
-
# and ':limit' options, etc.
-
#
-
# All the concrete database adapters follow the interface laid down in this class.
-
# ActiveRecord::Base.connection returns an AbstractAdapter object, which
-
# you can use.
-
#
-
# Most of the methods in the adapter are useful during migrations. Most
-
# notably, the instance methods provided by SchemaStatement are very useful.
-
2
class AbstractAdapter
-
2
include Quoting, DatabaseStatements, SchemaStatements
-
2
include DatabaseLimits
-
2
include QueryCache
-
2
include ActiveSupport::Callbacks
-
2
include MonitorMixin
-
2
include ColumnDumper
-
-
2
SIMPLE_INT = /\A\d+\z/
-
-
2
define_callbacks :checkout, :checkin
-
-
2
attr_accessor :visitor, :pool
-
2
attr_reader :schema_cache, :last_use, :in_use, :logger
-
2
alias :in_use? :in_use
-
-
2
def self.type_cast_config_to_integer(config)
-
4
if config =~ SIMPLE_INT
-
config.to_i
-
else
-
4
config
-
end
-
end
-
-
2
def self.type_cast_config_to_boolean(config)
-
2
if config == "false"
-
false
-
else
-
2
config
-
end
-
end
-
-
2
def initialize(connection, logger = nil, pool = nil) #:nodoc:
-
2
super()
-
-
2
@connection = connection
-
2
@in_use = false
-
2
@instrumenter = ActiveSupport::Notifications.instrumenter
-
2
@last_use = false
-
2
@logger = logger
-
2
@pool = pool
-
2
@schema_cache = SchemaCache.new self
-
2
@visitor = nil
-
2
@prepared_statements = false
-
end
-
-
2
def valid_type?(type)
-
true
-
end
-
-
2
def schema_creation
-
SchemaCreation.new self
-
end
-
-
2
def lease
-
22
synchronize do
-
22
unless in_use
-
22
@in_use = true
-
22
@last_use = Time.now
-
end
-
end
-
end
-
-
2
def schema_cache=(cache)
-
cache.connection = self
-
@schema_cache = cache
-
end
-
-
2
def expire
-
21
@in_use = false
-
end
-
-
2
def unprepared_visitor
-
self.class::BindSubstitution.new self
-
end
-
-
2
def unprepared_statement
-
old_prepared_statements, @prepared_statements = @prepared_statements, false
-
old_visitor, @visitor = @visitor, unprepared_visitor
-
yield
-
ensure
-
@visitor, @prepared_statements = old_visitor, old_prepared_statements
-
end
-
-
# Returns the human-readable name of the adapter. Use mixed case - one
-
# can always use downcase if needed.
-
2
def adapter_name
-
'Abstract'
-
end
-
-
# Does this adapter support migrations? Backend specific, as the
-
# abstract adapter always returns +false+.
-
2
def supports_migrations?
-
false
-
end
-
-
# Can this adapter determine the primary key for tables not attached
-
# to an Active Record class, such as join tables? Backend specific, as
-
# the abstract adapter always returns +false+.
-
2
def supports_primary_key?
-
false
-
end
-
-
# Does this adapter support using DISTINCT within COUNT? This is +true+
-
# for all adapters except sqlite.
-
2
def supports_count_distinct?
-
true
-
end
-
-
# Does this adapter support DDL rollbacks in transactions? That is, would
-
# CREATE TABLE or ALTER TABLE get rolled back by a transaction? PostgreSQL,
-
# SQL Server, and others support this. MySQL and others do not.
-
2
def supports_ddl_transactions?
-
false
-
end
-
-
2
def supports_bulk_alter?
-
false
-
end
-
-
# Does this adapter support savepoints? PostgreSQL and MySQL do,
-
# SQLite < 3.6.8 does not.
-
2
def supports_savepoints?
-
false
-
end
-
-
# Should primary key values be selected from their corresponding
-
# sequence before the insert statement? If true, next_sequence_value
-
# is called before each insert to set the record's primary key.
-
# This is false for all adapters but Firebird.
-
2
def prefetch_primary_key?(table_name = nil)
-
267
false
-
end
-
-
# Does this adapter support index sort order?
-
2
def supports_index_sort_order?
-
false
-
end
-
-
# Does this adapter support partial indices?
-
2
def supports_partial_index?
-
false
-
end
-
-
# Does this adapter support explain? As of this writing sqlite3,
-
# mysql2, and postgresql are the only ones that do.
-
2
def supports_explain?
-
false
-
end
-
-
# Does this adapter support setting the isolation level for a transaction?
-
2
def supports_transaction_isolation?
-
false
-
end
-
-
# Does this adapter support database extensions? As of this writing only
-
# postgresql does.
-
2
def supports_extensions?
-
false
-
end
-
-
# This is meant to be implemented by the adapters that support extensions
-
2
def disable_extension(name)
-
end
-
-
# This is meant to be implemented by the adapters that support extensions
-
2
def enable_extension(name)
-
end
-
-
# A list of extensions, to be filled in by adapters that support them. At
-
# the moment only postgresql does.
-
2
def extensions
-
[]
-
end
-
-
# A list of index algorithms, to be filled by adapters that support them.
-
# MySQL and PostgreSQL have support for them right now.
-
2
def index_algorithms
-
{}
-
end
-
-
# QUOTING ==================================================
-
-
# Returns a bind substitution value given a bind +index+ and +column+
-
# NOTE: The column param is currently being used by the sqlserver-adapter
-
2
def substitute_at(column, index)
-
1981
Arel::Nodes::BindParam.new '?'
-
end
-
-
# REFERENTIAL INTEGRITY ====================================
-
-
# Override to turn off referential integrity while executing <tt>&block</tt>.
-
2
def disable_referential_integrity
-
yield
-
end
-
-
# CONNECTION MANAGEMENT ====================================
-
-
# Checks whether the connection to the database is still active. This includes
-
# checking whether the database is actually capable of responding, i.e. whether
-
# the connection isn't stale.
-
2
def active?
-
end
-
-
# Adapter should redefine this if it needs a threadsafe way to approximate
-
# if the connection is active
-
2
def active_threadsafe?
-
active?
-
end
-
-
# Disconnects from the database if already connected, and establishes a
-
# new connection with the database. Implementors should call super if they
-
# override the default implementation.
-
2
def reconnect!
-
clear_cache!
-
reset_transaction
-
end
-
-
# Disconnects from the database if already connected. Otherwise, this
-
# method does nothing.
-
2
def disconnect!
-
clear_cache!
-
reset_transaction
-
end
-
-
# Reset the state of this connection, directing the DBMS to clear
-
# transactions and other connection-related server-side state. Usually a
-
# database-dependent operation.
-
#
-
# The default implementation does nothing; the implementation should be
-
# overridden by concrete adapters.
-
2
def reset!
-
# this should be overridden by concrete adapters
-
end
-
-
###
-
# Clear any caching the database adapter may be doing, for example
-
# clearing the prepared statement cache. This is database specific.
-
2
def clear_cache!
-
# this should be overridden by concrete adapters
-
end
-
-
# Returns true if its required to reload the connection between requests for development mode.
-
# This is not the case for Ruby/MySQL and it's not necessary for any adapters except SQLite.
-
2
def requires_reloading?
-
false
-
end
-
-
# Checks whether the connection to the database is still active (i.e. not stale).
-
# This is done under the hood by calling <tt>active?</tt>. If the connection
-
# is no longer active, then this method will reconnect to the database.
-
2
def verify!(*ignored)
-
22
reconnect! unless active?
-
end
-
-
# Provides access to the underlying database driver for this adapter. For
-
# example, this method returns a Mysql object in case of MysqlAdapter,
-
# and a PGconn object in case of PostgreSQLAdapter.
-
#
-
# This is useful for when you need to call a proprietary method such as
-
# PostgreSQL's lo_* methods.
-
2
def raw_connection
-
@connection
-
end
-
-
2
def open_transactions
-
400
@transaction.number
-
end
-
-
2
def create_savepoint(name = nil)
-
end
-
-
2
def rollback_to_savepoint(name = nil)
-
end
-
-
2
def release_savepoint(name = nil)
-
end
-
-
2
def case_sensitive_modifier(node)
-
195
node
-
end
-
-
2
def case_insensitive_comparison(table, attribute, column, value)
-
table[attribute].lower.eq(table.lower(value))
-
end
-
-
2
def current_savepoint_name
-
394
"active_record_#{open_transactions}"
-
end
-
-
# Check the connection back in to the connection pool
-
2
def close
-
pool.checkin self
-
end
-
-
2
protected
-
-
2
def translate_exception_class(e, sql)
-
message = "#{e.class.name}: #{e.message}: #{sql}"
-
@logger.error message if @logger
-
exception = translate_exception(e, message)
-
exception.set_backtrace e.backtrace
-
exception
-
end
-
-
2
def log(sql, name = "SQL", binds = [], statement_name = nil)
-
@instrumenter.instrument(
-
"sql.active_record",
-
:sql => sql,
-
:name => name,
-
:connection_id => object_id,
-
:statement_name => statement_name,
-
1934
:binds => binds) { yield }
-
rescue => e
-
raise translate_exception_class(e, sql)
-
end
-
-
2
def translate_exception(exception, message)
-
# override in derived class
-
ActiveRecord::StatementInvalid.new(message, exception)
-
end
-
-
2
def without_prepared_statement?(binds)
-
507
!@prepared_statements || binds.empty?
-
end
-
end
-
end
-
end
-
2
require 'set'
-
-
2
module ActiveRecord
-
# :stopdoc:
-
2
module ConnectionAdapters
-
# An abstract definition of a column in a table.
-
2
class Column
-
2
TRUE_VALUES = [true, 1, '1', 't', 'T', 'true', 'TRUE', 'on', 'ON'].to_set
-
2
FALSE_VALUES = [false, 0, '0', 'f', 'F', 'false', 'FALSE', 'off', 'OFF'].to_set
-
-
2
module Format
-
2
ISO_DATE = /\A(\d{4})-(\d\d)-(\d\d)\z/
-
2
ISO_DATETIME = /\A(\d{4})-(\d\d)-(\d\d) (\d\d):(\d\d):(\d\d)(\.\d+)?\z/
-
end
-
-
2
attr_reader :name, :default, :type, :limit, :null, :sql_type, :precision, :scale, :default_function
-
2
attr_accessor :primary, :coder
-
-
2
alias :encoded? :coder
-
-
# Instantiates a new column in the table.
-
#
-
# +name+ is the column's name, such as <tt>supplier_id</tt> in <tt>supplier_id int(11)</tt>.
-
# +default+ is the type-casted default value, such as +new+ in <tt>sales_stage varchar(20) default 'new'</tt>.
-
# +sql_type+ is used to extract the column's length, if necessary. For example +60+ in
-
# <tt>company_name varchar(60)</tt>.
-
# It will be mapped to one of the standard Rails SQL types in the <tt>type</tt> attribute.
-
# +null+ determines if this column allows +NULL+ values.
-
2
def initialize(name, default, sql_type = nil, null = true)
-
100
@name = name
-
100
@sql_type = sql_type
-
100
@null = null
-
100
@limit = extract_limit(sql_type)
-
100
@precision = extract_precision(sql_type)
-
100
@scale = extract_scale(sql_type)
-
100
@type = simplified_type(sql_type)
-
100
@default = extract_default(default)
-
100
@default_function = nil
-
100
@primary = nil
-
100
@coder = nil
-
end
-
-
# Returns +true+ if the column is either of type string or text.
-
2
def text?
-
195
type == :string || type == :text
-
end
-
-
# Returns +true+ if the column is either of type integer, float or decimal.
-
2
def number?
-
8656
type == :integer || type == :float || type == :decimal
-
end
-
-
2
def has_default?
-
!default.nil?
-
end
-
-
# Returns the Ruby class that corresponds to the abstract data type.
-
2
def klass
-
case type
-
when :integer then Fixnum
-
when :float then Float
-
when :decimal then BigDecimal
-
when :datetime, :timestamp, :time then Time
-
when :date then Date
-
when :text, :string, :binary then String
-
when :boolean then Object
-
end
-
end
-
-
2
def binary?
-
3915
type == :binary
-
end
-
-
# Casts a Ruby value to something appropriate for writing to the database.
-
2
def type_cast_for_write(value)
-
2438
return value unless number?
-
-
755
case value
-
when FalseClass
-
0
-
when TrueClass
-
1
-
when String
-
2
value.presence
-
else
-
753
value
-
end
-
end
-
-
# Casts value (which is a String) to an appropriate instance.
-
2
def type_cast(value)
-
9788
return nil if value.nil?
-
3858
return coder.load(value) if encoded?
-
-
3858
klass = self.class
-
-
3858
case type
-
2031
when :string, :text then value
-
759
when :integer then klass.value_to_integer(value)
-
when :float then value.to_f
-
when :decimal then klass.value_to_decimal(value)
-
1068
when :datetime, :timestamp then klass.string_to_time(value)
-
when :time then klass.string_to_dummy_time(value)
-
when :date then klass.value_to_date(value)
-
when :binary then klass.binary_to_string(value)
-
when :boolean then klass.value_to_boolean(value)
-
else value
-
end
-
end
-
-
# Returns the human name of the column name.
-
#
-
# ===== Examples
-
# Column.new('sales_stage', ...).human_name # => 'Sales stage'
-
2
def human_name
-
Base.human_attribute_name(@name)
-
end
-
-
2
def extract_default(default)
-
100
type_cast(default)
-
end
-
-
2
class << self
-
# Used to convert from BLOBs to Strings
-
2
def binary_to_string(value)
-
value
-
end
-
-
2
def value_to_date(value)
-
if value.is_a?(String)
-
return nil if value.empty?
-
fast_string_to_date(value) || fallback_string_to_date(value)
-
elsif value.respond_to?(:to_date)
-
value.to_date
-
else
-
value
-
end
-
end
-
-
2
def string_to_time(string)
-
1068
return string unless string.is_a?(String)
-
return nil if string.empty?
-
-
fast_string_to_time(string) || fallback_string_to_time(string)
-
end
-
-
2
def string_to_dummy_time(string)
-
return string unless string.is_a?(String)
-
return nil if string.empty?
-
-
dummy_time_string = "2000-01-01 #{string}"
-
-
fast_string_to_time(dummy_time_string) || begin
-
time_hash = Date._parse(dummy_time_string)
-
return nil if time_hash[:hour].nil?
-
new_time(*time_hash.values_at(:year, :mon, :mday, :hour, :min, :sec, :sec_fraction))
-
end
-
end
-
-
# convert something to a boolean
-
2
def value_to_boolean(value)
-
if value.is_a?(String) && value.empty?
-
nil
-
else
-
TRUE_VALUES.include?(value)
-
end
-
end
-
-
# Used to convert values to integer.
-
# handle the case when an integer column is used to store boolean values
-
2
def value_to_integer(value)
-
759
case value
-
when TrueClass, FalseClass
-
value ? 1 : 0
-
else
-
759
value.to_i rescue nil
-
end
-
end
-
-
# convert something to a BigDecimal
-
2
def value_to_decimal(value)
-
# Using .class is faster than .is_a? and
-
# subclasses of BigDecimal will be handled
-
# in the else clause
-
if value.class == BigDecimal
-
value
-
elsif value.respond_to?(:to_d)
-
value.to_d
-
else
-
value.to_s.to_d
-
end
-
end
-
-
2
protected
-
# '0.123456' -> 123456
-
# '1.123456' -> 123456
-
2
def microseconds(time)
-
time[:sec_fraction] ? (time[:sec_fraction] * 1_000_000).to_i : 0
-
end
-
-
2
def new_date(year, mon, mday)
-
if year && year != 0
-
Date.new(year, mon, mday) rescue nil
-
end
-
end
-
-
2
def new_time(year, mon, mday, hour, min, sec, microsec, offset = nil)
-
# Treat 0000-00-00 00:00:00 as nil.
-
return nil if year.nil? || (year == 0 && mon == 0 && mday == 0)
-
-
if offset
-
time = Time.utc(year, mon, mday, hour, min, sec, microsec) rescue nil
-
return nil unless time
-
-
time -= offset
-
Base.default_timezone == :utc ? time : time.getlocal
-
else
-
Time.public_send(Base.default_timezone, year, mon, mday, hour, min, sec, microsec) rescue nil
-
end
-
end
-
-
2
def fast_string_to_date(string)
-
if string =~ Format::ISO_DATE
-
new_date $1.to_i, $2.to_i, $3.to_i
-
end
-
end
-
-
# Doesn't handle time zones.
-
2
def fast_string_to_time(string)
-
if string =~ Format::ISO_DATETIME
-
microsec = ($7.to_r * 1_000_000).to_i
-
new_time $1.to_i, $2.to_i, $3.to_i, $4.to_i, $5.to_i, $6.to_i, microsec
-
end
-
end
-
-
2
def fallback_string_to_date(string)
-
new_date(*::Date._parse(string, false).values_at(:year, :mon, :mday))
-
end
-
-
2
def fallback_string_to_time(string)
-
time_hash = Date._parse(string)
-
time_hash[:sec_fraction] = microseconds(time_hash)
-
-
new_time(*time_hash.values_at(:year, :mon, :mday, :hour, :min, :sec, :sec_fraction, :offset))
-
end
-
end
-
-
2
private
-
2
def extract_limit(sql_type)
-
100
$1.to_i if sql_type =~ /\((.*)\)/
-
end
-
-
2
def extract_precision(sql_type)
-
100
$2.to_i if sql_type =~ /^(numeric|decimal|number)\((\d+)(,\d+)?\)/i
-
end
-
-
2
def extract_scale(sql_type)
-
100
case sql_type
-
when /^(numeric|decimal|number)\((\d+)\)/i then 0
-
when /^(numeric|decimal|number)\((\d+)(,(\d+))\)/i then $4.to_i
-
end
-
end
-
-
2
def simplified_type(field_type)
-
100
case field_type
-
when /int/i
-
29
:integer
-
when /float|double/i
-
:float
-
when /decimal|numeric|number/i
-
extract_scale(field_type) == 0 ? :integer : :decimal
-
when /datetime/i
-
22
:datetime
-
when /timestamp/i
-
:timestamp
-
when /time/i
-
:time
-
when /date/i
-
:date
-
when /clob/i, /text/i
-
1
:text
-
when /blob/i, /binary/i
-
:binary
-
when /char/i
-
48
:string
-
when /boolean/i
-
:boolean
-
end
-
end
-
end
-
end
-
# :startdoc:
-
end
-
2
require 'uri'
-
-
2
module ActiveRecord
-
2
module ConnectionAdapters
-
2
class ConnectionSpecification #:nodoc:
-
2
attr_reader :config, :adapter_method
-
-
2
def initialize(config, adapter_method)
-
2
@config, @adapter_method = config, adapter_method
-
end
-
-
2
def initialize_dup(original)
-
@config = original.config.dup
-
end
-
-
# Expands a connection string into a hash.
-
2
class ConnectionUrlResolver # :nodoc:
-
-
# == Example
-
#
-
# url = "postgresql://foo:bar@localhost:9000/foo_test?pool=5&timeout=3000"
-
# ConnectionUrlResolver.new(url).to_hash
-
# # => {
-
# "adapter" => "postgresql",
-
# "host" => "localhost",
-
# "port" => 9000,
-
# "database" => "foo_test",
-
# "username" => "foo",
-
# "password" => "bar",
-
# "pool" => "5",
-
# "timeout" => "3000"
-
# }
-
2
def initialize(url)
-
raise "Database URL cannot be empty" if url.blank?
-
@uri = URI.parse(url)
-
@adapter = @uri.scheme.gsub('-', '_')
-
@adapter = "postgresql" if @adapter == "postgres"
-
-
if @uri.opaque
-
@uri.opaque, @query = @uri.opaque.split('?', 2)
-
else
-
@query = @uri.query
-
end
-
@authority = url =~ %r{\A[^:]*://}
-
end
-
-
# Converts the given URL to a full connection hash.
-
2
def to_hash
-
config = raw_config.reject { |_,value| value.blank? }
-
config.map { |key,value| config[key] = uri_parser.unescape(value) if value.is_a? String }
-
config
-
end
-
-
2
private
-
-
2
def uri
-
@uri
-
end
-
-
2
def uri_parser
-
@uri_parser ||= URI::Parser.new
-
end
-
-
# Converts the query parameters of the URI into a hash.
-
#
-
# "localhost?pool=5&reap_frequency=2"
-
# # => { "pool" => "5", "reap_frequency" => "2" }
-
#
-
# returns empty hash if no query present.
-
#
-
# "localhost"
-
# # => {}
-
2
def query_hash
-
Hash[(@query || '').split("&").map { |pair| pair.split("=") }]
-
end
-
-
2
def raw_config
-
if uri.opaque
-
query_hash.merge({
-
"adapter" => @adapter,
-
"database" => uri.opaque })
-
else
-
query_hash.merge({
-
"adapter" => @adapter,
-
"username" => uri.user,
-
"password" => uri.password,
-
"port" => uri.port,
-
"database" => database_from_path,
-
"host" => uri.hostname })
-
end
-
end
-
-
# Returns name of the database.
-
# Sqlite3's handling of a leading slash is in transition as of
-
# Rails 4.1.
-
2
def database_from_path
-
if @authority && @adapter == 'sqlite3'
-
# 'sqlite3:///foo' is relative, for backwards compatibility.
-
-
database_name = uri.path.sub(%r{^/}, "")
-
-
msg = "Paths in SQLite3 database URLs of the form `sqlite3:///path` will be treated as absolute in Rails 4.2. " \
-
"Please switch to `sqlite3:#{database_name}`."
-
ActiveSupport::Deprecation.warn(msg)
-
-
database_name
-
-
elsif @adapter == 'sqlite3'
-
# 'sqlite3:/foo' is absolute, because that makes sense. The
-
# corresponding relative version, 'sqlite3:foo', is handled
-
# elsewhere, as an "opaque".
-
-
uri.path
-
else
-
# Only SQLite uses a filename as the "database" name; for
-
# anything else, a leading slash would be silly.
-
-
uri.path.sub(%r{^/}, "")
-
end
-
end
-
end
-
-
##
-
# Builds a ConnectionSpecification from user input.
-
2
class Resolver # :nodoc:
-
2
attr_reader :configurations
-
-
# Accepts a hash two layers deep, keys on the first layer represent
-
# environments such as "production". Keys must be strings.
-
2
def initialize(configurations)
-
6
@configurations = configurations
-
end
-
-
# Returns a hash with database connection information.
-
#
-
# == Examples
-
#
-
# Full hash Configuration.
-
#
-
# configurations = { "production" => { "host" => "localhost", "database" => "foo", "adapter" => "sqlite3" } }
-
# Resolver.new(configurations).resolve(:production)
-
# # => { "host" => "localhost", "database" => "foo", "adapter" => "sqlite3"}
-
#
-
# Initialized with URL configuration strings.
-
#
-
# configurations = { "production" => "postgresql://localhost/foo" }
-
# Resolver.new(configurations).resolve(:production)
-
# # => { "host" => "localhost", "database" => "foo", "adapter" => "postgresql" }
-
#
-
2
def resolve(config)
-
12
if config
-
12
resolve_connection config
-
elsif env = ActiveRecord::ConnectionHandling::RAILS_ENV.call
-
resolve_symbol_connection env.to_sym
-
else
-
raise AdapterNotSpecified
-
end
-
end
-
-
# Expands each key in @configurations hash into fully resolved hash
-
2
def resolve_all
-
4
config = configurations.dup
-
4
config.each do |key, value|
-
10
config[key] = resolve(value) if value
-
end
-
4
config
-
end
-
-
# Returns an instance of ConnectionSpecification for a given adapter.
-
# Accepts a hash one layer deep that contains all connection information.
-
#
-
# == Example
-
#
-
# config = { "production" => { "host" => "localhost", "database" => "foo", "adapter" => "sqlite3" } }
-
# spec = Resolver.new(config).spec(:production)
-
# spec.adapter_method
-
# # => "sqlite3"
-
# spec.config
-
# # => { "host" => "localhost", "database" => "foo", "adapter" => "sqlite3" }
-
#
-
2
def spec(config)
-
2
spec = resolve(config).symbolize_keys
-
-
2
raise(AdapterNotSpecified, "database configuration does not specify adapter") unless spec.key?(:adapter)
-
-
2
path_to_adapter = "active_record/connection_adapters/#{spec[:adapter]}_adapter"
-
2
begin
-
2
require path_to_adapter
-
rescue Gem::LoadError => e
-
raise Gem::LoadError, "Specified '#{spec[:adapter]}' for database adapter, but the gem is not loaded. Add `gem '#{e.name}'` to your Gemfile (and ensure its version is at the minimum required by ActiveRecord)."
-
rescue LoadError => e
-
raise LoadError, "Could not load '#{path_to_adapter}'. Make sure that the adapter in config/database.yml is valid. If you use an adapter other than 'mysql', 'mysql2', 'postgresql' or 'sqlite3' add the necessary adapter gem to the Gemfile.", e.backtrace
-
end
-
-
2
adapter_method = "#{spec[:adapter]}_connection"
-
2
ConnectionSpecification.new(spec, adapter_method)
-
end
-
-
2
private
-
-
# Returns fully resolved connection, accepts hash, string or symbol.
-
# Always returns a hash.
-
#
-
# == Examples
-
#
-
# Symbol representing current environment.
-
#
-
# Resolver.new("production" => {}).resolve_connection(:production)
-
# # => {}
-
#
-
# One layer deep hash of connection values.
-
#
-
# Resolver.new({}).resolve_connection("adapter" => "sqlite3")
-
# # => { "adapter" => "sqlite3" }
-
#
-
# Connection URL.
-
#
-
# Resolver.new({}).resolve_connection("postgresql://localhost/foo")
-
# # => { "host" => "localhost", "database" => "foo", "adapter" => "postgresql" }
-
#
-
2
def resolve_connection(spec)
-
14
case spec
-
when Symbol
-
2
resolve_symbol_connection spec
-
when String
-
resolve_string_connection spec
-
when Hash
-
12
resolve_hash_connection spec
-
end
-
end
-
-
2
def resolve_string_connection(spec)
-
# Rails has historically accepted a string to mean either
-
# an environment key or a URL spec, so we have deprecated
-
# this ambiguous behaviour and in the future this function
-
# can be removed in favor of resolve_url_connection.
-
if configurations.key?(spec) || spec !~ /:/
-
ActiveSupport::Deprecation.warn "Passing a string to ActiveRecord::Base.establish_connection " \
-
"for a configuration lookup is deprecated, please pass a symbol (#{spec.to_sym.inspect}) instead"
-
resolve_symbol_connection(spec)
-
else
-
resolve_url_connection(spec)
-
end
-
end
-
-
# Takes the environment such as `:production` or `:development`.
-
# This requires that the @configurations was initialized with a key that
-
# matches.
-
#
-
# Resolver.new("production" => {}).resolve_symbol_connection(:production)
-
# # => {}
-
#
-
2
def resolve_symbol_connection(spec)
-
2
if config = configurations[spec.to_s]
-
2
resolve_connection(config)
-
else
-
raise(AdapterNotSpecified, "'#{spec}' database is not configured. Available: #{configurations.keys.inspect}")
-
end
-
end
-
-
# Accepts a hash. Expands the "url" key that contains a
-
# URL database connection to a full connection
-
# hash and merges with the rest of the hash.
-
# Connection details inside of the "url" key win any merge conflicts
-
2
def resolve_hash_connection(spec)
-
12
if spec["url"] && spec["url"] !~ /^jdbc:/
-
connection_hash = resolve_string_connection(spec.delete("url"))
-
spec.merge!(connection_hash)
-
end
-
12
spec
-
end
-
-
# Takes a connection URL.
-
#
-
# Resolver.new({}).resolve_url_connection("postgresql://localhost/foo")
-
# # => { "host" => "localhost", "database" => "foo", "adapter" => "postgresql" }
-
#
-
2
def resolve_url_connection(url)
-
ConnectionUrlResolver.new(url).to_hash
-
end
-
end
-
end
-
end
-
end
-
-
2
module ActiveRecord
-
2
module ConnectionAdapters
-
2
class SchemaCache
-
2
attr_reader :version
-
2
attr_accessor :connection
-
-
2
def initialize(conn)
-
2
@connection = conn
-
-
2
@columns = {}
-
2
@columns_hash = {}
-
2
@primary_keys = {}
-
2
@tables = {}
-
2
prepare_default_proc
-
end
-
-
2
def primary_keys(table_name)
-
9
@primary_keys[table_name]
-
end
-
-
# A cached lookup for table existence.
-
2
def table_exists?(name)
-
215
return @tables[name] if @tables.key? name
-
-
9
@tables[name] = connection.table_exists?(name)
-
end
-
-
# Add internal cache for table with +table_name+.
-
2
def add(table_name)
-
if table_exists?(table_name)
-
@primary_keys[table_name]
-
@columns[table_name]
-
@columns_hash[table_name]
-
end
-
end
-
-
2
def tables(name)
-
@tables[name]
-
end
-
-
# Get the columns for a table
-
2
def columns(table)
-
15
@columns[table]
-
end
-
-
# Get the columns for a table as a hash, key is the column name
-
# value is the column object.
-
2
def columns_hash(table)
-
341
@columns_hash[table]
-
end
-
-
# Clears out internal caches
-
2
def clear!
-
@columns.clear
-
@columns_hash.clear
-
@primary_keys.clear
-
@tables.clear
-
@version = nil
-
end
-
-
2
def size
-
[@columns, @columns_hash, @primary_keys, @tables].map { |x|
-
x.size
-
}.inject :+
-
end
-
-
# Clear out internal caches for table with +table_name+.
-
2
def clear_table_cache!(table_name)
-
@columns.delete table_name
-
@columns_hash.delete table_name
-
@primary_keys.delete table_name
-
@tables.delete table_name
-
end
-
-
2
def marshal_dump
-
# if we get current version during initialization, it happens stack over flow.
-
@version = ActiveRecord::Migrator.current_version
-
[@version] + [@columns, @columns_hash, @primary_keys, @tables].map { |val|
-
Hash[val]
-
}
-
end
-
-
2
def marshal_load(array)
-
@version, @columns, @columns_hash, @primary_keys, @tables = array
-
prepare_default_proc
-
end
-
-
2
private
-
-
2
def prepare_default_proc
-
2
@columns.default_proc = Proc.new do |h, table_name|
-
10
h[table_name] = connection.columns(table_name)
-
end
-
-
2
@columns_hash.default_proc = Proc.new do |h, table_name|
-
4
h[table_name] = Hash[columns(table_name).map { |col|
-
57
[col.name, col]
-
}]
-
end
-
-
2
@primary_keys.default_proc = Proc.new do |h, table_name|
-
9
h[table_name] = table_exists?(table_name) ? connection.primary_key(table_name) : nil
-
end
-
end
-
end
-
end
-
end
-
2
require 'active_record/connection_adapters/abstract_adapter'
-
2
require 'active_record/connection_adapters/statement_pool'
-
2
require 'arel/visitors/bind_visitor'
-
-
2
gem 'sqlite3', '~> 1.3.6'
-
2
require 'sqlite3'
-
-
2
module ActiveRecord
-
2
module ConnectionHandling # :nodoc:
-
# sqlite3 adapter reuses sqlite_connection.
-
2
def sqlite3_connection(config)
-
# Require database.
-
2
unless config[:database]
-
raise ArgumentError, "No database file specified. Missing argument: database"
-
end
-
-
# Allow database path relative to Rails.root, but only if
-
# the database path is not the special path that tells
-
# Sqlite to build a database only in memory.
-
2
if ':memory:' != config[:database]
-
2
config[:database] = File.expand_path(config[:database], Rails.root) if defined?(Rails.root)
-
2
dirname = File.dirname(config[:database])
-
2
Dir.mkdir(dirname) unless File.directory?(dirname)
-
end
-
-
2
db = SQLite3::Database.new(
-
config[:database].to_s,
-
:results_as_hash => true
-
)
-
-
2
db.busy_timeout(ConnectionAdapters::SQLite3Adapter.type_cast_config_to_integer(config[:timeout])) if config[:timeout]
-
-
2
ConnectionAdapters::SQLite3Adapter.new(db, logger, config)
-
rescue Errno::ENOENT => error
-
if error.message.include?("No such file or directory")
-
raise ActiveRecord::NoDatabaseError.new(error.message)
-
else
-
raise error
-
end
-
end
-
end
-
-
2
module ConnectionAdapters #:nodoc:
-
2
class SQLite3Column < Column #:nodoc:
-
2
class << self
-
2
def binary_to_string(value)
-
if value.encoding != Encoding::ASCII_8BIT
-
value = value.force_encoding(Encoding::ASCII_8BIT)
-
end
-
value
-
end
-
end
-
end
-
-
# The SQLite3 adapter works SQLite 3.6.16 or newer
-
# with the sqlite3-ruby drivers (available as gem from https://rubygems.org/gems/sqlite3).
-
#
-
# Options:
-
#
-
# * <tt>:database</tt> - Path to the database file.
-
2
class SQLite3Adapter < AbstractAdapter
-
2
include Savepoints
-
-
2
NATIVE_DATABASE_TYPES = {
-
primary_key: 'INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL',
-
string: { name: "varchar", limit: 255 },
-
text: { name: "text" },
-
integer: { name: "integer" },
-
float: { name: "float" },
-
decimal: { name: "decimal" },
-
datetime: { name: "datetime" },
-
timestamp: { name: "datetime" },
-
time: { name: "time" },
-
date: { name: "date" },
-
binary: { name: "blob" },
-
boolean: { name: "boolean" }
-
}
-
-
2
class Version
-
2
include Comparable
-
-
2
def initialize(version_string)
-
@version = version_string.split('.').map { |v| v.to_i }
-
end
-
-
2
def <=>(version_string)
-
@version <=> version_string.split('.').map { |v| v.to_i }
-
end
-
end
-
-
2
class StatementPool < ConnectionAdapters::StatementPool
-
2
def initialize(connection, max)
-
2
super
-
4
@cache = Hash.new { |h,pid| h[pid] = {} }
-
end
-
-
2
def each(&block); cache.each(&block); end
-
2
def key?(key); cache.key?(key); end
-
269
def [](key); cache[key]; end
-
2
def length; cache.length; end
-
-
2
def []=(sql, key)
-
5
while @max <= cache.size
-
dealloc(cache.shift.last[:stmt])
-
end
-
5
cache[sql] = key
-
end
-
-
2
def clear
-
cache.values.each do |hash|
-
dealloc hash[:stmt]
-
end
-
cache.clear
-
end
-
-
2
private
-
2
def cache
-
277
@cache[$$]
-
end
-
-
2
def dealloc(stmt)
-
stmt.close unless stmt.closed?
-
end
-
end
-
-
2
class BindSubstitution < Arel::Visitors::SQLite # :nodoc:
-
2
include Arel::Visitors::BindVisitor
-
end
-
-
2
def initialize(connection, logger, config)
-
2
super(connection, logger)
-
-
2
@active = nil
-
2
@statements = StatementPool.new(@connection,
-
2
self.class.type_cast_config_to_integer(config.fetch(:statement_limit) { 1000 }))
-
2
@config = config
-
-
4
if self.class.type_cast_config_to_boolean(config.fetch(:prepared_statements) { true })
-
2
@prepared_statements = true
-
2
@visitor = Arel::Visitors::SQLite.new self
-
else
-
@visitor = unprepared_visitor
-
end
-
end
-
-
2
def adapter_name #:nodoc:
-
'SQLite'
-
end
-
-
2
def supports_ddl_transactions?
-
true
-
end
-
-
2
def supports_savepoints?
-
true
-
end
-
-
2
def supports_partial_index?
-
sqlite_version >= '3.8.0'
-
end
-
-
# Returns true, since this connection adapter supports prepared statement
-
# caching.
-
2
def supports_statement_cache?
-
true
-
end
-
-
# Returns true, since this connection adapter supports migrations.
-
2
def supports_migrations? #:nodoc:
-
true
-
end
-
-
2
def supports_primary_key? #:nodoc:
-
true
-
end
-
-
2
def requires_reloading?
-
true
-
end
-
-
2
def supports_add_column?
-
true
-
end
-
-
2
def active?
-
22
@active != false
-
end
-
-
# Disconnects from the database if already connected. Otherwise, this
-
# method does nothing.
-
2
def disconnect!
-
super
-
@active = false
-
@connection.close rescue nil
-
end
-
-
# Clears the prepared statements cache.
-
2
def clear_cache!
-
@statements.clear
-
end
-
-
2
def supports_index_sort_order?
-
true
-
end
-
-
# Returns 62. SQLite supports index names up to 64
-
# characters. The rest is used by rails internally to perform
-
# temporary rename operations
-
2
def allowed_index_name_length
-
index_name_length - 2
-
end
-
-
2
def native_database_types #:nodoc:
-
NATIVE_DATABASE_TYPES
-
end
-
-
# Returns the current database encoding format as a string, eg: 'UTF-8'
-
2
def encoding
-
@connection.encoding.to_s
-
end
-
-
2
def supports_explain?
-
true
-
end
-
-
# QUOTING ==================================================
-
-
2
def quote(value, column = nil)
-
197
if value.kind_of?(String) && column && column.type == :binary
-
s = value.unpack("H*")[0]
-
"x'#{s}'"
-
else
-
197
super
-
end
-
end
-
-
2
def quote_string(s) #:nodoc:
-
197
@connection.class.quote(s)
-
end
-
-
2
def quote_table_name_for_assignment(table, attr)
-
quote_column_name(attr)
-
end
-
-
2
def quote_column_name(name) #:nodoc:
-
54
%Q("#{name.to_s.gsub('"', '""')}")
-
end
-
-
# Quote date/time values for use in SQL input. Includes microseconds
-
# if the value is a Time responding to usec.
-
2
def quoted_date(value) #:nodoc:
-
534
if value.respond_to?(:usec)
-
534
"#{super}.#{sprintf("%06d", value.usec)}"
-
else
-
super
-
end
-
end
-
-
2
def type_cast(value, column) # :nodoc:
-
1600
return value.to_f if BigDecimal === value
-
1600
return super unless String === value
-
990
return super unless column && value
-
-
990
value = super
-
990
if column.type == :string && value.encoding == Encoding::ASCII_8BIT
-
193
logger.error "Binary data inserted for `string` type on column `#{column.name}`" if logger
-
193
value = value.encode Encoding::UTF_8
-
end
-
990
value
-
end
-
-
# DATABASE STATEMENTS ======================================
-
-
2
def explain(arel, binds = [])
-
sql = "EXPLAIN QUERY PLAN #{to_sql(arel, binds)}"
-
ExplainPrettyPrinter.new.pp(exec_query(sql, 'EXPLAIN', binds))
-
end
-
-
2
class ExplainPrettyPrinter
-
# Pretty prints the result of a EXPLAIN QUERY PLAN in a way that resembles
-
# the output of the SQLite shell:
-
#
-
# 0|0|0|SEARCH TABLE users USING INTEGER PRIMARY KEY (rowid=?) (~1 rows)
-
# 0|1|1|SCAN TABLE posts (~100000 rows)
-
#
-
2
def pp(result) # :nodoc:
-
result.rows.map do |row|
-
row.join('|')
-
end.join("\n") + "\n"
-
end
-
end
-
-
2
def exec_query(sql, name = nil, binds = [])
-
507
type_casted_binds = binds.map { |col, val|
-
1405
[col, type_cast(val, col)]
-
}
-
-
507
log(sql, name, type_casted_binds) do
-
# Don't cache statements if they are not prepared
-
507
if without_prepared_statement?(binds)
-
240
stmt = @connection.prepare(sql)
-
240
begin
-
240
cols = stmt.columns
-
240
records = stmt.to_a
-
ensure
-
240
stmt.close
-
end
-
240
stmt = records
-
else
-
267
cache = @statements[sql] ||= {
-
:stmt => @connection.prepare(sql)
-
}
-
267
stmt = cache[:stmt]
-
267
cols = cache[:cols] ||= stmt.columns
-
267
stmt.reset!
-
1672
stmt.bind_params type_casted_binds.map { |_, val| val }
-
end
-
-
507
ActiveRecord::Result.new(cols, stmt.to_a)
-
end
-
end
-
-
2
def exec_delete(sql, name = 'SQL', binds = [])
-
exec_query(sql, name, binds)
-
@connection.changes
-
end
-
2
alias :exec_update :exec_delete
-
-
2
def last_inserted_id(result)
-
267
@connection.last_insert_row_id
-
end
-
-
2
def execute(sql, name = nil) #:nodoc:
-
788
log(sql, name) { @connection.execute(sql) }
-
end
-
-
2
def update_sql(sql, name = nil) #:nodoc:
-
super
-
@connection.changes
-
end
-
-
2
def delete_sql(sql, name = nil) #:nodoc:
-
sql += " WHERE 1=1" unless sql =~ /WHERE/i
-
super sql, name
-
end
-
-
2
def insert_sql(sql, name = nil, pk = nil, id_value = nil, sequence_name = nil) #:nodoc:
-
super
-
id_value || @connection.last_insert_row_id
-
end
-
2
alias :create :insert_sql
-
-
2
def select_rows(sql, name = nil, binds = [])
-
exec_query(sql, name, binds).rows
-
end
-
-
2
def begin_db_transaction #:nodoc:
-
66
log('begin transaction',nil) { @connection.transaction }
-
end
-
-
2
def commit_db_transaction #:nodoc:
-
12
log('commit transaction',nil) { @connection.commit }
-
end
-
-
2
def rollback_db_transaction #:nodoc:
-
54
log('rollback transaction',nil) { @connection.rollback }
-
end
-
-
# SCHEMA STATEMENTS ========================================
-
-
2
def tables(name = nil, table_name = nil) #:nodoc:
-
10
sql = <<-SQL
-
SELECT name
-
FROM sqlite_master
-
WHERE type = 'table' AND NOT name = 'sqlite_sequence'
-
SQL
-
10
sql << " AND name = #{quote_table_name(table_name)}" if table_name
-
-
10
exec_query(sql, 'SCHEMA').map do |row|
-
10
row['name']
-
end
-
end
-
-
2
def table_exists?(table_name)
-
10
table_name && tables(nil, table_name).any?
-
end
-
-
# Returns an array of +SQLite3Column+ objects for the table specified by +table_name+.
-
2
def columns(table_name) #:nodoc:
-
10
table_structure(table_name).map do |field|
-
100
case field["dflt_value"]
-
when /^null$/i
-
field["dflt_value"] = nil
-
when /^'(.*)'$/m
-
field["dflt_value"] = $1.gsub("''", "'")
-
when /^"(.*)"$/m
-
field["dflt_value"] = $1.gsub('""', '"')
-
end
-
-
100
SQLite3Column.new(field['name'], field['dflt_value'], field['type'], field['notnull'].to_i == 0)
-
end
-
end
-
-
# Returns an array of indexes for the given table.
-
2
def indexes(table_name, name = nil) #:nodoc:
-
exec_query("PRAGMA index_list(#{quote_table_name(table_name)})", 'SCHEMA').map do |row|
-
sql = <<-SQL
-
SELECT sql
-
FROM sqlite_master
-
WHERE name=#{quote(row['name'])} AND type='index'
-
UNION ALL
-
SELECT sql
-
FROM sqlite_temp_master
-
WHERE name=#{quote(row['name'])} AND type='index'
-
SQL
-
index_sql = exec_query(sql).first['sql']
-
match = /\sWHERE\s+(.+)$/i.match(index_sql)
-
where = match[1] if match
-
IndexDefinition.new(
-
table_name,
-
row['name'],
-
row['unique'] != 0,
-
exec_query("PRAGMA index_info('#{row['name']}')", "SCHEMA").map { |col|
-
col['name']
-
}, nil, nil, where)
-
end
-
end
-
-
2
def primary_key(table_name) #:nodoc:
-
9
column = table_structure(table_name).find { |field|
-
9
field['pk'] == 1
-
}
-
9
column && column['name']
-
end
-
-
2
def remove_index!(table_name, index_name) #:nodoc:
-
exec_query "DROP INDEX #{quote_column_name(index_name)}"
-
end
-
-
# Renames a table.
-
#
-
# Example:
-
# rename_table('octopuses', 'octopi')
-
2
def rename_table(table_name, new_name)
-
exec_query "ALTER TABLE #{quote_table_name(table_name)} RENAME TO #{quote_table_name(new_name)}"
-
rename_table_indexes(table_name, new_name)
-
end
-
-
# See: http://www.sqlite.org/lang_altertable.html
-
# SQLite has an additional restriction on the ALTER TABLE statement
-
2
def valid_alter_table_options( type, options)
-
type.to_sym != :primary_key
-
end
-
-
2
def add_column(table_name, column_name, type, options = {}) #:nodoc:
-
if supports_add_column? && valid_alter_table_options( type, options )
-
super(table_name, column_name, type, options)
-
else
-
alter_table(table_name) do |definition|
-
definition.column(column_name, type, options)
-
end
-
end
-
end
-
-
2
def remove_column(table_name, column_name, type = nil, options = {}) #:nodoc:
-
alter_table(table_name) do |definition|
-
definition.remove_column column_name
-
end
-
end
-
-
2
def change_column_default(table_name, column_name, default) #:nodoc:
-
alter_table(table_name) do |definition|
-
definition[column_name].default = default
-
end
-
end
-
-
2
def change_column_null(table_name, column_name, null, default = nil)
-
unless null || default.nil?
-
exec_query("UPDATE #{quote_table_name(table_name)} SET #{quote_column_name(column_name)}=#{quote(default)} WHERE #{quote_column_name(column_name)} IS NULL")
-
end
-
alter_table(table_name) do |definition|
-
definition[column_name].null = null
-
end
-
end
-
-
2
def change_column(table_name, column_name, type, options = {}) #:nodoc:
-
alter_table(table_name) do |definition|
-
include_default = options_include_default?(options)
-
definition[column_name].instance_eval do
-
self.type = type
-
self.limit = options[:limit] if options.include?(:limit)
-
self.default = options[:default] if include_default
-
self.null = options[:null] if options.include?(:null)
-
self.precision = options[:precision] if options.include?(:precision)
-
self.scale = options[:scale] if options.include?(:scale)
-
end
-
end
-
end
-
-
2
def rename_column(table_name, column_name, new_column_name) #:nodoc:
-
unless columns(table_name).detect{|c| c.name == column_name.to_s }
-
raise ActiveRecord::ActiveRecordError, "Missing column #{table_name}.#{column_name}"
-
end
-
alter_table(table_name, :rename => {column_name.to_s => new_column_name.to_s})
-
rename_column_indexes(table_name, column_name, new_column_name)
-
end
-
-
2
protected
-
2
def select(sql, name = nil, binds = []) #:nodoc:
-
211
exec_query(sql, name, binds)
-
end
-
-
2
def table_structure(table_name)
-
19
structure = exec_query("PRAGMA table_info(#{quote_table_name(table_name)})", 'SCHEMA').to_hash
-
19
raise(ActiveRecord::StatementInvalid, "Could not find table '#{table_name}'") if structure.empty?
-
19
structure
-
end
-
-
2
def alter_table(table_name, options = {}) #:nodoc:
-
altered_table_name = "a#{table_name}"
-
caller = lambda {|definition| yield definition if block_given?}
-
-
transaction do
-
move_table(table_name, altered_table_name,
-
options.merge(:temporary => true))
-
move_table(altered_table_name, table_name, &caller)
-
end
-
end
-
-
2
def move_table(from, to, options = {}, &block) #:nodoc:
-
copy_table(from, to, options, &block)
-
drop_table(from)
-
end
-
-
2
def copy_table(from, to, options = {}) #:nodoc:
-
from_primary_key = primary_key(from)
-
options[:id] = false
-
create_table(to, options) do |definition|
-
@definition = definition
-
@definition.primary_key(from_primary_key) if from_primary_key.present?
-
columns(from).each do |column|
-
column_name = options[:rename] ?
-
(options[:rename][column.name] ||
-
options[:rename][column.name.to_sym] ||
-
column.name) : column.name
-
next if column_name == from_primary_key
-
-
@definition.column(column_name, column.type,
-
:limit => column.limit, :default => column.default,
-
:precision => column.precision, :scale => column.scale,
-
:null => column.null)
-
end
-
yield @definition if block_given?
-
end
-
copy_table_indexes(from, to, options[:rename] || {})
-
copy_table_contents(from, to,
-
@definition.columns.map {|column| column.name},
-
options[:rename] || {})
-
end
-
-
2
def copy_table_indexes(from, to, rename = {}) #:nodoc:
-
indexes(from).each do |index|
-
name = index.name
-
if to == "a#{from}"
-
name = "t#{name}"
-
elsif from == "a#{to}"
-
name = name[1..-1]
-
end
-
-
to_column_names = columns(to).map { |c| c.name }
-
columns = index.columns.map {|c| rename[c] || c }.select do |column|
-
to_column_names.include?(column)
-
end
-
-
unless columns.empty?
-
# index name can't be the same
-
opts = { name: name.gsub(/(^|_)(#{from})_/, "\\1#{to}_"), internal: true }
-
opts[:unique] = true if index.unique
-
add_index(to, columns, opts)
-
end
-
end
-
end
-
-
2
def copy_table_contents(from, to, columns, rename = {}) #:nodoc:
-
column_mappings = Hash[columns.map {|name| [name, name]}]
-
rename.each { |a| column_mappings[a.last] = a.first }
-
from_columns = columns(from).collect {|col| col.name}
-
columns = columns.find_all{|col| from_columns.include?(column_mappings[col])}
-
quoted_columns = columns.map { |col| quote_column_name(col) } * ','
-
-
quoted_to = quote_table_name(to)
-
-
raw_column_mappings = Hash[columns(from).map { |c| [c.name, c] }]
-
-
exec_query("SELECT * FROM #{quote_table_name(from)}").each do |row|
-
sql = "INSERT INTO #{quoted_to} (#{quoted_columns}) VALUES ("
-
-
column_values = columns.map do |col|
-
quote(row[column_mappings[col]], raw_column_mappings[col])
-
end
-
-
sql << column_values * ', '
-
sql << ')'
-
exec_query sql
-
end
-
end
-
-
2
def sqlite_version
-
@sqlite_version ||= SQLite3Adapter::Version.new(select_value('select sqlite_version(*)'))
-
end
-
-
2
def translate_exception(exception, message)
-
case exception.message
-
# SQLite 3.8.2 returns a newly formatted error message:
-
# UNIQUE constraint failed: *table_name*.*column_name*
-
# Older versions of SQLite return:
-
# column *column_name* is not unique
-
when /column(s)? .* (is|are) not unique/, /UNIQUE constraint failed: .*/
-
RecordNotUnique.new(message, exception)
-
else
-
super
-
end
-
end
-
end
-
end
-
end
-
2
module ActiveRecord
-
2
module ConnectionAdapters
-
2
class StatementPool
-
2
include Enumerable
-
-
2
def initialize(connection, max = 1000)
-
2
@connection = connection
-
2
@max = max
-
end
-
-
2
def each
-
raise NotImplementedError
-
end
-
-
2
def key?(key)
-
raise NotImplementedError
-
end
-
-
2
def [](key)
-
raise NotImplementedError
-
end
-
-
2
def length
-
raise NotImplementedError
-
end
-
-
2
def []=(sql, key)
-
raise NotImplementedError
-
end
-
-
2
def clear
-
raise NotImplementedError
-
end
-
-
2
def delete(key)
-
raise NotImplementedError
-
end
-
end
-
end
-
end
-
2
module ActiveRecord
-
2
module ConnectionHandling
-
8
RAILS_ENV = -> { (Rails.env if defined?(Rails)) || ENV["RAILS_ENV"] || ENV["RACK_ENV"] }
-
8
DEFAULT_ENV = -> { RAILS_ENV.call || "default_env" }
-
-
# Establishes the connection to the database. Accepts a hash as input where
-
# the <tt>:adapter</tt> key must be specified with the name of a database adapter (in lower-case)
-
# example for regular databases (MySQL, Postgresql, etc):
-
#
-
# ActiveRecord::Base.establish_connection(
-
# adapter: "mysql",
-
# host: "localhost",
-
# username: "myuser",
-
# password: "mypass",
-
# database: "somedatabase"
-
# )
-
#
-
# Example for SQLite database:
-
#
-
# ActiveRecord::Base.establish_connection(
-
# adapter: "sqlite3",
-
# database: "path/to/dbfile"
-
# )
-
#
-
# Also accepts keys as strings (for parsing from YAML for example):
-
#
-
# ActiveRecord::Base.establish_connection(
-
# "adapter" => "sqlite3",
-
# "database" => "path/to/dbfile"
-
# )
-
#
-
# Or a URL:
-
#
-
# ActiveRecord::Base.establish_connection(
-
# "postgres://myuser:mypass@localhost/somedatabase"
-
# )
-
#
-
# In case <tt>ActiveRecord::Base.configurations</tt> is set (Rails
-
# automatically loads the contents of config/database.yml into it),
-
# a symbol can also be given as argument, representing a key in the
-
# configuration hash:
-
#
-
# ActiveRecord::Base.establish_connection(:production)
-
#
-
# The exceptions AdapterNotSpecified, AdapterNotFound and ArgumentError
-
# may be returned on an error.
-
2
def establish_connection(spec = nil)
-
2
spec ||= DEFAULT_ENV.call.to_sym
-
2
resolver = ConnectionAdapters::ConnectionSpecification::Resolver.new configurations
-
2
spec = resolver.spec(spec)
-
-
2
unless respond_to?(spec.adapter_method)
-
raise AdapterNotFound, "database configuration specifies nonexistent #{spec.config[:adapter]} adapter"
-
end
-
-
2
remove_connection
-
2
connection_handler.establish_connection self, spec
-
end
-
-
2
class MergeAndResolveDefaultUrlConfig # :nodoc:
-
2
def initialize(raw_configurations)
-
4
@raw_config = raw_configurations.dup
-
4
@env = DEFAULT_ENV.call.to_s
-
end
-
-
# Returns fully resolved connection hashes.
-
# Merges connection information from `ENV['DATABASE_URL']` if available.
-
2
def resolve
-
4
ConnectionAdapters::ConnectionSpecification::Resolver.new(config).resolve_all
-
end
-
-
2
private
-
2
def config
-
4
@raw_config.dup.tap do |cfg|
-
4
if url = ENV['DATABASE_URL']
-
cfg[@env] ||= {}
-
cfg[@env]["url"] ||= url
-
end
-
end
-
end
-
end
-
-
# Returns the connection currently associated with the class. This can
-
# also be used to "borrow" the connection to do database work unrelated
-
# to any of the specific Active Records.
-
2
def connection
-
73
retrieve_connection
-
end
-
-
2
def connection_id
-
4401
ActiveRecord::RuntimeRegistry.connection_id
-
end
-
-
2
def connection_id=(connection_id)
-
15
ActiveRecord::RuntimeRegistry.connection_id = connection_id
-
end
-
-
# Returns the configuration of the associated connection as a hash:
-
#
-
# ActiveRecord::Base.connection_config
-
# # => {pool: 5, timeout: 5000, database: "db/development.sqlite3", adapter: "sqlite3"}
-
#
-
# Please use only for reading.
-
2
def connection_config
-
connection_pool.spec.config
-
end
-
-
2
def connection_pool
-
6
connection_handler.retrieve_connection_pool(self) or raise ConnectionNotEstablished
-
end
-
-
2
def retrieve_connection
-
4303
connection_handler.retrieve_connection(self)
-
end
-
-
# Returns +true+ if Active Record is connected.
-
2
def connected?
-
50
connection_handler.connected?(self)
-
end
-
-
2
def remove_connection(klass = self)
-
2
connection_handler.remove_connection(klass)
-
end
-
-
2
def clear_cache! # :nodoc:
-
connection.schema_cache.clear!
-
end
-
-
2
delegate :clear_active_connections!, :clear_reloadable_connections!,
-
:clear_all_connections!, :to => :connection_handler
-
end
-
end
-
2
require 'active_support/core_ext/hash/indifferent_access'
-
2
require 'active_support/core_ext/object/duplicable'
-
2
require 'thread'
-
-
2
module ActiveRecord
-
2
module Core
-
2
extend ActiveSupport::Concern
-
-
2
included do
-
##
-
# :singleton-method:
-
#
-
# Accepts a logger conforming to the interface of Log4r which is then
-
# passed on to any new database connections made and which can be
-
# retrieved on both a class and instance level by calling +logger+.
-
2
mattr_accessor :logger, instance_writer: false
-
-
##
-
# :singleton-method:
-
# Contains the database configuration - as is typically stored in config/database.yml -
-
# as a Hash.
-
#
-
# For example, the following database.yml...
-
#
-
# development:
-
# adapter: sqlite3
-
# database: db/development.sqlite3
-
#
-
# production:
-
# adapter: sqlite3
-
# database: db/production.sqlite3
-
#
-
# ...would result in ActiveRecord::Base.configurations to look like this:
-
#
-
# {
-
# 'development' => {
-
# 'adapter' => 'sqlite3',
-
# 'database' => 'db/development.sqlite3'
-
# },
-
# 'production' => {
-
# 'adapter' => 'sqlite3',
-
# 'database' => 'db/production.sqlite3'
-
# }
-
# }
-
2
def self.configurations=(config)
-
4
@@configurations = ActiveRecord::ConnectionHandling::MergeAndResolveDefaultUrlConfig.new(config).resolve
-
end
-
2
self.configurations = {}
-
-
# Returns fully resolved configurations hash
-
2
def self.configurations
-
2
@@configurations
-
end
-
-
##
-
# :singleton-method:
-
# Determines whether to use Time.utc (using :utc) or Time.local (using :local) when pulling
-
# dates and times from the database. This is set to :utc by default.
-
2
mattr_accessor :default_timezone, instance_writer: false
-
2
self.default_timezone = :utc
-
-
##
-
# :singleton-method:
-
# Specifies the format to use when dumping the database schema with Rails'
-
# Rakefile. If :sql, the schema is dumped as (potentially database-
-
# specific) SQL statements. If :ruby, the schema is dumped as an
-
# ActiveRecord::Schema file which can be loaded into any database that
-
# supports migrations. Use :ruby if you want to have different database
-
# adapters for, e.g., your development and test environments.
-
2
mattr_accessor :schema_format, instance_writer: false
-
2
self.schema_format = :ruby
-
-
##
-
# :singleton-method:
-
# Specify whether or not to use timestamps for migration versions
-
2
mattr_accessor :timestamped_migrations, instance_writer: false
-
2
self.timestamped_migrations = true
-
-
##
-
# :singleton-method:
-
# Specify whether schema dump should happen at the end of the
-
# db:migrate rake task. This is true by default, which is useful for the
-
# development environment. This should ideally be false in the production
-
# environment where dumping schema is rarely needed.
-
2
mattr_accessor :dump_schema_after_migration, instance_writer: false
-
2
self.dump_schema_after_migration = true
-
-
# :nodoc:
-
2
mattr_accessor :maintain_test_schema, instance_accessor: false
-
-
2
def self.disable_implicit_join_references=(value)
-
ActiveSupport::Deprecation.warn("Implicit join references were removed with Rails 4.1." \
-
"Make sure to remove this configuration because it does nothing.")
-
end
-
-
2
class_attribute :default_connection_handler, instance_writer: false
-
-
2
def self.connection_handler
-
4417
ActiveRecord::RuntimeRegistry.connection_handler || default_connection_handler
-
end
-
-
2
def self.connection_handler=(handler)
-
ActiveRecord::RuntimeRegistry.connection_handler = handler
-
end
-
-
2
self.default_connection_handler = ConnectionAdapters::ConnectionHandler.new
-
end
-
-
2
module ClassMethods
-
2
def initialize_generated_modules
-
15
generated_association_methods
-
end
-
-
2
def generated_association_methods
-
@generated_association_methods ||= begin
-
15
mod = const_set(:GeneratedAssociationMethods, Module.new)
-
15
include mod
-
15
mod
-
64
end
-
end
-
-
# Returns a string like 'Post(id:integer, title:string, body:text)'
-
2
def inspect
-
if self == Base
-
super
-
elsif abstract_class?
-
"#{super}(abstract)"
-
elsif !connected?
-
"#{super} (call '#{super}.connection' to establish a connection)"
-
elsif table_exists?
-
attr_list = columns.map { |c| "#{c.name}: #{c.type}" } * ', '
-
"#{super}(#{attr_list})"
-
else
-
"#{super}(Table doesn't exist)"
-
end
-
end
-
-
# Overwrite the default class equality method to provide support for association proxies.
-
2
def ===(object)
-
210
object.is_a?(self)
-
end
-
-
# Returns an instance of <tt>Arel::Table</tt> loaded with the current table name.
-
#
-
# class Post < ActiveRecord::Base
-
# scope :published_and_commented, -> { published.and(self.arel_table[:comments_count].gt(0)) }
-
# end
-
2
def arel_table # :nodoc:
-
1826
@arel_table ||= Arel::Table.new(table_name, arel_engine)
-
end
-
-
# Returns the Arel engine.
-
2
def arel_engine # :nodoc:
-
@arel_engine ||=
-
if Base == self || connection_handler.retrieve_connection_pool(self)
-
12
self
-
else
-
superclass.arel_engine
-
13
end
-
end
-
-
2
private
-
-
2
def relation #:nodoc:
-
854
relation = Relation.create(self, arel_table)
-
-
854
if finder_needs_type_condition?
-
relation.where(type_condition).create_with(inheritance_column.to_sym => sti_name)
-
else
-
854
relation
-
end
-
end
-
end
-
-
# New objects can be instantiated as either empty (pass no construction parameter) or pre-set with
-
# attributes but not yet saved (pass a hash with key names matching the associated table column names).
-
# In both instances, valid attribute keys are determined by the column names of the associated table --
-
# hence you can't have attributes that aren't part of the table columns.
-
#
-
# ==== Example:
-
# # Instantiates a single new object
-
# User.new(first_name: 'Jamie')
-
2
def initialize(attributes = nil, options = {})
-
279
defaults = self.class.column_defaults.dup
-
4131
defaults.each { |k, v| defaults[k] = v.dup if v.duplicable? }
-
-
279
@attributes = self.class.initialize_attributes(defaults)
-
279
@column_types_override = nil
-
279
@column_types = self.class.column_types
-
-
279
init_internals
-
279
initialize_internals_callback
-
-
# +options+ argument is only needed to make protected_attributes gem easier to hook.
-
# Remove it when we drop support to this gem.
-
279
init_attributes(attributes, options) if attributes
-
-
279
yield self if block_given?
-
279
run_callbacks :initialize unless _initialize_callbacks.empty?
-
end
-
-
# Initialize an empty model object from +coder+. +coder+ must contain
-
# the attributes necessary for initializing an empty model object. For
-
# example:
-
#
-
# class Post < ActiveRecord::Base
-
# end
-
#
-
# post = Post.allocate
-
# post.init_with('attributes' => { 'title' => 'hello world' })
-
# post.title # => 'hello world'
-
2
def init_with(coder)
-
32
@attributes = self.class.initialize_attributes(coder['attributes'])
-
32
@column_types_override = coder['column_types']
-
32
@column_types = self.class.column_types
-
-
32
init_internals
-
-
32
@new_record = false
-
-
32
self.class.define_attribute_methods
-
-
32
run_callbacks :find
-
32
run_callbacks :initialize
-
-
32
self
-
end
-
-
##
-
# :method: clone
-
# Identical to Ruby's clone method. This is a "shallow" copy. Be warned that your attributes are not copied.
-
# That means that modifying attributes of the clone will modify the original, since they will both point to the
-
# same attributes hash. If you need a copy of your attributes hash, please use the #dup method.
-
#
-
# user = User.first
-
# new_user = user.clone
-
# user.name # => "Bob"
-
# new_user.name = "Joe"
-
# user.name # => "Joe"
-
#
-
# user.object_id == new_user.object_id # => false
-
# user.name.object_id == new_user.name.object_id # => true
-
#
-
# user.name.object_id == user.dup.name.object_id # => false
-
-
##
-
# :method: dup
-
# Duped objects have no id assigned and are treated as new records. Note
-
# that this is a "shallow" copy as it copies the object's attributes
-
# only, not its associations. The extent of a "deep" copy is application
-
# specific and is therefore left to the application to implement according
-
# to its need.
-
# The dup method does not preserve the timestamps (created|updated)_(at|on).
-
-
##
-
2
def initialize_dup(other) # :nodoc:
-
cloned_attributes = other.clone_attributes(:read_attribute_before_type_cast)
-
self.class.initialize_attributes(cloned_attributes, :serialized => false)
-
-
@attributes = cloned_attributes
-
@attributes[self.class.primary_key] = nil
-
-
run_callbacks(:initialize) unless _initialize_callbacks.empty?
-
-
@aggregation_cache = {}
-
@association_cache = {}
-
@attributes_cache = {}
-
-
@new_record = true
-
@destroyed = false
-
-
super
-
end
-
-
# Populate +coder+ with attributes about this record that should be
-
# serialized. The structure of +coder+ defined in this method is
-
# guaranteed to match the structure of +coder+ passed to the +init_with+
-
# method.
-
#
-
# Example:
-
#
-
# class Post < ActiveRecord::Base
-
# end
-
# coder = {}
-
# Post.new.encode_with(coder)
-
# coder # => {"attributes" => {"id" => nil, ... }}
-
2
def encode_with(coder)
-
coder['attributes'] = attributes_for_coder
-
end
-
-
# Returns true if +comparison_object+ is the same exact object, or +comparison_object+
-
# is of the same type and +self+ has an ID and it is equal to +comparison_object.id+.
-
#
-
# Note that new records are different from any other record by definition, unless the
-
# other record is the receiver itself. Besides, if you fetch existing records with
-
# +select+ and leave the ID out, you're on your own, this predicate will return false.
-
#
-
# Note also that destroying a record preserves its ID in the model instance, so deleted
-
# models are still comparable.
-
2
def ==(comparison_object)
-
super ||
-
comparison_object.instance_of?(self.class) &&
-
!id.nil? &&
-
144
comparison_object.id == id
-
end
-
2
alias :eql? :==
-
-
# Delegates to id in order to allow two records of the same type and id to work with something like:
-
# [ Person.find(1), Person.find(2), Person.find(3) ] & [ Person.find(1), Person.find(4) ] # => [ Person.find(1) ]
-
2
def hash
-
378
id.hash
-
end
-
-
# Clone and freeze the attributes hash such that associations are still
-
# accessible, even on destroyed records, but cloned models will not be
-
# frozen.
-
2
def freeze
-
@attributes = @attributes.clone.freeze
-
self
-
end
-
-
# Returns +true+ if the attributes hash has been frozen.
-
2
def frozen?
-
1749
@attributes.frozen?
-
end
-
-
# Allows sort on objects
-
2
def <=>(other_object)
-
if other_object.is_a?(self.class)
-
self.to_key <=> other_object.to_key
-
else
-
super
-
end
-
end
-
-
# Returns +true+ if the record is read only. Records loaded through joins with piggy-back
-
# attributes will be marked as read only since they cannot be saved.
-
2
def readonly?
-
267
@readonly
-
end
-
-
# Marks this record as read only.
-
2
def readonly!
-
@readonly = true
-
end
-
-
2
def connection_handler
-
self.class.connection_handler
-
end
-
-
# Returns the contents of the record as a nicely formatted string.
-
2
def inspect
-
# We check defined?(@attributes) not to issue warnings if the object is
-
# allocated but not initialized.
-
inspection = if defined?(@attributes) && @attributes
-
self.class.column_names.collect { |name|
-
if has_attribute?(name)
-
"#{name}: #{attribute_for_inspect(name)}"
-
end
-
}.compact.join(", ")
-
else
-
"not initialized"
-
end
-
"#<#{self.class} #{inspection}>"
-
end
-
-
# Returns a hash of the given methods with their names as keys and returned values as values.
-
2
def slice(*methods)
-
Hash[methods.map! { |method| [method, public_send(method)] }].with_indifferent_access
-
end
-
-
2
def set_transaction_state(state) # :nodoc:
-
74
@transaction_state = state
-
end
-
-
2
def has_transactional_callbacks? # :nodoc:
-
462
!_rollback_callbacks.empty? || !_commit_callbacks.empty? || !_create_callbacks.empty?
-
end
-
-
2
private
-
-
# Updates the attributes on this particular ActiveRecord object so that
-
# if it is associated with a transaction, then the state of the AR object
-
# will be updated to reflect the current state of the transaction
-
#
-
# The @transaction_state variable stores the states of the associated
-
# transaction. This relies on the fact that a transaction can only be in
-
# one rollback or commit (otherwise a list of states would be required)
-
# Each AR object inside of a transaction carries that transaction's
-
# TransactionState.
-
#
-
# This method checks to see if the ActiveRecord object's state reflects
-
# the TransactionState, and rolls back or commits the ActiveRecord object
-
# as appropriate.
-
#
-
# Since ActiveRecord objects can be inside multiple transactions, this
-
# method recursively goes through the parent of the TransactionState and
-
# checks if the ActiveRecord object reflects the state of the object.
-
2
def sync_with_transaction_state
-
1152
update_attributes_from_transaction_state(@transaction_state, 0)
-
end
-
-
2
def update_attributes_from_transaction_state(transaction_state, depth)
-
1152
if transaction_state && transaction_state.finalized? && !has_transactional_callbacks?
-
unless @reflects_state[depth]
-
restore_transaction_record_state if transaction_state.rolledback?
-
clear_transaction_record_state
-
@reflects_state[depth] = true
-
end
-
-
if transaction_state.parent && !@reflects_state[depth+1]
-
update_attributes_from_transaction_state(transaction_state.parent, depth+1)
-
end
-
end
-
end
-
-
# Under Ruby 1.9, Array#flatten will call #to_ary (recursively) on each of the elements
-
# of the array, and then rescues from the possible NoMethodError. If those elements are
-
# ActiveRecord::Base's, then this triggers the various method_missing's that we have,
-
# which significantly impacts upon performance.
-
#
-
# So we can avoid the method_missing hit by explicitly defining #to_ary as nil here.
-
#
-
# See also http://tenderlovemaking.com/2011/06/28/til-its-ok-to-return-nil-from-to_ary.html
-
2
def to_ary # :nodoc:
-
nil
-
end
-
-
2
def init_internals
-
311
pk = self.class.primary_key
-
311
@attributes[pk] = nil unless @attributes.key?(pk)
-
-
311
@aggregation_cache = {}
-
311
@association_cache = {}
-
311
@attributes_cache = {}
-
311
@readonly = false
-
311
@destroyed = false
-
311
@marked_for_destruction = false
-
311
@destroyed_by_association = nil
-
311
@new_record = true
-
311
@txn = nil
-
311
@_start_transaction_state = {}
-
311
@transaction_state = nil
-
311
@reflects_state = [false]
-
end
-
-
2
def initialize_internals_callback
-
end
-
-
# This method is needed to make protected_attributes gem easier to hook.
-
# Remove it when we drop support to this gem.
-
2
def init_attributes(attributes, options)
-
275
assign_attributes(attributes)
-
end
-
end
-
end
-
2
module ActiveRecord
-
# = Active Record Counter Cache
-
2
module CounterCache
-
2
extend ActiveSupport::Concern
-
-
2
module ClassMethods
-
# Resets one or more counter caches to their correct value using an SQL
-
# count query. This is useful when adding new counter caches, or if the
-
# counter has been corrupted or modified directly by SQL.
-
#
-
# ==== Parameters
-
#
-
# * +id+ - The id of the object you wish to reset a counter on.
-
# * +counters+ - One or more association counters to reset
-
#
-
# ==== Examples
-
#
-
# # For Post with id #1 records reset the comments_count
-
# Post.reset_counters(1, :comments)
-
2
def reset_counters(id, *counters)
-
object = find(id)
-
counters.each do |association|
-
has_many_association = _reflect_on_association(association.to_sym)
-
raise ArgumentError, "'#{self.name}' has no association called '#{association}'" unless has_many_association
-
-
if has_many_association.is_a? ActiveRecord::Reflection::ThroughReflection
-
has_many_association = has_many_association.through_reflection
-
end
-
-
foreign_key = has_many_association.foreign_key.to_s
-
child_class = has_many_association.klass
-
reflection = child_class._reflections.values.find { |e| :belongs_to == e.macro && e.foreign_key.to_s == foreign_key && e.options[:counter_cache].present? }
-
counter_name = reflection.counter_cache_column
-
-
stmt = unscoped.where(arel_table[primary_key].eq(object.id)).arel.compile_update({
-
arel_table[counter_name] => object.send(association).count(:all)
-
}, primary_key)
-
connection.update stmt
-
end
-
return true
-
end
-
-
# A generic "counter updater" implementation, intended primarily to be
-
# used by increment_counter and decrement_counter, but which may also
-
# be useful on its own. It simply does a direct SQL update for the record
-
# with the given ID, altering the given hash of counters by the amount
-
# given by the corresponding value:
-
#
-
# ==== Parameters
-
#
-
# * +id+ - The id of the object you wish to update a counter on or an Array of ids.
-
# * +counters+ - A Hash containing the names of the fields
-
# to update as keys and the amount to update the field by as values.
-
#
-
# ==== Examples
-
#
-
# # For the Post with id of 5, decrement the comment_count by 1, and
-
# # increment the action_count by 1
-
# Post.update_counters 5, comment_count: -1, action_count: 1
-
# # Executes the following SQL:
-
# # UPDATE posts
-
# # SET comment_count = COALESCE(comment_count, 0) - 1,
-
# # action_count = COALESCE(action_count, 0) + 1
-
# # WHERE id = 5
-
#
-
# # For the Posts with id of 10 and 15, increment the comment_count by 1
-
# Post.update_counters [10, 15], comment_count: 1
-
# # Executes the following SQL:
-
# # UPDATE posts
-
# # SET comment_count = COALESCE(comment_count, 0) + 1
-
# # WHERE id IN (10, 15)
-
2
def update_counters(id, counters)
-
updates = counters.map do |counter_name, value|
-
operator = value < 0 ? '-' : '+'
-
quoted_column = connection.quote_column_name(counter_name)
-
"#{quoted_column} = COALESCE(#{quoted_column}, 0) #{operator} #{value.abs}"
-
end
-
-
unscoped.where(primary_key => id).update_all updates.join(', ')
-
end
-
-
# Increment a numeric field by one, via a direct SQL update.
-
#
-
# This method is used primarily for maintaining counter_cache columns that are
-
# used to store aggregate values. For example, a DiscussionBoard may cache
-
# posts_count and comments_count to avoid running an SQL query to calculate the
-
# number of posts and comments there are, each time it is displayed.
-
#
-
# ==== Parameters
-
#
-
# * +counter_name+ - The name of the field that should be incremented.
-
# * +id+ - The id of the object that should be incremented or an Array of ids.
-
#
-
# ==== Examples
-
#
-
# # Increment the post_count column for the record with an id of 5
-
# DiscussionBoard.increment_counter(:post_count, 5)
-
2
def increment_counter(counter_name, id)
-
update_counters(id, counter_name => 1)
-
end
-
-
# Decrement a numeric field by one, via a direct SQL update.
-
#
-
# This works the same as increment_counter but reduces the column value by
-
# 1 instead of increasing it.
-
#
-
# ==== Parameters
-
#
-
# * +counter_name+ - The name of the field that should be decremented.
-
# * +id+ - The id of the object that should be decremented or an Array of ids.
-
#
-
# ==== Examples
-
#
-
# # Decrement the post_count column for the record with an id of 5
-
# DiscussionBoard.decrement_counter(:post_count, 5)
-
2
def decrement_counter(counter_name, id)
-
update_counters(id, counter_name => -1)
-
end
-
end
-
end
-
end
-
2
module ActiveRecord
-
2
module DynamicMatchers #:nodoc:
-
# This code in this file seems to have a lot of indirection, but the indirection
-
# is there to provide extension points for the activerecord-deprecated_finders
-
# gem. When we stop supporting activerecord-deprecated_finders (from Rails 5),
-
# then we can remove the indirection.
-
-
2
def respond_to?(name, include_private = false)
-
1070
if self == Base
-
10
super
-
else
-
1060
match = Method.match(self, name)
-
1060
match && match.valid? || super
-
end
-
end
-
-
2
private
-
-
2
def method_missing(name, *arguments, &block)
-
match = Method.match(self, name)
-
-
if match && match.valid?
-
match.define
-
send(name, *arguments, &block)
-
else
-
super
-
end
-
end
-
-
2
class Method
-
2
@matchers = []
-
-
2
class << self
-
2
attr_reader :matchers
-
-
2
def match(model, name)
-
3180
klass = matchers.find { |k| name =~ k.pattern }
-
1060
klass.new(model, name) if klass
-
end
-
-
2
def pattern
-
2120
@pattern ||= /\A#{prefix}_([_a-zA-Z]\w*)#{suffix}\Z/
-
end
-
-
2
def prefix
-
raise NotImplementedError
-
end
-
-
2
def suffix
-
2
''
-
end
-
end
-
-
2
attr_reader :model, :name, :attribute_names
-
-
2
def initialize(model, name)
-
@model = model
-
@name = name.to_s
-
@attribute_names = @name.match(self.class.pattern)[1].split('_and_')
-
@attribute_names.map! { |n| @model.attribute_aliases[n] || n }
-
end
-
-
2
def valid?
-
attribute_names.all? { |name| model.columns_hash[name] || model.reflect_on_aggregation(name.to_sym) }
-
end
-
-
2
def define
-
model.class_eval <<-CODE, __FILE__, __LINE__ + 1
-
def self.#{name}(#{signature})
-
#{body}
-
end
-
CODE
-
end
-
-
2
def body
-
raise NotImplementedError
-
end
-
end
-
-
2
module Finder
-
# Extended in activerecord-deprecated_finders
-
2
def body
-
result
-
end
-
-
# Extended in activerecord-deprecated_finders
-
2
def result
-
"#{finder}(#{attributes_hash})"
-
end
-
-
# The parameters in the signature may have reserved Ruby words, in order
-
# to prevent errors, we start each param name with `_`.
-
#
-
# Extended in activerecord-deprecated_finders
-
2
def signature
-
attribute_names.map { |name| "_#{name}" }.join(', ')
-
end
-
-
# Given that the parameters starts with `_`, the finder needs to use the
-
# same parameter name.
-
2
def attributes_hash
-
"{" + attribute_names.map { |name| ":#{name} => _#{name}" }.join(',') + "}"
-
end
-
-
2
def finder
-
raise NotImplementedError
-
end
-
end
-
-
2
class FindBy < Method
-
2
Method.matchers << self
-
2
include Finder
-
-
2
def self.prefix
-
2
"find_by"
-
end
-
-
2
def finder
-
"find_by"
-
end
-
end
-
-
2
class FindByBang < Method
-
2
Method.matchers << self
-
2
include Finder
-
-
2
def self.prefix
-
2
"find_by"
-
end
-
-
2
def self.suffix
-
2
"!"
-
end
-
-
2
def finder
-
"find_by!"
-
end
-
end
-
end
-
end
-
2
require 'active_support/core_ext/object/deep_dup'
-
-
2
module ActiveRecord
-
# Declare an enum attribute where the values map to integers in the database,
-
# but can be queried by name. Example:
-
#
-
# class Conversation < ActiveRecord::Base
-
# enum status: [ :active, :archived ]
-
# end
-
#
-
# # conversation.update! status: 0
-
# conversation.active!
-
# conversation.active? # => true
-
# conversation.status # => "active"
-
#
-
# # conversation.update! status: 1
-
# conversation.archived!
-
# conversation.archived? # => true
-
# conversation.status # => "archived"
-
#
-
# # conversation.update! status: 1
-
# conversation.status = "archived"
-
#
-
# # conversation.update! status: nil
-
# conversation.status = nil
-
# conversation.status.nil? # => true
-
# conversation.status # => nil
-
#
-
# Scopes based on the allowed values of the enum field will be provided
-
# as well. With the above example, it will create an +active+ and +archived+
-
# scope.
-
#
-
# You can set the default value from the database declaration, like:
-
#
-
# create_table :conversations do |t|
-
# t.column :status, :integer, default: 0
-
# end
-
#
-
# Good practice is to let the first declared status be the default.
-
#
-
# Finally, it's also possible to explicitly map the relation between attribute and
-
# database integer with a +Hash+:
-
#
-
# class Conversation < ActiveRecord::Base
-
# enum status: { active: 0, archived: 1 }
-
# end
-
#
-
# Note that when an +Array+ is used, the implicit mapping from the values to database
-
# integers is derived from the order the values appear in the array. In the example,
-
# <tt>:active</tt> is mapped to +0+ as it's the first element, and <tt>:archived</tt>
-
# is mapped to +1+. In general, the +i+-th element is mapped to <tt>i-1</tt> in the
-
# database.
-
#
-
# Therefore, once a value is added to the enum array, its position in the array must
-
# be maintained, and new values should only be added to the end of the array. To
-
# remove unused values, the explicit +Hash+ syntax should be used.
-
#
-
# In rare circumstances you might need to access the mapping directly.
-
# The mappings are exposed through a class method with the pluralized attribute
-
# name:
-
#
-
# Conversation.statuses # => { "active" => 0, "archived" => 1 }
-
#
-
# Use that class method when you need to know the ordinal value of an enum:
-
#
-
# Conversation.where("status <> ?", Conversation.statuses[:archived])
-
#
-
# Where conditions on an enum attribute must use the ordinal value of an enum.
-
2
module Enum
-
2
def self.extended(base) # :nodoc:
-
2
base.class_attribute(:defined_enums)
-
2
base.defined_enums = {}
-
end
-
-
2
def inherited(base) # :nodoc:
-
13
base.defined_enums = defined_enums.deep_dup
-
13
super
-
end
-
-
2
def enum(definitions)
-
klass = self
-
definitions.each do |name, values|
-
# statuses = { }
-
enum_values = ActiveSupport::HashWithIndifferentAccess.new
-
name = name.to_sym
-
-
# def self.statuses statuses end
-
detect_enum_conflict!(name, name.to_s.pluralize, true)
-
klass.singleton_class.send(:define_method, name.to_s.pluralize) { enum_values }
-
-
_enum_methods_module.module_eval do
-
# def status=(value) self[:status] = statuses[value] end
-
klass.send(:detect_enum_conflict!, name, "#{name}=")
-
define_method("#{name}=") { |value|
-
if enum_values.has_key?(value) || value.blank?
-
self[name] = enum_values[value]
-
elsif enum_values.has_value?(value)
-
# Assigning a value directly is not a end-user feature, hence it's not documented.
-
# This is used internally to make building objects from the generated scopes work
-
# as expected, i.e. +Conversation.archived.build.archived?+ should be true.
-
self[name] = value
-
else
-
raise ArgumentError, "'#{value}' is not a valid #{name}"
-
end
-
}
-
-
# def status() statuses.key self[:status] end
-
klass.send(:detect_enum_conflict!, name, name)
-
define_method(name) { enum_values.key self[name] }
-
-
# def status_before_type_cast() statuses.key self[:status] end
-
klass.send(:detect_enum_conflict!, name, "#{name}_before_type_cast")
-
define_method("#{name}_before_type_cast") { enum_values.key self[name] }
-
-
pairs = values.respond_to?(:each_pair) ? values.each_pair : values.each_with_index
-
pairs.each do |value, i|
-
enum_values[value] = i
-
-
# def active?() status == 0 end
-
klass.send(:detect_enum_conflict!, name, "#{value}?")
-
define_method("#{value}?") { self[name] == i }
-
-
# def active!() update! status: :active end
-
klass.send(:detect_enum_conflict!, name, "#{value}!")
-
define_method("#{value}!") { update! name => value }
-
-
# scope :active, -> { where status: 0 }
-
klass.send(:detect_enum_conflict!, name, value, true)
-
klass.scope value, -> { klass.where name => i }
-
end
-
end
-
defined_enums[name.to_s] = enum_values
-
end
-
end
-
-
2
private
-
2
def _enum_methods_module
-
@_enum_methods_module ||= begin
-
mod = Module.new do
-
private
-
def save_changed_attribute(attr_name, value)
-
if (mapping = self.class.defined_enums[attr_name.to_s])
-
if attribute_changed?(attr_name)
-
old = changed_attributes[attr_name]
-
-
if mapping[old] == value
-
changed_attributes.delete(attr_name)
-
end
-
else
-
old = clone_attribute_value(:read_attribute, attr_name)
-
-
if old != value
-
changed_attributes[attr_name] = mapping.key old
-
end
-
end
-
else
-
super
-
end
-
end
-
end
-
include mod
-
mod
-
end
-
end
-
-
2
ENUM_CONFLICT_MESSAGE = \
-
"You tried to define an enum named \"%{enum}\" on the model \"%{klass}\", but " \
-
"this will generate a %{type} method \"%{method}\", which is already defined " \
-
"by %{source}."
-
-
2
def detect_enum_conflict!(enum_name, method_name, klass_method = false)
-
if klass_method && dangerous_class_method?(method_name)
-
raise ArgumentError, ENUM_CONFLICT_MESSAGE % {
-
enum: enum_name,
-
klass: self.name,
-
type: 'class',
-
method: method_name,
-
source: 'Active Record'
-
}
-
elsif !klass_method && dangerous_attribute_method?(method_name)
-
raise ArgumentError, ENUM_CONFLICT_MESSAGE % {
-
enum: enum_name,
-
klass: self.name,
-
type: 'instance',
-
method: method_name,
-
source: 'Active Record'
-
}
-
elsif !klass_method && method_defined_within?(method_name, _enum_methods_module, Module)
-
raise ArgumentError, ENUM_CONFLICT_MESSAGE % {
-
enum: enum_name,
-
klass: self.name,
-
type: 'instance',
-
method: method_name,
-
source: 'another enum'
-
}
-
end
-
end
-
end
-
end
-
2
module ActiveRecord
-
-
# = Active Record Errors
-
#
-
# Generic Active Record exception class.
-
2
class ActiveRecordError < StandardError
-
end
-
-
# Raised when the single-table inheritance mechanism fails to locate the subclass
-
# (for example due to improper usage of column that +inheritance_column+ points to).
-
2
class SubclassNotFound < ActiveRecordError #:nodoc:
-
end
-
-
# Raised when an object assigned to an association has an incorrect type.
-
#
-
# class Ticket < ActiveRecord::Base
-
# has_many :patches
-
# end
-
#
-
# class Patch < ActiveRecord::Base
-
# belongs_to :ticket
-
# end
-
#
-
# # Comments are not patches, this assignment raises AssociationTypeMismatch.
-
# @ticket.patches << Comment.new(content: "Please attach tests to your patch.")
-
2
class AssociationTypeMismatch < ActiveRecordError
-
end
-
-
# Raised when unserialized object's type mismatches one specified for serializable field.
-
2
class SerializationTypeMismatch < ActiveRecordError
-
end
-
-
# Raised when adapter not specified on connection (or configuration file <tt>config/database.yml</tt>
-
# misses adapter field).
-
2
class AdapterNotSpecified < ActiveRecordError
-
end
-
-
# Raised when Active Record cannot find database adapter specified in <tt>config/database.yml</tt> or programmatically.
-
2
class AdapterNotFound < ActiveRecordError
-
end
-
-
# Raised when connection to the database could not been established (for example when <tt>connection=</tt>
-
# is given a nil object).
-
2
class ConnectionNotEstablished < ActiveRecordError
-
end
-
-
# Raised when Active Record cannot find record by given id or set of ids.
-
2
class RecordNotFound < ActiveRecordError
-
end
-
-
# Raised by ActiveRecord::Base.save! and ActiveRecord::Base.create! methods when record cannot be
-
# saved because record is invalid.
-
2
class RecordNotSaved < ActiveRecordError
-
end
-
-
# Raised by ActiveRecord::Base.destroy! when a call to destroy would return false.
-
2
class RecordNotDestroyed < ActiveRecordError
-
end
-
-
# Superclass for all database execution errors.
-
#
-
# Wraps the underlying database error as +original_exception+.
-
2
class StatementInvalid < ActiveRecordError
-
2
attr_reader :original_exception
-
-
2
def initialize(message, original_exception = nil)
-
super(message)
-
@original_exception = original_exception
-
end
-
end
-
-
# Defunct wrapper class kept for compatibility.
-
# +StatementInvalid+ wraps the original exception now.
-
2
class WrappedDatabaseException < StatementInvalid
-
end
-
-
# Raised when a record cannot be inserted because it would violate a uniqueness constraint.
-
2
class RecordNotUnique < WrappedDatabaseException
-
end
-
-
# Raised when a record cannot be inserted or updated because it references a non-existent record.
-
2
class InvalidForeignKey < WrappedDatabaseException
-
end
-
-
# Raised when number of bind variables in statement given to <tt>:condition</tt> key (for example,
-
# when using +find+ method)
-
# does not match number of expected variables.
-
#
-
# For example, in
-
#
-
# Location.where("lat = ? AND lng = ?", 53.7362)
-
#
-
# two placeholders are given but only one variable to fill them.
-
2
class PreparedStatementInvalid < ActiveRecordError
-
end
-
-
# Raised when a given database does not exist
-
2
class NoDatabaseError < ActiveRecordError
-
2
def initialize(message)
-
super extend_message(message)
-
end
-
-
# can be over written to add additional error information.
-
2
def extend_message(message)
-
message
-
end
-
end
-
-
# Raised on attempt to save stale record. Record is stale when it's being saved in another query after
-
# instantiation, for example, when two users edit the same wiki page and one starts editing and saves
-
# the page before the other.
-
#
-
# Read more about optimistic locking in ActiveRecord::Locking module RDoc.
-
2
class StaleObjectError < ActiveRecordError
-
2
attr_reader :record, :attempted_action
-
-
2
def initialize(record, attempted_action)
-
super("Attempted to #{attempted_action} a stale object: #{record.class.name}")
-
@record = record
-
@attempted_action = attempted_action
-
end
-
-
end
-
-
# Raised when association is being configured improperly or
-
# user tries to use offset and limit together with has_many or has_and_belongs_to_many associations.
-
2
class ConfigurationError < ActiveRecordError
-
end
-
-
# Raised on attempt to update record that is instantiated as read only.
-
2
class ReadOnlyRecord < ActiveRecordError
-
end
-
-
# ActiveRecord::Transactions::ClassMethods.transaction uses this exception
-
# to distinguish a deliberate rollback from other exceptional situations.
-
# Normally, raising an exception will cause the +transaction+ method to rollback
-
# the database transaction *and* pass on the exception. But if you raise an
-
# ActiveRecord::Rollback exception, then the database transaction will be rolled back,
-
# without passing on the exception.
-
#
-
# For example, you could do this in your controller to rollback a transaction:
-
#
-
# class BooksController < ActionController::Base
-
# def create
-
# Book.transaction do
-
# book = Book.new(params[:book])
-
# book.save!
-
# if today_is_friday?
-
# # The system must fail on Friday so that our support department
-
# # won't be out of job. We silently rollback this transaction
-
# # without telling the user.
-
# raise ActiveRecord::Rollback, "Call tech support!"
-
# end
-
# end
-
# # ActiveRecord::Rollback is the only exception that won't be passed on
-
# # by ActiveRecord::Base.transaction, so this line will still be reached
-
# # even on Friday.
-
# redirect_to root_url
-
# end
-
# end
-
2
class Rollback < ActiveRecordError
-
end
-
-
# Raised when attribute has a name reserved by Active Record (when attribute has name of one of Active Record instance methods).
-
2
class DangerousAttributeError < ActiveRecordError
-
end
-
-
# Raised when unknown attributes are supplied via mass assignment.
-
2
class UnknownAttributeError < NoMethodError
-
-
2
attr_reader :record, :attribute
-
-
2
def initialize(record, attribute)
-
@record = record
-
@attribute = attribute.to_s
-
super("unknown attribute: #{attribute}")
-
end
-
-
end
-
-
# Raised when an error occurred while doing a mass assignment to an attribute through the
-
# <tt>attributes=</tt> method. The exception has an +attribute+ property that is the name of the
-
# offending attribute.
-
2
class AttributeAssignmentError < ActiveRecordError
-
2
attr_reader :exception, :attribute
-
2
def initialize(message, exception, attribute)
-
super(message)
-
@exception = exception
-
@attribute = attribute
-
end
-
end
-
-
# Raised when there are multiple errors while doing a mass assignment through the +attributes+
-
# method. The exception has an +errors+ property that contains an array of AttributeAssignmentError
-
# objects, each corresponding to the error while assigning to an attribute.
-
2
class MultiparameterAssignmentErrors < ActiveRecordError
-
2
attr_reader :errors
-
2
def initialize(errors)
-
@errors = errors
-
end
-
end
-
-
# Raised when a primary key is needed, but not specified in the schema or model.
-
2
class UnknownPrimaryKey < ActiveRecordError
-
2
attr_reader :model
-
-
2
def initialize(model)
-
super("Unknown primary key for table #{model.table_name} in model #{model}.")
-
@model = model
-
end
-
-
end
-
-
# Raised when a relation cannot be mutated because it's already loaded.
-
#
-
# class Task < ActiveRecord::Base
-
# end
-
#
-
# relation = Task.all
-
# relation.loaded? # => true
-
#
-
# # Methods which try to mutate a loaded relation fail.
-
# relation.where!(title: 'TODO') # => ActiveRecord::ImmutableRelation
-
# relation.limit!(5) # => ActiveRecord::ImmutableRelation
-
2
class ImmutableRelation < ActiveRecordError
-
end
-
-
2
class TransactionIsolationError < ActiveRecordError
-
end
-
end
-
2
require 'active_support/lazy_load_hooks'
-
2
require 'active_record/explain_registry'
-
-
2
module ActiveRecord
-
2
module Explain
-
# Executes the block with the collect flag enabled. Queries are collected
-
# asynchronously by the subscriber and returned.
-
2
def collecting_queries_for_explain # :nodoc:
-
ExplainRegistry.collect = true
-
yield
-
ExplainRegistry.queries
-
ensure
-
ExplainRegistry.reset
-
end
-
-
# Makes the adapter execute EXPLAIN for the tuples of queries and bindings.
-
# Returns a formatted string ready to be logged.
-
2
def exec_explain(queries) # :nodoc:
-
str = queries.map do |sql, bind|
-
[].tap do |msg|
-
msg << "EXPLAIN for: #{sql}"
-
unless bind.empty?
-
bind_msg = bind.map {|col, val| [col.name, val]}.inspect
-
msg.last << " #{bind_msg}"
-
end
-
msg << connection.explain(sql, bind)
-
end.join("\n")
-
end.join("\n")
-
-
# Overriding inspect to be more human readable, specially in the console.
-
def str.inspect
-
self
-
end
-
-
str
-
end
-
end
-
end
-
2
require 'active_support/per_thread_registry'
-
-
2
module ActiveRecord
-
# This is a thread locals registry for EXPLAIN. For example
-
#
-
# ActiveRecord::ExplainRegistry.queries
-
#
-
# returns the collected queries local to the current thread.
-
#
-
# See the documentation of <tt>ActiveSupport::PerThreadRegistry</tt>
-
# for further details.
-
2
class ExplainRegistry # :nodoc:
-
2
extend ActiveSupport::PerThreadRegistry
-
-
2
attr_accessor :queries, :collect
-
-
2
def initialize
-
2
reset
-
end
-
-
2
def collect?
-
967
@collect
-
end
-
-
2
def reset
-
2
@collect = false
-
2
@queries = []
-
end
-
end
-
end
-
2
require 'active_support/notifications'
-
2
require 'active_record/explain_registry'
-
-
2
module ActiveRecord
-
2
class ExplainSubscriber # :nodoc:
-
2
def start(name, id, payload)
-
# unused
-
end
-
-
2
def finish(name, id, payload)
-
967
if ExplainRegistry.collect? && !ignore_payload?(payload)
-
ExplainRegistry.queries << payload.values_at(:sql, :binds)
-
end
-
end
-
-
# SCHEMA queries cannot be EXPLAINed, also we do not want to run EXPLAIN on
-
# our own EXPLAINs now matter how loopingly beautiful that would be.
-
#
-
# On the other hand, we want to monitor the performance of our real database
-
# queries, not the performance of the access to the query cache.
-
2
IGNORED_PAYLOADS = %w(SCHEMA EXPLAIN CACHE)
-
2
EXPLAINED_SQLS = /\A\s*(select|update|delete|insert)\b/i
-
2
def ignore_payload?(payload)
-
payload[:exception] || IGNORED_PAYLOADS.include?(payload[:name]) || payload[:sql] !~ EXPLAINED_SQLS
-
end
-
-
2
ActiveSupport::Notifications.subscribe("sql.active_record", new)
-
end
-
end
-
2
require 'erb'
-
2
require 'yaml'
-
-
2
module ActiveRecord
-
2
class FixtureSet
-
2
class File # :nodoc:
-
2
include Enumerable
-
-
##
-
# Open a fixture file named +file+. When called with a block, the block
-
# is called with the filehandle and the filehandle is automatically closed
-
# when the block finishes.
-
2
def self.open(file)
-
x = new file
-
block_given? ? yield(x) : x
-
end
-
-
2
def initialize(file)
-
@file = file
-
@rows = nil
-
end
-
-
2
def each(&block)
-
rows.each(&block)
-
end
-
-
-
2
private
-
2
def rows
-
return @rows if @rows
-
-
begin
-
data = YAML.load(render(IO.read(@file)))
-
rescue ArgumentError, Psych::SyntaxError => error
-
raise Fixture::FormatError, "a YAML error occurred parsing #{@file}. Please note that YAML must be consistently indented using spaces. Tabs are not allowed. Please have a look at http://www.yaml.org/faq.html\nThe exact error was:\n #{error.class}: #{error}", error.backtrace
-
end
-
@rows = data ? validate(data).to_a : []
-
end
-
-
2
def render(content)
-
context = ActiveRecord::FixtureSet::RenderContext.create_subclass.new
-
ERB.new(content).result(context.get_binding)
-
end
-
-
# Validate our unmarshalled data.
-
2
def validate(data)
-
unless Hash === data || YAML::Omap === data
-
raise Fixture::FormatError, 'fixture is not a hash'
-
end
-
-
raise Fixture::FormatError unless data.all? { |name, row| Hash === row }
-
data
-
end
-
end
-
end
-
end
-
2
require 'erb'
-
2
require 'yaml'
-
2
require 'zlib'
-
2
require 'active_support/dependencies'
-
2
require 'active_record/fixture_set/file'
-
2
require 'active_record/errors'
-
-
2
module ActiveRecord
-
2
class FixtureClassNotFound < ActiveRecord::ActiveRecordError #:nodoc:
-
end
-
-
# \Fixtures are a way of organizing data that you want to test against; in short, sample data.
-
#
-
# They are stored in YAML files, one file per model, which are placed in the directory
-
# appointed by <tt>ActiveSupport::TestCase.fixture_path=(path)</tt> (this is automatically
-
# configured for Rails, so you can just put your files in <tt><your-rails-app>/test/fixtures/</tt>).
-
# The fixture file ends with the <tt>.yml</tt> file extension (Rails example:
-
# <tt><your-rails-app>/test/fixtures/web_sites.yml</tt>). The format of a fixture file looks
-
# like this:
-
#
-
# rubyonrails:
-
# id: 1
-
# name: Ruby on Rails
-
# url: http://www.rubyonrails.org
-
#
-
# google:
-
# id: 2
-
# name: Google
-
# url: http://www.google.com
-
#
-
# This fixture file includes two fixtures. Each YAML fixture (ie. record) is given a name and
-
# is followed by an indented list of key/value pairs in the "key: value" format. Records are
-
# separated by a blank line for your viewing pleasure.
-
#
-
# Note that fixtures are unordered. If you want ordered fixtures, use the omap YAML type.
-
# See http://yaml.org/type/omap.html
-
# for the specification. You will need ordered fixtures when you have foreign key constraints
-
# on keys in the same table. This is commonly needed for tree structures. Example:
-
#
-
# --- !omap
-
# - parent:
-
# id: 1
-
# parent_id: NULL
-
# title: Parent
-
# - child:
-
# id: 2
-
# parent_id: 1
-
# title: Child
-
#
-
# = Using Fixtures in Test Cases
-
#
-
# Since fixtures are a testing construct, we use them in our unit and functional tests. There
-
# are two ways to use the fixtures, but first let's take a look at a sample unit test:
-
#
-
# require 'test_helper'
-
#
-
# class WebSiteTest < ActiveSupport::TestCase
-
# test "web_site_count" do
-
# assert_equal 2, WebSite.count
-
# end
-
# end
-
#
-
# By default, <tt>test_helper.rb</tt> will load all of your fixtures into your test database,
-
# so this test will succeed.
-
#
-
# The testing environment will automatically load the all fixtures into the database before each
-
# test. To ensure consistent data, the environment deletes the fixtures before running the load.
-
#
-
# In addition to being available in the database, the fixture's data may also be accessed by
-
# using a special dynamic method, which has the same name as the model, and accepts the
-
# name of the fixture to instantiate:
-
#
-
# test "find" do
-
# assert_equal "Ruby on Rails", web_sites(:rubyonrails).name
-
# end
-
#
-
# Alternatively, you may enable auto-instantiation of the fixture data. For instance, take the
-
# following tests:
-
#
-
# test "find_alt_method_1" do
-
# assert_equal "Ruby on Rails", @web_sites['rubyonrails']['name']
-
# end
-
#
-
# test "find_alt_method_2" do
-
# assert_equal "Ruby on Rails", @rubyonrails.name
-
# end
-
#
-
# In order to use these methods to access fixtured data within your testcases, you must specify one of the
-
# following in your <tt>ActiveSupport::TestCase</tt>-derived class:
-
#
-
# - to fully enable instantiated fixtures (enable alternate methods #1 and #2 above)
-
# self.use_instantiated_fixtures = true
-
#
-
# - create only the hash for the fixtures, do not 'find' each instance (enable alternate method #1 only)
-
# self.use_instantiated_fixtures = :no_instances
-
#
-
# Using either of these alternate methods incurs a performance hit, as the fixtured data must be fully
-
# traversed in the database to create the fixture hash and/or instance variables. This is expensive for
-
# large sets of fixtured data.
-
#
-
# = Dynamic fixtures with ERB
-
#
-
# Some times you don't care about the content of the fixtures as much as you care about the volume.
-
# In these cases, you can mix ERB in with your YAML fixtures to create a bunch of fixtures for load
-
# testing, like:
-
#
-
# <% 1.upto(1000) do |i| %>
-
# fix_<%= i %>:
-
# id: <%= i %>
-
# name: guy_<%= 1 %>
-
# <% end %>
-
#
-
# This will create 1000 very simple fixtures.
-
#
-
# Using ERB, you can also inject dynamic values into your fixtures with inserts like
-
# <tt><%= Date.today.strftime("%Y-%m-%d") %></tt>.
-
# This is however a feature to be used with some caution. The point of fixtures are that they're
-
# stable units of predictable sample data. If you feel that you need to inject dynamic values, then
-
# perhaps you should reexamine whether your application is properly testable. Hence, dynamic values
-
# in fixtures are to be considered a code smell.
-
#
-
# Helper methods defined in a fixture will not be available in other fixtures, to prevent against
-
# unwanted inter-test dependencies. Methods used by multiple fixtures should be defined in a module
-
# that is included in <tt>ActiveRecord::FixtureSet.context_class</tt>.
-
#
-
# - define a helper method in `test_helper.rb`
-
# module FixtureFileHelpers
-
# def file_sha(path)
-
# Digest::SHA2.hexdigest(File.read(Rails.root.join('test/fixtures', path)))
-
# end
-
# end
-
# ActiveRecord::FixtureSet.context_class.send :include, FixtureFileHelpers
-
#
-
# - use the helper method in a fixture
-
# photo:
-
# name: kitten.png
-
# sha: <%= file_sha 'files/kitten.png' %>
-
#
-
# = Transactional Fixtures
-
#
-
# Test cases can use begin+rollback to isolate their changes to the database instead of having to
-
# delete+insert for every test case.
-
#
-
# class FooTest < ActiveSupport::TestCase
-
# self.use_transactional_fixtures = true
-
#
-
# test "godzilla" do
-
# assert !Foo.all.empty?
-
# Foo.destroy_all
-
# assert Foo.all.empty?
-
# end
-
#
-
# test "godzilla aftermath" do
-
# assert !Foo.all.empty?
-
# end
-
# end
-
#
-
# If you preload your test database with all fixture data (probably in the rake task) and use
-
# transactional fixtures, then you may omit all fixtures declarations in your test cases since
-
# all the data's already there and every case rolls back its changes.
-
#
-
# In order to use instantiated fixtures with preloaded data, set +self.pre_loaded_fixtures+ to
-
# true. This will provide access to fixture data for every table that has been loaded through
-
# fixtures (depending on the value of +use_instantiated_fixtures+).
-
#
-
# When *not* to use transactional fixtures:
-
#
-
# 1. You're testing whether a transaction works correctly. Nested transactions don't commit until
-
# all parent transactions commit, particularly, the fixtures transaction which is begun in setup
-
# and rolled back in teardown. Thus, you won't be able to verify
-
# the results of your transaction until Active Record supports nested transactions or savepoints (in progress).
-
# 2. Your database does not support transactions. Every Active Record database supports transactions except MySQL MyISAM.
-
# Use InnoDB, MaxDB, or NDB instead.
-
#
-
# = Advanced Fixtures
-
#
-
# Fixtures that don't specify an ID get some extra features:
-
#
-
# * Stable, autogenerated IDs
-
# * Label references for associations (belongs_to, has_one, has_many)
-
# * HABTM associations as inline lists
-
# * Autofilled timestamp columns
-
# * Fixture label interpolation
-
# * Support for YAML defaults
-
#
-
# == Stable, Autogenerated IDs
-
#
-
# Here, have a monkey fixture:
-
#
-
# george:
-
# id: 1
-
# name: George the Monkey
-
#
-
# reginald:
-
# id: 2
-
# name: Reginald the Pirate
-
#
-
# Each of these fixtures has two unique identifiers: one for the database
-
# and one for the humans. Why don't we generate the primary key instead?
-
# Hashing each fixture's label yields a consistent ID:
-
#
-
# george: # generated id: 503576764
-
# name: George the Monkey
-
#
-
# reginald: # generated id: 324201669
-
# name: Reginald the Pirate
-
#
-
# Active Record looks at the fixture's model class, discovers the correct
-
# primary key, and generates it right before inserting the fixture
-
# into the database.
-
#
-
# The generated ID for a given label is constant, so we can discover
-
# any fixture's ID without loading anything, as long as we know the label.
-
#
-
# == Label references for associations (belongs_to, has_one, has_many)
-
#
-
# Specifying foreign keys in fixtures can be very fragile, not to
-
# mention difficult to read. Since Active Record can figure out the ID of
-
# any fixture from its label, you can specify FK's by label instead of ID.
-
#
-
# === belongs_to
-
#
-
# Let's break out some more monkeys and pirates.
-
#
-
# ### in pirates.yml
-
#
-
# reginald:
-
# id: 1
-
# name: Reginald the Pirate
-
# monkey_id: 1
-
#
-
# ### in monkeys.yml
-
#
-
# george:
-
# id: 1
-
# name: George the Monkey
-
# pirate_id: 1
-
#
-
# Add a few more monkeys and pirates and break this into multiple files,
-
# and it gets pretty hard to keep track of what's going on. Let's
-
# use labels instead of IDs:
-
#
-
# ### in pirates.yml
-
#
-
# reginald:
-
# name: Reginald the Pirate
-
# monkey: george
-
#
-
# ### in monkeys.yml
-
#
-
# george:
-
# name: George the Monkey
-
# pirate: reginald
-
#
-
# Pow! All is made clear. Active Record reflects on the fixture's model class,
-
# finds all the +belongs_to+ associations, and allows you to specify
-
# a target *label* for the *association* (monkey: george) rather than
-
# a target *id* for the *FK* (<tt>monkey_id: 1</tt>).
-
#
-
# ==== Polymorphic belongs_to
-
#
-
# Supporting polymorphic relationships is a little bit more complicated, since
-
# Active Record needs to know what type your association is pointing at. Something
-
# like this should look familiar:
-
#
-
# ### in fruit.rb
-
#
-
# belongs_to :eater, polymorphic: true
-
#
-
# ### in fruits.yml
-
#
-
# apple:
-
# id: 1
-
# name: apple
-
# eater_id: 1
-
# eater_type: Monkey
-
#
-
# Can we do better? You bet!
-
#
-
# apple:
-
# eater: george (Monkey)
-
#
-
# Just provide the polymorphic target type and Active Record will take care of the rest.
-
#
-
# === has_and_belongs_to_many
-
#
-
# Time to give our monkey some fruit.
-
#
-
# ### in monkeys.yml
-
#
-
# george:
-
# id: 1
-
# name: George the Monkey
-
#
-
# ### in fruits.yml
-
#
-
# apple:
-
# id: 1
-
# name: apple
-
#
-
# orange:
-
# id: 2
-
# name: orange
-
#
-
# grape:
-
# id: 3
-
# name: grape
-
#
-
# ### in fruits_monkeys.yml
-
#
-
# apple_george:
-
# fruit_id: 1
-
# monkey_id: 1
-
#
-
# orange_george:
-
# fruit_id: 2
-
# monkey_id: 1
-
#
-
# grape_george:
-
# fruit_id: 3
-
# monkey_id: 1
-
#
-
# Let's make the HABTM fixture go away.
-
#
-
# ### in monkeys.yml
-
#
-
# george:
-
# id: 1
-
# name: George the Monkey
-
# fruits: apple, orange, grape
-
#
-
# ### in fruits.yml
-
#
-
# apple:
-
# name: apple
-
#
-
# orange:
-
# name: orange
-
#
-
# grape:
-
# name: grape
-
#
-
# Zap! No more fruits_monkeys.yml file. We've specified the list of fruits
-
# on George's fixture, but we could've just as easily specified a list
-
# of monkeys on each fruit. As with +belongs_to+, Active Record reflects on
-
# the fixture's model class and discovers the +has_and_belongs_to_many+
-
# associations.
-
#
-
# == Autofilled Timestamp Columns
-
#
-
# If your table/model specifies any of Active Record's
-
# standard timestamp columns (+created_at+, +created_on+, +updated_at+, +updated_on+),
-
# they will automatically be set to <tt>Time.now</tt>.
-
#
-
# If you've set specific values, they'll be left alone.
-
#
-
# == Fixture label interpolation
-
#
-
# The label of the current fixture is always available as a column value:
-
#
-
# geeksomnia:
-
# name: Geeksomnia's Account
-
# subdomain: $LABEL
-
#
-
# Also, sometimes (like when porting older join table fixtures) you'll need
-
# to be able to get a hold of the identifier for a given label. ERB
-
# to the rescue:
-
#
-
# george_reginald:
-
# monkey_id: <%= ActiveRecord::FixtureSet.identify(:reginald) %>
-
# pirate_id: <%= ActiveRecord::FixtureSet.identify(:george) %>
-
#
-
# == Support for YAML defaults
-
#
-
# You probably already know how to use YAML to set and reuse defaults in
-
# your <tt>database.yml</tt> file. You can use the same technique in your fixtures:
-
#
-
# DEFAULTS: &DEFAULTS
-
# created_on: <%= 3.weeks.ago.to_s(:db) %>
-
#
-
# first:
-
# name: Smurf
-
# <<: *DEFAULTS
-
#
-
# second:
-
# name: Fraggle
-
# <<: *DEFAULTS
-
#
-
# Any fixture labeled "DEFAULTS" is safely ignored.
-
2
class FixtureSet
-
#--
-
# An instance of FixtureSet is normally stored in a single YAML file and possibly in a folder with the same name.
-
#++
-
-
2
MAX_ID = 2 ** 30 - 1
-
-
3
@@all_cached_fixtures = Hash.new { |h,k| h[k] = {} }
-
-
2
def self.default_fixture_model_name(fixture_set_name, config = ActiveRecord::Base) # :nodoc:
-
config.pluralize_table_names ?
-
fixture_set_name.singularize.camelize :
-
fixture_set_name.camelize
-
end
-
-
2
def self.default_fixture_table_name(fixture_set_name, config = ActiveRecord::Base) # :nodoc:
-
"#{ config.table_name_prefix }"\
-
"#{ fixture_set_name.tr('/', '_') }"\
-
"#{ config.table_name_suffix }".to_sym
-
end
-
-
2
def self.reset_cache
-
@@all_cached_fixtures.clear
-
end
-
-
2
def self.cache_for_connection(connection)
-
21
@@all_cached_fixtures[connection]
-
end
-
-
2
def self.fixture_is_cached?(connection, table_name)
-
cache_for_connection(connection)[table_name]
-
end
-
-
2
def self.cached_fixtures(connection, keys_to_fetch = nil)
-
21
if keys_to_fetch
-
21
cache_for_connection(connection).values_at(*keys_to_fetch)
-
else
-
cache_for_connection(connection).values
-
end
-
end
-
-
2
def self.cache_fixtures(connection, fixtures_map)
-
cache_for_connection(connection).update(fixtures_map)
-
end
-
-
2
def self.instantiate_fixtures(object, fixture_set, load_instances = true)
-
if load_instances
-
fixture_set.each do |fixture_name, fixture|
-
begin
-
object.instance_variable_set "@#{fixture_name}", fixture.find
-
rescue FixtureClassNotFound
-
nil
-
end
-
end
-
end
-
end
-
-
2
def self.instantiate_all_loaded_fixtures(object, load_instances = true)
-
all_loaded_fixtures.each_value do |fixture_set|
-
instantiate_fixtures(object, fixture_set, load_instances)
-
end
-
end
-
-
2
cattr_accessor :all_loaded_fixtures
-
2
self.all_loaded_fixtures = {}
-
-
2
class ClassCache
-
2
def initialize(class_names, config)
-
21
@class_names = class_names.stringify_keys
-
21
@config = config
-
-
# Remove string values that aren't constants or subclasses of AR
-
21
@class_names.delete_if { |k,klass|
-
unless klass.is_a? Class
-
klass = klass.safe_constantize
-
ActiveSupport::Deprecation.warn("The ability to pass in strings as a class name to `set_fixture_class` will be removed in Rails 4.2. Use the class itself instead.")
-
end
-
!insert_class(@class_names, k, klass)
-
}
-
end
-
-
2
def [](fs_name)
-
@class_names.fetch(fs_name) {
-
klass = default_fixture_model(fs_name, @config).safe_constantize
-
insert_class(@class_names, fs_name, klass)
-
}
-
end
-
-
2
private
-
-
2
def insert_class(class_names, name, klass)
-
# We only want to deal with AR objects.
-
if klass && klass < ActiveRecord::Base
-
class_names[name] = klass
-
else
-
class_names[name] = nil
-
end
-
end
-
-
2
def default_fixture_model(fs_name, config)
-
ActiveRecord::FixtureSet.default_fixture_model_name(fs_name, config)
-
end
-
end
-
-
2
def self.create_fixtures(fixtures_directory, fixture_set_names, class_names = {}, config = ActiveRecord::Base)
-
21
fixture_set_names = Array(fixture_set_names).map(&:to_s)
-
21
class_names = ClassCache.new class_names, config
-
-
# FIXME: Apparently JK uses this.
-
21
connection = block_given? ? yield : ActiveRecord::Base.connection
-
-
21
files_to_read = fixture_set_names.reject { |fs_name|
-
fixture_is_cached?(connection, fs_name)
-
}
-
-
21
unless files_to_read.empty?
-
connection.disable_referential_integrity do
-
fixtures_map = {}
-
-
fixture_sets = files_to_read.map do |fs_name|
-
klass = class_names[fs_name]
-
conn = klass ? klass.connection : connection
-
fixtures_map[fs_name] = new( # ActiveRecord::FixtureSet.new
-
conn,
-
fs_name,
-
klass,
-
::File.join(fixtures_directory, fs_name))
-
end
-
-
all_loaded_fixtures.update(fixtures_map)
-
-
connection.transaction(:requires_new => true) do
-
fixture_sets.each do |fs|
-
conn = fs.model_class.respond_to?(:connection) ? fs.model_class.connection : connection
-
table_rows = fs.table_rows
-
-
table_rows.keys.each do |table|
-
conn.delete "DELETE FROM #{conn.quote_table_name(table)}", 'Fixture Delete'
-
end
-
-
table_rows.each do |fixture_set_name, rows|
-
rows.each do |row|
-
conn.insert_fixture(row, fixture_set_name)
-
end
-
end
-
end
-
-
# Cap primary key sequences to max(pk).
-
if connection.respond_to?(:reset_pk_sequence!)
-
fixture_sets.each do |fs|
-
connection.reset_pk_sequence!(fs.table_name)
-
end
-
end
-
end
-
-
cache_fixtures(connection, fixtures_map)
-
end
-
end
-
21
cached_fixtures(connection, fixture_set_names)
-
end
-
-
# Returns a consistent, platform-independent identifier for +label+.
-
# Identifiers are positive integers less than 2^32.
-
2
def self.identify(label)
-
Zlib.crc32(label.to_s) % MAX_ID
-
end
-
-
# Superclass for the evaluation contexts used by ERB fixtures.
-
2
def self.context_class
-
@context_class ||= Class.new
-
end
-
-
2
attr_reader :table_name, :name, :fixtures, :model_class, :config
-
-
2
def initialize(connection, name, class_name, path, config = ActiveRecord::Base)
-
@name = name
-
@path = path
-
@config = config
-
@model_class = nil
-
-
if class_name.is_a?(String)
-
ActiveSupport::Deprecation.warn("The ability to pass in strings as a class name to `FixtureSet.new` will be removed in Rails 4.2. Use the class itself instead.")
-
end
-
-
if class_name.is_a?(Class) # TODO: Should be an AR::Base type class, or any?
-
@model_class = class_name
-
else
-
@model_class = class_name.safe_constantize if class_name
-
end
-
-
@connection = connection
-
-
@table_name = ( model_class.respond_to?(:table_name) ?
-
model_class.table_name :
-
self.class.default_fixture_table_name(name, config) )
-
-
@fixtures = read_fixture_files path, @model_class
-
end
-
-
2
def [](x)
-
fixtures[x]
-
end
-
-
2
def []=(k,v)
-
fixtures[k] = v
-
end
-
-
2
def each(&block)
-
fixtures.each(&block)
-
end
-
-
2
def size
-
fixtures.size
-
end
-
-
# Returns a hash of rows to be inserted. The key is the table, the value is
-
# a list of rows to insert to that table.
-
2
def table_rows
-
now = config.default_timezone == :utc ? Time.now.utc : Time.now
-
now = now.to_s(:db)
-
-
# allow a standard key to be used for doing defaults in YAML
-
fixtures.delete('DEFAULTS')
-
-
# track any join tables we need to insert later
-
rows = Hash.new { |h,table| h[table] = [] }
-
-
rows[table_name] = fixtures.map do |label, fixture|
-
row = fixture.to_hash
-
-
if model_class
-
# fill in timestamp columns if they aren't specified and the model is set to record_timestamps
-
if model_class.record_timestamps
-
timestamp_column_names.each do |c_name|
-
row[c_name] = now unless row.key?(c_name)
-
end
-
end
-
-
# interpolate the fixture label
-
row.each do |key, value|
-
row[key] = label if "$LABEL" == value
-
end
-
-
# generate a primary key if necessary
-
if has_primary_key_column? && !row.include?(primary_key_name)
-
row[primary_key_name] = ActiveRecord::FixtureSet.identify(label)
-
end
-
-
# If STI is used, find the correct subclass for association reflection
-
reflection_class =
-
if row.include?(inheritance_column_name)
-
row[inheritance_column_name].constantize rescue model_class
-
else
-
model_class
-
end
-
-
reflection_class._reflections.values.each do |association|
-
case association.macro
-
when :belongs_to
-
# Do not replace association name with association foreign key if they are named the same
-
fk_name = (association.options[:foreign_key] || "#{association.name}_id").to_s
-
-
if association.name.to_s != fk_name && value = row.delete(association.name.to_s)
-
if association.options[:polymorphic] && value.sub!(/\s*\(([^\)]*)\)\s*$/, "")
-
# support polymorphic belongs_to as "label (Type)"
-
row[association.foreign_type] = $1
-
end
-
-
row[fk_name] = ActiveRecord::FixtureSet.identify(value)
-
end
-
when :has_many
-
if association.options[:through]
-
add_join_records(rows, row, HasManyThroughProxy.new(association))
-
end
-
end
-
end
-
end
-
-
row
-
end
-
rows
-
end
-
-
2
class ReflectionProxy # :nodoc:
-
2
def initialize(association)
-
@association = association
-
end
-
-
2
def join_table
-
@association.join_table
-
end
-
-
2
def name
-
@association.name
-
end
-
end
-
-
2
class HasManyThroughProxy < ReflectionProxy # :nodoc:
-
2
def rhs_key
-
@association.foreign_key
-
end
-
-
2
def lhs_key
-
@association.through_reflection.foreign_key
-
end
-
end
-
-
2
private
-
2
def primary_key_name
-
@primary_key_name ||= model_class && model_class.primary_key
-
end
-
-
2
def add_join_records(rows, row, association)
-
# This is the case when the join table has no fixtures file
-
if (targets = row.delete(association.name.to_s))
-
table_name = association.join_table
-
lhs_key = association.lhs_key
-
rhs_key = association.rhs_key
-
-
targets = targets.is_a?(Array) ? targets : targets.split(/\s*,\s*/)
-
rows[table_name].concat targets.map { |target|
-
{ lhs_key => row[primary_key_name],
-
rhs_key => ActiveRecord::FixtureSet.identify(target) }
-
}
-
end
-
end
-
-
2
def has_primary_key_column?
-
@has_primary_key_column ||= primary_key_name &&
-
model_class.columns.any? { |c| c.name == primary_key_name }
-
end
-
-
2
def timestamp_column_names
-
@timestamp_column_names ||=
-
%w(created_at created_on updated_at updated_on) & column_names
-
end
-
-
2
def inheritance_column_name
-
@inheritance_column_name ||= model_class && model_class.inheritance_column
-
end
-
-
2
def column_names
-
@column_names ||= @connection.columns(@table_name).collect { |c| c.name }
-
end
-
-
2
def read_fixture_files(path, model_class)
-
yaml_files = Dir["#{path}/{**,*}/*.yml"].select { |f|
-
::File.file?(f)
-
} + [yaml_file_path(path)]
-
-
yaml_files.each_with_object({}) do |file, fixtures|
-
FixtureSet::File.open(file) do |fh|
-
fh.each do |fixture_name, row|
-
fixtures[fixture_name] = ActiveRecord::Fixture.new(row, model_class)
-
end
-
end
-
end
-
end
-
-
2
def yaml_file_path(path)
-
"#{path}.yml"
-
end
-
-
end
-
-
#--
-
# Deprecate 'Fixtures' in favor of 'FixtureSet'.
-
#++
-
# :nodoc:
-
2
Fixtures = ActiveSupport::Deprecation::DeprecatedConstantProxy.new('ActiveRecord::Fixtures', 'ActiveRecord::FixtureSet')
-
-
2
class Fixture #:nodoc:
-
2
include Enumerable
-
-
2
class FixtureError < StandardError #:nodoc:
-
end
-
-
2
class FormatError < FixtureError #:nodoc:
-
end
-
-
2
attr_reader :model_class, :fixture
-
-
2
def initialize(fixture, model_class)
-
@fixture = fixture
-
@model_class = model_class
-
end
-
-
2
def class_name
-
model_class.name if model_class
-
end
-
-
2
def each
-
fixture.each { |item| yield item }
-
end
-
-
2
def [](key)
-
fixture[key]
-
end
-
-
2
alias :to_hash :fixture
-
-
2
def find
-
if model_class
-
model_class.find(fixture[model_class.primary_key])
-
else
-
raise FixtureClassNotFound, "No class attached to find."
-
end
-
end
-
end
-
end
-
-
2
module ActiveRecord
-
2
module TestFixtures
-
2
extend ActiveSupport::Concern
-
-
2
def before_setup
-
21
setup_fixtures
-
21
super
-
end
-
-
2
def after_teardown
-
21
super
-
21
teardown_fixtures
-
end
-
-
2
included do
-
14
class_attribute :fixture_path, :instance_writer => false
-
14
class_attribute :fixture_table_names
-
14
class_attribute :fixture_class_names
-
14
class_attribute :use_transactional_fixtures
-
14
class_attribute :use_instantiated_fixtures # true, false, or :no_instances
-
14
class_attribute :pre_loaded_fixtures
-
14
class_attribute :config
-
-
14
self.fixture_table_names = []
-
14
self.use_transactional_fixtures = true
-
14
self.use_instantiated_fixtures = false
-
14
self.pre_loaded_fixtures = false
-
14
self.config = ActiveRecord::Base
-
-
14
self.fixture_class_names = Hash.new do |h, fixture_set_name|
-
h[fixture_set_name] = ActiveRecord::FixtureSet.default_fixture_model_name(fixture_set_name, self.config)
-
end
-
end
-
-
2
module ClassMethods
-
# Sets the model class for a fixture when the class name cannot be inferred from the fixture name.
-
#
-
# Examples:
-
#
-
# set_fixture_class some_fixture: SomeModel,
-
# 'namespaced/fixture' => Another::Model
-
#
-
# The keys must be the fixture names, that coincide with the short paths to the fixture files.
-
2
def set_fixture_class(class_names = {})
-
self.fixture_class_names = self.fixture_class_names.merge(class_names.stringify_keys)
-
end
-
-
2
def fixtures(*fixture_set_names)
-
if fixture_set_names.first == :all
-
fixture_set_names = Dir["#{fixture_path}/{**,*}/*.{yml}"]
-
fixture_set_names.map! { |f| f[(fixture_path.to_s.size + 1)..-5] }
-
else
-
fixture_set_names = fixture_set_names.flatten.map { |n| n.to_s }
-
end
-
-
self.fixture_table_names |= fixture_set_names
-
require_fixture_classes(fixture_set_names, self.config)
-
setup_fixture_accessors(fixture_set_names)
-
end
-
-
2
def try_to_load_dependency(file_name)
-
require_dependency file_name
-
rescue LoadError => e
-
unless fixture_class_names.key?(file_name.pluralize)
-
if ActiveRecord::Base.logger
-
ActiveRecord::Base.logger.warn("Unable to load #{file_name}, make sure you added it to ActiveSupport::TestCase.set_fixture_class")
-
ActiveRecord::Base.logger.warn("underlying cause #{e.message} \n\n #{e.backtrace.join("\n")}")
-
end
-
end
-
end
-
-
2
def require_fixture_classes(fixture_set_names = nil, config = ActiveRecord::Base)
-
if fixture_set_names
-
fixture_set_names = fixture_set_names.map { |n| n.to_s }
-
else
-
fixture_set_names = fixture_table_names
-
end
-
-
fixture_set_names.each do |file_name|
-
file_name = file_name.singularize if config.pluralize_table_names
-
try_to_load_dependency(file_name)
-
end
-
end
-
-
2
def setup_fixture_accessors(fixture_set_names = nil)
-
fixture_set_names = Array(fixture_set_names || fixture_table_names)
-
methods = Module.new do
-
fixture_set_names.each do |fs_name|
-
fs_name = fs_name.to_s
-
accessor_name = fs_name.tr('/', '_').to_sym
-
-
define_method(accessor_name) do |*fixture_names|
-
force_reload = fixture_names.pop if fixture_names.last == true || fixture_names.last == :reload
-
-
@fixture_cache[fs_name] ||= {}
-
-
instances = fixture_names.map do |f_name|
-
f_name = f_name.to_s
-
@fixture_cache[fs_name].delete(f_name) if force_reload
-
-
if @loaded_fixtures[fs_name][f_name]
-
@fixture_cache[fs_name][f_name] ||= @loaded_fixtures[fs_name][f_name].find
-
else
-
raise StandardError, "No fixture named '#{f_name}' found for fixture set '#{fs_name}'"
-
end
-
end
-
-
instances.size == 1 ? instances.first : instances
-
end
-
private accessor_name
-
end
-
end
-
include methods
-
end
-
-
2
def uses_transaction(*methods)
-
@uses_transaction = [] unless defined?(@uses_transaction)
-
@uses_transaction.concat methods.map { |m| m.to_s }
-
end
-
-
2
def uses_transaction?(method)
-
42
@uses_transaction = [] unless defined?(@uses_transaction)
-
42
@uses_transaction.include?(method.to_s)
-
end
-
end
-
-
2
def run_in_transaction?
-
use_transactional_fixtures &&
-
42
!self.class.uses_transaction?(method_name)
-
end
-
-
2
def setup_fixtures(config = ActiveRecord::Base)
-
21
if pre_loaded_fixtures && !use_transactional_fixtures
-
raise RuntimeError, 'pre_loaded_fixtures requires use_transactional_fixtures'
-
end
-
-
21
@fixture_cache = {}
-
21
@fixture_connections = []
-
21
@@already_loaded_fixtures ||= {}
-
-
# Load fixtures once and begin transaction.
-
21
if run_in_transaction?
-
21
if @@already_loaded_fixtures[self.class]
-
@loaded_fixtures = @@already_loaded_fixtures[self.class]
-
else
-
21
@loaded_fixtures = load_fixtures(config)
-
21
@@already_loaded_fixtures[self.class] = @loaded_fixtures
-
end
-
21
@fixture_connections = enlist_fixture_connections
-
21
@fixture_connections.each do |connection|
-
21
connection.begin_transaction joinable: false
-
end
-
# Load fixtures for every test.
-
else
-
ActiveRecord::FixtureSet.reset_cache
-
@@already_loaded_fixtures[self.class] = nil
-
@loaded_fixtures = load_fixtures(config)
-
end
-
-
# Instantiate fixtures for every test if requested.
-
21
instantiate_fixtures(config) if use_instantiated_fixtures
-
end
-
-
2
def teardown_fixtures
-
# Rollback changes if a transaction is active.
-
21
if run_in_transaction?
-
21
@fixture_connections.each do |connection|
-
21
connection.rollback_transaction if connection.transaction_open?
-
end
-
21
@fixture_connections.clear
-
else
-
ActiveRecord::FixtureSet.reset_cache
-
end
-
-
21
ActiveRecord::Base.clear_active_connections!
-
end
-
-
2
def enlist_fixture_connections
-
21
ActiveRecord::Base.connection_handler.connection_pool_list.map(&:connection)
-
end
-
-
2
private
-
2
def load_fixtures(config)
-
21
fixtures = ActiveRecord::FixtureSet.create_fixtures(fixture_path, fixture_table_names, fixture_class_names, config)
-
21
Hash[fixtures.map { |f| [f.name, f] }]
-
end
-
-
# for pre_loaded_fixtures, only require the classes once. huge speed improvement
-
2
@@required_fixture_classes = false
-
-
2
def instantiate_fixtures(config)
-
if pre_loaded_fixtures
-
raise RuntimeError, 'Load fixtures before instantiating them.' if ActiveRecord::FixtureSet.all_loaded_fixtures.empty?
-
unless @@required_fixture_classes
-
self.class.require_fixture_classes ActiveRecord::FixtureSet.all_loaded_fixtures.keys, config
-
@@required_fixture_classes = true
-
end
-
ActiveRecord::FixtureSet.instantiate_all_loaded_fixtures(self, load_instances?)
-
else
-
raise RuntimeError, 'Load fixtures before instantiating them.' if @loaded_fixtures.nil?
-
@loaded_fixtures.each_value do |fixture_set|
-
ActiveRecord::FixtureSet.instantiate_fixtures(self, fixture_set, load_instances?)
-
end
-
end
-
end
-
-
2
def load_instances?
-
use_instantiated_fixtures != :no_instances
-
end
-
end
-
end
-
-
2
class ActiveRecord::FixtureSet::RenderContext # :nodoc:
-
2
def self.create_subclass
-
Class.new ActiveRecord::FixtureSet.context_class do
-
def get_binding
-
binding()
-
end
-
end
-
end
-
end
-
2
module ActiveRecord
-
# Returns the version of the currently loaded ActiveRecord as a <tt>Gem::Version</tt>
-
2
def self.gem_version
-
Gem::Version.new VERSION::STRING
-
end
-
-
2
module VERSION
-
2
MAJOR = 4
-
2
MINOR = 1
-
2
TINY = 8
-
2
PRE = nil
-
-
2
STRING = [MAJOR, MINOR, TINY, PRE].compact.join(".")
-
end
-
end
-
2
require 'active_support/core_ext/hash/indifferent_access'
-
-
2
module ActiveRecord
-
2
module Inheritance
-
2
extend ActiveSupport::Concern
-
-
2
included do
-
# Determines whether to store the full constant name including namespace when using STI.
-
2
class_attribute :store_full_sti_class, instance_writer: false
-
2
self.store_full_sti_class = true
-
end
-
-
2
module ClassMethods
-
# Determines if one of the attributes passed in is the inheritance column,
-
# and if the inheritance column is attr accessible, it initializes an
-
# instance of the given subclass instead of the base class.
-
2
def new(*args, &block)
-
279
if abstract_class? || self == Base
-
raise NotImplementedError, "#{self} is an abstract class and cannot be instantiated."
-
end
-
-
279
attrs = args.first
-
279
if subclass_from_attributes?(attrs)
-
subclass = subclass_from_attributes(attrs)
-
end
-
-
279
if subclass
-
subclass.new(*args, &block)
-
else
-
279
super
-
end
-
end
-
-
# Returns +true+ if this does not need STI type condition. Returns
-
# +false+ if STI type condition needs to be applied.
-
2
def descends_from_active_record?
-
10
if self == Base
-
false
-
10
elsif superclass.abstract_class?
-
superclass.descends_from_active_record?
-
else
-
10
superclass == Base || !columns_hash.include?(inheritance_column)
-
end
-
end
-
-
2
def finder_needs_type_condition? #:nodoc:
-
# This is like this because benchmarking justifies the strange :false stuff
-
1133
:true == (@finder_needs_type_condition ||= descends_from_active_record? ? :false : :true)
-
end
-
-
2
def symbolized_base_class
-
ActiveSupport::Deprecation.warn("ActiveRecord::Base.symbolized_base_class is deprecated and will be removed without replacement.")
-
@symbolized_base_class ||= base_class.to_s.to_sym
-
end
-
-
2
def symbolized_sti_name
-
ActiveSupport::Deprecation.warn("ActiveRecord::Base.symbolized_sti_name is deprecated and will be removed without replacement.")
-
@symbolized_sti_name ||= sti_name.present? ? sti_name.to_sym : symbolized_base_class
-
end
-
-
# Returns the class descending directly from ActiveRecord::Base, or
-
# an abstract class, if any, in the inheritance hierarchy.
-
#
-
# If A extends AR::Base, A.base_class will return A. If B descends from A
-
# through some arbitrarily deep hierarchy, B.base_class will return A.
-
#
-
# If B < A and C < B and if A is an abstract_class then both B.base_class
-
# and C.base_class would return B as the answer since A is an abstract_class.
-
2
def base_class
-
1464
unless self < Base
-
raise ActiveRecordError, "#{name} doesn't belong in a hierarchy descending from ActiveRecord"
-
end
-
-
1464
if superclass == Base || superclass.abstract_class?
-
1244
self
-
else
-
220
superclass.base_class
-
end
-
end
-
-
# Set this to true if this is an abstract class (see <tt>abstract_class?</tt>).
-
# If you are using inheritance with ActiveRecord and don't want child classes
-
# to utilize the implied STI table name of the parent class, this will need to be true.
-
# For example, given the following:
-
#
-
# class SuperClass < ActiveRecord::Base
-
# self.abstract_class = true
-
# end
-
# class Child < SuperClass
-
# self.table_name = 'the_table_i_really_want'
-
# end
-
#
-
#
-
# <tt>self.abstract_class = true</tt> is required to make <tt>Child<.find,.create, or any Arel method></tt> use <tt>the_table_i_really_want</tt> instead of a table called <tt>super_classes</tt>
-
#
-
2
attr_accessor :abstract_class
-
-
# Returns whether this class is an abstract class or not.
-
2
def abstract_class?
-
722
defined?(@abstract_class) && @abstract_class == true
-
end
-
-
2
def sti_name
-
store_full_sti_class ? name : name.demodulize
-
end
-
-
2
protected
-
-
# Returns the class type of the record using the current module as a prefix. So descendants of
-
# MyApp::Business::Account would appear as MyApp::Business::AccountSubclass.
-
2
def compute_type(type_name)
-
1
if type_name.match(/^::/)
-
# If the type is prefixed with a scope operator then we assume that
-
# the type_name is an absolute reference.
-
1
ActiveSupport::Dependencies.constantize(type_name)
-
else
-
# Build a list of candidates to search for
-
candidates = []
-
name.scan(/::|$/) { candidates.unshift "#{$`}::#{type_name}" }
-
candidates << type_name
-
-
candidates.each do |candidate|
-
begin
-
constant = ActiveSupport::Dependencies.constantize(candidate)
-
return constant if candidate == constant.to_s
-
# We don't want to swallow NoMethodError < NameError errors
-
rescue NoMethodError
-
raise
-
rescue NameError
-
end
-
end
-
-
raise NameError.new("uninitialized constant #{candidates.first}", candidates.first)
-
end
-
end
-
-
2
private
-
-
# Called by +instantiate+ to decide which class to use for a new
-
# record instance. For single-table inheritance, we check the record
-
# for a +type+ column and return the corresponding class.
-
2
def discriminate_class_for_record(record)
-
32
if using_single_table_inheritance?(record)
-
find_sti_class(record[inheritance_column])
-
else
-
32
super
-
end
-
end
-
-
2
def using_single_table_inheritance?(record)
-
32
record[inheritance_column].present? && columns_hash.include?(inheritance_column)
-
end
-
-
2
def find_sti_class(type_name)
-
if store_full_sti_class
-
ActiveSupport::Dependencies.constantize(type_name)
-
else
-
compute_type(type_name)
-
end
-
rescue NameError
-
raise SubclassNotFound,
-
"The single-table inheritance mechanism failed to locate the subclass: '#{type_name}'. " +
-
"This error is raised because the column '#{inheritance_column}' is reserved for storing the class in case of inheritance. " +
-
"Please rename this column if you didn't intend it to be used for storing the inheritance class " +
-
"or overwrite #{name}.inheritance_column to use another column for that information."
-
end
-
-
2
def type_condition(table = arel_table)
-
sti_column = table[inheritance_column]
-
sti_names = ([self] + descendants).map { |model| model.sti_name }
-
-
sti_column.in(sti_names)
-
end
-
-
# Detect the subclass from the inheritance column of attrs. If the inheritance column value
-
# is not self or a valid subclass, raises ActiveRecord::SubclassNotFound
-
# If this is a StrongParameters hash, and access to inheritance_column is not permitted,
-
# this will ignore the inheritance column and return nil
-
2
def subclass_from_attributes?(attrs)
-
279
columns_hash.include?(inheritance_column) && attrs.is_a?(Hash)
-
end
-
-
2
def subclass_from_attributes(attrs)
-
subclass_name = attrs.with_indifferent_access[inheritance_column]
-
-
if subclass_name.present? && subclass_name != self.name
-
subclass = subclass_name.safe_constantize
-
-
unless descendants.include?(subclass)
-
raise ActiveRecord::SubclassNotFound.new("Invalid single-table inheritance type: #{subclass_name} is not a subclass of #{name}")
-
end
-
-
subclass
-
end
-
end
-
end
-
-
2
def initialize_dup(other)
-
super
-
ensure_proper_type
-
end
-
-
2
private
-
-
2
def initialize_internals_callback
-
279
super
-
279
ensure_proper_type
-
end
-
-
# Sets the attribute used for single table inheritance to this class name if this is not the
-
# ActiveRecord::Base descendant.
-
# Considering the hierarchy Reply < Message < ActiveRecord::Base, this makes it possible to
-
# do Reply.new without having to set <tt>Reply[Reply.inheritance_column] = "Reply"</tt> yourself.
-
# No such attribute would be set for objects of the Message class in that example.
-
2
def ensure_proper_type
-
279
klass = self.class
-
279
if klass.finder_needs_type_condition?
-
write_attribute(klass.inheritance_column, klass.sti_name)
-
end
-
end
-
end
-
end
-
2
require 'active_support/core_ext/string/filters'
-
-
2
module ActiveRecord
-
2
module Integration
-
2
extend ActiveSupport::Concern
-
-
2
included do
-
##
-
# :singleton-method:
-
# Indicates the format used to generate the timestamp in the cache key.
-
# Accepts any of the symbols in <tt>Time::DATE_FORMATS</tt>.
-
#
-
# This is +:nsec+, by default.
-
2
class_attribute :cache_timestamp_format, :instance_writer => false
-
2
self.cache_timestamp_format = :nsec
-
end
-
-
# Returns a String, which Action Pack uses for constructing an URL to this
-
# object. The default implementation returns this record's id as a String,
-
# or nil if this record's unsaved.
-
#
-
# For example, suppose that you have a User model, and that you have a
-
# <tt>resources :users</tt> route. Normally, +user_path+ will
-
# construct a path with the user object's 'id' in it:
-
#
-
# user = User.find_by(name: 'Phusion')
-
# user_path(user) # => "/users/1"
-
#
-
# You can override +to_param+ in your model to make +user_path+ construct
-
# a path using the user's name instead of the user's id:
-
#
-
# class User < ActiveRecord::Base
-
# def to_param # overridden
-
# name
-
# end
-
# end
-
#
-
# user = User.find_by(name: 'Phusion')
-
# user_path(user) # => "/users/Phusion"
-
2
def to_param
-
# We can't use alias_method here, because method 'id' optimizes itself on the fly.
-
id && id.to_s # Be sure to stringify the id for routes
-
end
-
-
# Returns a cache key that can be used to identify this record.
-
#
-
# Product.new.cache_key # => "products/new"
-
# Product.find(5).cache_key # => "products/5" (updated_at not available)
-
# Person.find(5).cache_key # => "people/5-20071224150000" (updated_at available)
-
#
-
# You can also pass a list of named timestamps, and the newest in the list will be
-
# used to generate the key:
-
#
-
# Person.find(5).cache_key(:updated_at, :last_reviewed_at)
-
2
def cache_key(*timestamp_names)
-
case
-
when new_record?
-
"#{self.class.model_name.cache_key}/new"
-
when timestamp_names.any?
-
timestamp = max_updated_column_timestamp(timestamp_names)
-
timestamp = timestamp.utc.to_s(cache_timestamp_format)
-
"#{self.class.model_name.cache_key}/#{id}-#{timestamp}"
-
when timestamp = max_updated_column_timestamp
-
timestamp = timestamp.utc.to_s(cache_timestamp_format)
-
"#{self.class.model_name.cache_key}/#{id}-#{timestamp}"
-
else
-
"#{self.class.model_name.cache_key}/#{id}"
-
end
-
end
-
-
2
module ClassMethods
-
# Defines your model's +to_param+ method to generate "pretty" URLs
-
# using +method_name+, which can be any attribute or method that
-
# responds to +to_s+.
-
#
-
# class User < ActiveRecord::Base
-
# to_param :name
-
# end
-
#
-
# user = User.find_by(name: 'Fancy Pants')
-
# user.id # => 123
-
# user_path(user) # => "/users/123-fancy-pants"
-
#
-
# Values longer than 20 characters will be truncated. The value
-
# is truncated word by word.
-
#
-
# user = User.find_by(name: 'David HeinemeierHansson')
-
# user.id # => 125
-
# user_path(user) # => "/users/125-david"
-
#
-
# Because the generated param begins with the record's +id+, it is
-
# suitable for passing to +find+. In a controller, for example:
-
#
-
# params[:id] # => "123-fancy-pants"
-
# User.find(params[:id]).id # => 123
-
2
def to_param(method_name = nil)
-
if method_name.nil?
-
super()
-
else
-
define_method :to_param do
-
if (default = super()) &&
-
(result = send(method_name).to_s).present? &&
-
(param = result.squish.truncate(20, separator: /\s/, omission: nil).parameterize).present?
-
"#{default}-#{param}"
-
else
-
default
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
2
module ActiveRecord
-
2
module Locking
-
# == What is Optimistic Locking
-
#
-
# Optimistic locking allows multiple users to access the same record for edits, and assumes a minimum of
-
# conflicts with the data. It does this by checking whether another process has made changes to a record since
-
# it was opened, an <tt>ActiveRecord::StaleObjectError</tt> exception is thrown if that has occurred
-
# and the update is ignored.
-
#
-
# Check out <tt>ActiveRecord::Locking::Pessimistic</tt> for an alternative.
-
#
-
# == Usage
-
#
-
# Active Records support optimistic locking if the field +lock_version+ is present. Each update to the
-
# record increments the +lock_version+ column and the locking facilities ensure that records instantiated twice
-
# will let the last one saved raise a +StaleObjectError+ if the first was also updated. Example:
-
#
-
# p1 = Person.find(1)
-
# p2 = Person.find(1)
-
#
-
# p1.first_name = "Michael"
-
# p1.save
-
#
-
# p2.first_name = "should fail"
-
# p2.save # Raises a ActiveRecord::StaleObjectError
-
#
-
# Optimistic locking will also check for stale data when objects are destroyed. Example:
-
#
-
# p1 = Person.find(1)
-
# p2 = Person.find(1)
-
#
-
# p1.first_name = "Michael"
-
# p1.save
-
#
-
# p2.destroy # Raises a ActiveRecord::StaleObjectError
-
#
-
# You're then responsible for dealing with the conflict by rescuing the exception and either rolling back, merging,
-
# or otherwise apply the business logic needed to resolve the conflict.
-
#
-
# This locking mechanism will function inside a single Ruby process. To make it work across all
-
# web requests, the recommended approach is to add +lock_version+ as a hidden field to your form.
-
#
-
# This behavior can be turned off by setting <tt>ActiveRecord::Base.lock_optimistically = false</tt>.
-
# To override the name of the +lock_version+ column, set the <tt>locking_column</tt> class attribute:
-
#
-
# class Person < ActiveRecord::Base
-
# self.locking_column = :lock_person
-
# end
-
#
-
2
module Optimistic
-
2
extend ActiveSupport::Concern
-
-
2
included do
-
2
class_attribute :lock_optimistically, instance_writer: false
-
2
self.lock_optimistically = true
-
end
-
-
2
def locking_enabled? #:nodoc:
-
self.class.locking_enabled?
-
end
-
-
2
private
-
2
def increment_lock
-
lock_col = self.class.locking_column
-
previous_lock_value = send(lock_col).to_i
-
send(lock_col + '=', previous_lock_value + 1)
-
end
-
-
2
def _update_record(attribute_names = @attributes.keys) #:nodoc:
-
return super unless locking_enabled?
-
return 0 if attribute_names.empty?
-
-
lock_col = self.class.locking_column
-
previous_lock_value = send(lock_col).to_i
-
increment_lock
-
-
attribute_names += [lock_col]
-
attribute_names.uniq!
-
-
begin
-
relation = self.class.unscoped
-
-
stmt = relation.where(
-
relation.table[self.class.primary_key].eq(id).and(
-
relation.table[lock_col].eq(self.class.quote_value(previous_lock_value, column_for_attribute(lock_col)))
-
)
-
).arel.compile_update(
-
arel_attributes_with_values_for_update(attribute_names),
-
self.class.primary_key
-
)
-
-
affected_rows = self.class.connection.update stmt
-
-
unless affected_rows == 1
-
raise ActiveRecord::StaleObjectError.new(self, "update")
-
end
-
-
affected_rows
-
-
# If something went wrong, revert the version.
-
rescue Exception
-
send(lock_col + '=', previous_lock_value)
-
raise
-
end
-
end
-
-
2
def destroy_row
-
affected_rows = super
-
-
if locking_enabled? && affected_rows != 1
-
raise ActiveRecord::StaleObjectError.new(self, "destroy")
-
end
-
-
affected_rows
-
end
-
-
2
def relation_for_destroy
-
relation = super
-
-
if locking_enabled?
-
column_name = self.class.locking_column
-
column = self.class.columns_hash[column_name]
-
substitute = self.class.connection.substitute_at(column, relation.bind_values.length)
-
-
relation = relation.where(self.class.arel_table[column_name].eq(substitute))
-
relation.bind_values << [column, self[column_name].to_i]
-
end
-
-
relation
-
end
-
-
2
module ClassMethods
-
2
DEFAULT_LOCKING_COLUMN = 'lock_version'
-
-
# Returns true if the +lock_optimistically+ flag is set to true
-
# (which it is, by default) and the table includes the
-
# +locking_column+ column (defaults to +lock_version+).
-
2
def locking_enabled?
-
lock_optimistically && columns_hash[locking_column]
-
end
-
-
# Set the column to use for optimistic locking. Defaults to +lock_version+.
-
2
def locking_column=(value)
-
9
@column_defaults = nil
-
9
@locking_column = value.to_s
-
end
-
-
# The version column used for optimistic locking. Defaults to +lock_version+.
-
2
def locking_column
-
9
reset_locking_column unless defined?(@locking_column)
-
9
@locking_column
-
end
-
-
# Quote the column name used for optimistic locking.
-
2
def quoted_locking_column
-
ActiveSupport::Deprecation.warn "ActiveRecord::Base.quoted_locking_column is deprecated and will be removed in Rails 4.2 or later."
-
connection.quote_column_name(locking_column)
-
end
-
-
# Reset the column used for optimistic locking back to the +lock_version+ default.
-
2
def reset_locking_column
-
9
self.locking_column = DEFAULT_LOCKING_COLUMN
-
end
-
-
# Make sure the lock version column gets updated when counters are
-
# updated.
-
2
def update_counters(id, counters)
-
counters = counters.merge(locking_column => 1) if locking_enabled?
-
super
-
end
-
-
2
def column_defaults
-
@column_defaults ||= begin
-
9
defaults = super
-
-
9
if defaults.key?(locking_column) && lock_optimistically
-
defaults[locking_column] ||= 0
-
end
-
-
9
defaults
-
279
end
-
end
-
end
-
end
-
end
-
end
-
2
module ActiveRecord
-
2
module Locking
-
# Locking::Pessimistic provides support for row-level locking using
-
# SELECT ... FOR UPDATE and other lock types.
-
#
-
# Chain <tt>ActiveRecord::Base#find</tt> to <tt>ActiveRecord::QueryMethods#lock</tt> to obtain an exclusive
-
# lock on the selected rows:
-
# # select * from accounts where id=1 for update
-
# Account.lock.find(1)
-
#
-
# Call <tt>lock('some locking clause')</tt> to use a database-specific locking clause
-
# of your own such as 'LOCK IN SHARE MODE' or 'FOR UPDATE NOWAIT'. Example:
-
#
-
# Account.transaction do
-
# # select * from accounts where name = 'shugo' limit 1 for update
-
# shugo = Account.where("name = 'shugo'").lock(true).first
-
# yuko = Account.where("name = 'yuko'").lock(true).first
-
# shugo.balance -= 100
-
# shugo.save!
-
# yuko.balance += 100
-
# yuko.save!
-
# end
-
#
-
# You can also use <tt>ActiveRecord::Base#lock!</tt> method to lock one record by id.
-
# This may be better if you don't need to lock every row. Example:
-
#
-
# Account.transaction do
-
# # select * from accounts where ...
-
# accounts = Account.where(...)
-
# account1 = accounts.detect { |account| ... }
-
# account2 = accounts.detect { |account| ... }
-
# # select * from accounts where id=? for update
-
# account1.lock!
-
# account2.lock!
-
# account1.balance -= 100
-
# account1.save!
-
# account2.balance += 100
-
# account2.save!
-
# end
-
#
-
# You can start a transaction and acquire the lock in one go by calling
-
# <tt>with_lock</tt> with a block. The block is called from within
-
# a transaction, the object is already locked. Example:
-
#
-
# account = Account.first
-
# account.with_lock do
-
# # This block is called within a transaction,
-
# # account is already locked.
-
# account.balance -= 100
-
# account.save!
-
# end
-
#
-
# Database-specific information on row locking:
-
# MySQL: http://dev.mysql.com/doc/refman/5.1/en/innodb-locking-reads.html
-
# PostgreSQL: http://www.postgresql.org/docs/current/interactive/sql-select.html#SQL-FOR-UPDATE-SHARE
-
2
module Pessimistic
-
# Obtain a row lock on this record. Reloads the record to obtain the requested
-
# lock. Pass an SQL locking clause to append the end of the SELECT statement
-
# or pass true for "FOR UPDATE" (the default, an exclusive row lock). Returns
-
# the locked record.
-
2
def lock!(lock = true)
-
reload(:lock => lock) if persisted?
-
self
-
end
-
-
# Wraps the passed block in a transaction, locking the object
-
# before yielding. You can pass the SQL locking clause
-
# as argument (see <tt>lock!</tt>).
-
2
def with_lock(lock = true)
-
transaction do
-
lock!(lock)
-
yield
-
end
-
end
-
end
-
end
-
end
-
2
module ActiveRecord
-
2
class LogSubscriber < ActiveSupport::LogSubscriber
-
2
IGNORE_PAYLOAD_NAMES = ["SCHEMA", "EXPLAIN"]
-
-
2
def self.runtime=(value)
-
1063
ActiveRecord::RuntimeRegistry.sql_runtime = value
-
end
-
-
2
def self.runtime
-
1063
ActiveRecord::RuntimeRegistry.sql_runtime ||= 0
-
end
-
-
2
def self.reset_runtime
-
96
rt, self.runtime = runtime, 0
-
96
rt
-
end
-
-
2
def initialize
-
2
super
-
2
@odd = false
-
end
-
-
2
def render_bind(column, value)
-
1405
if column
-
1405
if column.binary?
-
# This specifically deals with the PG adapter that casts bytea columns into a Hash.
-
value = value[:value] if value.is_a?(Hash)
-
value = value ? "<#{value.bytesize} bytes of binary data>" : "<NULL binary data>"
-
end
-
-
1405
[column.name, value]
-
else
-
[nil, value]
-
end
-
end
-
-
2
def sql(event)
-
967
self.class.runtime += event.duration
-
967
return unless logger.debug?
-
-
967
payload = event.payload
-
-
967
return if IGNORE_PAYLOAD_NAMES.include?(payload[:name])
-
-
938
name = "#{payload[:name]} (#{event.duration.round(1)}ms)"
-
938
sql = payload[:sql]
-
938
binds = nil
-
-
938
unless (payload[:binds] || []).empty?
-
267
binds = " " + payload[:binds].map { |col,v|
-
1405
render_bind(col, v)
-
}.inspect
-
end
-
-
938
if odd?
-
469
name = color(name, CYAN, true)
-
469
sql = color(sql, nil, true)
-
else
-
469
name = color(name, MAGENTA, true)
-
end
-
-
938
debug " #{name} #{sql}#{binds}"
-
end
-
-
2
def odd?
-
938
@odd = !@odd
-
end
-
-
2
def logger
-
4777
ActiveRecord::Base.logger
-
end
-
end
-
end
-
-
2
ActiveRecord::LogSubscriber.attach_to :active_record
-
2
require "active_support/core_ext/module/attribute_accessors"
-
2
require 'set'
-
-
2
module ActiveRecord
-
2
class MigrationError < ActiveRecordError#:nodoc:
-
2
def initialize(message = nil)
-
message = "\n\n#{message}\n\n" if message
-
super
-
end
-
end
-
-
# Exception that can be raised to stop migrations from going backwards.
-
2
class IrreversibleMigration < MigrationError
-
end
-
-
2
class DuplicateMigrationVersionError < MigrationError#:nodoc:
-
2
def initialize(version)
-
super("Multiple migrations have the version number #{version}")
-
end
-
end
-
-
2
class DuplicateMigrationNameError < MigrationError#:nodoc:
-
2
def initialize(name)
-
super("Multiple migrations have the name #{name}")
-
end
-
end
-
-
2
class UnknownMigrationVersionError < MigrationError #:nodoc:
-
2
def initialize(version)
-
super("No migration with version number #{version}")
-
end
-
end
-
-
2
class IllegalMigrationNameError < MigrationError#:nodoc:
-
2
def initialize(name)
-
super("Illegal name for migration file: #{name}\n\t(only lower case letters, numbers, and '_' allowed)")
-
end
-
end
-
-
2
class PendingMigrationError < MigrationError#:nodoc:
-
2
def initialize
-
if defined?(Rails)
-
super("Migrations are pending. To resolve this issue, run:\n\n\tbin/rake db:migrate RAILS_ENV=#{::Rails.env}")
-
else
-
super("Migrations are pending. To resolve this issue, run:\n\n\tbin/rake db:migrate")
-
end
-
end
-
end
-
-
# = Active Record Migrations
-
#
-
# Migrations can manage the evolution of a schema used by several physical
-
# databases. It's a solution to the common problem of adding a field to make
-
# a new feature work in your local database, but being unsure of how to
-
# push that change to other developers and to the production server. With
-
# migrations, you can describe the transformations in self-contained classes
-
# that can be checked into version control systems and executed against
-
# another database that might be one, two, or five versions behind.
-
#
-
# Example of a simple migration:
-
#
-
# class AddSsl < ActiveRecord::Migration
-
# def up
-
# add_column :accounts, :ssl_enabled, :boolean, default: true
-
# end
-
#
-
# def down
-
# remove_column :accounts, :ssl_enabled
-
# end
-
# end
-
#
-
# This migration will add a boolean flag to the accounts table and remove it
-
# if you're backing out of the migration. It shows how all migrations have
-
# two methods +up+ and +down+ that describes the transformations
-
# required to implement or remove the migration. These methods can consist
-
# of both the migration specific methods like +add_column+ and +remove_column+,
-
# but may also contain regular Ruby code for generating data needed for the
-
# transformations.
-
#
-
# Example of a more complex migration that also needs to initialize data:
-
#
-
# class AddSystemSettings < ActiveRecord::Migration
-
# def up
-
# create_table :system_settings do |t|
-
# t.string :name
-
# t.string :label
-
# t.text :value
-
# t.string :type
-
# t.integer :position
-
# end
-
#
-
# SystemSetting.create name: 'notice',
-
# label: 'Use notice?',
-
# value: 1
-
# end
-
#
-
# def down
-
# drop_table :system_settings
-
# end
-
# end
-
#
-
# This migration first adds the +system_settings+ table, then creates the very
-
# first row in it using the Active Record model that relies on the table. It
-
# also uses the more advanced +create_table+ syntax where you can specify a
-
# complete table schema in one block call.
-
#
-
# == Available transformations
-
#
-
# * <tt>create_table(name, options)</tt>: Creates a table called +name+ and
-
# makes the table object available to a block that can then add columns to it,
-
# following the same format as +add_column+. See example above. The options hash
-
# is for fragments like "DEFAULT CHARSET=UTF-8" that are appended to the create
-
# table definition.
-
# * <tt>drop_table(name)</tt>: Drops the table called +name+.
-
# * <tt>change_table(name, options)</tt>: Allows to make column alterations to
-
# the table called +name+. It makes the table object available to a block that
-
# can then add/remove columns, indexes or foreign keys to it.
-
# * <tt>rename_table(old_name, new_name)</tt>: Renames the table called +old_name+
-
# to +new_name+.
-
# * <tt>add_column(table_name, column_name, type, options)</tt>: Adds a new column
-
# to the table called +table_name+
-
# named +column_name+ specified to be one of the following types:
-
# <tt>:string</tt>, <tt>:text</tt>, <tt>:integer</tt>, <tt>:float</tt>,
-
# <tt>:decimal</tt>, <tt>:datetime</tt>, <tt>:timestamp</tt>, <tt>:time</tt>,
-
# <tt>:date</tt>, <tt>:binary</tt>, <tt>:boolean</tt>. A default value can be
-
# specified by passing an +options+ hash like <tt>{ default: 11 }</tt>.
-
# Other options include <tt>:limit</tt> and <tt>:null</tt> (e.g.
-
# <tt>{ limit: 50, null: false }</tt>) -- see
-
# ActiveRecord::ConnectionAdapters::TableDefinition#column for details.
-
# * <tt>rename_column(table_name, column_name, new_column_name)</tt>: Renames
-
# a column but keeps the type and content.
-
# * <tt>change_column(table_name, column_name, type, options)</tt>: Changes
-
# the column to a different type using the same parameters as add_column.
-
# * <tt>remove_column(table_name, column_name, type, options)</tt>: Removes the column
-
# named +column_name+ from the table called +table_name+.
-
# * <tt>add_index(table_name, column_names, options)</tt>: Adds a new index
-
# with the name of the column. Other options include
-
# <tt>:name</tt>, <tt>:unique</tt> (e.g.
-
# <tt>{ name: 'users_name_index', unique: true }</tt>) and <tt>:order</tt>
-
# (e.g. <tt>{ order: { name: :desc } }</tt>).
-
# * <tt>remove_index(table_name, column: column_name)</tt>: Removes the index
-
# specified by +column_name+.
-
# * <tt>remove_index(table_name, name: index_name)</tt>: Removes the index
-
# specified by +index_name+.
-
#
-
# == Irreversible transformations
-
#
-
# Some transformations are destructive in a manner that cannot be reversed.
-
# Migrations of that kind should raise an <tt>ActiveRecord::IrreversibleMigration</tt>
-
# exception in their +down+ method.
-
#
-
# == Running migrations from within Rails
-
#
-
# The Rails package has several tools to help create and apply migrations.
-
#
-
# To generate a new migration, you can use
-
# rails generate migration MyNewMigration
-
#
-
# where MyNewMigration is the name of your migration. The generator will
-
# create an empty migration file <tt>timestamp_my_new_migration.rb</tt>
-
# in the <tt>db/migrate/</tt> directory where <tt>timestamp</tt> is the
-
# UTC formatted date and time that the migration was generated.
-
#
-
# You may then edit the <tt>up</tt> and <tt>down</tt> methods of
-
# MyNewMigration.
-
#
-
# There is a special syntactic shortcut to generate migrations that add fields to a table.
-
#
-
# rails generate migration add_fieldname_to_tablename fieldname:string
-
#
-
# This will generate the file <tt>timestamp_add_fieldname_to_tablename</tt>, which will look like this:
-
# class AddFieldnameToTablename < ActiveRecord::Migration
-
# def up
-
# add_column :tablenames, :fieldname, :string
-
# end
-
#
-
# def down
-
# remove_column :tablenames, :fieldname
-
# end
-
# end
-
#
-
# To run migrations against the currently configured database, use
-
# <tt>rake db:migrate</tt>. This will update the database by running all of the
-
# pending migrations, creating the <tt>schema_migrations</tt> table
-
# (see "About the schema_migrations table" section below) if missing. It will also
-
# invoke the db:schema:dump task, which will update your db/schema.rb file
-
# to match the structure of your database.
-
#
-
# To roll the database back to a previous migration version, use
-
# <tt>rake db:migrate VERSION=X</tt> where <tt>X</tt> is the version to which
-
# you wish to downgrade. If any of the migrations throw an
-
# <tt>ActiveRecord::IrreversibleMigration</tt> exception, that step will fail and you'll
-
# have some manual work to do.
-
#
-
# == Database support
-
#
-
# Migrations are currently supported in MySQL, PostgreSQL, SQLite,
-
# SQL Server, Sybase, and Oracle (all supported databases except DB2).
-
#
-
# == More examples
-
#
-
# Not all migrations change the schema. Some just fix the data:
-
#
-
# class RemoveEmptyTags < ActiveRecord::Migration
-
# def up
-
# Tag.all.each { |tag| tag.destroy if tag.pages.empty? }
-
# end
-
#
-
# def down
-
# # not much we can do to restore deleted data
-
# raise ActiveRecord::IrreversibleMigration, "Can't recover the deleted tags"
-
# end
-
# end
-
#
-
# Others remove columns when they migrate up instead of down:
-
#
-
# class RemoveUnnecessaryItemAttributes < ActiveRecord::Migration
-
# def up
-
# remove_column :items, :incomplete_items_count
-
# remove_column :items, :completed_items_count
-
# end
-
#
-
# def down
-
# add_column :items, :incomplete_items_count
-
# add_column :items, :completed_items_count
-
# end
-
# end
-
#
-
# And sometimes you need to do something in SQL not abstracted directly by migrations:
-
#
-
# class MakeJoinUnique < ActiveRecord::Migration
-
# def up
-
# execute "ALTER TABLE `pages_linked_pages` ADD UNIQUE `page_id_linked_page_id` (`page_id`,`linked_page_id`)"
-
# end
-
#
-
# def down
-
# execute "ALTER TABLE `pages_linked_pages` DROP INDEX `page_id_linked_page_id`"
-
# end
-
# end
-
#
-
# == Using a model after changing its table
-
#
-
# Sometimes you'll want to add a column in a migration and populate it
-
# immediately after. In that case, you'll need to make a call to
-
# <tt>Base#reset_column_information</tt> in order to ensure that the model has the
-
# latest column data from after the new column was added. Example:
-
#
-
# class AddPeopleSalary < ActiveRecord::Migration
-
# def up
-
# add_column :people, :salary, :integer
-
# Person.reset_column_information
-
# Person.all.each do |p|
-
# p.update_attribute :salary, SalaryCalculator.compute(p)
-
# end
-
# end
-
# end
-
#
-
# == Controlling verbosity
-
#
-
# By default, migrations will describe the actions they are taking, writing
-
# them to the console as they happen, along with benchmarks describing how
-
# long each step took.
-
#
-
# You can quiet them down by setting ActiveRecord::Migration.verbose = false.
-
#
-
# You can also insert your own messages and benchmarks by using the +say_with_time+
-
# method:
-
#
-
# def up
-
# ...
-
# say_with_time "Updating salaries..." do
-
# Person.all.each do |p|
-
# p.update_attribute :salary, SalaryCalculator.compute(p)
-
# end
-
# end
-
# ...
-
# end
-
#
-
# The phrase "Updating salaries..." would then be printed, along with the
-
# benchmark for the block when the block completes.
-
#
-
# == About the schema_migrations table
-
#
-
# Rails versions 2.0 and prior used to create a table called
-
# <tt>schema_info</tt> when using migrations. This table contained the
-
# version of the schema as of the last applied migration.
-
#
-
# Starting with Rails 2.1, the <tt>schema_info</tt> table is
-
# (automatically) replaced by the <tt>schema_migrations</tt> table, which
-
# contains the version numbers of all the migrations applied.
-
#
-
# As a result, it is now possible to add migration files that are numbered
-
# lower than the current schema version: when migrating up, those
-
# never-applied "interleaved" migrations will be automatically applied, and
-
# when migrating down, never-applied "interleaved" migrations will be skipped.
-
#
-
# == Timestamped Migrations
-
#
-
# By default, Rails generates migrations that look like:
-
#
-
# 20080717013526_your_migration_name.rb
-
#
-
# The prefix is a generation timestamp (in UTC).
-
#
-
# If you'd prefer to use numeric prefixes, you can turn timestamped migrations
-
# off by setting:
-
#
-
# config.active_record.timestamped_migrations = false
-
#
-
# In application.rb.
-
#
-
# == Reversible Migrations
-
#
-
# Starting with Rails 3.1, you will be able to define reversible migrations.
-
# Reversible migrations are migrations that know how to go +down+ for you.
-
# You simply supply the +up+ logic, and the Migration system will figure out
-
# how to execute the down commands for you.
-
#
-
# To define a reversible migration, define the +change+ method in your
-
# migration like this:
-
#
-
# class TenderloveMigration < ActiveRecord::Migration
-
# def change
-
# create_table(:horses) do |t|
-
# t.column :content, :text
-
# t.column :remind_at, :datetime
-
# end
-
# end
-
# end
-
#
-
# This migration will create the horses table for you on the way up, and
-
# automatically figure out how to drop the table on the way down.
-
#
-
# Some commands like +remove_column+ cannot be reversed. If you care to
-
# define how to move up and down in these cases, you should define the +up+
-
# and +down+ methods as before.
-
#
-
# If a command cannot be reversed, an
-
# <tt>ActiveRecord::IrreversibleMigration</tt> exception will be raised when
-
# the migration is moving down.
-
#
-
# For a list of commands that are reversible, please see
-
# <tt>ActiveRecord::Migration::CommandRecorder</tt>.
-
#
-
# == Transactional Migrations
-
#
-
# If the database adapter supports DDL transactions, all migrations will
-
# automatically be wrapped in a transaction. There are queries that you
-
# can't execute inside a transaction though, and for these situations
-
# you can turn the automatic transactions off.
-
#
-
# class ChangeEnum < ActiveRecord::Migration
-
# disable_ddl_transaction!
-
#
-
# def up
-
# execute "ALTER TYPE model_size ADD VALUE 'new_value'"
-
# end
-
# end
-
#
-
# Remember that you can still open your own transactions, even if you
-
# are in a Migration with <tt>self.disable_ddl_transaction!</tt>.
-
2
class Migration
-
2
autoload :CommandRecorder, 'active_record/migration/command_recorder'
-
-
-
# This class is used to verify that all migrations have been run before
-
# loading a web page if config.active_record.migration_error is set to :page_load
-
2
class CheckPending
-
2
def initialize(app)
-
@app = app
-
@last_check = 0
-
end
-
-
2
def call(env)
-
mtime = ActiveRecord::Migrator.last_migration.mtime.to_i
-
if @last_check < mtime
-
ActiveRecord::Migration.check_pending!
-
@last_check = mtime
-
end
-
@app.call(env)
-
end
-
end
-
-
2
class << self
-
2
attr_accessor :delegate # :nodoc:
-
2
attr_accessor :disable_ddl_transaction # :nodoc:
-
-
2
def check_pending!(connection = Base.connection)
-
raise ActiveRecord::PendingMigrationError if ActiveRecord::Migrator.needs_migration?(connection)
-
end
-
-
2
def load_schema_if_pending!
-
1
if ActiveRecord::Migrator.needs_migration?
-
ActiveRecord::Tasks::DatabaseTasks.load_schema_current
-
check_pending!
-
end
-
end
-
-
2
def maintain_test_schema! # :nodoc:
-
1
if ActiveRecord::Base.maintain_test_schema
-
2
suppress_messages { load_schema_if_pending! }
-
end
-
end
-
-
2
def method_missing(name, *args, &block) # :nodoc:
-
1
(delegate || superclass.delegate).send(name, *args, &block)
-
end
-
-
2
def migrate(direction)
-
new.migrate direction
-
end
-
-
# Disable DDL transactions for this migration.
-
2
def disable_ddl_transaction!
-
@disable_ddl_transaction = true
-
end
-
end
-
-
2
def disable_ddl_transaction # :nodoc:
-
self.class.disable_ddl_transaction
-
end
-
-
2
cattr_accessor :verbose
-
2
attr_accessor :name, :version
-
-
2
def initialize(name = self.class.name, version = nil)
-
2
@name = name
-
2
@version = version
-
2
@connection = nil
-
end
-
-
2
self.verbose = true
-
# instantiate the delegate object after initialize is defined
-
2
self.delegate = new
-
-
# Reverses the migration commands for the given block and
-
# the given migrations.
-
#
-
# The following migration will remove the table 'horses'
-
# and create the table 'apples' on the way up, and the reverse
-
# on the way down.
-
#
-
# class FixTLMigration < ActiveRecord::Migration
-
# def change
-
# revert do
-
# create_table(:horses) do |t|
-
# t.text :content
-
# t.datetime :remind_at
-
# end
-
# end
-
# create_table(:apples) do |t|
-
# t.string :variety
-
# end
-
# end
-
# end
-
#
-
# Or equivalently, if +TenderloveMigration+ is defined as in the
-
# documentation for Migration:
-
#
-
# require_relative '2012121212_tenderlove_migration'
-
#
-
# class FixupTLMigration < ActiveRecord::Migration
-
# def change
-
# revert TenderloveMigration
-
#
-
# create_table(:apples) do |t|
-
# t.string :variety
-
# end
-
# end
-
# end
-
#
-
# This command can be nested.
-
2
def revert(*migration_classes)
-
run(*migration_classes.reverse, revert: true) unless migration_classes.empty?
-
if block_given?
-
if @connection.respond_to? :revert
-
@connection.revert { yield }
-
else
-
recorder = CommandRecorder.new(@connection)
-
@connection = recorder
-
suppress_messages do
-
@connection.revert { yield }
-
end
-
@connection = recorder.delegate
-
recorder.commands.each do |cmd, args, block|
-
send(cmd, *args, &block)
-
end
-
end
-
end
-
end
-
-
2
def reverting?
-
@connection.respond_to?(:reverting) && @connection.reverting
-
end
-
-
2
class ReversibleBlockHelper < Struct.new(:reverting) # :nodoc:
-
2
def up
-
yield unless reverting
-
end
-
-
2
def down
-
yield if reverting
-
end
-
end
-
-
# Used to specify an operation that can be run in one direction or another.
-
# Call the methods +up+ and +down+ of the yielded object to run a block
-
# only in one given direction.
-
# The whole block will be called in the right order within the migration.
-
#
-
# In the following example, the looping on users will always be done
-
# when the three columns 'first_name', 'last_name' and 'full_name' exist,
-
# even when migrating down:
-
#
-
# class SplitNameMigration < ActiveRecord::Migration
-
# def change
-
# add_column :users, :first_name, :string
-
# add_column :users, :last_name, :string
-
#
-
# reversible do |dir|
-
# User.reset_column_information
-
# User.all.each do |u|
-
# dir.up { u.first_name, u.last_name = u.full_name.split(' ') }
-
# dir.down { u.full_name = "#{u.first_name} #{u.last_name}" }
-
# u.save
-
# end
-
# end
-
#
-
# revert { add_column :users, :full_name, :string }
-
# end
-
# end
-
2
def reversible
-
helper = ReversibleBlockHelper.new(reverting?)
-
execute_block{ yield helper }
-
end
-
-
# Runs the given migration classes.
-
# Last argument can specify options:
-
# - :direction (default is :up)
-
# - :revert (default is false)
-
2
def run(*migration_classes)
-
opts = migration_classes.extract_options!
-
dir = opts[:direction] || :up
-
dir = (dir == :down ? :up : :down) if opts[:revert]
-
if reverting?
-
# If in revert and going :up, say, we want to execute :down without reverting, so
-
revert { run(*migration_classes, direction: dir, revert: true) }
-
else
-
migration_classes.each do |migration_class|
-
migration_class.new.exec_migration(@connection, dir)
-
end
-
end
-
end
-
-
2
def up
-
self.class.delegate = self
-
return unless self.class.respond_to?(:up)
-
self.class.up
-
end
-
-
2
def down
-
self.class.delegate = self
-
return unless self.class.respond_to?(:down)
-
self.class.down
-
end
-
-
# Execute this migration in the named direction
-
2
def migrate(direction)
-
return unless respond_to?(direction)
-
-
case direction
-
when :up then announce "migrating"
-
when :down then announce "reverting"
-
end
-
-
time = nil
-
ActiveRecord::Base.connection_pool.with_connection do |conn|
-
time = Benchmark.measure do
-
exec_migration(conn, direction)
-
end
-
end
-
-
case direction
-
when :up then announce "migrated (%.4fs)" % time.real; write
-
when :down then announce "reverted (%.4fs)" % time.real; write
-
end
-
end
-
-
2
def exec_migration(conn, direction)
-
@connection = conn
-
if respond_to?(:change)
-
if direction == :down
-
revert { change }
-
else
-
change
-
end
-
else
-
send(direction)
-
end
-
ensure
-
@connection = nil
-
end
-
-
2
def write(text="")
-
puts(text) if verbose
-
end
-
-
2
def announce(message)
-
text = "#{version} #{name}: #{message}"
-
length = [0, 75 - text.length].max
-
write "== %s %s" % [text, "=" * length]
-
end
-
-
2
def say(message, subitem=false)
-
write "#{subitem ? " ->" : "--"} #{message}"
-
end
-
-
2
def say_with_time(message)
-
say(message)
-
result = nil
-
time = Benchmark.measure { result = yield }
-
say "%.4fs" % time.real, :subitem
-
say("#{result} rows", :subitem) if result.is_a?(Integer)
-
result
-
end
-
-
2
def suppress_messages
-
1
save, self.verbose = verbose, false
-
1
yield
-
ensure
-
1
self.verbose = save
-
end
-
-
2
def connection
-
@connection || ActiveRecord::Base.connection
-
end
-
-
2
def method_missing(method, *arguments, &block)
-
arg_list = arguments.map{ |a| a.inspect } * ', '
-
-
say_with_time "#{method}(#{arg_list})" do
-
unless @connection.respond_to? :revert
-
unless arguments.empty? || [:execute, :enable_extension, :disable_extension].include?(method)
-
arguments[0] = proper_table_name(arguments.first, table_name_options)
-
arguments[1] = proper_table_name(arguments.second, table_name_options) if method == :rename_table
-
end
-
end
-
return super unless connection.respond_to?(method)
-
connection.send(method, *arguments, &block)
-
end
-
end
-
-
2
def copy(destination, sources, options = {})
-
copied = []
-
-
FileUtils.mkdir_p(destination) unless File.exist?(destination)
-
-
destination_migrations = ActiveRecord::Migrator.migrations(destination)
-
last = destination_migrations.last
-
sources.each do |scope, path|
-
source_migrations = ActiveRecord::Migrator.migrations(path)
-
-
source_migrations.each do |migration|
-
source = File.binread(migration.filename)
-
inserted_comment = "# This migration comes from #{scope} (originally #{migration.version})\n"
-
if /\A#.*\b(?:en)?coding:\s*\S+/ =~ source
-
# If we have a magic comment in the original migration,
-
# insert our comment after the first newline(end of the magic comment line)
-
# so the magic keep working.
-
# Note that magic comments must be at the first line(except sh-bang).
-
source[/\n/] = "\n#{inserted_comment}"
-
else
-
source = "#{inserted_comment}#{source}"
-
end
-
-
if duplicate = destination_migrations.detect { |m| m.name == migration.name }
-
if options[:on_skip] && duplicate.scope != scope.to_s
-
options[:on_skip].call(scope, migration)
-
end
-
next
-
end
-
-
migration.version = next_migration_number(last ? last.version + 1 : 0).to_i
-
new_path = File.join(destination, "#{migration.version}_#{migration.name.underscore}.#{scope}.rb")
-
old_path, migration.filename = migration.filename, new_path
-
last = migration
-
-
File.binwrite(migration.filename, source)
-
copied << migration
-
options[:on_copy].call(scope, migration, old_path) if options[:on_copy]
-
destination_migrations << migration
-
end
-
end
-
-
copied
-
end
-
-
# Finds the correct table name given an Active Record object.
-
# Uses the Active Record object's own table_name, or pre/suffix from the
-
# options passed in.
-
2
def proper_table_name(name, options = {})
-
if name.respond_to? :table_name
-
name.table_name
-
else
-
"#{options[:table_name_prefix]}#{name}#{options[:table_name_suffix]}"
-
end
-
end
-
-
# Determines the version number of the next migration.
-
2
def next_migration_number(number)
-
if ActiveRecord::Base.timestamped_migrations
-
[Time.now.utc.strftime("%Y%m%d%H%M%S"), "%.14d" % number].max
-
else
-
SchemaMigration.normalize_migration_number(number)
-
end
-
end
-
-
2
def table_name_options(config = ActiveRecord::Base)
-
{
-
table_name_prefix: config.table_name_prefix,
-
table_name_suffix: config.table_name_suffix
-
}
-
end
-
-
2
private
-
2
def execute_block
-
if connection.respond_to? :execute_block
-
super # use normal delegation to record the block
-
else
-
yield
-
end
-
end
-
end
-
-
# MigrationProxy is used to defer loading of the actual migration classes
-
# until they are needed
-
2
class MigrationProxy < Struct.new(:name, :version, :filename, :scope)
-
-
2
def initialize(name, version, filename, scope)
-
32
super
-
32
@migration = nil
-
end
-
-
2
def basename
-
File.basename(filename)
-
end
-
-
2
def mtime
-
File.mtime filename
-
end
-
-
2
delegate :migrate, :announce, :write, :disable_ddl_transaction, to: :migration
-
-
2
private
-
-
2
def migration
-
@migration ||= load_migration
-
end
-
-
2
def load_migration
-
require(File.expand_path(filename))
-
name.constantize.new(name, version)
-
end
-
-
end
-
-
2
class NullMigration < MigrationProxy #:nodoc:
-
2
def initialize
-
super(nil, 0, nil, nil)
-
end
-
-
2
def mtime
-
0
-
end
-
end
-
-
2
class Migrator#:nodoc:
-
2
class << self
-
2
attr_writer :migrations_paths
-
2
alias :migrations_path= :migrations_paths=
-
-
2
def migrate(migrations_paths, target_version = nil, &block)
-
case
-
when target_version.nil?
-
up(migrations_paths, target_version, &block)
-
when current_version == 0 && target_version == 0
-
[]
-
when current_version > target_version
-
down(migrations_paths, target_version, &block)
-
else
-
up(migrations_paths, target_version, &block)
-
end
-
end
-
-
2
def rollback(migrations_paths, steps=1)
-
move(:down, migrations_paths, steps)
-
end
-
-
2
def forward(migrations_paths, steps=1)
-
move(:up, migrations_paths, steps)
-
end
-
-
2
def up(migrations_paths, target_version = nil)
-
migrations = migrations(migrations_paths)
-
migrations.select! { |m| yield m } if block_given?
-
-
self.new(:up, migrations, target_version).migrate
-
end
-
-
2
def down(migrations_paths, target_version = nil, &block)
-
migrations = migrations(migrations_paths)
-
migrations.select! { |m| yield m } if block_given?
-
-
self.new(:down, migrations, target_version).migrate
-
end
-
-
2
def run(direction, migrations_paths, target_version)
-
self.new(direction, migrations(migrations_paths), target_version).run
-
end
-
-
2
def open(migrations_paths)
-
self.new(:up, migrations(migrations_paths), nil)
-
end
-
-
2
def schema_migrations_table_name
-
1
SchemaMigration.table_name
-
end
-
-
2
def get_all_versions(connection = Base.connection)
-
1
if connection.table_exists?(schema_migrations_table_name)
-
33
SchemaMigration.all.map { |x| x.version.to_i }.sort
-
else
-
[]
-
end
-
end
-
-
2
def current_version(connection = Base.connection)
-
get_all_versions(connection).max || 0
-
end
-
-
2
def needs_migration?(connection = Base.connection)
-
1
(migrations(migrations_paths).collect(&:version) - get_all_versions(connection)).size > 0
-
end
-
-
2
def last_version
-
last_migration.version
-
end
-
-
2
def last_migration #:nodoc:
-
migrations(migrations_paths).last || NullMigration.new
-
end
-
-
2
def proper_table_name(name, options = {})
-
ActiveSupport::Deprecation.warn "ActiveRecord::Migrator.proper_table_name is deprecated and will be removed in Rails 4.2. Use the proper_table_name instance method on ActiveRecord::Migration instead"
-
options = {
-
table_name_prefix: ActiveRecord::Base.table_name_prefix,
-
table_name_suffix: ActiveRecord::Base.table_name_suffix
-
}.merge(options)
-
if name.respond_to? :table_name
-
name.table_name
-
else
-
"#{options[:table_name_prefix]}#{name}#{options[:table_name_suffix]}"
-
end
-
end
-
-
2
def migrations_paths
-
1
@migrations_paths ||= ['db/migrate']
-
# just to not break things if someone uses: migration_path = some_string
-
1
Array(@migrations_paths)
-
end
-
-
2
def migrations_path
-
migrations_paths.first
-
end
-
-
2
def migrations(paths)
-
1
paths = Array(paths)
-
-
2
files = Dir[*paths.map { |p| "#{p}/**/[0-9]*_*.rb" }]
-
-
1
migrations = files.map do |file|
-
32
version, name, scope = file.scan(/([0-9]+)_([_a-z0-9]*)\.?([_a-z0-9]*)?\.rb\z/).first
-
-
32
raise IllegalMigrationNameError.new(file) unless version
-
32
version = version.to_i
-
32
name = name.camelize
-
-
32
MigrationProxy.new(name, version, file, scope)
-
end
-
-
1
migrations.sort_by(&:version)
-
end
-
-
2
private
-
-
2
def move(direction, migrations_paths, steps)
-
migrator = self.new(direction, migrations(migrations_paths))
-
start_index = migrator.migrations.index(migrator.current_migration)
-
-
if start_index
-
finish = migrator.migrations[start_index + steps]
-
version = finish ? finish.version : 0
-
send(direction, migrations_paths, version)
-
end
-
end
-
end
-
-
2
def initialize(direction, migrations, target_version = nil)
-
raise StandardError.new("This database does not yet support migrations") unless Base.connection.supports_migrations?
-
-
@direction = direction
-
@target_version = target_version
-
@migrated_versions = nil
-
@migrations = migrations
-
-
validate(@migrations)
-
-
Base.connection.initialize_schema_migrations_table
-
end
-
-
2
def current_version
-
migrated.max || 0
-
end
-
-
2
def current_migration
-
migrations.detect { |m| m.version == current_version }
-
end
-
2
alias :current :current_migration
-
-
2
def run
-
migration = migrations.detect { |m| m.version == @target_version }
-
raise UnknownMigrationVersionError.new(@target_version) if migration.nil?
-
unless (up? && migrated.include?(migration.version.to_i)) || (down? && !migrated.include?(migration.version.to_i))
-
begin
-
execute_migration_in_transaction(migration, @direction)
-
rescue => e
-
canceled_msg = use_transaction?(migration) ? ", this migration was canceled" : ""
-
raise StandardError, "An error has occurred#{canceled_msg}:\n\n#{e}", e.backtrace
-
end
-
end
-
end
-
-
2
def migrate
-
if !target && @target_version && @target_version > 0
-
raise UnknownMigrationVersionError.new(@target_version)
-
end
-
-
runnable.each do |migration|
-
Base.logger.info "Migrating to #{migration.name} (#{migration.version})" if Base.logger
-
-
begin
-
execute_migration_in_transaction(migration, @direction)
-
rescue => e
-
canceled_msg = use_transaction?(migration) ? "this and " : ""
-
raise StandardError, "An error has occurred, #{canceled_msg}all later migrations canceled:\n\n#{e}", e.backtrace
-
end
-
end
-
end
-
-
2
def runnable
-
runnable = migrations[start..finish]
-
if up?
-
runnable.reject { |m| ran?(m) }
-
else
-
# skip the last migration if we're headed down, but not ALL the way down
-
runnable.pop if target
-
runnable.find_all { |m| ran?(m) }
-
end
-
end
-
-
2
def migrations
-
down? ? @migrations.reverse : @migrations.sort_by(&:version)
-
end
-
-
2
def pending_migrations
-
already_migrated = migrated
-
migrations.reject { |m| already_migrated.include?(m.version) }
-
end
-
-
2
def migrated
-
@migrated_versions ||= Set.new(self.class.get_all_versions)
-
end
-
-
2
private
-
2
def ran?(migration)
-
migrated.include?(migration.version.to_i)
-
end
-
-
2
def execute_migration_in_transaction(migration, direction)
-
ddl_transaction(migration) do
-
migration.migrate(direction)
-
record_version_state_after_migrating(migration.version)
-
end
-
end
-
-
2
def target
-
migrations.detect { |m| m.version == @target_version }
-
end
-
-
2
def finish
-
migrations.index(target) || migrations.size - 1
-
end
-
-
2
def start
-
up? ? 0 : (migrations.index(current) || 0)
-
end
-
-
2
def validate(migrations)
-
name ,= migrations.group_by(&:name).find { |_,v| v.length > 1 }
-
raise DuplicateMigrationNameError.new(name) if name
-
-
version ,= migrations.group_by(&:version).find { |_,v| v.length > 1 }
-
raise DuplicateMigrationVersionError.new(version) if version
-
end
-
-
2
def record_version_state_after_migrating(version)
-
if down?
-
migrated.delete(version)
-
ActiveRecord::SchemaMigration.where(:version => version.to_s).delete_all
-
else
-
migrated << version
-
ActiveRecord::SchemaMigration.create!(:version => version.to_s)
-
end
-
end
-
-
2
def up?
-
@direction == :up
-
end
-
-
2
def down?
-
@direction == :down
-
end
-
-
# Wrap the migration in a transaction only if supported by the adapter.
-
2
def ddl_transaction(migration)
-
if use_transaction?(migration)
-
Base.transaction { yield }
-
else
-
yield
-
end
-
end
-
-
2
def use_transaction?(migration)
-
!migration.disable_ddl_transaction && Base.connection.supports_ddl_transactions?
-
end
-
end
-
end
-
2
module ActiveRecord
-
2
class Migration
-
# <tt>ActiveRecord::Migration::CommandRecorder</tt> records commands done during
-
# a migration and knows how to reverse those commands. The CommandRecorder
-
# knows how to invert the following commands:
-
#
-
# * add_column
-
# * add_index
-
# * add_timestamps
-
# * create_table
-
# * create_join_table
-
# * remove_timestamps
-
# * rename_column
-
# * rename_index
-
# * rename_table
-
2
class CommandRecorder
-
2
include JoinTable
-
-
2
attr_accessor :commands, :delegate, :reverting
-
-
2
def initialize(delegate = nil)
-
@commands = []
-
@delegate = delegate
-
@reverting = false
-
end
-
-
# While executing the given block, the recorded will be in reverting mode.
-
# All commands recorded will end up being recorded reverted
-
# and in reverse order.
-
# For example:
-
#
-
# recorder.revert{ recorder.record(:rename_table, [:old, :new]) }
-
# # same effect as recorder.record(:rename_table, [:new, :old])
-
2
def revert
-
@reverting = !@reverting
-
previous = @commands
-
@commands = []
-
yield
-
ensure
-
@commands = previous.concat(@commands.reverse)
-
@reverting = !@reverting
-
end
-
-
# record +command+. +command+ should be a method name and arguments.
-
# For example:
-
#
-
# recorder.record(:method_name, [:arg1, :arg2])
-
2
def record(*command, &block)
-
if @reverting
-
@commands << inverse_of(*command, &block)
-
else
-
@commands << (command << block)
-
end
-
end
-
-
# Returns the inverse of the given command. For example:
-
#
-
# recorder.inverse_of(:rename_table, [:old, :new])
-
# # => [:rename_table, [:new, :old]]
-
#
-
# This method will raise an +IrreversibleMigration+ exception if it cannot
-
# invert the +command+.
-
2
def inverse_of(command, args, &block)
-
method = :"invert_#{command}"
-
raise IrreversibleMigration unless respond_to?(method, true)
-
send(method, args, &block)
-
end
-
-
2
def respond_to?(*args) # :nodoc:
-
super || delegate.respond_to?(*args)
-
end
-
-
[:create_table, :create_join_table, :rename_table, :add_column, :remove_column,
-
:rename_index, :rename_column, :add_index, :remove_index, :add_timestamps, :remove_timestamps,
-
:change_column_default, :add_reference, :remove_reference, :transaction,
-
:drop_join_table, :drop_table, :execute_block, :enable_extension,
-
:change_column, :execute, :remove_columns, :change_column_null # irreversible methods need to be here too
-
2
].each do |method|
-
46
class_eval <<-EOV, __FILE__, __LINE__ + 1
-
def #{method}(*args, &block) # def create_table(*args, &block)
-
record(:"#{method}", args, &block) # record(:create_table, args, &block)
-
end # end
-
EOV
-
end
-
2
alias :add_belongs_to :add_reference
-
2
alias :remove_belongs_to :remove_reference
-
-
2
def change_table(table_name, options = {})
-
yield delegate.update_table_definition(table_name, self)
-
end
-
-
2
private
-
-
2
module StraightReversions
-
2
private
-
{ transaction: :transaction,
-
execute_block: :execute_block,
-
create_table: :drop_table,
-
create_join_table: :drop_join_table,
-
add_column: :remove_column,
-
add_timestamps: :remove_timestamps,
-
add_reference: :remove_reference,
-
enable_extension: :disable_extension
-
2
}.each do |cmd, inv|
-
16
[[inv, cmd], [cmd, inv]].uniq.each do |method, inverse|
-
28
class_eval <<-EOV, __FILE__, __LINE__ + 1
-
def invert_#{method}(args, &block) # def invert_create_table(args, &block)
-
[:#{inverse}, args, block] # [:drop_table, args, block]
-
end # end
-
EOV
-
end
-
end
-
end
-
-
2
include StraightReversions
-
-
2
def invert_drop_table(args, &block)
-
if args.size == 1 && block == nil
-
raise ActiveRecord::IrreversibleMigration, "To avoid mistakes, drop_table is only reversible if given options or a block (can be empty)."
-
end
-
super
-
end
-
-
2
def invert_rename_table(args)
-
[:rename_table, args.reverse]
-
end
-
-
2
def invert_remove_column(args)
-
raise ActiveRecord::IrreversibleMigration, "remove_column is only reversible if given a type." if args.size <= 2
-
super
-
end
-
-
2
def invert_rename_index(args)
-
[:rename_index, [args.first] + args.last(2).reverse]
-
end
-
-
2
def invert_rename_column(args)
-
[:rename_column, [args.first] + args.last(2).reverse]
-
end
-
-
2
def invert_add_index(args)
-
table, columns, options = *args
-
options ||= {}
-
-
index_name = options[:name]
-
options_hash = index_name ? { name: index_name } : { column: columns }
-
-
[:remove_index, [table, options_hash]]
-
end
-
-
2
def invert_remove_index(args)
-
table, options = *args
-
-
unless options && options.is_a?(Hash) && options[:column]
-
raise ActiveRecord::IrreversibleMigration, "remove_index is only reversible if given a :column option."
-
end
-
-
options = options.dup
-
[:add_index, [table, options.delete(:column), options]]
-
end
-
-
2
alias :invert_add_belongs_to :invert_add_reference
-
2
alias :invert_remove_belongs_to :invert_remove_reference
-
-
2
def invert_change_column_null(args)
-
args[2] = !args[2]
-
[:change_column_null, args]
-
end
-
-
# Forwards any missing method call to the \target.
-
2
def method_missing(method, *args, &block)
-
if @delegate.respond_to?(method)
-
@delegate.send(method, *args, &block)
-
else
-
super
-
end
-
end
-
end
-
end
-
end
-
2
module ActiveRecord
-
2
class Migration
-
2
module JoinTable #:nodoc:
-
2
private
-
-
2
def find_join_table_name(table_1, table_2, options = {})
-
options.delete(:table_name) || join_table_name(table_1, table_2)
-
end
-
-
2
def join_table_name(table_1, table_2)
-
[table_1.to_s, table_2.to_s].sort.join("_").to_sym
-
end
-
end
-
end
-
end
-
2
module ActiveRecord
-
2
module ModelSchema
-
2
extend ActiveSupport::Concern
-
-
2
included do
-
##
-
# :singleton-method:
-
# Accessor for the prefix type that will be prepended to every primary key column name.
-
# The options are :table_name and :table_name_with_underscore. If the first is specified,
-
# the Product class will look for "productid" instead of "id" as the primary column. If the
-
# latter is specified, the Product class will look for "product_id" instead of "id". Remember
-
# that this is a global setting for all Active Records.
-
2
mattr_accessor :primary_key_prefix_type, instance_writer: false
-
-
##
-
# :singleton-method:
-
# Accessor for the name of the prefix string to prepend to every table name. So if set
-
# to "basecamp_", all table names will be named like "basecamp_projects", "basecamp_people",
-
# etc. This is a convenient way of creating a namespace for tables in a shared database.
-
# By default, the prefix is the empty string.
-
#
-
# If you are organising your models within modules you can add a prefix to the models within
-
# a namespace by defining a singleton method in the parent module called table_name_prefix which
-
# returns your chosen prefix.
-
2
class_attribute :table_name_prefix, instance_writer: false
-
2
self.table_name_prefix = ""
-
-
##
-
# :singleton-method:
-
# Works like +table_name_prefix+, but appends instead of prepends (set to "_basecamp" gives "projects_basecamp",
-
# "people_basecamp"). By default, the suffix is the empty string.
-
2
class_attribute :table_name_suffix, instance_writer: false
-
2
self.table_name_suffix = ""
-
-
##
-
# :singleton-method:
-
# Accessor for the name of the schema migrations table. By default, the value is "schema_migrations"
-
2
class_attribute :schema_migrations_table_name, instance_accessor: false
-
2
self.schema_migrations_table_name = "schema_migrations"
-
-
##
-
# :singleton-method:
-
# Indicates whether table names should be the pluralized versions of the corresponding class names.
-
# If true, the default table name for a Product class will be +products+. If false, it would just be +product+.
-
# See table_name for the full rules on table/class naming. This is true, by default.
-
2
class_attribute :pluralize_table_names, instance_writer: false
-
2
self.pluralize_table_names = true
-
-
2
self.inheritance_column = 'type'
-
end
-
-
2
module ClassMethods
-
# Guesses the table name (in forced lower-case) based on the name of the class in the
-
# inheritance hierarchy descending directly from ActiveRecord::Base. So if the hierarchy
-
# looks like: Reply < Message < ActiveRecord::Base, then Message is used
-
# to guess the table name even when called on Reply. The rules used to do the guess
-
# are handled by the Inflector class in Active Support, which knows almost all common
-
# English inflections. You can add new inflections in config/initializers/inflections.rb.
-
#
-
# Nested classes are given table names prefixed by the singular form of
-
# the parent's table name. Enclosing modules are not considered.
-
#
-
# ==== Examples
-
#
-
# class Invoice < ActiveRecord::Base
-
# end
-
#
-
# file class table_name
-
# invoice.rb Invoice invoices
-
#
-
# class Invoice < ActiveRecord::Base
-
# class Lineitem < ActiveRecord::Base
-
# end
-
# end
-
#
-
# file class table_name
-
# invoice.rb Invoice::Lineitem invoice_lineitems
-
#
-
# module Invoice
-
# class Lineitem < ActiveRecord::Base
-
# end
-
# end
-
#
-
# file class table_name
-
# invoice/lineitem.rb Invoice::Lineitem lineitems
-
#
-
# Additionally, the class-level +table_name_prefix+ is prepended and the
-
# +table_name_suffix+ is appended. So if you have "myapp_" as a prefix,
-
# the table name guess for an Invoice class becomes "myapp_invoices".
-
# Invoice::Lineitem becomes "myapp_invoice_lineitems".
-
#
-
# You can also set your own table name explicitly:
-
#
-
# class Mouse < ActiveRecord::Base
-
# self.table_name = "mice"
-
# end
-
#
-
# Alternatively, you can override the table_name method to define your
-
# own computation. (Possibly using <tt>super</tt> to manipulate the default
-
# table name.) Example:
-
#
-
# class Post < ActiveRecord::Base
-
# def self.table_name
-
# "special_" + super
-
# end
-
# end
-
# Post.table_name # => "special_posts"
-
2
def table_name
-
1247
reset_table_name unless defined?(@table_name)
-
1247
@table_name
-
end
-
-
# Sets the table name explicitly. Example:
-
#
-
# class Project < ActiveRecord::Base
-
# self.table_name = "project"
-
# end
-
#
-
# You can also just define your own <tt>self.table_name</tt> method; see
-
# the documentation for ActiveRecord::Base#table_name.
-
2
def table_name=(value)
-
11
value = value && value.to_s
-
-
11
if defined?(@table_name)
-
return if value == @table_name
-
reset_column_information if connected?
-
end
-
-
11
@table_name = value
-
11
@quoted_table_name = nil
-
11
@arel_table = nil
-
11
@sequence_name = nil unless defined?(@explicit_sequence_name) && @explicit_sequence_name
-
11
@relation = Relation.create(self, arel_table)
-
end
-
-
# Returns a quoted version of the table name, used to construct SQL statements.
-
2
def quoted_table_name
-
@quoted_table_name ||= connection.quote_table_name(table_name)
-
end
-
-
# Computes the table name, (re)sets it internally, and returns it.
-
2
def reset_table_name #:nodoc:
-
9
self.table_name = if abstract_class?
-
superclass == Base ? nil : superclass.table_name
-
elsif superclass.abstract_class?
-
superclass.table_name || compute_table_name
-
else
-
9
compute_table_name
-
end
-
end
-
-
2
def full_table_name_prefix #:nodoc:
-
16
(parents.detect{ |p| p.respond_to?(:table_name_prefix) } || self).table_name_prefix
-
end
-
-
# Defines the name of the table column which will store the class name on single-table
-
# inheritance situations.
-
#
-
# The default inheritance column name is +type+, which means it's a
-
# reserved word inside Active Record. To be able to use single-table
-
# inheritance with another column name, or to use the column +type+ in
-
# your own model for something else, you can set +inheritance_column+:
-
#
-
# self.inheritance_column = 'zoink'
-
2
def inheritance_column
-
697
(@inheritance_column ||= nil) || superclass.inheritance_column
-
end
-
-
# Sets the value of inheritance_column
-
2
def inheritance_column=(value)
-
2
@inheritance_column = value.to_s
-
2
@explicit_inheritance_column = true
-
end
-
-
2
def sequence_name
-
if base_class == self
-
@sequence_name ||= reset_sequence_name
-
else
-
(@sequence_name ||= nil) || base_class.sequence_name
-
end
-
end
-
-
2
def reset_sequence_name #:nodoc:
-
@explicit_sequence_name = false
-
@sequence_name = connection.default_sequence_name(table_name, primary_key)
-
end
-
-
# Sets the name of the sequence to use when generating ids to the given
-
# value, or (if the value is nil or false) to the value returned by the
-
# given block. This is required for Oracle and is useful for any
-
# database which relies on sequences for primary key generation.
-
#
-
# If a sequence name is not explicitly set when using Oracle or Firebird,
-
# it will default to the commonly used pattern of: #{table_name}_seq
-
#
-
# If a sequence name is not explicitly set when using PostgreSQL, it
-
# will discover the sequence corresponding to your primary key for you.
-
#
-
# class Project < ActiveRecord::Base
-
# self.sequence_name = "projectseq" # default would have been "project_seq"
-
# end
-
2
def sequence_name=(value)
-
@sequence_name = value.to_s
-
@explicit_sequence_name = true
-
end
-
-
# Indicates whether the table associated with this class exists
-
2
def table_exists?
-
9
connection.schema_cache.table_exists?(table_name)
-
end
-
-
# Returns an array of column objects for the table associated with this class.
-
2
def columns
-
@columns ||= connection.schema_cache.columns(table_name).map do |col|
-
111
col = col.dup
-
111
col.primary = (col.name == primary_key)
-
111
col
-
320
end
-
end
-
-
# Returns a hash of column objects for the table associated with this class.
-
2
def columns_hash
-
13865
@columns_hash ||= Hash[columns.map { |c| [c.name, c] }]
-
end
-
-
2
def column_types # :nodoc:
-
311
@column_types ||= decorate_columns(columns_hash.dup)
-
end
-
-
2
def decorate_columns(columns_hash) # :nodoc:
-
42
return if columns_hash.empty?
-
-
@serialized_column_names ||= self.columns_hash.keys.find_all do |name|
-
100
serialized_attributes.key?(name)
-
10
end
-
-
10
@serialized_column_names.each do |name|
-
1
columns_hash[name] = AttributeMethods::Serialization::Type.new(columns_hash[name])
-
end
-
-
@time_zone_column_names ||= self.columns_hash.find_all do |name, col|
-
100
create_time_zone_conversion_attribute?(name, col)
-
10
end.map!(&:first)
-
-
10
@time_zone_column_names.each do |name|
-
22
columns_hash[name] = AttributeMethods::TimeZoneConversion::Type.new(columns_hash[name])
-
end
-
-
10
columns_hash
-
end
-
-
# Returns a hash where the keys are column names and the values are
-
# default values when instantiating the AR object for this table.
-
2
def column_defaults
-
108
@column_defaults ||= Hash[columns.map { |c| [c.name, c.default] }]
-
end
-
-
# Returns an array of column names as strings.
-
2
def column_names
-
1266
@column_names ||= columns.map { |column| column.name }
-
end
-
-
# Returns an array of column objects where the primary id, all columns ending in "_id" or "_count",
-
# and columns used for single table inheritance have been removed.
-
2
def content_columns
-
@content_columns ||= columns.reject { |c| c.primary || c.name =~ /(_id|_count)$/ || c.name == inheritance_column }
-
end
-
-
# Resets all the cached information about columns, which will cause them
-
# to be reloaded on the next request.
-
#
-
# The most common usage pattern for this method is probably in a migration,
-
# when just after creating a table you want to populate it with some default
-
# values, eg:
-
#
-
# class CreateJobLevels < ActiveRecord::Migration
-
# def up
-
# create_table :job_levels do |t|
-
# t.integer :id
-
# t.string :name
-
#
-
# t.timestamps
-
# end
-
#
-
# JobLevel.reset_column_information
-
# %w{assistant executive manager director}.each do |type|
-
# JobLevel.create(name: type)
-
# end
-
# end
-
#
-
# def down
-
# drop_table :job_levels
-
# end
-
# end
-
2
def reset_column_information
-
connection.clear_cache!
-
undefine_attribute_methods
-
connection.schema_cache.clear_table_cache!(table_name) if table_exists?
-
-
@arel_engine = nil
-
@column_defaults = nil
-
@column_names = nil
-
@columns = nil
-
@columns_hash = nil
-
@column_types = nil
-
@content_columns = nil
-
@dynamic_methods_hash = nil
-
@inheritance_column = nil unless defined?(@explicit_inheritance_column) && @explicit_inheritance_column
-
@relation = nil
-
@serialized_column_names = nil
-
@time_zone_column_names = nil
-
@cached_time_zone = nil
-
end
-
-
# This is a hook for use by modules that need to do extra stuff to
-
# attributes when they are initialized. (e.g. attribute
-
# serialization)
-
2
def initialize_attributes(attributes, options = {}) #:nodoc:
-
311
attributes
-
end
-
-
2
private
-
-
# Guesses the table name, but does not decorate it with prefix and suffix information.
-
2
def undecorated_table_name(class_name = base_class.name)
-
8
table_name = class_name.to_s.demodulize.underscore
-
8
pluralize_table_names ? table_name.pluralize : table_name
-
end
-
-
# Computes and returns a table name according to default conventions.
-
2
def compute_table_name
-
9
base = base_class
-
9
if self == base
-
# Nested classes are prefixed with singular parent table name.
-
8
if parent < Base && !parent.abstract_class?
-
contained = parent.table_name
-
contained = contained.singularize if parent.pluralize_table_names
-
contained += '_'
-
end
-
8
"#{full_table_name_prefix}#{contained}#{undecorated_table_name(name)}#{table_name_suffix}"
-
else
-
# STI subclasses always use their superclass' table.
-
1
base.table_name
-
end
-
end
-
end
-
end
-
end
-
2
require 'active_support/core_ext/hash/except'
-
2
require 'active_support/core_ext/object/try'
-
2
require 'active_support/core_ext/hash/indifferent_access'
-
-
2
module ActiveRecord
-
2
module NestedAttributes #:nodoc:
-
2
class TooManyRecords < ActiveRecordError
-
end
-
-
2
extend ActiveSupport::Concern
-
-
2
included do
-
2
class_attribute :nested_attributes_options, instance_writer: false
-
2
self.nested_attributes_options = {}
-
end
-
-
# = Active Record Nested Attributes
-
#
-
# Nested attributes allow you to save attributes on associated records
-
# through the parent. By default nested attribute updating is turned off
-
# and you can enable it using the accepts_nested_attributes_for class
-
# method. When you enable nested attributes an attribute writer is
-
# defined on the model.
-
#
-
# The attribute writer is named after the association, which means that
-
# in the following example, two new methods are added to your model:
-
#
-
# <tt>author_attributes=(attributes)</tt> and
-
# <tt>pages_attributes=(attributes)</tt>.
-
#
-
# class Book < ActiveRecord::Base
-
# has_one :author
-
# has_many :pages
-
#
-
# accepts_nested_attributes_for :author, :pages
-
# end
-
#
-
# Note that the <tt>:autosave</tt> option is automatically enabled on every
-
# association that accepts_nested_attributes_for is used for.
-
#
-
# === One-to-one
-
#
-
# Consider a Member model that has one Avatar:
-
#
-
# class Member < ActiveRecord::Base
-
# has_one :avatar
-
# accepts_nested_attributes_for :avatar
-
# end
-
#
-
# Enabling nested attributes on a one-to-one association allows you to
-
# create the member and avatar in one go:
-
#
-
# params = { member: { name: 'Jack', avatar_attributes: { icon: 'smiling' } } }
-
# member = Member.create(params[:member])
-
# member.avatar.id # => 2
-
# member.avatar.icon # => 'smiling'
-
#
-
# It also allows you to update the avatar through the member:
-
#
-
# params = { member: { avatar_attributes: { id: '2', icon: 'sad' } } }
-
# member.update params[:member]
-
# member.avatar.icon # => 'sad'
-
#
-
# By default you will only be able to set and update attributes on the
-
# associated model. If you want to destroy the associated model through the
-
# attributes hash, you have to enable it first using the
-
# <tt>:allow_destroy</tt> option.
-
#
-
# class Member < ActiveRecord::Base
-
# has_one :avatar
-
# accepts_nested_attributes_for :avatar, allow_destroy: true
-
# end
-
#
-
# Now, when you add the <tt>_destroy</tt> key to the attributes hash, with a
-
# value that evaluates to +true+, you will destroy the associated model:
-
#
-
# member.avatar_attributes = { id: '2', _destroy: '1' }
-
# member.avatar.marked_for_destruction? # => true
-
# member.save
-
# member.reload.avatar # => nil
-
#
-
# Note that the model will _not_ be destroyed until the parent is saved.
-
#
-
# === One-to-many
-
#
-
# Consider a member that has a number of posts:
-
#
-
# class Member < ActiveRecord::Base
-
# has_many :posts
-
# accepts_nested_attributes_for :posts
-
# end
-
#
-
# You can now set or update attributes on the associated posts through
-
# an attribute hash for a member: include the key +:posts_attributes+
-
# with an array of hashes of post attributes as a value.
-
#
-
# For each hash that does _not_ have an <tt>id</tt> key a new record will
-
# be instantiated, unless the hash also contains a <tt>_destroy</tt> key
-
# that evaluates to +true+.
-
#
-
# params = { member: {
-
# name: 'joe', posts_attributes: [
-
# { title: 'Kari, the awesome Ruby documentation browser!' },
-
# { title: 'The egalitarian assumption of the modern citizen' },
-
# { title: '', _destroy: '1' } # this will be ignored
-
# ]
-
# }}
-
#
-
# member = Member.create(params[:member])
-
# member.posts.length # => 2
-
# member.posts.first.title # => 'Kari, the awesome Ruby documentation browser!'
-
# member.posts.second.title # => 'The egalitarian assumption of the modern citizen'
-
#
-
# You may also set a :reject_if proc to silently ignore any new record
-
# hashes if they fail to pass your criteria. For example, the previous
-
# example could be rewritten as:
-
#
-
# class Member < ActiveRecord::Base
-
# has_many :posts
-
# accepts_nested_attributes_for :posts, reject_if: proc { |attributes| attributes['title'].blank? }
-
# end
-
#
-
# params = { member: {
-
# name: 'joe', posts_attributes: [
-
# { title: 'Kari, the awesome Ruby documentation browser!' },
-
# { title: 'The egalitarian assumption of the modern citizen' },
-
# { title: '' } # this will be ignored because of the :reject_if proc
-
# ]
-
# }}
-
#
-
# member = Member.create(params[:member])
-
# member.posts.length # => 2
-
# member.posts.first.title # => 'Kari, the awesome Ruby documentation browser!'
-
# member.posts.second.title # => 'The egalitarian assumption of the modern citizen'
-
#
-
# Alternatively, :reject_if also accepts a symbol for using methods:
-
#
-
# class Member < ActiveRecord::Base
-
# has_many :posts
-
# accepts_nested_attributes_for :posts, reject_if: :new_record?
-
# end
-
#
-
# class Member < ActiveRecord::Base
-
# has_many :posts
-
# accepts_nested_attributes_for :posts, reject_if: :reject_posts
-
#
-
# def reject_posts(attributed)
-
# attributed['title'].blank?
-
# end
-
# end
-
#
-
# If the hash contains an <tt>id</tt> key that matches an already
-
# associated record, the matching record will be modified:
-
#
-
# member.attributes = {
-
# name: 'Joe',
-
# posts_attributes: [
-
# { id: 1, title: '[UPDATED] An, as of yet, undisclosed awesome Ruby documentation browser!' },
-
# { id: 2, title: '[UPDATED] other post' }
-
# ]
-
# }
-
#
-
# member.posts.first.title # => '[UPDATED] An, as of yet, undisclosed awesome Ruby documentation browser!'
-
# member.posts.second.title # => '[UPDATED] other post'
-
#
-
# By default the associated records are protected from being destroyed. If
-
# you want to destroy any of the associated records through the attributes
-
# hash, you have to enable it first using the <tt>:allow_destroy</tt>
-
# option. This will allow you to also use the <tt>_destroy</tt> key to
-
# destroy existing records:
-
#
-
# class Member < ActiveRecord::Base
-
# has_many :posts
-
# accepts_nested_attributes_for :posts, allow_destroy: true
-
# end
-
#
-
# params = { member: {
-
# posts_attributes: [{ id: '2', _destroy: '1' }]
-
# }}
-
#
-
# member.attributes = params[:member]
-
# member.posts.detect { |p| p.id == 2 }.marked_for_destruction? # => true
-
# member.posts.length # => 2
-
# member.save
-
# member.reload.posts.length # => 1
-
#
-
# Nested attributes for an associated collection can also be passed in
-
# the form of a hash of hashes instead of an array of hashes:
-
#
-
# Member.create(name: 'joe',
-
# posts_attributes: { first: { title: 'Foo' },
-
# second: { title: 'Bar' } })
-
#
-
# has the same effect as
-
#
-
# Member.create(name: 'joe',
-
# posts_attributes: [ { title: 'Foo' },
-
# { title: 'Bar' } ])
-
#
-
# The keys of the hash which is the value for +:posts_attributes+ are
-
# ignored in this case.
-
# However, it is not allowed to use +'id'+ or +:id+ for one of
-
# such keys, otherwise the hash will be wrapped in an array and
-
# interpreted as an attribute hash for a single post.
-
#
-
# Passing attributes for an associated collection in the form of a hash
-
# of hashes can be used with hashes generated from HTTP/HTML parameters,
-
# where there maybe no natural way to submit an array of hashes.
-
#
-
# === Saving
-
#
-
# All changes to models, including the destruction of those marked for
-
# destruction, are saved and destroyed automatically and atomically when
-
# the parent model is saved. This happens inside the transaction initiated
-
# by the parents save method. See ActiveRecord::AutosaveAssociation.
-
#
-
# === Validating the presence of a parent model
-
#
-
# If you want to validate that a child record is associated with a parent
-
# record, you can use <tt>validates_presence_of</tt> and
-
# <tt>inverse_of</tt> as this example illustrates:
-
#
-
# class Member < ActiveRecord::Base
-
# has_many :posts, inverse_of: :member
-
# accepts_nested_attributes_for :posts
-
# end
-
#
-
# class Post < ActiveRecord::Base
-
# belongs_to :member, inverse_of: :posts
-
# validates_presence_of :member
-
# end
-
#
-
# Note that if you do not specify the <tt>inverse_of</tt> option, then
-
# Active Record will try to automatically guess the inverse association
-
# based on heuristics.
-
#
-
# For one-to-one nested associations, if you build the new (in-memory)
-
# child object yourself before assignment, then this module will not
-
# overwrite it, e.g.:
-
#
-
# class Member < ActiveRecord::Base
-
# has_one :avatar
-
# accepts_nested_attributes_for :avatar
-
#
-
# def avatar
-
# super || build_avatar(width: 200)
-
# end
-
# end
-
#
-
# member = Member.new
-
# member.avatar_attributes = {icon: 'sad'}
-
# member.avatar.width # => 200
-
2
module ClassMethods
-
2
REJECT_ALL_BLANK_PROC = proc { |attributes| attributes.all? { |key, value| key == '_destroy' || value.blank? } }
-
-
# Defines an attributes writer for the specified association(s).
-
#
-
# Supported options:
-
# [:allow_destroy]
-
# If true, destroys any members from the attributes hash with a
-
# <tt>_destroy</tt> key and a value that evaluates to +true+
-
# (eg. 1, '1', true, or 'true'). This option is off by default.
-
# [:reject_if]
-
# Allows you to specify a Proc or a Symbol pointing to a method
-
# that checks whether a record should be built for a certain attribute
-
# hash. The hash is passed to the supplied Proc or the method
-
# and it should return either +true+ or +false+. When no :reject_if
-
# is specified, a record will be built for all attribute hashes that
-
# do not have a <tt>_destroy</tt> value that evaluates to true.
-
# Passing <tt>:all_blank</tt> instead of a Proc will create a proc
-
# that will reject a record where all the attributes are blank excluding
-
# any value for _destroy.
-
# [:limit]
-
# Allows you to specify the maximum number of the associated records that
-
# can be processed with the nested attributes. Limit also can be specified as a
-
# Proc or a Symbol pointing to a method that should return number. If the size of the
-
# nested attributes array exceeds the specified limit, NestedAttributes::TooManyRecords
-
# exception is raised. If omitted, any number associations can be processed.
-
# Note that the :limit option is only applicable to one-to-many associations.
-
# [:update_only]
-
# For a one-to-one association, this option allows you to specify how
-
# nested attributes are to be used when an associated record already
-
# exists. In general, an existing record may either be updated with the
-
# new set of attribute values or be replaced by a wholly new record
-
# containing those values. By default the :update_only option is +false+
-
# and the nested attributes are used to update the existing record only
-
# if they include the record's <tt>:id</tt> value. Otherwise a new
-
# record will be instantiated and used to replace the existing one.
-
# However if the :update_only option is +true+, the nested attributes
-
# are used to update the record's attributes always, regardless of
-
# whether the <tt>:id</tt> is present. The option is ignored for collection
-
# associations.
-
#
-
# Examples:
-
# # creates avatar_attributes=
-
# accepts_nested_attributes_for :avatar, reject_if: proc { |attributes| attributes['name'].blank? }
-
# # creates avatar_attributes=
-
# accepts_nested_attributes_for :avatar, reject_if: :all_blank
-
# # creates avatar_attributes= and posts_attributes=
-
# accepts_nested_attributes_for :avatar, :posts, allow_destroy: true
-
2
def accepts_nested_attributes_for(*attr_names)
-
options = { :allow_destroy => false, :update_only => false }
-
options.update(attr_names.extract_options!)
-
options.assert_valid_keys(:allow_destroy, :reject_if, :limit, :update_only)
-
options[:reject_if] = REJECT_ALL_BLANK_PROC if options[:reject_if] == :all_blank
-
-
attr_names.each do |association_name|
-
if reflection = _reflect_on_association(association_name)
-
reflection.autosave = true
-
add_autosave_association_callbacks(reflection)
-
-
nested_attributes_options = self.nested_attributes_options.dup
-
nested_attributes_options[association_name.to_sym] = options
-
self.nested_attributes_options = nested_attributes_options
-
-
type = (reflection.collection? ? :collection : :one_to_one)
-
generate_association_writer(association_name, type)
-
else
-
raise ArgumentError, "No association found for name `#{association_name}'. Has it been defined yet?"
-
end
-
end
-
end
-
-
2
private
-
-
# Generates a writer method for this association. Serves as a point for
-
# accessing the objects in the association. For example, this method
-
# could generate the following:
-
#
-
# def pirate_attributes=(attributes)
-
# assign_nested_attributes_for_one_to_one_association(:pirate, attributes)
-
# end
-
#
-
# This redirects the attempts to write objects in an association through
-
# the helper methods defined below. Makes it seem like the nested
-
# associations are just regular associations.
-
2
def generate_association_writer(association_name, type)
-
generated_association_methods.module_eval <<-eoruby, __FILE__, __LINE__ + 1
-
if method_defined?(:#{association_name}_attributes=)
-
remove_method(:#{association_name}_attributes=)
-
end
-
def #{association_name}_attributes=(attributes)
-
assign_nested_attributes_for_#{type}_association(:#{association_name}, attributes)
-
end
-
eoruby
-
end
-
end
-
-
# Returns ActiveRecord::AutosaveAssociation::marked_for_destruction? It's
-
# used in conjunction with fields_for to build a form element for the
-
# destruction of this association.
-
#
-
# See ActionView::Helpers::FormHelper::fields_for for more info.
-
2
def _destroy
-
marked_for_destruction?
-
end
-
-
2
private
-
-
# Attribute hash keys that should not be assigned as normal attributes.
-
# These hash keys are nested attributes implementation details.
-
2
UNASSIGNABLE_KEYS = %w( id _destroy )
-
-
# Assigns the given attributes to the association.
-
#
-
# If an associated record does not yet exist, one will be instantiated. If
-
# an associated record already exists, the method's behavior depends on
-
# the value of the update_only option. If update_only is +false+ and the
-
# given attributes include an <tt>:id</tt> that matches the existing record's
-
# id, then the existing record will be modified. If no <tt>:id</tt> is provided
-
# it will be replaced with a new record. If update_only is +true+ the existing
-
# record will be modified regardless of whether an <tt>:id</tt> is provided.
-
#
-
# If the given attributes include a matching <tt>:id</tt> attribute, or
-
# update_only is true, and a <tt>:_destroy</tt> key set to a truthy value,
-
# then the existing record will be marked for destruction.
-
2
def assign_nested_attributes_for_one_to_one_association(association_name, attributes)
-
options = self.nested_attributes_options[association_name]
-
attributes = attributes.with_indifferent_access
-
existing_record = send(association_name)
-
-
if (options[:update_only] || !attributes['id'].blank?) && existing_record &&
-
(options[:update_only] || existing_record.id.to_s == attributes['id'].to_s)
-
assign_to_or_mark_for_destruction(existing_record, attributes, options[:allow_destroy]) unless call_reject_if(association_name, attributes)
-
-
elsif attributes['id'].present?
-
raise_nested_attributes_record_not_found!(association_name, attributes['id'])
-
-
elsif !reject_new_record?(association_name, attributes)
-
assignable_attributes = attributes.except(*UNASSIGNABLE_KEYS)
-
-
if existing_record && existing_record.new_record?
-
existing_record.assign_attributes(assignable_attributes)
-
association(association_name).initialize_attributes(existing_record)
-
else
-
method = "build_#{association_name}"
-
if respond_to?(method)
-
send(method, assignable_attributes)
-
else
-
raise ArgumentError, "Cannot build association `#{association_name}'. Are you trying to build a polymorphic one-to-one association?"
-
end
-
end
-
end
-
end
-
-
# Assigns the given attributes to the collection association.
-
#
-
# Hashes with an <tt>:id</tt> value matching an existing associated record
-
# will update that record. Hashes without an <tt>:id</tt> value will build
-
# a new record for the association. Hashes with a matching <tt>:id</tt>
-
# value and a <tt>:_destroy</tt> key set to a truthy value will mark the
-
# matched record for destruction.
-
#
-
# For example:
-
#
-
# assign_nested_attributes_for_collection_association(:people, {
-
# '1' => { id: '1', name: 'Peter' },
-
# '2' => { name: 'John' },
-
# '3' => { id: '2', _destroy: true }
-
# })
-
#
-
# Will update the name of the Person with ID 1, build a new associated
-
# person with the name 'John', and mark the associated Person with ID 2
-
# for destruction.
-
#
-
# Also accepts an Array of attribute hashes:
-
#
-
# assign_nested_attributes_for_collection_association(:people, [
-
# { id: '1', name: 'Peter' },
-
# { name: 'John' },
-
# { id: '2', _destroy: true }
-
# ])
-
2
def assign_nested_attributes_for_collection_association(association_name, attributes_collection)
-
options = self.nested_attributes_options[association_name]
-
-
unless attributes_collection.is_a?(Hash) || attributes_collection.is_a?(Array)
-
raise ArgumentError, "Hash or Array expected, got #{attributes_collection.class.name} (#{attributes_collection.inspect})"
-
end
-
-
check_record_limit!(options[:limit], attributes_collection)
-
-
if attributes_collection.is_a? Hash
-
keys = attributes_collection.keys
-
attributes_collection = if keys.include?('id') || keys.include?(:id)
-
[attributes_collection]
-
else
-
attributes_collection.values
-
end
-
end
-
-
association = association(association_name)
-
-
existing_records = if association.loaded?
-
association.target
-
else
-
attribute_ids = attributes_collection.map {|a| a['id'] || a[:id] }.compact
-
attribute_ids.empty? ? [] : association.scope.where(association.klass.primary_key => attribute_ids)
-
end
-
-
attributes_collection.each do |attributes|
-
attributes = attributes.with_indifferent_access
-
-
if attributes['id'].blank?
-
unless reject_new_record?(association_name, attributes)
-
association.build(attributes.except(*UNASSIGNABLE_KEYS))
-
end
-
elsif existing_record = existing_records.detect { |record| record.id.to_s == attributes['id'].to_s }
-
unless call_reject_if(association_name, attributes)
-
# Make sure we are operating on the actual object which is in the association's
-
# proxy_target array (either by finding it, or adding it if not found)
-
# Take into account that the proxy_target may have changed due to callbacks
-
target_record = association.target.detect { |record| record.id.to_s == attributes['id'].to_s }
-
if target_record
-
existing_record = target_record
-
else
-
association.add_to_target(existing_record, :skip_callbacks)
-
end
-
-
assign_to_or_mark_for_destruction(existing_record, attributes, options[:allow_destroy])
-
end
-
else
-
raise_nested_attributes_record_not_found!(association_name, attributes['id'])
-
end
-
end
-
end
-
-
# Takes in a limit and checks if the attributes_collection has too many
-
# records. The method will take limits in the form of symbols, procs, and
-
# number-like objects (anything that can be compared with an integer).
-
#
-
# Will raise an TooManyRecords error if the attributes_collection is
-
# larger than the limit.
-
2
def check_record_limit!(limit, attributes_collection)
-
if limit
-
limit = case limit
-
when Symbol
-
send(limit)
-
when Proc
-
limit.call
-
else
-
limit
-
end
-
-
if limit && attributes_collection.size > limit
-
raise TooManyRecords, "Maximum #{limit} records are allowed. Got #{attributes_collection.size} records instead."
-
end
-
end
-
end
-
-
# Updates a record with the +attributes+ or marks it for destruction if
-
# +allow_destroy+ is +true+ and has_destroy_flag? returns +true+.
-
2
def assign_to_or_mark_for_destruction(record, attributes, allow_destroy)
-
record.assign_attributes(attributes.except(*UNASSIGNABLE_KEYS))
-
record.mark_for_destruction if has_destroy_flag?(attributes) && allow_destroy
-
end
-
-
# Determines if a hash contains a truthy _destroy key.
-
2
def has_destroy_flag?(hash)
-
ConnectionAdapters::Column.value_to_boolean(hash['_destroy'])
-
end
-
-
# Determines if a new record should be build by checking for
-
# has_destroy_flag? or if a <tt>:reject_if</tt> proc exists for this
-
# association and evaluates to +true+.
-
2
def reject_new_record?(association_name, attributes)
-
has_destroy_flag?(attributes) || call_reject_if(association_name, attributes)
-
end
-
-
# Determines if a record with the particular +attributes+ should be
-
# rejected by calling the reject_if Symbol or Proc (if defined).
-
# The reject_if option is defined by +accepts_nested_attributes_for+.
-
#
-
# Returns false if there is a +destroy_flag+ on the attributes.
-
2
def call_reject_if(association_name, attributes)
-
return false if has_destroy_flag?(attributes)
-
case callback = self.nested_attributes_options[association_name][:reject_if]
-
when Symbol
-
method(callback).arity == 0 ? send(callback) : send(callback, attributes)
-
when Proc
-
callback.call(attributes)
-
end
-
end
-
-
2
def raise_nested_attributes_record_not_found!(association_name, record_id)
-
raise RecordNotFound, "Couldn't find #{self.class._reflect_on_association(association_name).klass.name} with ID=#{record_id} for #{self.class.name} with ID=#{id}"
-
end
-
end
-
end
-
2
module ActiveRecord
-
# = Active Record No Touching
-
2
module NoTouching
-
2
extend ActiveSupport::Concern
-
-
2
module ClassMethods
-
# Lets you selectively disable calls to `touch` for the
-
# duration of a block.
-
#
-
# ==== Examples
-
# ActiveRecord::Base.no_touching do
-
# Project.first.touch # does nothing
-
# Message.first.touch # does nothing
-
# end
-
#
-
# Project.no_touching do
-
# Project.first.touch # does nothing
-
# Message.first.touch # works, but does not touch the associated project
-
# end
-
#
-
2
def no_touching(&block)
-
NoTouching.apply_to(self, &block)
-
end
-
end
-
-
2
class << self
-
2
def apply_to(klass) #:nodoc:
-
klasses.push(klass)
-
yield
-
ensure
-
klasses.pop
-
end
-
-
2
def applied_to?(klass) #:nodoc:
-
klasses.any? { |k| k >= klass }
-
end
-
-
2
private
-
2
def klasses
-
Thread.current[:no_touching_classes] ||= []
-
end
-
end
-
-
2
def no_touching?
-
NoTouching.applied_to?(self.class)
-
end
-
-
2
def touch(*)
-
super unless no_touching?
-
end
-
end
-
end
-
# -*- coding: utf-8 -*-
-
-
2
module ActiveRecord
-
2
module NullRelation # :nodoc:
-
2
def exec_queries
-
@records = []
-
end
-
-
2
def pluck(*column_names)
-
[]
-
end
-
-
2
def delete_all(_conditions = nil)
-
0
-
end
-
-
2
def update_all(_updates, _conditions = nil, _options = {})
-
0
-
end
-
-
2
def delete(_id_or_array)
-
0
-
end
-
-
2
def size
-
calculate :size, nil
-
end
-
-
2
def empty?
-
true
-
end
-
-
2
def any?
-
false
-
end
-
-
2
def many?
-
false
-
end
-
-
2
def to_sql
-
""
-
end
-
-
2
def count(*)
-
calculate :count, nil
-
end
-
-
2
def sum(*)
-
calculate :sum, nil
-
end
-
-
2
def average(*)
-
calculate :average, nil
-
end
-
-
2
def minimum(*)
-
calculate :minimum, nil
-
end
-
-
2
def maximum(*)
-
calculate :maximum, nil
-
end
-
-
2
def calculate(operation, _column_name, _options = {})
-
# TODO: Remove _options argument as soon we remove support to
-
# activerecord-deprecated_finders.
-
if [:count, :sum, :size].include? operation
-
group_values.any? ? Hash.new : 0
-
elsif [:average, :minimum, :maximum].include?(operation) && group_values.any?
-
Hash.new
-
else
-
nil
-
end
-
end
-
-
2
def exists?(_id = false)
-
false
-
end
-
end
-
end
-
2
module ActiveRecord
-
# = Active Record Persistence
-
2
module Persistence
-
2
extend ActiveSupport::Concern
-
-
2
module ClassMethods
-
# Creates an object (or multiple objects) and saves it to the database, if validations pass.
-
# The resulting object is returned whether the object was saved successfully to the database or not.
-
#
-
# The +attributes+ parameter can be either a Hash or an Array of Hashes. These Hashes describe the
-
# attributes on the objects that are to be created.
-
#
-
# ==== Examples
-
# # Create a single new object
-
# User.create(first_name: 'Jamie')
-
#
-
# # Create an Array of new objects
-
# User.create([{ first_name: 'Jamie' }, { first_name: 'Jeremy' }])
-
#
-
# # Create a single object and pass it into a block to set other attributes.
-
# User.create(first_name: 'Jamie') do |u|
-
# u.is_admin = false
-
# end
-
#
-
# # Creating an Array of new objects using a block, where the block is executed for each object:
-
# User.create([{ first_name: 'Jamie' }, { first_name: 'Jeremy' }]) do |u|
-
# u.is_admin = false
-
# end
-
2
def create(attributes = nil, &block)
-
if attributes.is_a?(Array)
-
attributes.collect { |attr| create(attr, &block) }
-
else
-
object = new(attributes, &block)
-
object.save
-
object
-
end
-
end
-
-
# Given an attributes hash, +instantiate+ returns a new instance of
-
# the appropriate class. Accepts only keys as strings.
-
#
-
# For example, +Post.all+ may return Comments, Messages, and Emails
-
# by storing the record's subclass in a +type+ attribute. By calling
-
# +instantiate+ instead of +new+, finder methods ensure they get new
-
# instances of the appropriate class for each record.
-
#
-
# See +ActiveRecord::Inheritance#discriminate_class_for_record+ to see
-
# how this "single-table" inheritance mapping is implemented.
-
2
def instantiate(attributes, column_types = {})
-
32
klass = discriminate_class_for_record(attributes)
-
32
column_types = klass.decorate_columns(column_types.dup)
-
32
klass.allocate.init_with('attributes' => attributes, 'column_types' => column_types)
-
end
-
-
2
private
-
# Called by +instantiate+ to decide which class to use for a new
-
# record instance.
-
#
-
# See +ActiveRecord::Inheritance#discriminate_class_for_record+ for
-
# the single-table inheritance discriminator.
-
2
def discriminate_class_for_record(record)
-
32
self
-
end
-
end
-
-
# Returns true if this object hasn't been saved yet -- that is, a record
-
# for the object doesn't exist in the database yet; otherwise, returns false.
-
2
def new_record?
-
1076
sync_with_transaction_state
-
1076
@new_record
-
end
-
-
# Returns true if this object has been destroyed, otherwise returns false.
-
2
def destroyed?
-
72
sync_with_transaction_state
-
72
@destroyed
-
end
-
-
# Returns true if the record is persisted, i.e. it's not a new record and it was
-
# not destroyed, otherwise returns false.
-
2
def persisted?
-
275
!(new_record? || destroyed?)
-
end
-
-
# Saves the model.
-
#
-
# If the model is new a record gets created in the database, otherwise
-
# the existing record gets updated.
-
#
-
# By default, save always run validations. If any of them fail the action
-
# is cancelled and +save+ returns +false+. However, if you supply
-
# validate: false, validations are bypassed altogether. See
-
# ActiveRecord::Validations for more information.
-
#
-
# There's a series of callbacks associated with +save+. If any of the
-
# <tt>before_*</tt> callbacks return +false+ the action is cancelled and
-
# +save+ returns +false+. See ActiveRecord::Callbacks for further
-
# details.
-
#
-
# Attributes marked as readonly are silently ignored if the record is
-
# being updated.
-
2
def save(*)
-
72
create_or_update
-
rescue ActiveRecord::RecordInvalid
-
false
-
end
-
-
# Saves the model.
-
#
-
# If the model is new a record gets created in the database, otherwise
-
# the existing record gets updated.
-
#
-
# With <tt>save!</tt> validations always run. If any of them fail
-
# ActiveRecord::RecordInvalid gets raised. See ActiveRecord::Validations
-
# for more information.
-
#
-
# There's a series of callbacks associated with <tt>save!</tt>. If any of
-
# the <tt>before_*</tt> callbacks return +false+ the action is cancelled
-
# and <tt>save!</tt> raises ActiveRecord::RecordNotSaved. See
-
# ActiveRecord::Callbacks for further details.
-
#
-
# Attributes marked as readonly are silently ignored if the record is
-
# being updated.
-
2
def save!(*)
-
195
create_or_update || raise(RecordNotSaved)
-
end
-
-
# Deletes the record in the database and freezes this instance to
-
# reflect that no changes should be made (since they can't be
-
# persisted). Returns the frozen instance.
-
#
-
# The row is simply removed with an SQL +DELETE+ statement on the
-
# record's primary key, and no callbacks are executed.
-
#
-
# To enforce the object's +before_destroy+ and +after_destroy+
-
# callbacks or any <tt>:dependent</tt> association
-
# options, use <tt>#destroy</tt>.
-
2
def delete
-
self.class.delete(id) if persisted?
-
@destroyed = true
-
freeze
-
end
-
-
# Deletes the record in the database and freezes this instance to reflect
-
# that no changes should be made (since they can't be persisted).
-
#
-
# There's a series of callbacks associated with <tt>destroy</tt>. If
-
# the <tt>before_destroy</tt> callback return +false+ the action is cancelled
-
# and <tt>destroy</tt> returns +false+. See
-
# ActiveRecord::Callbacks for further details.
-
2
def destroy
-
raise ReadOnlyRecord if readonly?
-
destroy_associations
-
destroy_row if persisted?
-
@destroyed = true
-
freeze
-
end
-
-
# Deletes the record in the database and freezes this instance to reflect
-
# that no changes should be made (since they can't be persisted).
-
#
-
# There's a series of callbacks associated with <tt>destroy!</tt>. If
-
# the <tt>before_destroy</tt> callback return +false+ the action is cancelled
-
# and <tt>destroy!</tt> raises ActiveRecord::RecordNotDestroyed. See
-
# ActiveRecord::Callbacks for further details.
-
2
def destroy!
-
destroy || raise(ActiveRecord::RecordNotDestroyed)
-
end
-
-
# Returns an instance of the specified +klass+ with the attributes of the
-
# current record. This is mostly useful in relation to single-table
-
# inheritance structures where you want a subclass to appear as the
-
# superclass. This can be used along with record identification in
-
# Action Pack to allow, say, <tt>Client < Company</tt> to do something
-
# like render <tt>partial: @client.becomes(Company)</tt> to render that
-
# instance using the companies/company partial instead of clients/client.
-
#
-
# Note: The new instance will share a link to the same attributes as the original class.
-
# So any change to the attributes in either instance will affect the other.
-
2
def becomes(klass)
-
became = klass.new
-
became.instance_variable_set("@attributes", @attributes)
-
became.instance_variable_set("@attributes_cache", @attributes_cache)
-
became.instance_variable_set("@changed_attributes", @changed_attributes) if defined?(@changed_attributes)
-
became.instance_variable_set("@new_record", new_record?)
-
became.instance_variable_set("@destroyed", destroyed?)
-
became.instance_variable_set("@errors", errors)
-
became
-
end
-
-
# Wrapper around +becomes+ that also changes the instance's sti column value.
-
# This is especially useful if you want to persist the changed class in your
-
# database.
-
#
-
# Note: The old instance's sti column value will be changed too, as both objects
-
# share the same set of attributes.
-
2
def becomes!(klass)
-
became = becomes(klass)
-
sti_type = nil
-
if !klass.descends_from_active_record?
-
sti_type = klass.sti_name
-
end
-
became.public_send("#{klass.inheritance_column}=", sti_type)
-
became
-
end
-
-
# Updates a single attribute and saves the record.
-
# This is especially useful for boolean flags on existing records. Also note that
-
#
-
# * Validation is skipped.
-
# * Callbacks are invoked.
-
# * updated_at/updated_on column is updated if that column is available.
-
# * Updates all the attributes that are dirty in this object.
-
#
-
# This method raises an +ActiveRecord::ActiveRecordError+ if the
-
# attribute is marked as readonly.
-
2
def update_attribute(name, value)
-
name = name.to_s
-
verify_readonly_attribute(name)
-
send("#{name}=", value)
-
save(validate: false)
-
end
-
-
# Updates the attributes of the model from the passed-in hash and saves the
-
# record, all wrapped in a transaction. If the object is invalid, the saving
-
# will fail and false will be returned.
-
2
def update(attributes)
-
# The following transaction covers any possible database side-effects of the
-
# attributes assignment. For example, setting the IDs of a child collection.
-
with_transaction_returning_status do
-
assign_attributes(attributes)
-
save
-
end
-
end
-
-
2
alias update_attributes update
-
-
# Updates its receiver just like +update+ but calls <tt>save!</tt> instead
-
# of +save+, so an exception is raised if the record is invalid.
-
2
def update!(attributes)
-
# The following transaction covers any possible database side-effects of the
-
# attributes assignment. For example, setting the IDs of a child collection.
-
with_transaction_returning_status do
-
assign_attributes(attributes)
-
save!
-
end
-
end
-
-
2
alias update_attributes! update!
-
-
# Equivalent to <code>update_columns(name => value)</code>.
-
2
def update_column(name, value)
-
update_columns(name => value)
-
end
-
-
# Updates the attributes directly in the database issuing an UPDATE SQL
-
# statement and sets them in the receiver:
-
#
-
# user.update_columns(last_request_at: Time.current)
-
#
-
# This is the fastest way to update attributes because it goes straight to
-
# the database, but take into account that in consequence the regular update
-
# procedures are totally bypassed. In particular:
-
#
-
# * Validations are skipped.
-
# * Callbacks are skipped.
-
# * +updated_at+/+updated_on+ are not updated.
-
#
-
# This method raises an +ActiveRecord::ActiveRecordError+ when called on new
-
# objects, or when at least one of the attributes is marked as readonly.
-
2
def update_columns(attributes)
-
raise ActiveRecordError, "cannot update on a new record object" unless persisted?
-
-
attributes.each_key do |key|
-
verify_readonly_attribute(key.to_s)
-
end
-
-
updated_count = self.class.unscoped.where(self.class.primary_key => id).update_all(attributes)
-
-
attributes.each do |k, v|
-
raw_write_attribute(k, v)
-
end
-
-
updated_count == 1
-
end
-
-
# Initializes +attribute+ to zero if +nil+ and adds the value passed as +by+ (default is 1).
-
# The increment is performed directly on the underlying attribute, no setter is invoked.
-
# Only makes sense for number-based attributes. Returns +self+.
-
2
def increment(attribute, by = 1)
-
self[attribute] ||= 0
-
self[attribute] += by
-
self
-
end
-
-
# Wrapper around +increment+ that saves the record. This method differs from
-
# its non-bang version in that it passes through the attribute setter.
-
# Saving is not subjected to validation checks. Returns +true+ if the
-
# record could be saved.
-
2
def increment!(attribute, by = 1)
-
increment(attribute, by).update_attribute(attribute, self[attribute])
-
end
-
-
# Initializes +attribute+ to zero if +nil+ and subtracts the value passed as +by+ (default is 1).
-
# The decrement is performed directly on the underlying attribute, no setter is invoked.
-
# Only makes sense for number-based attributes. Returns +self+.
-
2
def decrement(attribute, by = 1)
-
self[attribute] ||= 0
-
self[attribute] -= by
-
self
-
end
-
-
# Wrapper around +decrement+ that saves the record. This method differs from
-
# its non-bang version in that it passes through the attribute setter.
-
# Saving is not subjected to validation checks. Returns +true+ if the
-
# record could be saved.
-
2
def decrement!(attribute, by = 1)
-
decrement(attribute, by).update_attribute(attribute, self[attribute])
-
end
-
-
# Assigns to +attribute+ the boolean opposite of <tt>attribute?</tt>. So
-
# if the predicate returns +true+ the attribute will become +false+. This
-
# method toggles directly the underlying value without calling any setter.
-
# Returns +self+.
-
2
def toggle(attribute)
-
self[attribute] = !send("#{attribute}?")
-
self
-
end
-
-
# Wrapper around +toggle+ that saves the record. This method differs from
-
# its non-bang version in that it passes through the attribute setter.
-
# Saving is not subjected to validation checks. Returns +true+ if the
-
# record could be saved.
-
2
def toggle!(attribute)
-
toggle(attribute).update_attribute(attribute, self[attribute])
-
end
-
-
# Reloads the record from the database.
-
#
-
# This method finds record by its primary key (which could be assigned manually) and
-
# modifies the receiver in-place:
-
#
-
# account = Account.new
-
# # => #<Account id: nil, email: nil>
-
# account.id = 1
-
# account.reload
-
# # Account Load (1.2ms) SELECT "accounts".* FROM "accounts" WHERE "accounts"."id" = $1 LIMIT 1 [["id", 1]]
-
# # => #<Account id: 1, email: 'account@example.com'>
-
#
-
# Attributes are reloaded from the database, and caches busted, in
-
# particular the associations cache.
-
#
-
# If the record no longer exists in the database <tt>ActiveRecord::RecordNotFound</tt>
-
# is raised. Otherwise, in addition to the in-place modification the method
-
# returns +self+ for convenience.
-
#
-
# The optional <tt>:lock</tt> flag option allows you to lock the reloaded record:
-
#
-
# reload(lock: true) # reload with pessimistic locking
-
#
-
# Reloading is commonly used in test suites to test something is actually
-
# written to the database, or when some action modifies the corresponding
-
# row in the database but not the object in memory:
-
#
-
# assert account.deposit!(25)
-
# assert_equal 25, account.credit # check it is updated in memory
-
# assert_equal 25, account.reload.credit # check it is also persisted
-
#
-
# Another common use case is optimistic locking handling:
-
#
-
# def with_optimistic_retry
-
# begin
-
# yield
-
# rescue ActiveRecord::StaleObjectError
-
# begin
-
# # Reload lock_version in particular.
-
# reload
-
# rescue ActiveRecord::RecordNotFound
-
# # If the record is gone there is nothing to do.
-
# else
-
# retry
-
# end
-
# end
-
# end
-
#
-
2
def reload(options = nil)
-
clear_aggregation_cache
-
clear_association_cache
-
-
fresh_object =
-
if options && options[:lock]
-
self.class.unscoped { self.class.lock(options[:lock]).find(id) }
-
else
-
self.class.unscoped { self.class.find(id) }
-
end
-
-
@attributes.update(fresh_object.instance_variable_get('@attributes'))
-
-
@column_types = self.class.column_types
-
@column_types_override = fresh_object.instance_variable_get('@column_types_override')
-
@attributes_cache = {}
-
@new_record = false
-
self
-
end
-
-
# Saves the record with the updated_at/on attributes set to the current time.
-
# Please note that no validation is performed and only the +after_touch+,
-
# +after_commit+ and +after_rollback+ callbacks are executed.
-
# If an attribute name is passed, that attribute is updated along with
-
# updated_at/on attributes.
-
#
-
# product.touch # updates updated_at/on
-
# product.touch(:designed_at) # updates the designed_at attribute and updated_at/on
-
#
-
# If used along with +belongs_to+ then +touch+ will invoke +touch+ method on associated object.
-
#
-
# class Brake < ActiveRecord::Base
-
# belongs_to :car, touch: true
-
# end
-
#
-
# class Car < ActiveRecord::Base
-
# belongs_to :corporation, touch: true
-
# end
-
#
-
# # triggers @brake.car.touch and @brake.car.corporation.touch
-
# @brake.touch
-
#
-
# Note that +touch+ must be used on a persisted object, or else an
-
# ActiveRecordError will be thrown. For example:
-
#
-
# ball = Ball.new
-
# ball.touch(:updated_at) # => raises ActiveRecordError
-
#
-
2
def touch(name = nil)
-
raise ActiveRecordError, "cannot touch on a new record object" unless persisted?
-
-
attributes = timestamp_attributes_for_update_in_model
-
attributes << name if name
-
-
unless attributes.empty?
-
current_time = current_time_from_proper_timezone
-
changes = {}
-
-
attributes.each do |column|
-
column = column.to_s
-
changes[column] = write_attribute(column, current_time)
-
end
-
-
changes[self.class.locking_column] = increment_lock if locking_enabled?
-
-
changed_attributes.except!(*changes.keys)
-
primary_key = self.class.primary_key
-
self.class.unscoped.where(primary_key => self[primary_key]).update_all(changes) == 1
-
else
-
true
-
end
-
end
-
-
2
private
-
-
# A hook to be overridden by association modules.
-
2
def destroy_associations
-
end
-
-
2
def destroy_row
-
relation_for_destroy.delete_all
-
end
-
-
2
def relation_for_destroy
-
pk = self.class.primary_key
-
column = self.class.columns_hash[pk]
-
substitute = self.class.connection.substitute_at(column, 0)
-
-
relation = self.class.unscoped.where(
-
self.class.arel_table[pk].eq(substitute))
-
-
relation.bind_values = [[column, id]]
-
relation
-
end
-
-
2
def create_or_update
-
267
raise ReadOnlyRecord if readonly?
-
267
result = new_record? ? _create_record : _update_record
-
267
result != false
-
end
-
-
# Updates the associated record with values matching those of the instance attributes.
-
# Returns the number of affected rows.
-
2
def _update_record(attribute_names = @attributes.keys)
-
attributes_values = arel_attributes_with_values_for_update(attribute_names)
-
if attributes_values.empty?
-
0
-
else
-
self.class.unscoped._update_record attributes_values, id, id_was
-
end
-
end
-
-
# Creates a record with values matching those of the instance attributes
-
# and returns its id.
-
2
def _create_record(attribute_names = @attributes.keys)
-
267
attributes_values = arel_attributes_with_values_for_create(attribute_names)
-
-
267
new_id = self.class.unscoped.insert attributes_values
-
267
self.id ||= new_id if self.class.primary_key
-
-
267
@new_record = false
-
267
id
-
end
-
-
2
def verify_readonly_attribute(name)
-
raise ActiveRecordError, "#{name} is marked as readonly" if self.class.readonly_attributes.include?(name)
-
end
-
end
-
end
-
-
2
module ActiveRecord
-
# = Active Record Query Cache
-
2
class QueryCache
-
2
module ClassMethods
-
# Enable the query cache within the block if Active Record is configured.
-
# If it's not, it will execute the given block.
-
2
def cache(&block)
-
if ActiveRecord::Base.connected?
-
connection.cache(&block)
-
else
-
yield
-
end
-
end
-
-
# Disable the query cache within the block if Active Record is configured.
-
# If it's not, it will execute the given block.
-
2
def uncached(&block)
-
if ActiveRecord::Base.connected?
-
connection.uncached(&block)
-
else
-
yield
-
end
-
end
-
end
-
-
2
def initialize(app)
-
2
@app = app
-
end
-
-
2
def call(env)
-
13
enabled = ActiveRecord::Base.connection.query_cache_enabled
-
13
connection_id = ActiveRecord::Base.connection_id
-
13
ActiveRecord::Base.connection.enable_query_cache!
-
-
13
response = @app.call(env)
-
13
response[2] = Rack::BodyProxy.new(response[2]) do
-
13
restore_query_cache_settings(connection_id, enabled)
-
end
-
-
13
response
-
rescue Exception => e
-
restore_query_cache_settings(connection_id, enabled)
-
raise e
-
end
-
-
2
private
-
-
2
def restore_query_cache_settings(connection_id, enabled)
-
13
ActiveRecord::Base.connection_id = connection_id
-
13
ActiveRecord::Base.connection.clear_query_cache
-
13
ActiveRecord::Base.connection.disable_query_cache! unless enabled
-
end
-
-
end
-
end
-
2
module ActiveRecord
-
2
module Querying
-
2
delegate :find, :take, :take!, :first, :first!, :last, :last!, :exists?, :any?, :many?, to: :all
-
2
delegate :second, :second!, :third, :third!, :fourth, :fourth!, :fifth, :fifth!, :forty_two, :forty_two!, to: :all
-
2
delegate :first_or_create, :first_or_create!, :first_or_initialize, to: :all
-
2
delegate :find_or_create_by, :find_or_create_by!, :find_or_initialize_by, to: :all
-
2
delegate :find_by, :find_by!, to: :all
-
2
delegate :destroy, :destroy_all, :delete, :delete_all, :update, :update_all, to: :all
-
2
delegate :find_each, :find_in_batches, to: :all
-
2
delegate :select, :group, :order, :except, :reorder, :limit, :offset, :joins,
-
:where, :rewhere, :preload, :eager_load, :includes, :from, :lock, :readonly,
-
:having, :create_with, :uniq, :distinct, :references, :none, :unscope, to: :all
-
2
delegate :count, :average, :minimum, :maximum, :sum, :calculate, to: :all
-
2
delegate :pluck, :ids, to: :all
-
-
# Executes a custom SQL query against your database and returns all the results. The results will
-
# be returned as an array with columns requested encapsulated as attributes of the model you call
-
# this method from. If you call <tt>Product.find_by_sql</tt> then the results will be returned in
-
# a +Product+ object with the attributes you specified in the SQL query.
-
#
-
# If you call a complicated SQL query which spans multiple tables the columns specified by the
-
# SELECT will be attributes of the model, whether or not they are columns of the corresponding
-
# table.
-
#
-
# The +sql+ parameter is a full SQL query as a string. It will be called as is, there will be
-
# no database agnostic conversions performed. This should be a last resort because using, for example,
-
# MySQL specific terms will lock you to using that particular database engine or require you to
-
# change your call if you switch engines.
-
#
-
# # A simple SQL query spanning multiple tables
-
# Post.find_by_sql "SELECT p.title, c.author FROM posts p, comments c WHERE p.id = c.post_id"
-
# # => [#<Post:0x36bff9c @attributes={"title"=>"Ruby Meetup", "first_name"=>"Quentin"}>, ...]
-
#
-
# You can use the same string replacement techniques as you can with <tt>ActiveRecord::QueryMethods#where</tt>:
-
#
-
# Post.find_by_sql ["SELECT title FROM posts WHERE author = ? AND created > ?", author_id, start_date]
-
# Post.find_by_sql ["SELECT body FROM comments WHERE author = :user_id OR approved_by = :user_id", { :user_id => user_id }]
-
2
def find_by_sql(sql, binds = [])
-
16
result_set = connection.select_all(sanitize_sql(sql), "#{name} Load", binds)
-
16
column_types = {}
-
-
16
if result_set.respond_to? :column_types
-
16
column_types = result_set.column_types
-
else
-
ActiveSupport::Deprecation.warn "the object returned from `select_all` must respond to `column_types`"
-
end
-
-
48
result_set.map { |record| instantiate(record, column_types) }
-
end
-
-
# Returns the result of an SQL statement that should only include a COUNT(*) in the SELECT part.
-
# The use of this method should be restricted to complicated SQL queries that can't be executed
-
# using the ActiveRecord::Calculations class methods. Look into those before using this.
-
#
-
# ==== Parameters
-
#
-
# * +sql+ - An SQL statement which should return a count query from the database, see the example below.
-
#
-
# Product.count_by_sql "SELECT COUNT(*) FROM sales s, customers c WHERE s.customer_id = c.id"
-
2
def count_by_sql(sql)
-
sql = sanitize_conditions(sql)
-
connection.select_value(sql, "#{name} Count").to_i
-
end
-
end
-
end
-
2
require "active_record"
-
2
require "rails"
-
2
require "active_model/railtie"
-
-
# For now, action_controller must always be present with
-
# rails, so let's make sure that it gets required before
-
# here. This is needed for correctly setting up the middleware.
-
# In the future, this might become an optional require.
-
2
require "action_controller/railtie"
-
-
2
module ActiveRecord
-
# = Active Record Railtie
-
2
class Railtie < Rails::Railtie # :nodoc:
-
2
config.active_record = ActiveSupport::OrderedOptions.new
-
-
2
config.app_generators.orm :active_record, :migration => true,
-
:timestamps => true
-
-
2
config.app_middleware.insert_after "::ActionDispatch::Callbacks",
-
"ActiveRecord::QueryCache"
-
-
2
config.app_middleware.insert_after "::ActionDispatch::Callbacks",
-
"ActiveRecord::ConnectionAdapters::ConnectionManagement"
-
-
2
config.action_dispatch.rescue_responses.merge!(
-
'ActiveRecord::RecordNotFound' => :not_found,
-
'ActiveRecord::StaleObjectError' => :conflict,
-
'ActiveRecord::RecordInvalid' => :unprocessable_entity,
-
'ActiveRecord::RecordNotSaved' => :unprocessable_entity
-
)
-
-
-
2
config.active_record.use_schema_cache_dump = true
-
2
config.active_record.maintain_test_schema = true
-
-
2
config.eager_load_namespaces << ActiveRecord
-
-
2
rake_tasks do
-
require "active_record/base"
-
-
namespace :db do
-
task :load_config do
-
ActiveRecord::Tasks::DatabaseTasks.database_configuration = Rails.application.config.database_configuration
-
-
if defined?(ENGINE_PATH) && engine = Rails::Engine.find(ENGINE_PATH)
-
if engine.paths['db/migrate'].existent
-
ActiveRecord::Tasks::DatabaseTasks.migrations_paths += engine.paths['db/migrate'].to_a
-
end
-
end
-
end
-
end
-
-
load "active_record/railties/databases.rake"
-
end
-
-
# When loading console, force ActiveRecord::Base to be loaded
-
# to avoid cross references when loading a constant for the
-
# first time. Also, make it output to STDERR.
-
2
console do |app|
-
require "active_record/railties/console_sandbox" if app.sandbox?
-
require "active_record/base"
-
console = ActiveSupport::Logger.new(STDERR)
-
Rails.logger.extend ActiveSupport::Logger.broadcast console
-
end
-
-
2
runner do
-
require "active_record/base"
-
end
-
-
2
initializer "active_record.initialize_timezone" do
-
2
ActiveSupport.on_load(:active_record) do
-
2
self.time_zone_aware_attributes = true
-
2
self.default_timezone = :utc
-
end
-
end
-
-
2
initializer "active_record.logger" do
-
4
ActiveSupport.on_load(:active_record) { self.logger ||= ::Rails.logger }
-
end
-
-
2
initializer "active_record.migration_error" do
-
2
if config.active_record.delete(:migration_error) == :page_load
-
config.app_middleware.insert_after "::ActionDispatch::Callbacks",
-
"ActiveRecord::Migration::CheckPending"
-
end
-
end
-
-
2
initializer "active_record.check_schema_cache_dump" do
-
2
if config.active_record.delete(:use_schema_cache_dump)
-
2
config.after_initialize do |app|
-
2
ActiveSupport.on_load(:active_record) do
-
2
filename = File.join(app.config.paths["db"].first, "schema_cache.dump")
-
-
2
if File.file?(filename)
-
cache = Marshal.load File.binread filename
-
if cache.version == ActiveRecord::Migrator.current_version
-
self.connection.schema_cache = cache
-
else
-
warn "Ignoring db/schema_cache.dump because it has expired. The current schema version is #{ActiveRecord::Migrator.current_version}, but the one in the cache is #{cache.version}."
-
end
-
end
-
end
-
end
-
end
-
end
-
-
2
initializer "active_record.set_configs" do |app|
-
2
ActiveSupport.on_load(:active_record) do
-
2
app.config.active_record.each do |k,v|
-
2
send "#{k}=", v
-
end
-
end
-
end
-
-
# This sets the database configuration from Configuration#database_configuration
-
# and then establishes the connection.
-
2
initializer "active_record.initialize_database" do |app|
-
2
ActiveSupport.on_load(:active_record) do
-
-
2
class ActiveRecord::NoDatabaseError
-
2
remove_possible_method :extend_message
-
2
def extend_message(message)
-
message << "Run `$ bin/rake db:create db:migrate` to create your database"
-
message
-
end
-
end
-
-
2
self.configurations = Rails.application.config.database_configuration
-
2
establish_connection
-
end
-
end
-
-
# Expose database runtime to controller for logging.
-
2
initializer "active_record.log_runtime" do
-
2
require "active_record/railties/controller_runtime"
-
2
ActiveSupport.on_load(:action_controller) do
-
2
include ActiveRecord::Railties::ControllerRuntime
-
end
-
end
-
-
2
initializer "active_record.set_reloader_hooks" do |app|
-
2
hook = app.config.reload_classes_only_on_change ? :to_prepare : :to_cleanup
-
-
2
ActiveSupport.on_load(:active_record) do
-
2
ActionDispatch::Reloader.send(hook) do
-
2
if ActiveRecord::Base.connected?
-
ActiveRecord::Base.clear_reloadable_connections!
-
ActiveRecord::Base.clear_cache!
-
end
-
end
-
end
-
end
-
-
2
initializer "active_record.add_watchable_files" do |app|
-
2
path = app.paths["db"].first
-
2
config.watchable_files.concat ["#{path}/schema.rb", "#{path}/structure.sql"]
-
end
-
end
-
end
-
2
require 'active_support/core_ext/module/attr_internal'
-
2
require 'active_record/log_subscriber'
-
-
2
module ActiveRecord
-
2
module Railties # :nodoc:
-
2
module ControllerRuntime #:nodoc:
-
2
extend ActiveSupport::Concern
-
-
2
protected
-
-
2
attr_internal :db_runtime
-
-
2
def process_action(action, *args)
-
# We also need to reset the runtime before each action
-
# because of queries in middleware or in cases we are streaming
-
# and it won't be cleaned up by the method below.
-
24
ActiveRecord::LogSubscriber.reset_runtime
-
24
super
-
end
-
-
2
def cleanup_view_runtime
-
24
if ActiveRecord::Base.connected?
-
24
db_rt_before_render = ActiveRecord::LogSubscriber.reset_runtime
-
24
self.db_runtime = (db_runtime || 0) + db_rt_before_render
-
24
runtime = super
-
24
db_rt_after_render = ActiveRecord::LogSubscriber.reset_runtime
-
24
self.db_runtime += db_rt_after_render
-
24
runtime - db_rt_after_render
-
else
-
super
-
end
-
end
-
-
2
def append_info_to_payload(payload)
-
24
super
-
24
if ActiveRecord::Base.connected?
-
24
payload[:db_runtime] = (db_runtime || 0) + ActiveRecord::LogSubscriber.reset_runtime
-
end
-
end
-
-
2
module ClassMethods # :nodoc:
-
2
def log_process_action(payload)
-
24
messages, db_runtime = super, payload[:db_runtime]
-
24
messages << ("ActiveRecord: %.1fms" % db_runtime.to_f) if db_runtime
-
24
messages
-
end
-
end
-
end
-
end
-
end
-
-
2
module ActiveRecord
-
2
module ReadonlyAttributes
-
2
extend ActiveSupport::Concern
-
-
2
included do
-
2
class_attribute :_attr_readonly, instance_accessor: false
-
2
self._attr_readonly = []
-
end
-
-
2
module ClassMethods
-
# Attributes listed as readonly will be used to create a new record but update operations will
-
# ignore these fields.
-
2
def attr_readonly(*attributes)
-
self._attr_readonly = Set.new(attributes.map { |a| a.to_s }) + (self._attr_readonly || [])
-
end
-
-
# Returns an array of all the attributes that have been specified as readonly.
-
2
def readonly_attributes
-
self._attr_readonly
-
end
-
end
-
end
-
end
-
2
module ActiveRecord
-
# = Active Record Reflection
-
2
module Reflection # :nodoc:
-
2
extend ActiveSupport::Concern
-
-
2
included do
-
2
class_attribute :_reflections
-
2
class_attribute :aggregate_reflections
-
2
self._reflections = {}
-
2
self.aggregate_reflections = {}
-
end
-
-
2
def self.create(macro, name, scope, options, ar)
-
41
case macro
-
when :has_many, :belongs_to, :has_one
-
41
klass = options[:through] ? ThroughReflection : AssociationReflection
-
when :composed_of
-
klass = AggregateReflection
-
end
-
-
41
klass.new(macro, name, scope, options, ar)
-
end
-
-
2
def self.add_reflection(ar, name, reflection)
-
41
ar._reflections = ar._reflections.merge(name.to_sym => reflection)
-
end
-
-
2
def self.add_aggregate_reflection(ar, name, reflection)
-
ar.aggregate_reflections = ar.aggregate_reflections.merge(name.to_sym => reflection)
-
end
-
-
# \Reflection enables to interrogate Active Record classes and objects
-
# about their associations and aggregations. This information can,
-
# for example, be used in a form builder that takes an Active Record object
-
# and creates input fields for all of the attributes depending on their type
-
# and displays the associations to other objects.
-
#
-
# MacroReflection class has info for AggregateReflection and AssociationReflection
-
# classes.
-
2
module ClassMethods
-
# Returns an array of AggregateReflection objects for all the aggregations in the class.
-
2
def reflect_on_all_aggregations
-
aggregate_reflections.values
-
end
-
-
# Returns the AggregateReflection object for the named +aggregation+ (use the symbol).
-
#
-
# Account.reflect_on_aggregation(:balance) # => the balance AggregateReflection
-
#
-
2
def reflect_on_aggregation(aggregation)
-
15
aggregate_reflections[aggregation.to_sym]
-
end
-
-
# Returns a Hash of name of the reflection as the key and a AssociationReflection as the value.
-
#
-
# Account.reflections # => {balance: AggregateReflection}
-
#
-
# @api public
-
2
def reflections
-
ref = {}
-
_reflections.each do |name, reflection|
-
parent_name, parent_reflection = reflection.parent_reflection
-
if parent_name
-
ref[parent_name] = parent_reflection
-
else
-
ref[name] = reflection
-
end
-
end
-
ref
-
end
-
-
# Returns an array of AssociationReflection objects for all the
-
# associations in the class. If you only want to reflect on a certain
-
# association type, pass in the symbol (<tt>:has_many</tt>, <tt>:has_one</tt>,
-
# <tt>:belongs_to</tt>) as the first parameter.
-
#
-
# Example:
-
#
-
# Account.reflect_on_all_associations # returns an array of all associations
-
# Account.reflect_on_all_associations(:has_many) # returns an array of all has_many associations
-
#
-
# @api public
-
2
def reflect_on_all_associations(macro = nil)
-
association_reflections = reflections.values
-
macro ? association_reflections.select { |reflection| reflection.macro == macro } : association_reflections
-
end
-
-
# Returns the AssociationReflection object for the +association+ (use the symbol).
-
#
-
# Account.reflect_on_association(:owner) # returns the owner AssociationReflection
-
# Invoice.reflect_on_association(:line_items).macro # returns :has_many
-
#
-
# @api public
-
2
def reflect_on_association(association)
-
reflections[association.to_sym]
-
end
-
-
# @api private
-
2
def _reflect_on_association(association) #:nodoc:
-
1012
_reflections[association.to_sym]
-
end
-
-
# Returns an array of AssociationReflection objects for all associations which have <tt>:autosave</tt> enabled.
-
#
-
# @api public
-
2
def reflect_on_all_autosave_associations
-
reflections.values.select { |reflection| reflection.options[:autosave] }
-
end
-
end
-
-
# Base class for AggregateReflection and AssociationReflection. Objects of
-
# AggregateReflection and AssociationReflection are returned by the Reflection::ClassMethods.
-
#
-
# MacroReflection
-
# AggregateReflection
-
# AssociationReflection
-
# ThroughReflection
-
2
class MacroReflection
-
# Returns the name of the macro.
-
#
-
# <tt>composed_of :balance, class_name: 'Money'</tt> returns <tt>:balance</tt>
-
# <tt>has_many :clients</tt> returns <tt>:clients</tt>
-
2
attr_reader :name
-
-
# Returns the macro type.
-
#
-
# <tt>composed_of :balance, class_name: 'Money'</tt> returns <tt>:composed_of</tt>
-
# <tt>has_many :clients</tt> returns <tt>:has_many</tt>
-
2
attr_reader :macro
-
-
2
attr_reader :scope
-
-
# Returns the hash of options used for the macro.
-
#
-
# <tt>composed_of :balance, class_name: 'Money'</tt> returns <tt>{ class_name: "Money" }</tt>
-
# <tt>has_many :clients</tt> returns <tt>{}</tt>
-
2
attr_reader :options
-
-
2
attr_reader :active_record
-
-
2
attr_reader :plural_name # :nodoc:
-
-
2
def initialize(macro, name, scope, options, active_record)
-
41
@macro = macro
-
41
@name = name
-
41
@scope = scope
-
41
@options = options
-
41
@active_record = active_record
-
41
@klass = options[:class]
-
41
@plural_name = active_record.pluralize_table_names ?
-
name.to_s.pluralize : name.to_s
-
end
-
-
2
def autosave=(autosave)
-
@automatic_inverse_of = false
-
@options[:autosave] = autosave
-
_, parent_reflection = self.parent_reflection
-
if parent_reflection
-
parent_reflection.autosave = autosave
-
end
-
end
-
-
# Returns the class for the macro.
-
#
-
# <tt>composed_of :balance, class_name: 'Money'</tt> returns the Money class
-
# <tt>has_many :clients</tt> returns the Client class
-
2
def klass
-
@klass ||= class_name.constantize
-
end
-
-
# Returns the class name for the macro.
-
#
-
# <tt>composed_of :balance, class_name: 'Money'</tt> returns <tt>'Money'</tt>
-
# <tt>has_many :clients</tt> returns <tt>'Client'</tt>
-
2
def class_name
-
1
@class_name ||= (options[:class_name] || derive_class_name).to_s
-
end
-
-
# Returns +true+ if +self+ and +other_aggregation+ have the same +name+ attribute, +active_record+ attribute,
-
# and +other_aggregation+ has an options hash assigned to it.
-
2
def ==(other_aggregation)
-
super ||
-
other_aggregation.kind_of?(self.class) &&
-
name == other_aggregation.name &&
-
!other_aggregation.options.nil? &&
-
216
active_record == other_aggregation.active_record
-
end
-
-
2
private
-
2
def derive_class_name
-
name.to_s.camelize
-
end
-
end
-
-
-
# Holds all the meta-data about an aggregation as it was specified in the
-
# Active Record class.
-
2
class AggregateReflection < MacroReflection #:nodoc:
-
2
def mapping
-
mapping = options[:mapping] || [name, name]
-
mapping.first.is_a?(Array) ? mapping : [mapping]
-
end
-
end
-
-
# Holds all the meta-data about an association as it was specified in the
-
# Active Record class.
-
2
class AssociationReflection < MacroReflection #:nodoc:
-
# Returns the target association's class.
-
#
-
# class Author < ActiveRecord::Base
-
# has_many :books
-
# end
-
#
-
# Author.reflect_on_association(:books).klass
-
# # => Book
-
#
-
# <b>Note:</b> Do not call +klass.new+ or +klass.create+ to instantiate
-
# a new association object. Use +build_association+ or +create_association+
-
# instead. This allows plugins to hook into association object creation.
-
2
def klass
-
1010
@klass ||= active_record.send(:compute_type, class_name)
-
end
-
-
2
attr_reader :type, :foreign_type
-
2
attr_accessor :parent_reflection # [:name, Reflection]
-
-
2
def initialize(macro, name, scope, options, active_record)
-
41
super
-
41
@collection = [:has_many, :has_and_belongs_to_many].include?(macro)
-
41
@automatic_inverse_of = nil
-
41
@type = options[:as] && "#{options[:as]}_type"
-
41
@foreign_type = options[:foreign_type] || "#{name}_type"
-
41
@constructable = calculate_constructable(macro, options)
-
end
-
-
# Returns a new, unsaved instance of the associated class. +attributes+ will
-
# be passed to the class's constructor.
-
2
def build_association(attributes, &block)
-
72
klass.new(attributes, &block)
-
end
-
-
2
def constructable? # :nodoc:
-
14
@constructable
-
end
-
-
2
def table_name
-
klass.table_name
-
end
-
-
2
def quoted_table_name
-
klass.quoted_table_name
-
end
-
-
2
def join_table
-
@join_table ||= options[:join_table] || derive_join_table
-
end
-
-
2
def foreign_key
-
720
@foreign_key ||= options[:foreign_key] || derive_foreign_key
-
end
-
-
2
def primary_key_column
-
klass.columns_hash[klass.primary_key]
-
end
-
-
2
def association_foreign_key
-
@association_foreign_key ||= options[:association_foreign_key] || class_name.foreign_key
-
end
-
-
# klass option is necessary to support loading polymorphic associations
-
2
def association_primary_key(klass = nil)
-
options[:primary_key] || primary_key(klass || self.klass)
-
end
-
-
2
def active_record_primary_key
-
144
@active_record_primary_key ||= options[:primary_key] || primary_key(active_record)
-
end
-
-
2
def counter_cache_column
-
144
if options[:counter_cache] == true
-
"#{active_record.name.demodulize.underscore.pluralize}_count"
-
144
elsif options[:counter_cache]
-
options[:counter_cache].to_s
-
end
-
end
-
-
2
def check_validity!
-
216
check_validity_of_inverse!
-
end
-
-
2
def check_validity_of_inverse!
-
216
unless options[:polymorphic]
-
72
if has_inverse? && inverse_of.nil?
-
raise InverseOfAssociationNotFoundError.new(self)
-
end
-
end
-
end
-
-
2
def through_reflection
-
nil
-
end
-
-
2
def source_reflection
-
self
-
end
-
-
# A chain of reflections from this one back to the owner. For more see the explanation in
-
# ThroughReflection.
-
2
def chain
-
72
[self]
-
end
-
-
2
def nested?
-
false
-
end
-
-
# An array of arrays of scopes. Each item in the outside array corresponds to a reflection
-
# in the #chain.
-
2
def scope_chain
-
72
scope ? [[scope]] : [[]]
-
end
-
-
2
alias :source_macro :macro
-
-
2
def has_inverse?
-
72
inverse_name
-
end
-
-
2
def inverse_of
-
216
return unless inverse_name
-
-
@inverse_of ||= klass._reflect_on_association inverse_name
-
end
-
-
2
def polymorphic_inverse_of(associated_class)
-
if has_inverse?
-
if inverse_relationship = associated_class._reflect_on_association(options[:inverse_of])
-
inverse_relationship
-
else
-
raise InverseOfAssociationNotFoundError.new(self, associated_class)
-
end
-
end
-
end
-
-
# Returns whether or not this association reflection is for a collection
-
# association. Returns +true+ if the +macro+ is either +has_many+ or
-
# +has_and_belongs_to_many+, +false+ otherwise.
-
2
def collection?
-
41
@collection
-
end
-
-
# Returns whether or not the association should be validated as part of
-
# the parent's validation.
-
#
-
# Unless you explicitly disable validation with
-
# <tt>validate: false</tt>, validation will take place when:
-
#
-
# * you explicitly enable validation; <tt>validate: true</tt>
-
# * you use autosave; <tt>autosave: true</tt>
-
# * the association is a +has_many+ association
-
2
def validate?
-
41
!options[:validate].nil? ? options[:validate] : (options[:autosave] == true || macro == :has_many)
-
end
-
-
# Returns +true+ if +self+ is a +belongs_to+ reflection.
-
2
def belongs_to?
-
3
macro == :belongs_to
-
end
-
-
2
def association_class
-
216
case macro
-
when :belongs_to
-
144
if options[:polymorphic]
-
144
Associations::BelongsToPolymorphicAssociation
-
else
-
Associations::BelongsToAssociation
-
end
-
when :has_many
-
72
if options[:through]
-
Associations::HasManyThroughAssociation
-
else
-
72
Associations::HasManyAssociation
-
end
-
when :has_one
-
if options[:through]
-
Associations::HasOneThroughAssociation
-
else
-
Associations::HasOneAssociation
-
end
-
end
-
end
-
-
2
def polymorphic?
-
options.key? :polymorphic
-
end
-
-
2
VALID_AUTOMATIC_INVERSE_MACROS = [:has_many, :has_one, :belongs_to]
-
2
INVALID_AUTOMATIC_INVERSE_OPTIONS = [:conditions, :through, :polymorphic, :foreign_key]
-
-
2
protected
-
-
2
def actual_source_reflection # FIXME: this is a horrible name
-
self
-
end
-
-
2
private
-
-
2
def calculate_constructable(macro, options)
-
41
case macro
-
when :belongs_to
-
12
!options[:polymorphic]
-
when :has_one
-
2
!options[:through]
-
else
-
27
true
-
end
-
end
-
-
# Attempts to find the inverse association name automatically.
-
# If it cannot find a suitable inverse association name, it returns
-
# nil.
-
2
def inverse_name
-
288
options.fetch(:inverse_of) do
-
288
if @automatic_inverse_of == false
-
287
nil
-
else
-
1
@automatic_inverse_of ||= automatic_inverse_of
-
end
-
end
-
end
-
-
# returns either nil or the inverse association name that it finds.
-
2
def automatic_inverse_of
-
1
if can_find_inverse_of_automatically?(self)
-
1
inverse_name = ActiveSupport::Inflector.underscore(options[:as] || active_record.name).to_sym
-
-
1
begin
-
1
reflection = klass._reflect_on_association(inverse_name)
-
rescue NameError
-
# Give up: we couldn't compute the klass type so we won't be able
-
# to find any associations either.
-
reflection = false
-
end
-
-
1
if valid_inverse_reflection?(reflection)
-
return inverse_name
-
end
-
end
-
-
1
false
-
end
-
-
# Checks if the inverse reflection that is returned from the
-
# +automatic_inverse_of+ method is a valid reflection. We must
-
# make sure that the reflection's active_record name matches up
-
# with the current reflection's klass name.
-
#
-
# Note: klass will always be valid because when there's a NameError
-
# from calling +klass+, +reflection+ will already be set to false.
-
2
def valid_inverse_reflection?(reflection)
-
reflection &&
-
1
klass.name == reflection.active_record.name &&
-
can_find_inverse_of_automatically?(reflection)
-
end
-
-
# Checks to see if the reflection doesn't have any options that prevent
-
# us from being able to guess the inverse automatically. First, the
-
# <tt>inverse_of</tt> option cannot be set to false. Second, we must
-
# have <tt>has_many</tt>, <tt>has_one</tt>, <tt>belongs_to</tt> associations.
-
# Third, we must not have options such as <tt>:polymorphic</tt> or
-
# <tt>:foreign_key</tt> which prevent us from correctly guessing the
-
# inverse association.
-
#
-
# Anything with a scope can additionally ruin our attempt at finding an
-
# inverse, so we exclude reflections with scopes.
-
2
def can_find_inverse_of_automatically?(reflection)
-
reflection.options[:inverse_of] != false &&
-
1
VALID_AUTOMATIC_INVERSE_MACROS.include?(reflection.macro) &&
-
4
!INVALID_AUTOMATIC_INVERSE_OPTIONS.any? { |opt| reflection.options[opt] } &&
-
!reflection.scope
-
end
-
-
2
def derive_class_name
-
class_name = name.to_s
-
class_name = class_name.singularize if collection?
-
class_name.camelize
-
end
-
-
2
def derive_foreign_key
-
3
if belongs_to?
-
2
"#{name}_id"
-
1
elsif options[:as]
-
1
"#{options[:as]}_id"
-
else
-
active_record.name.foreign_key
-
end
-
end
-
-
2
def derive_join_table
-
[active_record.table_name, klass.table_name].sort.join("\0").gsub(/^(.*_)(.+)\0\1(.+)/, '\1\2_\3').gsub("\0", "_")
-
end
-
-
2
def primary_key(klass)
-
1
klass.primary_key || raise(UnknownPrimaryKey.new(klass))
-
end
-
end
-
-
# Holds all the meta-data about a :through association as it was specified
-
# in the Active Record class.
-
2
class ThroughReflection < AssociationReflection #:nodoc:
-
2
delegate :foreign_key, :foreign_type, :association_foreign_key,
-
:active_record_primary_key, :type, :to => :source_reflection
-
-
2
def initialize(macro, name, scope, options, active_record)
-
super
-
@source_reflection_name = options[:source]
-
end
-
-
# Returns the source of the through reflection. It checks both a singularized
-
# and pluralized form for <tt>:belongs_to</tt> or <tt>:has_many</tt>.
-
#
-
# class Post < ActiveRecord::Base
-
# has_many :taggings
-
# has_many :tags, through: :taggings
-
# end
-
#
-
# class Tagging < ActiveRecord::Base
-
# belongs_to :post
-
# belongs_to :tag
-
# end
-
#
-
# tags_reflection = Post.reflect_on_association(:tags)
-
# tags_reflection.source_reflection
-
# # => <ActiveRecord::Reflection::AssociationReflection: @macro=:belongs_to, @name=:tag, @active_record=Tagging, @plural_name="tags">
-
#
-
2
def source_reflection
-
through_reflection.klass._reflect_on_association(source_reflection_name)
-
end
-
-
# Returns the AssociationReflection object specified in the <tt>:through</tt> option
-
# of a HasManyThrough or HasOneThrough association.
-
#
-
# class Post < ActiveRecord::Base
-
# has_many :taggings
-
# has_many :tags, through: :taggings
-
# end
-
#
-
# tags_reflection = Post.reflect_on_association(:tags)
-
# tags_reflection.through_reflection
-
# # => <ActiveRecord::Reflection::AssociationReflection: @macro=:has_many, @name=:taggings, @active_record=Post, @plural_name="taggings">
-
#
-
2
def through_reflection
-
active_record._reflect_on_association(options[:through])
-
end
-
-
# Returns an array of reflections which are involved in this association. Each item in the
-
# array corresponds to a table which will be part of the query for this association.
-
#
-
# The chain is built by recursively calling #chain on the source reflection and the through
-
# reflection. The base case for the recursion is a normal association, which just returns
-
# [self] as its #chain.
-
#
-
# class Post < ActiveRecord::Base
-
# has_many :taggings
-
# has_many :tags, through: :taggings
-
# end
-
#
-
# tags_reflection = Post.reflect_on_association(:tags)
-
# tags_reflection.chain
-
# # => [<ActiveRecord::Reflection::ThroughReflection: @macro=:has_many, @name=:tags, @options={:through=>:taggings}, @active_record=Post>,
-
# <ActiveRecord::Reflection::AssociationReflection: @macro=:has_many, @name=:taggings, @options={}, @active_record=Post>]
-
#
-
2
def chain
-
@chain ||= begin
-
a = source_reflection.chain
-
b = through_reflection.chain
-
chain = a + b
-
chain[0] = self # Use self so we don't lose the information from :source_type
-
chain
-
end
-
end
-
-
# Consider the following example:
-
#
-
# class Person
-
# has_many :articles
-
# has_many :comment_tags, through: :articles
-
# end
-
#
-
# class Article
-
# has_many :comments
-
# has_many :comment_tags, through: :comments, source: :tags
-
# end
-
#
-
# class Comment
-
# has_many :tags
-
# end
-
#
-
# There may be scopes on Person.comment_tags, Article.comment_tags and/or Comment.tags,
-
# but only Comment.tags will be represented in the #chain. So this method creates an array
-
# of scopes corresponding to the chain.
-
2
def scope_chain
-
@scope_chain ||= begin
-
scope_chain = source_reflection.scope_chain.map(&:dup)
-
-
# Add to it the scope from this reflection (if any)
-
scope_chain.first << scope if scope
-
-
through_scope_chain = through_reflection.scope_chain.map(&:dup)
-
-
if options[:source_type]
-
through_scope_chain.first <<
-
through_reflection.klass.where(foreign_type => options[:source_type])
-
end
-
-
# Recursively fill out the rest of the array from the through reflection
-
scope_chain + through_scope_chain
-
end
-
end
-
-
# The macro used by the source association
-
2
def source_macro
-
source_reflection.source_macro
-
end
-
-
# A through association is nested if there would be more than one join table
-
2
def nested?
-
chain.length > 2
-
end
-
-
# We want to use the klass from this reflection, rather than just delegate straight to
-
# the source_reflection, because the source_reflection may be polymorphic. We still
-
# need to respect the source_reflection's :primary_key option, though.
-
2
def association_primary_key(klass = nil)
-
# Get the "actual" source reflection if the immediate source reflection has a
-
# source reflection itself
-
actual_source_reflection.options[:primary_key] || primary_key(klass || self.klass)
-
end
-
-
# Gets an array of possible <tt>:through</tt> source reflection names in both singular and plural form.
-
#
-
# class Post < ActiveRecord::Base
-
# has_many :taggings
-
# has_many :tags, through: :taggings
-
# end
-
#
-
# tags_reflection = Post.reflect_on_association(:tags)
-
# tags_reflection.source_reflection_names
-
# # => [:tag, :tags]
-
#
-
2
def source_reflection_names
-
(options[:source] ? [options[:source]] : [name.to_s.singularize, name]).collect { |n| n.to_sym }.uniq
-
end
-
-
2
def source_reflection_name # :nodoc:
-
return @source_reflection_name.to_sym if @source_reflection_name
-
-
names = [name.to_s.singularize, name].collect { |n| n.to_sym }.uniq
-
names = names.find_all { |n|
-
through_reflection.klass._reflect_on_association(n)
-
}
-
-
if names.length > 1
-
example_options = options.dup
-
example_options[:source] = source_reflection_names.first
-
ActiveSupport::Deprecation.warn <<-eowarn
-
Ambiguous source reflection for through association. Please specify a :source
-
directive on your declaration like:
-
-
class #{active_record.name} < ActiveRecord::Base
-
#{macro} :#{name}, #{example_options}
-
end
-
-
eowarn
-
end
-
-
@source_reflection_name = names.first
-
end
-
-
2
def source_options
-
source_reflection.options
-
end
-
-
2
def through_options
-
through_reflection.options
-
end
-
-
2
def check_validity!
-
if through_reflection.nil?
-
raise HasManyThroughAssociationNotFoundError.new(active_record.name, self)
-
end
-
-
if through_reflection.options[:polymorphic]
-
raise HasManyThroughAssociationPolymorphicThroughError.new(active_record.name, self)
-
end
-
-
if source_reflection.nil?
-
raise HasManyThroughSourceAssociationNotFoundError.new(self)
-
end
-
-
if options[:source_type] && source_reflection.options[:polymorphic].nil?
-
raise HasManyThroughAssociationPointlessSourceTypeError.new(active_record.name, self, source_reflection)
-
end
-
-
if source_reflection.options[:polymorphic] && options[:source_type].nil?
-
raise HasManyThroughAssociationPolymorphicSourceError.new(active_record.name, self, source_reflection)
-
end
-
-
if macro == :has_one && through_reflection.collection?
-
raise HasOneThroughCantAssociateThroughCollection.new(active_record.name, self, through_reflection)
-
end
-
-
check_validity_of_inverse!
-
end
-
-
2
protected
-
-
2
def actual_source_reflection # FIXME: this is a horrible name
-
source_reflection.actual_source_reflection
-
end
-
-
2
private
-
2
def derive_class_name
-
# get the class_name of the belongs_to association of the through reflection
-
options[:source_type] || source_reflection.class_name
-
end
-
end
-
end
-
end
-
# -*- coding: utf-8 -*-
-
-
2
module ActiveRecord
-
# = Active Record Relation
-
2
class Relation
-
2
JoinOperation = Struct.new(:relation, :join_class, :on)
-
-
2
MULTI_VALUE_METHODS = [:includes, :eager_load, :preload, :select, :group,
-
:order, :joins, :where, :having, :bind, :references,
-
:extending, :unscope]
-
-
2
SINGLE_VALUE_METHODS = [:limit, :offset, :lock, :readonly, :from, :reordering,
-
:reverse_order, :distinct, :create_with, :uniq]
-
-
2
VALUE_METHODS = MULTI_VALUE_METHODS + SINGLE_VALUE_METHODS
-
-
2
include FinderMethods, Calculations, SpawnMethods, QueryMethods, Batches, Explain, Delegation
-
-
2
attr_reader :table, :klass, :loaded
-
2
alias :model :klass
-
2
alias :loaded? :loaded
-
-
2
def initialize(klass, table, values = {})
-
1471
@klass = klass
-
1471
@table = table
-
1471
@values = values
-
1471
@offsets = {}
-
1471
@loaded = false
-
end
-
-
2
def initialize_copy(other)
-
# This method is a hot spot, so for now, use Hash[] to dup the hash.
-
# https://bugs.ruby-lang.org/issues/7166
-
1098
@values = Hash[@values]
-
1098
@values[:bind] = @values[:bind].dup if @values.key? :bind
-
1098
reset
-
end
-
-
2
def insert(values) # :nodoc:
-
267
primary_key_value = nil
-
-
267
if primary_key && Hash === values
-
267
primary_key_value = values[values.keys.find { |k|
-
1405
k.name == primary_key
-
}]
-
-
267
if !primary_key_value && connection.prefetch_primary_key?(klass.table_name)
-
primary_key_value = connection.next_sequence_value(klass.sequence_name)
-
values[klass.arel_table[klass.primary_key]] = primary_key_value
-
end
-
end
-
-
267
im = arel.create_insert
-
267
im.into @table
-
-
267
substitutes, binds = substitute_values values
-
-
267
if values.empty? # empty insert
-
im.values = Arel.sql(connection.empty_insert_statement_value)
-
else
-
267
im.insert substitutes
-
end
-
-
267
@klass.connection.insert(
-
im,
-
'SQL',
-
primary_key,
-
primary_key_value,
-
nil,
-
binds)
-
end
-
-
2
def _update_record(values, id, id_was) # :nodoc:
-
substitutes, binds = substitute_values values
-
-
scope = @klass.unscoped
-
-
if @klass.finder_needs_type_condition?
-
scope.unscope!(where: @klass.inheritance_column)
-
end
-
-
um = scope.where(@klass.arel_table[@klass.primary_key].eq(id_was || id)).arel.compile_update(substitutes, @klass.primary_key)
-
-
@klass.connection.update(
-
um,
-
'SQL',
-
binds)
-
end
-
-
2
def substitute_values(values) # :nodoc:
-
1672
substitutes = values.sort_by { |arel_attr,_| arel_attr.name }
-
267
binds = substitutes.map do |arel_attr, value|
-
1405
[@klass.columns_hash[arel_attr.name], value]
-
end
-
-
267
substitutes.each_with_index do |tuple, i|
-
1405
tuple[1] = @klass.connection.substitute_at(binds[i][0], i)
-
end
-
-
267
[substitutes, binds]
-
end
-
-
# Initializes new record from relation while maintaining the current
-
# scope.
-
#
-
# Expects arguments in the same format as +Base.new+.
-
#
-
# users = User.where(name: 'DHH')
-
# user = users.new # => #<User id: nil, name: "DHH", created_at: nil, updated_at: nil>
-
#
-
# You can also pass a block to new with the new record as argument:
-
#
-
# user = users.new { |user| user.name = 'Oscar' }
-
# user.name # => Oscar
-
2
def new(*args, &block)
-
scoping { @klass.new(*args, &block) }
-
end
-
-
2
alias build new
-
-
# Tries to create a new record with the same scoped attributes
-
# defined in the relation. Returns the initialized object if validation fails.
-
#
-
# Expects arguments in the same format as +Base.create+.
-
#
-
# ==== Examples
-
# users = User.where(name: 'Oscar')
-
# users.create # #<User id: 3, name: "oscar", ...>
-
#
-
# users.create(name: 'fxn')
-
# users.create # #<User id: 4, name: "fxn", ...>
-
#
-
# users.create { |user| user.name = 'tenderlove' }
-
# # #<User id: 5, name: "tenderlove", ...>
-
#
-
# users.create(name: nil) # validation on name
-
# # #<User id: nil, name: nil, ...>
-
2
def create(*args, &block)
-
scoping { @klass.create(*args, &block) }
-
end
-
-
# Similar to #create, but calls +create!+ on the base class. Raises
-
# an exception if a validation error occurs.
-
#
-
# Expects arguments in the same format as <tt>Base.create!</tt>.
-
2
def create!(*args, &block)
-
scoping { @klass.create!(*args, &block) }
-
end
-
-
2
def first_or_create(attributes = nil, &block) # :nodoc:
-
first || create(attributes, &block)
-
end
-
-
2
def first_or_create!(attributes = nil, &block) # :nodoc:
-
first || create!(attributes, &block)
-
end
-
-
2
def first_or_initialize(attributes = nil, &block) # :nodoc:
-
first || new(attributes, &block)
-
end
-
-
# Finds the first record with the given attributes, or creates a record
-
# with the attributes if one is not found:
-
#
-
# # Find the first user named "Penélope" or create a new one.
-
# User.find_or_create_by(first_name: 'Penélope')
-
# # => #<User id: 1, first_name: "Penélope", last_name: nil>
-
#
-
# # Find the first user named "Penélope" or create a new one.
-
# # We already have one so the existing record will be returned.
-
# User.find_or_create_by(first_name: 'Penélope')
-
# # => #<User id: 1, first_name: "Penélope", last_name: nil>
-
#
-
# # Find the first user named "Scarlett" or create a new one with
-
# # a particular last name.
-
# User.create_with(last_name: 'Johansson').find_or_create_by(first_name: 'Scarlett')
-
# # => #<User id: 2, first_name: "Scarlett", last_name: "Johansson">
-
#
-
# This method accepts a block, which is passed down to +create+. The last example
-
# above can be alternatively written this way:
-
#
-
# # Find the first user named "Scarlett" or create a new one with a
-
# # different last name.
-
# User.find_or_create_by(first_name: 'Scarlett') do |user|
-
# user.last_name = 'Johansson'
-
# end
-
# # => #<User id: 2, first_name: "Scarlett", last_name: "Johansson">
-
#
-
# This method always returns a record, but if creation was attempted and
-
# failed due to validation errors it won't be persisted, you get what
-
# +create+ returns in such situation.
-
#
-
# Please note *this method is not atomic*, it runs first a SELECT, and if
-
# there are no results an INSERT is attempted. If there are other threads
-
# or processes there is a race condition between both calls and it could
-
# be the case that you end up with two similar records.
-
#
-
# Whether that is a problem or not depends on the logic of the
-
# application, but in the particular case in which rows have a UNIQUE
-
# constraint an exception may be raised, just retry:
-
#
-
# begin
-
# CreditAccount.find_or_create_by(user_id: user.id)
-
# rescue ActiveRecord::RecordNotUnique
-
# retry
-
# end
-
#
-
2
def find_or_create_by(attributes, &block)
-
find_by(attributes) || create(attributes, &block)
-
end
-
-
# Like <tt>find_or_create_by</tt>, but calls <tt>create!</tt> so an exception
-
# is raised if the created record is invalid.
-
2
def find_or_create_by!(attributes, &block)
-
find_by(attributes) || create!(attributes, &block)
-
end
-
-
# Like <tt>find_or_create_by</tt>, but calls <tt>new</tt> instead of <tt>create</tt>.
-
2
def find_or_initialize_by(attributes, &block)
-
find_by(attributes) || new(attributes, &block)
-
end
-
-
# Runs EXPLAIN on the query or queries triggered by this relation and
-
# returns the result as a string. The string is formatted imitating the
-
# ones printed by the database shell.
-
#
-
# Note that this method actually runs the queries, since the results of some
-
# are needed by the next ones when eager loading is going on.
-
#
-
# Please see further details in the
-
# {Active Record Query Interface guide}[http://guides.rubyonrails.org/active_record_querying.html#running-explain].
-
2
def explain
-
exec_explain(collecting_queries_for_explain { exec_queries })
-
end
-
-
# Converts relation objects to Array.
-
2
def to_a
-
16
load
-
16
@records
-
end
-
-
2
def as_json(options = nil) #:nodoc:
-
to_a.as_json(options)
-
end
-
-
# Returns size of the records.
-
2
def size
-
loaded? ? @records.length : count(:all)
-
end
-
-
# Returns true if there are no records.
-
2
def empty?
-
return @records.empty? if loaded?
-
-
if limit_value == 0
-
true
-
else
-
c = count(:all)
-
c.respond_to?(:zero?) ? c.zero? : c.empty?
-
end
-
end
-
-
# Returns true if there are any records.
-
2
def any?
-
if block_given?
-
to_a.any? { |*block_args| yield(*block_args) }
-
else
-
!empty?
-
end
-
end
-
-
# Returns true if there is more than one record.
-
2
def many?
-
if block_given?
-
to_a.many? { |*block_args| yield(*block_args) }
-
else
-
limit_value ? to_a.many? : size > 1
-
end
-
end
-
-
# Scope all queries to the current scope.
-
#
-
# Comment.where(post_id: 1).scoping do
-
# Comment.first
-
# end
-
# # => SELECT "comments".* FROM "comments" WHERE "comments"."post_id" = 1 ORDER BY "comments"."id" ASC LIMIT 1
-
#
-
# Please check unscoped if you want to remove all previous scopes (including
-
# the default_scope) during the execution of a block.
-
2
def scoping
-
195
previous, klass.current_scope = klass.current_scope, self
-
195
yield
-
ensure
-
195
klass.current_scope = previous
-
end
-
-
# Updates all records with details given if they match a set of conditions supplied, limits and order can
-
# also be supplied. This method constructs a single SQL UPDATE statement and sends it straight to the
-
# database. It does not instantiate the involved models and it does not trigger Active Record callbacks
-
# or validations.
-
#
-
# ==== Parameters
-
#
-
# * +updates+ - A string, array, or hash representing the SET part of an SQL statement.
-
#
-
# ==== Examples
-
#
-
# # Update all customers with the given attributes
-
# Customer.update_all wants_email: true
-
#
-
# # Update all books with 'Rails' in their title
-
# Book.where('title LIKE ?', '%Rails%').update_all(author: 'David')
-
#
-
# # Update all books that match conditions, but limit it to 5 ordered by date
-
# Book.where('title LIKE ?', '%Rails%').order(:created_at).limit(5).update_all(author: 'David')
-
2
def update_all(updates)
-
raise ArgumentError, "Empty list of attributes to change" if updates.blank?
-
-
stmt = Arel::UpdateManager.new(arel.engine)
-
-
stmt.set Arel.sql(@klass.send(:sanitize_sql_for_assignment, updates))
-
stmt.table(table)
-
stmt.key = table[primary_key]
-
-
if joins_values.any?
-
@klass.connection.join_to_update(stmt, arel)
-
else
-
stmt.take(arel.limit)
-
stmt.order(*arel.orders)
-
stmt.wheres = arel.constraints
-
end
-
-
@klass.connection.update stmt, 'SQL', bind_values
-
end
-
-
# Updates an object (or multiple objects) and saves it to the database, if validations pass.
-
# The resulting object is returned whether the object was saved successfully to the database or not.
-
#
-
# ==== Parameters
-
#
-
# * +id+ - This should be the id or an array of ids to be updated.
-
# * +attributes+ - This should be a hash of attributes or an array of hashes.
-
#
-
# ==== Examples
-
#
-
# # Updates one record
-
# Person.update(15, user_name: 'Samuel', group: 'expert')
-
#
-
# # Updates multiple records
-
# people = { 1 => { "first_name" => "David" }, 2 => { "first_name" => "Jeremy" } }
-
# Person.update(people.keys, people.values)
-
2
def update(id, attributes)
-
if id.is_a?(Array)
-
id.map.with_index { |one_id, idx| update(one_id, attributes[idx]) }
-
else
-
object = find(id)
-
object.update(attributes)
-
object
-
end
-
end
-
-
# Destroys the records matching +conditions+ by instantiating each
-
# record and calling its +destroy+ method. Each object's callbacks are
-
# executed (including <tt>:dependent</tt> association options). Returns the
-
# collection of objects that were destroyed; each will be frozen, to
-
# reflect that no changes should be made (since they can't be persisted).
-
#
-
# Note: Instantiation, callback execution, and deletion of each
-
# record can be time consuming when you're removing many records at
-
# once. It generates at least one SQL +DELETE+ query per record (or
-
# possibly more, to enforce your callbacks). If you want to delete many
-
# rows quickly, without concern for their associations or callbacks, use
-
# +delete_all+ instead.
-
#
-
# ==== Parameters
-
#
-
# * +conditions+ - A string, array, or hash that specifies which records
-
# to destroy. If omitted, all records are destroyed. See the
-
# Conditions section in the introduction to ActiveRecord::Base for
-
# more information.
-
#
-
# ==== Examples
-
#
-
# Person.destroy_all("last_login < '2004-04-04'")
-
# Person.destroy_all(status: "inactive")
-
# Person.where(age: 0..18).destroy_all
-
2
def destroy_all(conditions = nil)
-
if conditions
-
where(conditions).destroy_all
-
else
-
to_a.each {|object| object.destroy }.tap { reset }
-
end
-
end
-
-
# Destroy an object (or multiple objects) that has the given id. The object is instantiated first,
-
# therefore all callbacks and filters are fired off before the object is deleted. This method is
-
# less efficient than ActiveRecord#delete but allows cleanup methods and other actions to be run.
-
#
-
# This essentially finds the object (or multiple objects) with the given id, creates a new object
-
# from the attributes, and then calls destroy on it.
-
#
-
# ==== Parameters
-
#
-
# * +id+ - Can be either an Integer or an Array of Integers.
-
#
-
# ==== Examples
-
#
-
# # Destroy a single object
-
# Todo.destroy(1)
-
#
-
# # Destroy multiple objects
-
# todos = [1,2,3]
-
# Todo.destroy(todos)
-
2
def destroy(id)
-
if id.is_a?(Array)
-
id.map { |one_id| destroy(one_id) }
-
else
-
find(id).destroy
-
end
-
end
-
-
# Deletes the records matching +conditions+ without instantiating the records
-
# first, and hence not calling the +destroy+ method nor invoking callbacks. This
-
# is a single SQL DELETE statement that goes straight to the database, much more
-
# efficient than +destroy_all+. Be careful with relations though, in particular
-
# <tt>:dependent</tt> rules defined on associations are not honored. Returns the
-
# number of rows affected.
-
#
-
# Post.delete_all("person_id = 5 AND (category = 'Something' OR category = 'Else')")
-
# Post.delete_all(["person_id = ? AND (category = ? OR category = ?)", 5, 'Something', 'Else'])
-
# Post.where(person_id: 5).where(category: ['Something', 'Else']).delete_all
-
#
-
# Both calls delete the affected posts all at once with a single DELETE statement.
-
# If you need to destroy dependent associations or call your <tt>before_*</tt> or
-
# +after_destroy+ callbacks, use the +destroy_all+ method instead.
-
#
-
# If a limit scope is supplied, +delete_all+ raises an ActiveRecord error:
-
#
-
# Post.limit(100).delete_all
-
# # => ActiveRecord::ActiveRecordError: delete_all doesn't support limit scope
-
2
def delete_all(conditions = nil)
-
raise ActiveRecordError.new("delete_all doesn't support limit scope") if self.limit_value
-
-
if conditions
-
where(conditions).delete_all
-
else
-
stmt = Arel::DeleteManager.new(arel.engine)
-
stmt.from(table)
-
-
if joins_values.any?
-
@klass.connection.join_to_delete(stmt, arel, table[primary_key])
-
else
-
stmt.wheres = arel.constraints
-
end
-
-
affected = @klass.connection.delete(stmt, 'SQL', bind_values)
-
-
reset
-
affected
-
end
-
end
-
-
# Deletes the row with a primary key matching the +id+ argument, using a
-
# SQL +DELETE+ statement, and returns the number of rows deleted. Active
-
# Record objects are not instantiated, so the object's callbacks are not
-
# executed, including any <tt>:dependent</tt> association options.
-
#
-
# You can delete multiple rows at once by passing an Array of <tt>id</tt>s.
-
#
-
# Note: Although it is often much faster than the alternative,
-
# <tt>#destroy</tt>, skipping callbacks might bypass business logic in
-
# your application that ensures referential integrity or performs other
-
# essential jobs.
-
#
-
# ==== Examples
-
#
-
# # Delete a single row
-
# Todo.delete(1)
-
#
-
# # Delete multiple rows
-
# Todo.delete([2,3,4])
-
2
def delete(id_or_array)
-
where(primary_key => id_or_array).delete_all
-
end
-
-
# Causes the records to be loaded from the database if they have not
-
# been loaded already. You can use this if for some reason you need
-
# to explicitly load some records before actually using them. The
-
# return value is the relation itself, not the records.
-
#
-
# Post.where(published: true).load # => #<ActiveRecord::Relation>
-
2
def load
-
16
exec_queries unless loaded?
-
-
16
self
-
end
-
-
# Forces reloading of relation.
-
2
def reload
-
reset
-
load
-
end
-
-
2
def reset
-
1098
@last = @to_sql = @order_clause = @scope_for_create = @arel = @loaded = nil
-
1098
@should_eager_load = @join_dependency = nil
-
1098
@records = []
-
1098
@offsets = {}
-
1098
self
-
end
-
-
# Returns sql statement for the relation.
-
#
-
# User.where(name: 'Oscar').to_sql
-
# # => SELECT "users".* FROM "users" WHERE "users"."name" = 'Oscar'
-
2
def to_sql
-
@to_sql ||= begin
-
relation = self
-
connection = klass.connection
-
visitor = connection.visitor
-
-
if eager_loading?
-
find_with_associations { |rel| relation = rel }
-
end
-
-
ast = relation.arel.ast
-
binds = relation.bind_values.dup
-
visitor.accept(ast) do
-
connection.quote(*binds.shift.reverse)
-
end
-
end
-
end
-
-
# Returns a hash of where conditions.
-
#
-
# User.where(name: 'Oscar').where_values_hash
-
# # => {name: "Oscar"}
-
2
def where_values_hash(relation_table_name = table_name)
-
72
equalities = where_values.grep(Arel::Nodes::Equality).find_all { |node|
-
144
node.left.relation.name == relation_table_name
-
}
-
-
216
binds = Hash[bind_values.find_all(&:first).map { |column, v| [column.name, v] }]
-
-
72
Hash[equalities.map { |where|
-
144
name = where.left.name
-
144
[name, binds.fetch(name.to_s) { where.right }]
-
}]
-
end
-
-
2
def scope_for_create
-
72
@scope_for_create ||= where_values_hash.merge(create_with_value)
-
end
-
-
# Returns true if relation needs eager loading.
-
2
def eager_loading?
-
@should_eager_load ||=
-
eager_load_values.any? ||
-
32
includes_values.any? && (joined_includes_values.any? || references_eager_loaded_tables?)
-
end
-
-
# Joins that are also marked for preloading. In which case we should just eager load them.
-
# Note that this is a naive implementation because we could have strings and symbols which
-
# represent the same association, but that aren't matched by this. Also, we could have
-
# nested hashes which partially match, e.g. { a: :b } & { a: [:b, :c] }
-
2
def joined_includes_values
-
includes_values & joins_values
-
end
-
-
# +uniq+ and +uniq!+ are silently deprecated. +uniq_value+ delegates to +distinct_value+
-
# to maintain backwards compatibility. Use +distinct_value+ instead.
-
2
def uniq_value
-
distinct_value
-
end
-
-
# Compares two relations for equality.
-
2
def ==(other)
-
case other
-
when Associations::CollectionProxy, AssociationRelation
-
self == other.to_a
-
when Relation
-
other.to_sql == to_sql
-
when Array
-
to_a == other
-
end
-
end
-
-
2
def pretty_print(q)
-
q.pp(self.to_a)
-
end
-
-
# Returns true if relation is blank.
-
2
def blank?
-
to_a.blank?
-
end
-
-
2
def values
-
750
Hash[@values]
-
end
-
-
2
def inspect
-
entries = to_a.take([limit_value, 11].compact.min).map!(&:inspect)
-
entries[10] = '...' if entries.size == 11
-
-
"#<#{self.class.name} [#{entries.join(', ')}]>"
-
end
-
-
2
private
-
-
2
def exec_queries
-
16
@records = eager_loading? ? find_with_associations : @klass.find_by_sql(arel, bind_values)
-
-
16
preload = preload_values
-
16
preload += includes_values unless eager_loading?
-
16
preloader = ActiveRecord::Associations::Preloader.new
-
16
preload.each do |associations|
-
preloader.preload @records, associations
-
end
-
-
16
@records.each { |record| record.readonly! } if readonly_value
-
-
16
@loaded = true
-
16
@records
-
end
-
-
2
def references_eager_loaded_tables?
-
joined_tables = arel.join_sources.map do |join|
-
if join.is_a?(Arel::Nodes::StringJoin)
-
tables_in_string(join.left)
-
else
-
[join.left.table_name, join.left.table_alias]
-
end
-
end
-
-
joined_tables += [table.name, table.table_alias]
-
-
# always convert table names to downcase as in Oracle quoted table names are in uppercase
-
joined_tables = joined_tables.flatten.compact.map { |t| t.downcase }.uniq
-
-
(references_values - joined_tables).any?
-
end
-
-
2
def tables_in_string(string)
-
return [] if string.blank?
-
# always convert table names to downcase as in Oracle quoted table names are in uppercase
-
# ignore raw_sql_ that is used by Oracle adapter as alias for limit/offset subqueries
-
string.scan(/([a-zA-Z_][.\w]+).?\./).flatten.map{ |s| s.downcase }.uniq - ['raw_sql_']
-
end
-
end
-
end
-
-
2
module ActiveRecord
-
2
module Batches
-
# Looping through a collection of records from the database
-
# (using the +all+ method, for example) is very inefficient
-
# since it will try to instantiate all the objects at once.
-
#
-
# In that case, batch processing methods allow you to work
-
# with the records in batches, thereby greatly reducing memory consumption.
-
#
-
# The #find_each method uses #find_in_batches with a batch size of 1000 (or as
-
# specified by the +:batch_size+ option).
-
#
-
# Person.find_each do |person|
-
# person.do_awesome_stuff
-
# end
-
#
-
# Person.where("age > 21").find_each do |person|
-
# person.party_all_night!
-
# end
-
#
-
# If you do not provide a block to #find_each, it will return an Enumerator
-
# for chaining with other methods:
-
#
-
# Person.find_each.with_index do |person, index|
-
# person.award_trophy(index + 1)
-
# end
-
#
-
# ==== Options
-
# * <tt>:batch_size</tt> - Specifies the size of the batch. Default to 1000.
-
# * <tt>:start</tt> - Specifies the starting point for the batch processing.
-
# This is especially useful if you want multiple workers dealing with
-
# the same processing queue. You can make worker 1 handle all the records
-
# between id 0 and 10,000 and worker 2 handle from 10,000 and beyond
-
# (by setting the +:start+ option on that worker).
-
#
-
# # Let's process for a batch of 2000 records, skipping the first 2000 rows
-
# Person.find_each(start: 2000, batch_size: 2000) do |person|
-
# person.party_all_night!
-
# end
-
#
-
# NOTE: It's not possible to set the order. That is automatically set to
-
# ascending on the primary key ("id ASC") to make the batch ordering
-
# work. This also means that this method only works with integer-based
-
# primary keys.
-
#
-
# NOTE: You can't set the limit either, that's used to control
-
# the batch sizes.
-
2
def find_each(options = {})
-
if block_given?
-
find_in_batches(options) do |records|
-
records.each { |record| yield record }
-
end
-
else
-
enum_for :find_each, options do
-
options[:start] ? where(table[primary_key].gteq(options[:start])).size : size
-
end
-
end
-
end
-
-
# Yields each batch of records that was found by the find +options+ as
-
# an array.
-
#
-
# Person.where("age > 21").find_in_batches do |group|
-
# sleep(50) # Make sure it doesn't get too crowded in there!
-
# group.each { |person| person.party_all_night! }
-
# end
-
#
-
# If you do not provide a block to #find_in_batches, it will return an Enumerator
-
# for chaining with other methods:
-
#
-
# Person.find_in_batches.with_index do |group, batch|
-
# puts "Processing group ##{batch}"
-
# group.each(&:recover_from_last_night!)
-
# end
-
#
-
# To be yielded each record one by one, use #find_each instead.
-
#
-
# ==== Options
-
# * <tt>:batch_size</tt> - Specifies the size of the batch. Default to 1000.
-
# * <tt>:start</tt> - Specifies the starting point for the batch processing.
-
# This is especially useful if you want multiple workers dealing with
-
# the same processing queue. You can make worker 1 handle all the records
-
# between id 0 and 10,000 and worker 2 handle from 10,000 and beyond
-
# (by setting the +:start+ option on that worker).
-
#
-
# # Let's process the next 2000 records
-
# Person.find_in_batches(start: 2000, batch_size: 2000) do |group|
-
# group.each { |person| person.party_all_night! }
-
# end
-
#
-
# NOTE: It's not possible to set the order. That is automatically set to
-
# ascending on the primary key ("id ASC") to make the batch ordering
-
# work. This also means that this method only works with integer-based
-
# primary keys.
-
#
-
# NOTE: You can't set the limit either, that's used to control
-
# the batch sizes.
-
2
def find_in_batches(options = {})
-
options.assert_valid_keys(:start, :batch_size)
-
-
relation = self
-
start = options[:start]
-
batch_size = options[:batch_size] || 1000
-
-
unless block_given?
-
return to_enum(:find_in_batches, options) do
-
total = start ? where(table[primary_key].gteq(start)).size : size
-
(total - 1).div(batch_size) + 1
-
end
-
end
-
-
if logger && (arel.orders.present? || arel.taken.present?)
-
logger.warn("Scoped order and limit are ignored, it's forced to be batch order and batch size")
-
end
-
-
relation = relation.reorder(batch_order).limit(batch_size)
-
records = start ? relation.where(table[primary_key].gteq(start)).to_a : relation.to_a
-
-
while records.any?
-
records_size = records.size
-
primary_key_offset = records.last.id
-
raise "Primary key not included in the custom select clause" unless primary_key_offset
-
-
yield records
-
-
break if records_size < batch_size
-
-
records = relation.where(table[primary_key].gt(primary_key_offset)).to_a
-
end
-
end
-
-
2
private
-
-
2
def batch_order
-
"#{quoted_table_name}.#{quoted_primary_key} ASC"
-
end
-
end
-
end
-
2
module ActiveRecord
-
2
module Calculations
-
# Count the records.
-
#
-
# Person.count
-
# # => the total count of all people
-
#
-
# Person.count(:age)
-
# # => returns the total count of all people whose age is present in database
-
#
-
# Person.count(:all)
-
# # => performs a COUNT(*) (:all is an alias for '*')
-
#
-
# Person.distinct.count(:age)
-
# # => counts the number of different age values
-
#
-
# If +count+ is used with +group+, it returns a Hash whose keys represent the aggregated column,
-
# and the values are the respective amounts:
-
#
-
# Person.group(:city).count
-
# # => { 'Rome' => 5, 'Paris' => 3 }
-
#
-
# If +count+ is used with +select+, it will count the selected columns:
-
#
-
# Person.select(:age).count
-
# # => counts the number of different age values
-
#
-
# Note: not all valid +select+ expressions are valid +count+ expressions. The specifics differ
-
# between databases. In invalid cases, an error from the databsae is thrown.
-
2
def count(column_name = nil, options = {})
-
# TODO: Remove options argument as soon we remove support to
-
# activerecord-deprecated_finders.
-
column_name, options = nil, column_name if column_name.is_a?(Hash)
-
calculate(:count, column_name, options)
-
end
-
-
# Calculates the average value on a given column. Returns +nil+ if there's
-
# no row. See +calculate+ for examples with options.
-
#
-
# Person.average(:age) # => 35.8
-
2
def average(column_name, options = {})
-
# TODO: Remove options argument as soon we remove support to
-
# activerecord-deprecated_finders.
-
calculate(:average, column_name, options)
-
end
-
-
# Calculates the minimum value on a given column. The value is returned
-
# with the same data type of the column, or +nil+ if there's no row. See
-
# +calculate+ for examples with options.
-
#
-
# Person.minimum(:age) # => 7
-
2
def minimum(column_name, options = {})
-
# TODO: Remove options argument as soon we remove support to
-
# activerecord-deprecated_finders.
-
calculate(:minimum, column_name, options)
-
end
-
-
# Calculates the maximum value on a given column. The value is returned
-
# with the same data type of the column, or +nil+ if there's no row. See
-
# +calculate+ for examples with options.
-
#
-
# Person.maximum(:age) # => 93
-
2
def maximum(column_name, options = {})
-
# TODO: Remove options argument as soon we remove support to
-
# activerecord-deprecated_finders.
-
calculate(:maximum, column_name, options)
-
end
-
-
# Calculates the sum of values on a given column. The value is returned
-
# with the same data type of the column, 0 if there's no row. See
-
# +calculate+ for examples with options.
-
#
-
# Person.sum(:age) # => 4562
-
2
def sum(*args)
-
calculate(:sum, *args)
-
end
-
-
# This calculates aggregate values in the given column. Methods for count, sum, average,
-
# minimum, and maximum have been added as shortcuts.
-
#
-
# There are two basic forms of output:
-
#
-
# * Single aggregate value: The single value is type cast to Fixnum for COUNT, Float
-
# for AVG, and the given column's type for everything else.
-
#
-
# * Grouped values: This returns an ordered hash of the values and groups them. It
-
# takes either a column name, or the name of a belongs_to association.
-
#
-
# values = Person.group('last_name').maximum(:age)
-
# puts values["Drake"]
-
# # => 43
-
#
-
# drake = Family.find_by(last_name: 'Drake')
-
# values = Person.group(:family).maximum(:age) # Person belongs_to :family
-
# puts values[drake]
-
# # => 43
-
#
-
# values.each do |family, max_age|
-
# ...
-
# end
-
#
-
# Person.calculate(:count, :all) # The same as Person.count
-
# Person.average(:age) # SELECT AVG(age) FROM people...
-
#
-
# # Selects the minimum age for any family without any minors
-
# Person.group(:last_name).having("min(age) > 17").minimum(:age)
-
#
-
# Person.sum("2 * age")
-
2
def calculate(operation, column_name, options = {})
-
# TODO: Remove options argument as soon we remove support to
-
# activerecord-deprecated_finders.
-
if column_name.is_a?(Symbol) && attribute_alias?(column_name)
-
column_name = attribute_alias(column_name)
-
end
-
-
if has_include?(column_name)
-
construct_relation_for_association_calculations.calculate(operation, column_name, options)
-
else
-
perform_calculation(operation, column_name, options)
-
end
-
end
-
-
# Use <tt>pluck</tt> as a shortcut to select one or more attributes without
-
# loading a bunch of records just to grab the attributes you want.
-
#
-
# Person.pluck(:name)
-
#
-
# instead of
-
#
-
# Person.all.map(&:name)
-
#
-
# Pluck returns an <tt>Array</tt> of attribute values type-casted to match
-
# the plucked column names, if they can be deduced. Plucking an SQL fragment
-
# returns String values by default.
-
#
-
# Person.pluck(:id)
-
# # SELECT people.id FROM people
-
# # => [1, 2, 3]
-
#
-
# Person.pluck(:id, :name)
-
# # SELECT people.id, people.name FROM people
-
# # => [[1, 'David'], [2, 'Jeremy'], [3, 'Jose']]
-
#
-
# Person.pluck('DISTINCT role')
-
# # SELECT DISTINCT role FROM people
-
# # => ['admin', 'member', 'guest']
-
#
-
# Person.where(age: 21).limit(5).pluck(:id)
-
# # SELECT people.id FROM people WHERE people.age = 21 LIMIT 5
-
# # => [2, 3]
-
#
-
# Person.pluck('DATEDIFF(updated_at, created_at)')
-
# # SELECT DATEDIFF(updated_at, created_at) FROM people
-
# # => ['0', '27761', '173']
-
#
-
2
def pluck(*column_names)
-
column_names.map! do |column_name|
-
if column_name.is_a?(Symbol) && attribute_alias?(column_name)
-
attribute_alias(column_name)
-
else
-
column_name.to_s
-
end
-
end
-
-
if has_include?(column_names.first)
-
construct_relation_for_association_calculations.pluck(*column_names)
-
else
-
relation = spawn
-
relation.select_values = column_names.map { |cn|
-
columns_hash.key?(cn) ? arel_table[cn] : cn
-
}
-
result = klass.connection.select_all(relation.arel, nil, bind_values)
-
columns = result.columns.map do |key|
-
klass.column_types.fetch(key) {
-
result.column_types.fetch(key) { result.identity_type }
-
}
-
end
-
-
result = result.rows.map do |values|
-
values = result.columns.zip(values).map do |column_name, value|
-
single_attr_hash = { column_name => value }
-
klass.initialize_attributes(single_attr_hash).values.first
-
end
-
-
columns.zip(values).map { |column, value| column.type_cast value }
-
end
-
columns.one? ? result.map!(&:first) : result
-
end
-
end
-
-
# Pluck all the ID's for the relation using the table's primary key
-
#
-
# Person.ids # SELECT people.id FROM people
-
# Person.joins(:companies).ids # SELECT people.id FROM people INNER JOIN companies ON companies.person_id = people.id
-
2
def ids
-
pluck primary_key
-
end
-
-
2
private
-
-
2
def has_include?(column_name)
-
eager_loading? || (includes_values.present? && ((column_name && column_name != :all) || references_eager_loaded_tables?))
-
end
-
-
2
def perform_calculation(operation, column_name, options = {})
-
# TODO: Remove options argument as soon we remove support to
-
# activerecord-deprecated_finders.
-
operation = operation.to_s.downcase
-
-
# If #count is used with #distinct / #uniq it is considered distinct. (eg. relation.distinct.count)
-
distinct = self.distinct_value
-
-
if operation == "count"
-
column_name ||= select_for_count
-
-
unless arel.ast.grep(Arel::Nodes::OuterJoin).empty?
-
distinct = true
-
end
-
-
column_name = primary_key if column_name == :all && distinct
-
distinct = nil if column_name =~ /\s*DISTINCT[\s(]+/i
-
end
-
-
if group_values.any?
-
execute_grouped_calculation(operation, column_name, distinct)
-
else
-
execute_simple_calculation(operation, column_name, distinct)
-
end
-
end
-
-
2
def aggregate_column(column_name)
-
if @klass.column_names.include?(column_name.to_s)
-
Arel::Attribute.new(@klass.unscoped.table, column_name)
-
else
-
Arel.sql(column_name == :all ? "*" : column_name.to_s)
-
end
-
end
-
-
2
def operation_over_aggregate_column(column, operation, distinct)
-
operation == 'count' ? column.count(distinct) : column.send(operation)
-
end
-
-
2
def execute_simple_calculation(operation, column_name, distinct) #:nodoc:
-
# Postgresql doesn't like ORDER BY when there are no GROUP BY
-
relation = unscope(:order)
-
-
column_alias = column_name
-
-
if operation == "count" && (relation.limit_value || relation.offset_value)
-
# Shortcut when limit is zero.
-
return 0 if relation.limit_value == 0
-
-
query_builder = build_count_subquery(relation, column_name, distinct)
-
else
-
column = aggregate_column(column_name)
-
-
select_value = operation_over_aggregate_column(column, operation, distinct)
-
-
column_alias = select_value.alias
-
relation.select_values = [select_value]
-
-
query_builder = relation.arel
-
end
-
-
result = @klass.connection.select_all(query_builder, nil, relation.bind_values)
-
row = result.first
-
value = row && row.values.first
-
column = result.column_types.fetch(column_alias) do
-
column_for(column_name)
-
end
-
-
type_cast_calculated_value(value, column, operation)
-
end
-
-
2
def execute_grouped_calculation(operation, column_name, distinct) #:nodoc:
-
group_attrs = group_values
-
-
if group_attrs.first.respond_to?(:to_sym)
-
association = @klass._reflect_on_association(group_attrs.first.to_sym)
-
associated = group_attrs.size == 1 && association && association.macro == :belongs_to # only count belongs_to associations
-
group_fields = Array(associated ? association.foreign_key : group_attrs)
-
else
-
group_fields = group_attrs
-
end
-
-
group_aliases = group_fields.map { |field|
-
column_alias_for(field)
-
}
-
group_columns = group_aliases.zip(group_fields).map { |aliaz,field|
-
[aliaz, field]
-
}
-
-
group = group_fields
-
-
if operation == 'count' && column_name == :all
-
aggregate_alias = 'count_all'
-
else
-
aggregate_alias = column_alias_for([operation, column_name].join(' '))
-
end
-
-
select_values = [
-
operation_over_aggregate_column(
-
aggregate_column(column_name),
-
operation,
-
distinct).as(aggregate_alias)
-
]
-
select_values += select_values unless having_values.empty?
-
-
select_values.concat group_fields.zip(group_aliases).map { |field,aliaz|
-
if field.respond_to?(:as)
-
field.as(aliaz)
-
else
-
"#{field} AS #{aliaz}"
-
end
-
}
-
-
relation = except(:group)
-
relation.group_values = group
-
relation.select_values = select_values
-
-
calculated_data = @klass.connection.select_all(relation, nil, bind_values)
-
-
if association
-
key_ids = calculated_data.collect { |row| row[group_aliases.first] }
-
key_records = association.klass.base_class.find(key_ids)
-
key_records = Hash[key_records.map { |r| [r.id, r] }]
-
end
-
-
Hash[calculated_data.map do |row|
-
key = group_columns.map { |aliaz, col_name|
-
column = calculated_data.column_types.fetch(aliaz) do
-
column_for(col_name)
-
end
-
type_cast_calculated_value(row[aliaz], column)
-
}
-
key = key.first if key.size == 1
-
key = key_records[key] if associated
-
-
column_type = calculated_data.column_types.fetch(aggregate_alias) { column_for(column_name) }
-
[key, type_cast_calculated_value(row[aggregate_alias], column_type, operation)]
-
end]
-
end
-
-
# Converts the given keys to the value that the database adapter returns as
-
# a usable column name:
-
#
-
# column_alias_for("users.id") # => "users_id"
-
# column_alias_for("sum(id)") # => "sum_id"
-
# column_alias_for("count(distinct users.id)") # => "count_distinct_users_id"
-
# column_alias_for("count(*)") # => "count_all"
-
# column_alias_for("count", "id") # => "count_id"
-
2
def column_alias_for(keys)
-
if keys.respond_to? :name
-
keys = "#{keys.relation.name}.#{keys.name}"
-
end
-
-
table_name = keys.to_s.downcase
-
table_name.gsub!(/\*/, 'all')
-
table_name.gsub!(/\W+/, ' ')
-
table_name.strip!
-
table_name.gsub!(/ +/, '_')
-
-
@klass.connection.table_alias_for(table_name)
-
end
-
-
2
def column_for(field)
-
field_name = field.respond_to?(:name) ? field.name.to_s : field.to_s.split('.').last
-
@klass.columns_hash[field_name]
-
end
-
-
2
def type_cast_calculated_value(value, column, operation = nil)
-
case operation
-
when 'count' then value.to_i
-
when 'sum' then type_cast_using_column(value || 0, column)
-
when 'average' then value.respond_to?(:to_d) ? value.to_d : value
-
else type_cast_using_column(value, column)
-
end
-
end
-
-
2
def type_cast_using_column(value, column)
-
column ? column.type_cast(value) : value
-
end
-
-
# TODO: refactor to allow non-string `select_values` (eg. Arel nodes).
-
2
def select_for_count
-
if select_values.present?
-
select_values.join(", ")
-
else
-
:all
-
end
-
end
-
-
2
def build_count_subquery(relation, column_name, distinct)
-
column_alias = Arel.sql('count_column')
-
subquery_alias = Arel.sql('subquery_for_count')
-
-
aliased_column = aggregate_column(column_name == :all ? 1 : column_name).as(column_alias)
-
relation.select_values = [aliased_column]
-
subquery = relation.arel.as(subquery_alias)
-
-
sm = Arel::SelectManager.new relation.engine
-
select_value = operation_over_aggregate_column(column_alias, 'count', distinct)
-
sm.project(select_value).from(subquery)
-
end
-
end
-
end
-
2
require 'set'
-
2
require 'active_support/concern'
-
2
require 'active_support/deprecation'
-
-
2
module ActiveRecord
-
2
module Delegation # :nodoc:
-
2
module DelegateCache
-
2
def relation_delegate_class(klass) # :nodoc:
-
1471
@relation_delegate_cache[klass]
-
end
-
-
2
def initialize_relation_delegate_cache # :nodoc:
-
13
@relation_delegate_cache = cache = {}
-
[
-
ActiveRecord::Relation,
-
ActiveRecord::Associations::CollectionProxy,
-
ActiveRecord::AssociationRelation
-
13
].each do |klass|
-
39
delegate = Class.new(klass) {
-
39
include ClassSpecificRelation
-
}
-
39
const_set klass.name.gsub('::', '_'), delegate
-
39
cache[klass] = delegate
-
end
-
end
-
-
2
def inherited(child_class)
-
13
child_class.initialize_relation_delegate_cache
-
13
super
-
end
-
end
-
-
2
extend ActiveSupport::Concern
-
-
# This module creates compiled delegation methods dynamically at runtime, which makes
-
# subsequent calls to that method faster by avoiding method_missing. The delegations
-
# may vary depending on the klass of a relation, so we create a subclass of Relation
-
# for each different klass, and the delegations are compiled into that subclass only.
-
-
2
BLACKLISTED_ARRAY_METHODS = [
-
:compact!, :flatten!, :reject!, :reverse!, :rotate!, :map!,
-
:shuffle!, :slice!, :sort!, :sort_by!, :delete_if,
-
:keep_if, :pop, :shift, :delete_at, :compact, :select!
-
].to_set # :nodoc:
-
-
2
delegate :to_xml, :to_yaml, :length, :collect, :map, :each, :all?, :include?, :to_ary, :join, to: :to_a
-
-
2
delegate :table_name, :quoted_table_name, :primary_key, :quoted_primary_key,
-
:connection, :columns_hash, :to => :klass
-
-
2
module ClassSpecificRelation # :nodoc:
-
2
extend ActiveSupport::Concern
-
-
2
included do
-
39
@delegation_mutex = Mutex.new
-
end
-
-
2
module ClassMethods # :nodoc:
-
2
def name
-
superclass.name
-
end
-
-
2
def delegate_to_scoped_klass(method)
-
3
@delegation_mutex.synchronize do
-
3
return if method_defined?(method)
-
-
3
if method.to_s =~ /\A[a-zA-Z_]\w*[!?]?\z/
-
3
module_eval <<-RUBY, __FILE__, __LINE__ + 1
-
def #{method}(*args, &block)
-
scoping { @klass.#{method}(*args, &block) }
-
end
-
RUBY
-
else
-
define_method method do |*args, &block|
-
scoping { @klass.public_send(method, *args, &block) }
-
end
-
end
-
end
-
end
-
-
2
def delegate(method, opts = {})
-
2
@delegation_mutex.synchronize do
-
2
return if method_defined?(method)
-
2
super
-
end
-
end
-
end
-
-
2
protected
-
-
2
def method_missing(method, *args, &block)
-
5
if @klass.respond_to?(method)
-
3
self.class.delegate_to_scoped_klass(method)
-
6
scoping { @klass.public_send(method, *args, &block) }
-
2
elsif arel.respond_to?(method)
-
2
self.class.delegate method, :to => :arel
-
2
arel.public_send(method, *args, &block)
-
else
-
super
-
end
-
end
-
end
-
-
2
module ClassMethods # :nodoc:
-
2
def create(klass, *args)
-
1471
relation_class_for(klass).new(klass, *args)
-
end
-
-
2
private
-
-
2
def relation_class_for(klass)
-
1471
klass.relation_delegate_class(self)
-
end
-
end
-
-
2
def respond_to?(method, include_private = false)
-
2
super || @klass.respond_to?(method, include_private) ||
-
array_delegable?(method) ||
-
arel.respond_to?(method, include_private)
-
end
-
-
2
protected
-
-
2
def array_delegable?(method)
-
2
Array.method_defined?(method) && BLACKLISTED_ARRAY_METHODS.exclude?(method)
-
end
-
-
2
def method_missing(method, *args, &block)
-
if @klass.respond_to?(method)
-
scoping { @klass.public_send(method, *args, &block) }
-
elsif array_delegable?(method)
-
to_a.public_send(method, *args, &block)
-
elsif arel.respond_to?(method)
-
arel.public_send(method, *args, &block)
-
else
-
super
-
end
-
end
-
end
-
end
-
2
module ActiveRecord
-
2
module FinderMethods
-
2
ONE_AS_ONE = '1 AS one'
-
-
# Find by id - This can either be a specific id (1), a list of ids (1, 5, 6), or an array of ids ([5, 6, 10]).
-
# If no record can be found for all of the listed ids, then RecordNotFound will be raised. If the primary key
-
# is an integer, find by id coerces its arguments using +to_i+.
-
#
-
# Person.find(1) # returns the object for ID = 1
-
# Person.find("1") # returns the object for ID = 1
-
# Person.find("31-sarah") # returns the object for ID = 31
-
# Person.find(1, 2, 6) # returns an array for objects with IDs in (1, 2, 6)
-
# Person.find([7, 17]) # returns an array for objects with IDs in (7, 17)
-
# Person.find([1]) # returns an array for the object with ID = 1
-
# Person.where("administrator = 1").order("created_on DESC").find(1)
-
#
-
# <tt>ActiveRecord::RecordNotFound</tt> will be raised if one or more ids are not found.
-
#
-
# NOTE: The returned records may not be in the same order as the ids you
-
# provide since database rows are unordered. You'd need to provide an explicit <tt>order</tt>
-
# option if you want the results are sorted.
-
#
-
# ==== Find with lock
-
#
-
# Example for find with a lock: Imagine two concurrent transactions:
-
# each will read <tt>person.visits == 2</tt>, add 1 to it, and save, resulting
-
# in two saves of <tt>person.visits = 3</tt>. By locking the row, the second
-
# transaction has to wait until the first is finished; we get the
-
# expected <tt>person.visits == 4</tt>.
-
#
-
# Person.transaction do
-
# person = Person.lock(true).find(1)
-
# person.visits += 1
-
# person.save!
-
# end
-
#
-
# ==== Variations of +find+
-
#
-
# Person.where(name: 'Spartacus', rating: 4)
-
# # returns a chainable list (which can be empty).
-
#
-
# Person.find_by(name: 'Spartacus', rating: 4)
-
# # returns the first item or nil.
-
#
-
# Person.where(name: 'Spartacus', rating: 4).first_or_initialize
-
# # returns the first item or returns a new instance (requires you call .save to persist against the database).
-
#
-
# Person.where(name: 'Spartacus', rating: 4).first_or_create
-
# # returns the first item or creates it and returns it, available since Rails 3.2.1.
-
#
-
# ==== Alternatives for +find+
-
#
-
# Person.where(name: 'Spartacus', rating: 4).exists?(conditions = :none)
-
# # returns a boolean indicating if any record with the given conditions exist.
-
#
-
# Person.where(name: 'Spartacus', rating: 4).select("field1, field2, field3")
-
# # returns a chainable list of instances with only the mentioned fields.
-
#
-
# Person.where(name: 'Spartacus', rating: 4).ids
-
# # returns an Array of ids, available since Rails 3.2.1.
-
#
-
# Person.where(name: 'Spartacus', rating: 4).pluck(:field1, :field2)
-
# # returns an Array of the required fields, available since Rails 3.1.
-
2
def find(*args)
-
if block_given?
-
to_a.find(*args) { |*block_args| yield(*block_args) }
-
else
-
find_with_ids(*args)
-
end
-
end
-
-
# Finds the first record matching the specified conditions. There
-
# is no implied ordering so if order matters, you should specify it
-
# yourself.
-
#
-
# If no record is found, returns <tt>nil</tt>.
-
#
-
# Post.find_by name: 'Spartacus', rating: 4
-
# Post.find_by "published_at < ?", 2.weeks.ago
-
2
def find_by(*args)
-
15
where(*args).take
-
end
-
-
# Like <tt>find_by</tt>, except that if no record is found, raises
-
# an <tt>ActiveRecord::RecordNotFound</tt> error.
-
2
def find_by!(*args)
-
where(*args).take!
-
end
-
-
# Gives a record (or N records if a parameter is supplied) without any implied
-
# order. The order will depend on the database implementation.
-
# If an order is supplied it will be respected.
-
#
-
# Person.take # returns an object fetched by SELECT * FROM people LIMIT 1
-
# Person.take(5) # returns 5 objects fetched by SELECT * FROM people LIMIT 5
-
# Person.where(["name LIKE '%?'", name]).take
-
2
def take(limit = nil)
-
15
limit ? limit(limit).to_a : find_take
-
end
-
-
# Same as +take+ but raises <tt>ActiveRecord::RecordNotFound</tt> if no record
-
# is found. Note that <tt>take!</tt> accepts no arguments.
-
2
def take!
-
take or raise RecordNotFound
-
end
-
-
# Find the first record (or first N records if a parameter is supplied).
-
# If no order is defined it will order by primary key.
-
#
-
# Person.first # returns the first object fetched by SELECT * FROM people
-
# Person.where(["user_name = ?", user_name]).first
-
# Person.where(["user_name = :u", { u: user_name }]).first
-
# Person.order("created_on DESC").offset(5).first
-
# Person.first(3) # returns the first three objects fetched by SELECT * FROM people LIMIT 3
-
#
-
# ==== Rails 3
-
#
-
# Person.first # SELECT "people".* FROM "people" LIMIT 1
-
#
-
# NOTE: Rails 3 may not order this query by the primary key and the order
-
# will depend on the database implementation. In order to ensure that behavior,
-
# use <tt>User.order(:id).first</tt> instead.
-
#
-
# ==== Rails 4
-
#
-
# Person.first # SELECT "people".* FROM "people" ORDER BY "people"."id" ASC LIMIT 1
-
#
-
2
def first(limit = nil)
-
if limit
-
find_nth_with_limit(offset_value, limit)
-
else
-
find_nth(:first, offset_value)
-
end
-
end
-
-
# Same as +first+ but raises <tt>ActiveRecord::RecordNotFound</tt> if no record
-
# is found. Note that <tt>first!</tt> accepts no arguments.
-
2
def first!
-
first or raise RecordNotFound
-
end
-
-
# Find the last record (or last N records if a parameter is supplied).
-
# If no order is defined it will order by primary key.
-
#
-
# Person.last # returns the last object fetched by SELECT * FROM people
-
# Person.where(["user_name = ?", user_name]).last
-
# Person.order("created_on DESC").offset(5).last
-
# Person.last(3) # returns the last three objects fetched by SELECT * FROM people.
-
#
-
# Take note that in that last case, the results are sorted in ascending order:
-
#
-
# [#<Person id:2>, #<Person id:3>, #<Person id:4>]
-
#
-
# and not:
-
#
-
# [#<Person id:4>, #<Person id:3>, #<Person id:2>]
-
2
def last(limit = nil)
-
if limit
-
if order_values.empty? && primary_key
-
order(arel_table[primary_key].desc).limit(limit).reverse
-
else
-
to_a.last(limit)
-
end
-
else
-
find_last
-
end
-
end
-
-
# Same as +last+ but raises <tt>ActiveRecord::RecordNotFound</tt> if no record
-
# is found. Note that <tt>last!</tt> accepts no arguments.
-
2
def last!
-
last or raise RecordNotFound
-
end
-
-
# Find the second record.
-
# If no order is defined it will order by primary key.
-
#
-
# Person.second # returns the second object fetched by SELECT * FROM people
-
# Person.offset(3).second # returns the second object from OFFSET 3 (which is OFFSET 4)
-
# Person.where(["user_name = :u", { u: user_name }]).second
-
2
def second
-
find_nth(:second, offset_value ? offset_value + 1 : 1)
-
end
-
-
# Same as +second+ but raises <tt>ActiveRecord::RecordNotFound</tt> if no record
-
# is found.
-
2
def second!
-
second or raise RecordNotFound
-
end
-
-
# Find the third record.
-
# If no order is defined it will order by primary key.
-
#
-
# Person.third # returns the third object fetched by SELECT * FROM people
-
# Person.offset(3).third # returns the third object from OFFSET 3 (which is OFFSET 5)
-
# Person.where(["user_name = :u", { u: user_name }]).third
-
2
def third
-
find_nth(:third, offset_value ? offset_value + 2 : 2)
-
end
-
-
# Same as +third+ but raises <tt>ActiveRecord::RecordNotFound</tt> if no record
-
# is found.
-
2
def third!
-
third or raise RecordNotFound
-
end
-
-
# Find the fourth record.
-
# If no order is defined it will order by primary key.
-
#
-
# Person.fourth # returns the fourth object fetched by SELECT * FROM people
-
# Person.offset(3).fourth # returns the fourth object from OFFSET 3 (which is OFFSET 6)
-
# Person.where(["user_name = :u", { u: user_name }]).fourth
-
2
def fourth
-
find_nth(:fourth, offset_value ? offset_value + 3 : 3)
-
end
-
-
# Same as +fourth+ but raises <tt>ActiveRecord::RecordNotFound</tt> if no record
-
# is found.
-
2
def fourth!
-
fourth or raise RecordNotFound
-
end
-
-
# Find the fifth record.
-
# If no order is defined it will order by primary key.
-
#
-
# Person.fifth # returns the fifth object fetched by SELECT * FROM people
-
# Person.offset(3).fifth # returns the fifth object from OFFSET 3 (which is OFFSET 7)
-
# Person.where(["user_name = :u", { u: user_name }]).fifth
-
2
def fifth
-
find_nth(:fifth, offset_value ? offset_value + 4 : 4)
-
end
-
-
# Same as +fifth+ but raises <tt>ActiveRecord::RecordNotFound</tt> if no record
-
# is found.
-
2
def fifth!
-
fifth or raise RecordNotFound
-
end
-
-
# Find the forty-second record. Also known as accessing "the reddit".
-
# If no order is defined it will order by primary key.
-
#
-
# Person.forty_two # returns the forty-second object fetched by SELECT * FROM people
-
# Person.offset(3).forty_two # returns the forty-second object from OFFSET 3 (which is OFFSET 44)
-
# Person.where(["user_name = :u", { u: user_name }]).forty_two
-
2
def forty_two
-
find_nth(:forty_two, offset_value ? offset_value + 41 : 41)
-
end
-
-
# Same as +forty_two+ but raises <tt>ActiveRecord::RecordNotFound</tt> if no record
-
# is found.
-
2
def forty_two!
-
forty_two or raise RecordNotFound
-
end
-
-
# Returns +true+ if a record exists in the table that matches the +id+ or
-
# conditions given, or +false+ otherwise. The argument can take six forms:
-
#
-
# * Integer - Finds the record with this primary key.
-
# * String - Finds the record with a primary key corresponding to this
-
# string (such as <tt>'5'</tt>).
-
# * Array - Finds the record that matches these +find+-style conditions
-
# (such as <tt>['name LIKE ?', "%#{query}%"]</tt>).
-
# * Hash - Finds the record that matches these +find+-style conditions
-
# (such as <tt>{name: 'David'}</tt>).
-
# * +false+ - Returns always +false+.
-
# * No args - Returns +false+ if the table is empty, +true+ otherwise.
-
#
-
# For more information about specifying conditions as a hash or array,
-
# see the Conditions section in the introduction to <tt>ActiveRecord::Base</tt>.
-
#
-
# Note: You can't pass in a condition as a string (like <tt>name =
-
# 'Jamie'</tt>), since it would be sanitized and then queried against
-
# the primary key column, like <tt>id = 'name = \'Jamie\''</tt>.
-
#
-
# Person.exists?(5)
-
# Person.exists?('5')
-
# Person.exists?(['name LIKE ?', "%#{query}%"])
-
# Person.exists?(id: [1, 4, 8])
-
# Person.exists?(name: 'David')
-
# Person.exists?(false)
-
# Person.exists?
-
2
def exists?(conditions = :none)
-
195
conditions = conditions.id if Base === conditions
-
195
return false if !conditions
-
-
195
relation = apply_join_dependency(self, construct_join_dependency)
-
195
return false if ActiveRecord::NullRelation === relation
-
-
195
relation = relation.except(:select, :order).select(ONE_AS_ONE).limit(1)
-
-
195
case conditions
-
when Array, Hash
-
relation = relation.where(conditions)
-
else
-
195
relation = relation.where(table[primary_key].eq(conditions)) if conditions != :none
-
end
-
-
195
connection.select_value(relation, "#{name} Exists", relation.bind_values) ? true : false
-
end
-
-
# This method is called whenever no records are found with either a single
-
# id or multiple ids and raises a +ActiveRecord::RecordNotFound+ exception.
-
#
-
# The error message is different depending on whether a single id or
-
# multiple ids are provided. If multiple ids are provided, then the number
-
# of results obtained should be provided in the +result_size+ argument and
-
# the expected number of results should be provided in the +expected_size+
-
# argument.
-
2
def raise_record_not_found_exception!(ids, result_size, expected_size) #:nodoc:
-
conditions = arel.where_sql
-
conditions = " [#{conditions}]" if conditions
-
-
if Array(ids).size == 1
-
error = "Couldn't find #{@klass.name} with '#{primary_key}'=#{ids}#{conditions}"
-
else
-
error = "Couldn't find all #{@klass.name.pluralize} with '#{primary_key}': "
-
error << "(#{ids.join(", ")})#{conditions} (found #{result_size} results, but was looking for #{expected_size})"
-
end
-
-
raise RecordNotFound, error
-
end
-
-
2
private
-
-
2
def find_with_associations
-
# NOTE: the JoinDependency constructed here needs to know about
-
# any joins already present in `self`, so pass them in
-
#
-
# failing to do so means that in cases like activerecord/test/cases/associations/inner_join_association_test.rb:136
-
# incorrect SQL is generated. In that case, the join dependency for
-
# SpecialCategorizations is constructed without knowledge of the
-
# preexisting join in joins_values to categorizations (by way of
-
# the `has_many :through` for categories).
-
#
-
join_dependency = construct_join_dependency(joins_values)
-
-
aliases = join_dependency.aliases
-
relation = select aliases.columns
-
relation = apply_join_dependency(relation, join_dependency)
-
-
if block_given?
-
yield relation
-
else
-
if ActiveRecord::NullRelation === relation
-
[]
-
else
-
rows = connection.select_all(relation.arel, 'SQL', relation.bind_values.dup)
-
join_dependency.instantiate(rows, aliases)
-
end
-
end
-
end
-
-
2
def construct_join_dependency(joins = [])
-
195
including = eager_load_values + includes_values
-
195
ActiveRecord::Associations::JoinDependency.new(@klass, including, joins)
-
end
-
-
2
def construct_relation_for_association_calculations
-
from = arel.froms.first
-
if Arel::Table === from
-
apply_join_dependency(self, construct_join_dependency)
-
else
-
# FIXME: as far as I can tell, `from` will always be an Arel::Table.
-
# There are no tests that test this branch, but presumably it's
-
# possible for `from` to be a list?
-
apply_join_dependency(self, construct_join_dependency(from))
-
end
-
end
-
-
2
def apply_join_dependency(relation, join_dependency)
-
195
relation = relation.except(:includes, :eager_load, :preload)
-
195
relation = relation.joins join_dependency
-
-
195
if using_limitable_reflections?(join_dependency.reflections)
-
195
relation
-
else
-
if relation.limit_value
-
limited_ids = limited_ids_for(relation)
-
limited_ids.empty? ? relation.none! : relation.where!(table[primary_key].in(limited_ids))
-
end
-
relation.except(:limit, :offset)
-
end
-
end
-
-
2
def limited_ids_for(relation)
-
values = @klass.connection.columns_for_distinct(
-
"#{quoted_table_name}.#{quoted_primary_key}", relation.order_values)
-
-
relation = relation.except(:select).select(values).distinct!
-
-
id_rows = @klass.connection.select_all(relation.arel, 'SQL', relation.bind_values)
-
id_rows.map {|row| row[primary_key]}
-
end
-
-
2
def using_limitable_reflections?(reflections)
-
195
reflections.none? { |r| r.collection? }
-
end
-
-
2
protected
-
-
2
def find_with_ids(*ids)
-
raise UnknownPrimaryKey.new(@klass) if primary_key.nil?
-
-
expects_array = ids.first.kind_of?(Array)
-
return ids.first if expects_array && ids.first.empty?
-
-
ids = ids.flatten.compact.uniq
-
-
case ids.size
-
when 0
-
raise RecordNotFound, "Couldn't find #{@klass.name} without an ID"
-
when 1
-
result = find_one(ids.first)
-
expects_array ? [ result ] : result
-
else
-
find_some(ids)
-
end
-
end
-
-
2
def find_one(id)
-
id = id.id if ActiveRecord::Base === id
-
-
column = columns_hash[primary_key]
-
substitute = connection.substitute_at(column, bind_values.length)
-
relation = where(table[primary_key].eq(substitute))
-
relation.bind_values += [[column, id]]
-
record = relation.take
-
-
raise_record_not_found_exception!(id, 0, 1) unless record
-
-
record
-
end
-
-
2
def find_some(ids)
-
result = where(table[primary_key].in(ids)).to_a
-
-
expected_size =
-
if limit_value && ids.size > limit_value
-
limit_value
-
else
-
ids.size
-
end
-
-
# 11 ids with limit 3, offset 9 should give 2 results.
-
if offset_value && (ids.size - offset_value < expected_size)
-
expected_size = ids.size - offset_value
-
end
-
-
if result.size == expected_size
-
result
-
else
-
raise_record_not_found_exception!(ids, result.size, expected_size)
-
end
-
end
-
-
2
def find_take
-
15
if loaded?
-
@records.first
-
else
-
15
@take ||= limit(1).to_a.first
-
end
-
end
-
-
2
def find_nth(ordinal, offset)
-
if loaded?
-
@records.send(ordinal)
-
else
-
@offsets[offset] ||= find_nth_with_limit(offset, 1).first
-
end
-
end
-
-
2
def find_nth_with_limit(offset, limit)
-
if order_values.empty? && primary_key
-
order(arel_table[primary_key].asc).limit(limit).offset(offset).to_a
-
else
-
limit(limit).offset(offset).to_a
-
end
-
end
-
-
2
def find_last
-
if loaded?
-
@records.last
-
else
-
@last ||=
-
if limit_value
-
to_a.last
-
else
-
reverse_order.limit(1).to_a.first
-
end
-
end
-
end
-
end
-
end
-
2
require 'active_support/core_ext/hash/keys'
-
2
require "set"
-
-
2
module ActiveRecord
-
2
class Relation
-
2
class HashMerger # :nodoc:
-
2
attr_reader :relation, :hash
-
-
2
def initialize(relation, hash)
-
hash.assert_valid_keys(*Relation::VALUE_METHODS)
-
-
@relation = relation
-
@hash = hash
-
end
-
-
2
def merge
-
Merger.new(relation, other).merge
-
end
-
-
# Applying values to a relation has some side effects. E.g.
-
# interpolation might take place for where values. So we should
-
# build a relation to merge in rather than directly merging
-
# the values.
-
2
def other
-
other = Relation.create(relation.klass, relation.table)
-
hash.each { |k, v|
-
if k == :joins
-
if Hash === v
-
other.joins!(v)
-
else
-
other.joins!(*v)
-
end
-
elsif k == :select
-
other._select!(v)
-
else
-
other.send("#{k}!", v)
-
end
-
}
-
other
-
end
-
end
-
-
2
class Merger # :nodoc:
-
2
attr_reader :relation, :values, :other
-
-
2
def initialize(relation, other)
-
360
@relation = relation
-
360
@values = other.values
-
360
@other = other
-
end
-
-
2
NORMAL_VALUES = Relation::SINGLE_VALUE_METHODS +
-
Relation::MULTI_VALUE_METHODS -
-
[:joins, :where, :order, :bind, :reverse_order, :lock, :create_with, :reordering, :from] # :nodoc:
-
-
2
def normal_values
-
360
NORMAL_VALUES
-
end
-
-
2
def merge
-
360
normal_values.each do |name|
-
5040
value = values[name]
-
# The unless clause is here mostly for performance reasons (since the `send` call might be moderately
-
# expensive), most of the time the value is going to be `nil` or `.blank?`, the only catch is that
-
# `false.blank?` returns `true`, so there needs to be an extra check so that explicit `false` values
-
# don't fall through the cracks.
-
5040
unless value.nil? || (value.blank? && false != value)
-
if name == :select
-
relation._select!(*value)
-
else
-
relation.send("#{name}!", *value)
-
end
-
end
-
end
-
-
360
merge_multi_values
-
360
merge_single_values
-
360
merge_joins
-
-
360
relation
-
end
-
-
2
private
-
-
2
def merge_joins
-
360
return if values[:joins].blank?
-
-
if other.klass == relation.klass
-
relation.joins!(*values[:joins])
-
else
-
joins_dependency, rest = values[:joins].partition do |join|
-
case join
-
when Hash, Symbol, Array
-
true
-
else
-
false
-
end
-
end
-
-
join_dependency = ActiveRecord::Associations::JoinDependency.new(other.klass,
-
joins_dependency,
-
[])
-
relation.joins! rest
-
-
@relation = relation.joins join_dependency
-
end
-
end
-
-
2
def merge_multi_values
-
360
lhs_wheres = relation.where_values
-
360
rhs_wheres = values[:where] || []
-
-
360
lhs_binds = relation.bind_values
-
360
rhs_binds = values[:bind] || []
-
-
360
removed, kept = partition_overwrites(lhs_wheres, rhs_wheres)
-
-
360
where_values = kept + rhs_wheres
-
360
bind_values = filter_binds(lhs_binds, removed) + rhs_binds
-
-
360
conn = relation.klass.connection
-
360
bv_index = 0
-
360
where_values.map! do |node|
-
432
if Arel::Nodes::Equality === node && Arel::Nodes::BindParam === node.right
-
432
substitute = conn.substitute_at(bind_values[bv_index].first, bv_index)
-
432
bv_index += 1
-
432
Arel::Nodes::Equality.new(node.left, substitute)
-
else
-
node
-
end
-
end
-
-
360
relation.where_values = where_values
-
360
relation.bind_values = bind_values
-
-
360
if values[:reordering]
-
# override any order specified in the original relation
-
relation.reorder! values[:order]
-
elsif values[:order]
-
# merge in order_values from relation
-
relation.order! values[:order]
-
end
-
-
360
relation.extend(*values[:extending]) unless values[:extending].blank?
-
end
-
-
2
def merge_single_values
-
360
relation.from_value = values[:from] unless relation.from_value
-
360
relation.lock_value = values[:lock] unless relation.lock_value
-
360
relation.reverse_order_value = values[:reverse_order]
-
-
360
unless values[:create_with].blank?
-
relation.create_with_value = (relation.create_with_value || {}).merge(values[:create_with])
-
end
-
end
-
-
2
def filter_binds(lhs_binds, removed_wheres)
-
360
return lhs_binds if removed_wheres.empty?
-
-
set = Set.new removed_wheres.map { |x| x.left.name.to_s }
-
lhs_binds.dup.delete_if { |col,_| set.include? col.name }
-
end
-
-
# Remove equalities from the existing relation with a LHS which is
-
# present in the relation being merged in.
-
# returns [things_to_remove, things_to_keep]
-
2
def partition_overwrites(lhs_wheres, rhs_wheres)
-
360
if lhs_wheres.empty? || rhs_wheres.empty?
-
360
return [[], lhs_wheres]
-
end
-
-
nodes = rhs_wheres.find_all do |w|
-
w.respond_to?(:operator) && w.operator == :==
-
end
-
seen = Set.new(nodes) { |node| node.left }
-
-
lhs_wheres.partition do |w|
-
w.respond_to?(:operator) && w.operator == :== && seen.include?(w.left)
-
end
-
end
-
end
-
end
-
end
-
1
module ActiveRecord
-
1
class PredicateBuilder # :nodoc:
-
1
@handlers = []
-
-
1
autoload :RelationHandler, 'active_record/relation/predicate_builder/relation_handler'
-
1
autoload :ArrayHandler, 'active_record/relation/predicate_builder/array_handler'
-
-
1
def self.resolve_column_aliases(klass, hash)
-
15
hash = hash.dup
-
15
hash.keys.grep(Symbol) do |key|
-
15
if klass.attribute_alias? key
-
hash[klass.attribute_alias(key)] = hash.delete key
-
end
-
end
-
15
hash
-
end
-
-
1
def self.build_from_hash(klass, attributes, default_table)
-
15
queries = []
-
-
15
attributes.each do |column, value|
-
15
table = default_table
-
-
15
if value.is_a?(Hash)
-
if value.empty?
-
queries << '1=0'
-
else
-
table = Arel::Table.new(column, default_table.engine)
-
association = klass._reflect_on_association(column.to_sym)
-
-
value.each do |k, v|
-
queries.concat expand(association && association.klass, table, k, v)
-
end
-
end
-
else
-
15
column = column.to_s
-
-
15
if column.include?('.')
-
table_name, column = column.split('.', 2)
-
table = Arel::Table.new(table_name, default_table.engine)
-
end
-
-
15
queries.concat expand(klass, table, column, value)
-
end
-
end
-
-
15
queries
-
end
-
-
1
def self.expand(klass, table, column, value)
-
15
queries = []
-
-
# Find the foreign key when using queries such as:
-
# Post.where(author: author)
-
#
-
# For polymorphic relationships, find the foreign key and type:
-
# PriceEstimate.where(estimate_of: treasure)
-
15
if klass && reflection = klass._reflect_on_association(column.to_sym)
-
if reflection.polymorphic? && base_class = polymorphic_base_class_from_value(value)
-
queries << build(table[reflection.foreign_type], base_class)
-
end
-
-
column = reflection.foreign_key
-
end
-
-
15
queries << build(table[column], value)
-
15
queries
-
end
-
-
1
def self.polymorphic_base_class_from_value(value)
-
case value
-
when Relation
-
value.klass.base_class
-
when Array
-
val = value.compact.first
-
val.class.base_class if val.is_a?(Base)
-
when Base
-
value.class.base_class
-
end
-
end
-
-
1
def self.references(attributes)
-
attributes.map do |key, value|
-
15
if value.is_a?(Hash)
-
key
-
else
-
15
key = key.to_s
-
15
key.split('.').first if key.include?('.')
-
end
-
15
end.compact
-
end
-
-
# Define how a class is converted to Arel nodes when passed to +where+.
-
# The handler can be any object that responds to +call+, and will be used
-
# for any value that +===+ the class given. For example:
-
#
-
# MyCustomDateRange = Struct.new(:start, :end)
-
# handler = proc do |column, range|
-
# Arel::Nodes::Between.new(column,
-
# Arel::Nodes::And.new([range.start, range.end])
-
# )
-
# end
-
# ActiveRecord::PredicateBuilder.register_handler(MyCustomDateRange, handler)
-
1
def self.register_handler(klass, handler)
-
6
@handlers.unshift([klass, handler])
-
end
-
-
16
register_handler(BasicObject, ->(attribute, value) { attribute.eq(value) })
-
# FIXME: I think we need to deprecate this behavior
-
1
register_handler(Class, ->(attribute, value) { attribute.eq(value.name) })
-
1
register_handler(Base, ->(attribute, value) { attribute.eq(value.id) })
-
1
register_handler(Range, ->(attribute, value) { attribute.in(value) })
-
1
register_handler(Relation, RelationHandler.new)
-
1
register_handler(Array, ArrayHandler.new)
-
-
1
private
-
1
def self.build(attribute, value)
-
15
handler_for(value).call(attribute, value)
-
end
-
-
1
def self.handler_for(object)
-
105
@handlers.detect { |klass, _| klass === object }.last
-
end
-
end
-
end
-
1
module ActiveRecord
-
1
class PredicateBuilder
-
1
class ArrayHandler # :nodoc:
-
1
def call(attribute, value)
-
values = value.map { |x| x.is_a?(Base) ? x.id : x }
-
ranges, values = values.partition { |v| v.is_a?(Range) }
-
-
values_predicate = if values.include?(nil)
-
values = values.compact
-
-
case values.length
-
when 0
-
attribute.eq(nil)
-
when 1
-
attribute.eq(values.first).or(attribute.eq(nil))
-
else
-
attribute.in(values).or(attribute.eq(nil))
-
end
-
else
-
attribute.in(values)
-
end
-
-
array_predicates = ranges.map { |range| attribute.in(range) }
-
array_predicates << values_predicate
-
array_predicates.inject { |composite, predicate| composite.or(predicate) }
-
end
-
end
-
end
-
end
-
1
module ActiveRecord
-
1
class PredicateBuilder
-
1
class RelationHandler # :nodoc:
-
1
def call(attribute, value)
-
if value.select_values.empty?
-
value = value.select(value.klass.arel_table[value.klass.primary_key])
-
end
-
-
attribute.in(value.arel.ast)
-
end
-
end
-
end
-
end
-
2
require 'active_support/core_ext/array/wrap'
-
2
require 'active_model/forbidden_attributes_protection'
-
-
2
module ActiveRecord
-
2
module QueryMethods
-
2
extend ActiveSupport::Concern
-
-
2
include ActiveModel::ForbiddenAttributesProtection
-
-
# WhereChain objects act as placeholder for queries in which #where does not have any parameter.
-
# In this case, #where must be chained with #not to return a new relation.
-
2
class WhereChain
-
2
def initialize(scope)
-
@scope = scope
-
end
-
-
# Returns a new relation expressing WHERE + NOT condition according to
-
# the conditions in the arguments.
-
#
-
# +not+ accepts conditions as a string, array, or hash. See #where for
-
# more details on each format.
-
#
-
# User.where.not("name = 'Jon'")
-
# # SELECT * FROM users WHERE NOT (name = 'Jon')
-
#
-
# User.where.not(["name = ?", "Jon"])
-
# # SELECT * FROM users WHERE NOT (name = 'Jon')
-
#
-
# User.where.not(name: "Jon")
-
# # SELECT * FROM users WHERE name != 'Jon'
-
#
-
# User.where.not(name: nil)
-
# # SELECT * FROM users WHERE name IS NOT NULL
-
#
-
# User.where.not(name: %w(Ko1 Nobu))
-
# # SELECT * FROM users WHERE name NOT IN ('Ko1', 'Nobu')
-
#
-
# User.where.not(name: "Jon", role: "admin")
-
# # SELECT * FROM users WHERE name != 'Jon' AND role != 'admin'
-
2
def not(opts, *rest)
-
where_value = @scope.send(:build_where, opts, rest).map do |rel|
-
case rel
-
when NilClass
-
raise ArgumentError, 'Invalid argument for .where.not(), got nil.'
-
when Arel::Nodes::In
-
Arel::Nodes::NotIn.new(rel.left, rel.right)
-
when Arel::Nodes::Equality
-
Arel::Nodes::NotEqual.new(rel.left, rel.right)
-
when String
-
Arel::Nodes::Not.new(Arel::Nodes::SqlLiteral.new(rel))
-
else
-
Arel::Nodes::Not.new(rel)
-
end
-
end
-
-
@scope.references!(PredicateBuilder.references(opts)) if Hash === opts
-
@scope.where_values += where_value
-
@scope
-
end
-
end
-
-
2
Relation::MULTI_VALUE_METHODS.each do |name|
-
26
class_eval <<-CODE, __FILE__, __LINE__ + 1
-
def #{name}_values # def select_values
-
@values[:#{name}] || [] # @values[:select] || []
-
end # end
-
#
-
def #{name}_values=(values) # def select_values=(values)
-
raise ImmutableRelation if @loaded # raise ImmutableRelation if @loaded
-
@values[:#{name}] = values # @values[:select] = values
-
end # end
-
CODE
-
end
-
-
2
(Relation::SINGLE_VALUE_METHODS - [:create_with]).each do |name|
-
18
class_eval <<-CODE, __FILE__, __LINE__ + 1
-
def #{name}_value # def readonly_value
-
@values[:#{name}] # @values[:readonly]
-
end # end
-
CODE
-
end
-
-
2
Relation::SINGLE_VALUE_METHODS.each do |name|
-
20
class_eval <<-CODE, __FILE__, __LINE__ + 1
-
def #{name}_value=(value) # def readonly_value=(value)
-
raise ImmutableRelation if @loaded # raise ImmutableRelation if @loaded
-
@values[:#{name}] = value # @values[:readonly] = value
-
end # end
-
CODE
-
end
-
-
2
def create_with_value # :nodoc:
-
72
@values[:create_with] || {}
-
end
-
-
2
alias extensions extending_values
-
-
# Specify relationships to be included in the result set. For
-
# example:
-
#
-
# users = User.includes(:address)
-
# users.each do |user|
-
# user.address.city
-
# end
-
#
-
# allows you to access the +address+ attribute of the +User+ model without
-
# firing an additional query. This will often result in a
-
# performance improvement over a simple +join+.
-
#
-
# You can also specify multiple relationships, like this:
-
#
-
# users = User.includes(:address, :friends)
-
#
-
# Loading nested relationships is possible using a Hash:
-
#
-
# users = User.includes(:address, friends: [:address, :followers])
-
#
-
# === conditions
-
#
-
# If you want to add conditions to your included models you'll have
-
# to explicitly reference them. For example:
-
#
-
# User.includes(:posts).where('posts.name = ?', 'example')
-
#
-
# Will throw an error, but this will work:
-
#
-
# User.includes(:posts).where('posts.name = ?', 'example').references(:posts)
-
#
-
# Note that +includes+ works with association names while +references+ needs
-
# the actual table name.
-
2
def includes(*args)
-
check_if_method_has_arguments!(:includes, args)
-
spawn.includes!(*args)
-
end
-
-
2
def includes!(*args) # :nodoc:
-
args.reject!(&:blank?)
-
args.flatten!
-
-
self.includes_values |= args
-
self
-
end
-
-
# Forces eager loading by performing a LEFT OUTER JOIN on +args+:
-
#
-
# User.eager_load(:posts)
-
# => SELECT "users"."id" AS t0_r0, "users"."name" AS t0_r1, ...
-
# FROM "users" LEFT OUTER JOIN "posts" ON "posts"."user_id" =
-
# "users"."id"
-
2
def eager_load(*args)
-
check_if_method_has_arguments!(:eager_load, args)
-
spawn.eager_load!(*args)
-
end
-
-
2
def eager_load!(*args) # :nodoc:
-
self.eager_load_values += args
-
self
-
end
-
-
# Allows preloading of +args+, in the same way that +includes+ does:
-
#
-
# User.preload(:posts)
-
# => SELECT "posts".* FROM "posts" WHERE "posts"."user_id" IN (1, 2, 3)
-
2
def preload(*args)
-
check_if_method_has_arguments!(:preload, args)
-
spawn.preload!(*args)
-
end
-
-
2
def preload!(*args) # :nodoc:
-
self.preload_values += args
-
self
-
end
-
-
# Use to indicate that the given +table_names+ are referenced by an SQL string,
-
# and should therefore be JOINed in any query rather than loaded separately.
-
# This method only works in conjuction with +includes+.
-
# See #includes for more details.
-
#
-
# User.includes(:posts).where("posts.name = 'foo'")
-
# # => Doesn't JOIN the posts table, resulting in an error.
-
#
-
# User.includes(:posts).where("posts.name = 'foo'").references(:posts)
-
# # => Query now knows the string references posts, so adds a JOIN
-
2
def references(*table_names)
-
check_if_method_has_arguments!(:references, table_names)
-
spawn.references!(*table_names)
-
end
-
-
2
def references!(*table_names) # :nodoc:
-
15
table_names.flatten!
-
15
table_names.map!(&:to_s)
-
-
15
self.references_values |= table_names
-
15
self
-
end
-
-
# Works in two unique ways.
-
#
-
# First: takes a block so it can be used just like Array#select.
-
#
-
# Model.all.select { |m| m.field == value }
-
#
-
# This will build an array of objects from the database for the scope,
-
# converting them into an array and iterating through them using Array#select.
-
#
-
# Second: Modifies the SELECT statement for the query so that only certain
-
# fields are retrieved:
-
#
-
# Model.select(:field)
-
# # => [#<Model field:value>]
-
#
-
# Although in the above example it looks as though this method returns an
-
# array, it actually returns a relation object and can have other query
-
# methods appended to it, such as the other methods in ActiveRecord::QueryMethods.
-
#
-
# The argument to the method can also be an array of fields.
-
#
-
# Model.select(:field, :other_field, :and_one_more)
-
# # => [#<Model field: "value", other_field: "value", and_one_more: "value">]
-
#
-
# You can also use one or more strings, which will be used unchanged as SELECT fields.
-
#
-
# Model.select('field AS field_one', 'other_field AS field_two')
-
# # => [#<Model field: "value", other_field: "value">]
-
#
-
# If an alias was specified, it will be accessible from the resulting objects:
-
#
-
# Model.select('field AS field_one').first.field_one
-
# # => "value"
-
#
-
# Accessing attributes of an object that do not have fields retrieved by a select
-
# will throw <tt>ActiveModel::MissingAttributeError</tt>:
-
#
-
# Model.select(:field).first.other_field
-
# # => ActiveModel::MissingAttributeError: missing attribute: other_field
-
2
def select(*fields)
-
195
if block_given?
-
to_a.select { |*block_args| yield(*block_args) }
-
else
-
195
raise ArgumentError, 'Call this with at least one field' if fields.empty?
-
195
spawn._select!(*fields)
-
end
-
end
-
-
2
def _select!(*fields) # :nodoc:
-
195
fields.flatten!
-
195
fields.map! do |field|
-
195
klass.attribute_alias?(field) ? klass.attribute_alias(field) : field
-
end
-
195
self.select_values += fields
-
195
self
-
end
-
-
# Allows to specify a group attribute:
-
#
-
# User.group(:name)
-
# => SELECT "users".* FROM "users" GROUP BY name
-
#
-
# Returns an array with distinct records based on the +group+ attribute:
-
#
-
# User.select([:id, :name])
-
# => [#<User id: 1, name: "Oscar">, #<User id: 2, name: "Oscar">, #<User id: 3, name: "Foo">
-
#
-
# User.group(:name)
-
# => [#<User id: 3, name: "Foo", ...>, #<User id: 2, name: "Oscar", ...>]
-
#
-
# User.group('name AS grouped_name, age')
-
# => [#<User id: 3, name: "Foo", age: 21, ...>, #<User id: 2, name: "Oscar", age: 21, ...>, #<User id: 5, name: "Foo", age: 23, ...>]
-
2
def group(*args)
-
check_if_method_has_arguments!(:group, args)
-
spawn.group!(*args)
-
end
-
-
2
def group!(*args) # :nodoc:
-
args.flatten!
-
-
self.group_values += args
-
self
-
end
-
-
# Allows to specify an order attribute:
-
#
-
# User.order('name')
-
# => SELECT "users".* FROM "users" ORDER BY name
-
#
-
# User.order('name DESC')
-
# => SELECT "users".* FROM "users" ORDER BY name DESC
-
#
-
# User.order('name DESC, email')
-
# => SELECT "users".* FROM "users" ORDER BY name DESC, email
-
#
-
# User.order(:name)
-
# => SELECT "users".* FROM "users" ORDER BY "users"."name" ASC
-
#
-
# User.order(email: :desc)
-
# => SELECT "users".* FROM "users" ORDER BY "users"."email" DESC
-
#
-
# User.order(:name, email: :desc)
-
# => SELECT "users".* FROM "users" ORDER BY "users"."name" ASC, "users"."email" DESC
-
2
def order(*args)
-
check_if_method_has_arguments!(:order, args)
-
spawn.order!(*args)
-
end
-
-
2
def order!(*args) # :nodoc:
-
preprocess_order_args(args)
-
-
self.order_values += args
-
self
-
end
-
-
# Replaces any existing order defined on the relation with the specified order.
-
#
-
# User.order('email DESC').reorder('id ASC') # generated SQL has 'ORDER BY id ASC'
-
#
-
# Subsequent calls to order on the same relation will be appended. For example:
-
#
-
# User.order('email DESC').reorder('id ASC').order('name ASC')
-
#
-
# generates a query with 'ORDER BY id ASC, name ASC'.
-
2
def reorder(*args)
-
check_if_method_has_arguments!(:reorder, args)
-
spawn.reorder!(*args)
-
end
-
-
2
def reorder!(*args) # :nodoc:
-
preprocess_order_args(args)
-
-
self.reordering_value = true
-
self.order_values = args
-
self
-
end
-
-
2
VALID_UNSCOPING_VALUES = Set.new([:where, :select, :group, :order, :lock,
-
:limit, :offset, :joins, :includes, :from,
-
:readonly, :having])
-
-
# Removes an unwanted relation that is already defined on a chain of relations.
-
# This is useful when passing around chains of relations and would like to
-
# modify the relations without reconstructing the entire chain.
-
#
-
# User.order('email DESC').unscope(:order) == User.all
-
#
-
# The method arguments are symbols which correspond to the names of the methods
-
# which should be unscoped. The valid arguments are given in VALID_UNSCOPING_VALUES.
-
# The method can also be called with multiple arguments. For example:
-
#
-
# User.order('email DESC').select('id').where(name: "John")
-
# .unscope(:order, :select, :where) == User.all
-
#
-
# One can additionally pass a hash as an argument to unscope specific :where values.
-
# This is done by passing a hash with a single key-value pair. The key should be
-
# :where and the value should be the where value to unscope. For example:
-
#
-
# User.where(name: "John", active: true).unscope(where: :name)
-
# == User.where(active: true)
-
#
-
# This method is similar to <tt>except</tt>, but unlike
-
# <tt>except</tt>, it persists across merges:
-
#
-
# User.order('email').merge(User.except(:order))
-
# == User.order('email')
-
#
-
# User.order('email').merge(User.unscope(:order))
-
# == User.all
-
#
-
# This means it can be used in association definitions:
-
#
-
# has_many :comments, -> { unscope where: :trashed }
-
#
-
2
def unscope(*args)
-
check_if_method_has_arguments!(:unscope, args)
-
spawn.unscope!(*args)
-
end
-
-
2
def unscope!(*args) # :nodoc:
-
args.flatten!
-
self.unscope_values += args
-
-
args.each do |scope|
-
case scope
-
when Symbol
-
symbol_unscoping(scope)
-
when Hash
-
scope.each do |key, target_value|
-
if key != :where
-
raise ArgumentError, "Hash arguments in .unscope(*args) must have :where as the key."
-
end
-
-
Array(target_value).each do |val|
-
where_unscoping(val)
-
end
-
end
-
else
-
raise ArgumentError, "Unrecognized scoping: #{args.inspect}. Use .unscope(where: :attribute_name) or .unscope(:order), for example."
-
end
-
end
-
-
self
-
end
-
-
# Performs a joins on +args+:
-
#
-
# User.joins(:posts)
-
# => SELECT "users".* FROM "users" INNER JOIN "posts" ON "posts"."user_id" = "users"."id"
-
#
-
# You can use strings in order to customize your joins:
-
#
-
# User.joins("LEFT JOIN bookmarks ON bookmarks.bookmarkable_type = 'Post' AND bookmarks.user_id = users.id")
-
# => SELECT "users".* FROM "users" LEFT JOIN bookmarks ON bookmarks.bookmarkable_type = 'Post' AND bookmarks.user_id = users.id
-
2
def joins(*args)
-
195
check_if_method_has_arguments!(:joins, args)
-
-
195
args.compact!
-
195
args.flatten!
-
-
195
spawn.joins!(*args)
-
end
-
-
2
def joins!(*args) # :nodoc:
-
195
self.joins_values += args
-
195
self
-
end
-
-
2
def bind(value)
-
spawn.bind!(value)
-
end
-
-
2
def bind!(value) # :nodoc:
-
self.bind_values += [value]
-
self
-
end
-
-
# Returns a new relation, which is the result of filtering the current relation
-
# according to the conditions in the arguments.
-
#
-
# #where accepts conditions in one of several formats. In the examples below, the resulting
-
# SQL is given as an illustration; the actual query generated may be different depending
-
# on the database adapter.
-
#
-
# === string
-
#
-
# A single string, without additional arguments, is passed to the query
-
# constructor as an SQL fragment, and used in the where clause of the query.
-
#
-
# Client.where("orders_count = '2'")
-
# # SELECT * from clients where orders_count = '2';
-
#
-
# Note that building your own string from user input may expose your application
-
# to injection attacks if not done properly. As an alternative, it is recommended
-
# to use one of the following methods.
-
#
-
# === array
-
#
-
# If an array is passed, then the first element of the array is treated as a template, and
-
# the remaining elements are inserted into the template to generate the condition.
-
# Active Record takes care of building the query to avoid injection attacks, and will
-
# convert from the ruby type to the database type where needed. Elements are inserted
-
# into the string in the order in which they appear.
-
#
-
# User.where(["name = ? and email = ?", "Joe", "joe@example.com"])
-
# # SELECT * FROM users WHERE name = 'Joe' AND email = 'joe@example.com';
-
#
-
# Alternatively, you can use named placeholders in the template, and pass a hash as the
-
# second element of the array. The names in the template are replaced with the corresponding
-
# values from the hash.
-
#
-
# User.where(["name = :name and email = :email", { name: "Joe", email: "joe@example.com" }])
-
# # SELECT * FROM users WHERE name = 'Joe' AND email = 'joe@example.com';
-
#
-
# This can make for more readable code in complex queries.
-
#
-
# Lastly, you can use sprintf-style % escapes in the template. This works slightly differently
-
# than the previous methods; you are responsible for ensuring that the values in the template
-
# are properly quoted. The values are passed to the connector for quoting, but the caller
-
# is responsible for ensuring they are enclosed in quotes in the resulting SQL. After quoting,
-
# the values are inserted using the same escapes as the Ruby core method <tt>Kernel::sprintf</tt>.
-
#
-
# User.where(["name = '%s' and email = '%s'", "Joe", "joe@example.com"])
-
# # SELECT * FROM users WHERE name = 'Joe' AND email = 'joe@example.com';
-
#
-
# If #where is called with multiple arguments, these are treated as if they were passed as
-
# the elements of a single array.
-
#
-
# User.where("name = :name and email = :email", { name: "Joe", email: "joe@example.com" })
-
# # SELECT * FROM users WHERE name = 'Joe' AND email = 'joe@example.com';
-
#
-
# When using strings to specify conditions, you can use any operator available from
-
# the database. While this provides the most flexibility, you can also unintentionally introduce
-
# dependencies on the underlying database. If your code is intended for general consumption,
-
# test with multiple database backends.
-
#
-
# === hash
-
#
-
# #where will also accept a hash condition, in which the keys are fields and the values
-
# are values to be searched for.
-
#
-
# Fields can be symbols or strings. Values can be single values, arrays, or ranges.
-
#
-
# User.where({ name: "Joe", email: "joe@example.com" })
-
# # SELECT * FROM users WHERE name = 'Joe' AND email = 'joe@example.com'
-
#
-
# User.where({ name: ["Alice", "Bob"]})
-
# # SELECT * FROM users WHERE name IN ('Alice', 'Bob')
-
#
-
# User.where({ created_at: (Time.now.midnight - 1.day)..Time.now.midnight })
-
# # SELECT * FROM users WHERE (created_at BETWEEN '2012-06-09 07:00:00.000000' AND '2012-06-10 07:00:00.000000')
-
#
-
# In the case of a belongs_to relationship, an association key can be used
-
# to specify the model if an ActiveRecord object is used as the value.
-
#
-
# author = Author.find(1)
-
#
-
# # The following queries will be equivalent:
-
# Post.where(author: author)
-
# Post.where(author_id: author)
-
#
-
# This also works with polymorphic belongs_to relationships:
-
#
-
# treasure = Treasure.create(name: 'gold coins')
-
# treasure.price_estimates << PriceEstimate.create(price: 125)
-
#
-
# # The following queries will be equivalent:
-
# PriceEstimate.where(estimate_of: treasure)
-
# PriceEstimate.where(estimate_of_type: 'Treasure', estimate_of_id: treasure)
-
#
-
# === Joins
-
#
-
# If the relation is the result of a join, you may create a condition which uses any of the
-
# tables in the join. For string and array conditions, use the table name in the condition.
-
#
-
# User.joins(:posts).where("posts.created_at < ?", Time.now)
-
#
-
# For hash conditions, you can either use the table name in the key, or use a sub-hash.
-
#
-
# User.joins(:posts).where({ "posts.published" => true })
-
# User.joins(:posts).where({ posts: { published: true } })
-
#
-
# === no argument
-
#
-
# If no argument is passed, #where returns a new instance of WhereChain, that
-
# can be chained with #not to return a new relation that negates the where clause.
-
#
-
# User.where.not(name: "Jon")
-
# # SELECT * FROM users WHERE name != 'Jon'
-
#
-
# See WhereChain for more details on #not.
-
#
-
# === blank condition
-
#
-
# If the condition is any blank-ish object, then #where is a no-op and returns
-
# the current relation.
-
2
def where(opts = :chain, *rest)
-
354
if opts == :chain
-
WhereChain.new(spawn)
-
354
elsif opts.blank?
-
self
-
else
-
354
spawn.where!(opts, *rest)
-
end
-
end
-
-
2
def where!(opts = :chain, *rest) # :nodoc:
-
354
if opts == :chain
-
WhereChain.new(self)
-
else
-
354
if Hash === opts
-
15
opts = sanitize_forbidden_attributes(opts)
-
15
references!(PredicateBuilder.references(opts))
-
end
-
-
354
self.where_values += build_where(opts, rest)
-
354
self
-
end
-
end
-
-
# Allows you to change a previously set where condition for a given attribute, instead of appending to that condition.
-
#
-
# Post.where(trashed: true).where(trashed: false) # => WHERE `trashed` = 1 AND `trashed` = 0
-
# Post.where(trashed: true).rewhere(trashed: false) # => WHERE `trashed` = 0
-
# Post.where(active: true).where(trashed: true).rewhere(trashed: false) # => WHERE `active` = 1 AND `trashed` = 0
-
#
-
# This is short-hand for unscope(where: conditions.keys).where(conditions). Note that unlike reorder, we're only unscoping
-
# the named conditions -- not the entire where statement.
-
2
def rewhere(conditions)
-
unscope(where: conditions.keys).where(conditions)
-
end
-
-
# Allows to specify a HAVING clause. Note that you can't use HAVING
-
# without also specifying a GROUP clause.
-
#
-
# Order.having('SUM(price) > 30').group('user_id')
-
2
def having(opts, *rest)
-
opts.blank? ? self : spawn.having!(opts, *rest)
-
end
-
-
2
def having!(opts, *rest) # :nodoc:
-
references!(PredicateBuilder.references(opts)) if Hash === opts
-
-
self.having_values += build_where(opts, rest)
-
self
-
end
-
-
# Specifies a limit for the number of records to retrieve.
-
#
-
# User.limit(10) # generated SQL has 'LIMIT 10'
-
#
-
# User.limit(10).limit(20) # generated SQL has 'LIMIT 20'
-
2
def limit(value)
-
210
spawn.limit!(value)
-
end
-
-
2
def limit!(value) # :nodoc:
-
210
self.limit_value = value
-
210
self
-
end
-
-
# Specifies the number of rows to skip before returning rows.
-
#
-
# User.offset(10) # generated SQL has "OFFSET 10"
-
#
-
# Should be used with order.
-
#
-
# User.offset(10).order("name ASC")
-
2
def offset(value)
-
spawn.offset!(value)
-
end
-
-
2
def offset!(value) # :nodoc:
-
self.offset_value = value
-
self
-
end
-
-
# Specifies locking settings (default to +true+). For more information
-
# on locking, please see +ActiveRecord::Locking+.
-
2
def lock(locks = true)
-
spawn.lock!(locks)
-
end
-
-
2
def lock!(locks = true) # :nodoc:
-
case locks
-
when String, TrueClass, NilClass
-
self.lock_value = locks || true
-
else
-
self.lock_value = false
-
end
-
-
self
-
end
-
-
# Returns a chainable relation with zero records.
-
#
-
# The returned relation implements the Null Object pattern. It is an
-
# object with defined null behavior and always returns an empty array of
-
# records without querying the database.
-
#
-
# Any subsequent condition chained to the returned relation will continue
-
# generating an empty relation and will not fire any query to the database.
-
#
-
# Used in cases where a method or scope could return zero records but the
-
# result needs to be chainable.
-
#
-
# For example:
-
#
-
# @posts = current_user.visible_posts.where(name: params[:name])
-
# # => the visible_posts method is expected to return a chainable Relation
-
#
-
# def visible_posts
-
# case role
-
# when 'Country Manager'
-
# Post.where(country: country)
-
# when 'Reviewer'
-
# Post.published
-
# when 'Bad User'
-
# Post.none # It can't be chained if [] is returned.
-
# end
-
# end
-
#
-
2
def none
-
extending(NullRelation)
-
end
-
-
2
def none! # :nodoc:
-
extending!(NullRelation)
-
end
-
-
# Sets readonly attributes for the returned relation. If value is
-
# true (default), attempting to update a record will result in an error.
-
#
-
# users = User.readonly
-
# users.first.save
-
# => ActiveRecord::ReadOnlyRecord: ActiveRecord::ReadOnlyRecord
-
2
def readonly(value = true)
-
spawn.readonly!(value)
-
end
-
-
2
def readonly!(value = true) # :nodoc:
-
self.readonly_value = value
-
self
-
end
-
-
# Sets attributes to be used when creating new records from a
-
# relation object.
-
#
-
# users = User.where(name: 'Oscar')
-
# users.new.name # => 'Oscar'
-
#
-
# users = users.create_with(name: 'DHH')
-
# users.new.name # => 'DHH'
-
#
-
# You can pass +nil+ to +create_with+ to reset attributes:
-
#
-
# users = users.create_with(nil)
-
# users.new.name # => 'Oscar'
-
2
def create_with(value)
-
spawn.create_with!(value)
-
end
-
-
2
def create_with!(value) # :nodoc:
-
if value
-
value = sanitize_forbidden_attributes(value)
-
self.create_with_value = create_with_value.merge(value)
-
else
-
self.create_with_value = {}
-
end
-
-
self
-
end
-
-
# Specifies table from which the records will be fetched. For example:
-
#
-
# Topic.select('title').from('posts')
-
# # => SELECT title FROM posts
-
#
-
# Can accept other relation objects. For example:
-
#
-
# Topic.select('title').from(Topic.approved)
-
# # => SELECT title FROM (SELECT * FROM topics WHERE approved = 't') subquery
-
#
-
# Topic.select('a.title').from(Topic.approved, :a)
-
# # => SELECT a.title FROM (SELECT * FROM topics WHERE approved = 't') a
-
#
-
2
def from(value, subquery_name = nil)
-
spawn.from!(value, subquery_name)
-
end
-
-
2
def from!(value, subquery_name = nil) # :nodoc:
-
self.from_value = [value, subquery_name]
-
self
-
end
-
-
# Specifies whether the records should be unique or not. For example:
-
#
-
# User.select(:name)
-
# # => Might return two records with the same name
-
#
-
# User.select(:name).distinct
-
# # => Returns 1 record per distinct name
-
#
-
# User.select(:name).distinct.distinct(false)
-
# # => You can also remove the uniqueness
-
2
def distinct(value = true)
-
spawn.distinct!(value)
-
end
-
2
alias uniq distinct
-
-
# Like #distinct, but modifies relation in place.
-
2
def distinct!(value = true) # :nodoc:
-
self.distinct_value = value
-
self
-
end
-
2
alias uniq! distinct!
-
-
# Used to extend a scope with additional methods, either through
-
# a module or through a block provided.
-
#
-
# The object returned is a relation, which can be further extended.
-
#
-
# === Using a module
-
#
-
# module Pagination
-
# def page(number)
-
# # pagination code goes here
-
# end
-
# end
-
#
-
# scope = Model.all.extending(Pagination)
-
# scope.page(params[:page])
-
#
-
# You can also pass a list of modules:
-
#
-
# scope = Model.all.extending(Pagination, SomethingElse)
-
#
-
# === Using a block
-
#
-
# scope = Model.all.extending do
-
# def page(number)
-
# # pagination code goes here
-
# end
-
# end
-
# scope.page(params[:page])
-
#
-
# You can also use a block and a module list:
-
#
-
# scope = Model.all.extending(Pagination) do
-
# def per_page(number)
-
# # pagination code goes here
-
# end
-
# end
-
2
def extending(*modules, &block)
-
if modules.any? || block
-
spawn.extending!(*modules, &block)
-
else
-
self
-
end
-
end
-
-
2
def extending!(*modules, &block) # :nodoc:
-
72
modules << Module.new(&block) if block
-
72
modules.flatten!
-
-
72
self.extending_values += modules
-
72
extend(*extending_values) if extending_values.any?
-
-
72
self
-
end
-
-
# Reverse the existing order clause on the relation.
-
#
-
# User.order('name ASC').reverse_order # generated SQL has 'ORDER BY name DESC'
-
2
def reverse_order
-
spawn.reverse_order!
-
end
-
-
2
def reverse_order! # :nodoc:
-
self.reverse_order_value = !reverse_order_value
-
self
-
end
-
-
# Returns the Arel object associated with the relation.
-
2
def arel # :nodoc:
-
484
@arel ||= build_arel
-
end
-
-
2
private
-
-
2
def build_arel
-
478
arel = Arel::SelectManager.new(table.engine, table)
-
-
478
build_joins(arel, joins_values.flatten) unless joins_values.empty?
-
-
478
collapse_wheres(arel, (where_values - ['']).uniq)
-
-
478
arel.having(*having_values.uniq.reject(&:blank?)) unless having_values.empty?
-
-
478
arel.take(connection.sanitize_limit(limit_value)) if limit_value
-
478
arel.skip(offset_value.to_i) if offset_value
-
-
478
arel.group(*group_values.uniq.reject(&:blank?)) unless group_values.empty?
-
-
478
build_order(arel)
-
-
478
build_select(arel, select_values.uniq)
-
-
478
arel.distinct(distinct_value)
-
478
arel.from(build_from) if from_value
-
478
arel.lock(lock_value) if lock_value
-
-
# Reorder bind indexes if joins produced bind values
-
478
bvs = arel.bind_values + bind_values
-
478
arel.ast.grep(Arel::Nodes::BindParam).each_with_index do |bp, i|
-
column = bvs[i].first
-
bp.replace connection.substitute_at(column, i)
-
end
-
-
478
arel
-
end
-
-
2
def symbol_unscoping(scope)
-
if !VALID_UNSCOPING_VALUES.include?(scope)
-
raise ArgumentError, "Called unscope() with invalid unscoping argument ':#{scope}'. Valid arguments are :#{VALID_UNSCOPING_VALUES.to_a.join(", :")}."
-
end
-
-
single_val_method = Relation::SINGLE_VALUE_METHODS.include?(scope)
-
unscope_code = "#{scope}_value#{'s' unless single_val_method}="
-
-
case scope
-
when :order
-
self.reverse_order_value = false
-
result = []
-
else
-
result = [] unless single_val_method
-
end
-
-
self.send(unscope_code, result)
-
end
-
-
2
def where_unscoping(target_value)
-
target_value = target_value.to_s
-
-
where_values.reject! do |rel|
-
case rel
-
when Arel::Nodes::In, Arel::Nodes::NotIn, Arel::Nodes::Equality, Arel::Nodes::NotEqual
-
subrelation = (rel.left.kind_of?(Arel::Attributes::Attribute) ? rel.left : rel.right)
-
subrelation.name == target_value
-
end
-
end
-
-
bind_values.reject! { |col,_| col.name == target_value }
-
end
-
-
2
def custom_join_ast(table, joins)
-
195
joins = joins.reject(&:blank?)
-
-
195
return [] if joins.empty?
-
-
joins.map! do |join|
-
case join
-
when Array
-
join = Arel.sql(join.join(' ')) if array_of_strings?(join)
-
when String
-
join = Arel.sql(join)
-
end
-
table.create_string_join(join)
-
end
-
end
-
-
2
def collapse_wheres(arel, wheres)
-
478
predicates = wheres.map do |where|
-
210
next where if ::Arel::Nodes::Equality === where
-
where = Arel.sql(where) if String === where
-
Arel::Nodes::Grouping.new(where)
-
end
-
-
478
arel.where(Arel::Nodes::And.new(predicates)) if predicates.present?
-
end
-
-
2
def build_where(opts, other = [])
-
354
case opts
-
when String, Array
-
#TODO: Remove duplication with: /activerecord/lib/active_record/sanitization.rb:113
-
values = Hash === other.first ? other.first.values : other
-
-
values.grep(ActiveRecord::Relation) do |rel|
-
self.bind_values += rel.bind_values
-
end
-
-
[@klass.send(:sanitize_sql, other.empty? ? opts : ([opts] + other))]
-
when Hash
-
15
opts = PredicateBuilder.resolve_column_aliases(klass, opts)
-
15
attributes = @klass.send(:expand_hash_conditions_for_aggregates, opts)
-
-
15
add_relations_to_bind_values(attributes)
-
-
15
PredicateBuilder.build_from_hash(klass, attributes, table)
-
else
-
339
[opts]
-
end
-
end
-
-
2
def build_from
-
opts, name = from_value
-
case opts
-
when Relation
-
name ||= 'subquery'
-
self.bind_values = opts.bind_values + self.bind_values
-
opts.arel.as(name.to_s)
-
else
-
opts
-
end
-
end
-
-
2
def build_joins(manager, joins)
-
195
buckets = joins.group_by do |join|
-
195
case join
-
when String
-
:string_join
-
when Hash, Symbol, Array
-
:association_join
-
when ActiveRecord::Associations::JoinDependency
-
195
:stashed_join
-
when Arel::Nodes::Join
-
:join_node
-
else
-
raise 'unknown class: %s' % join.class.name
-
end
-
end
-
-
195
association_joins = buckets[:association_join] || []
-
195
stashed_association_joins = buckets[:stashed_join] || []
-
195
join_nodes = (buckets[:join_node] || []).uniq
-
195
string_joins = (buckets[:string_join] || []).map(&:strip).uniq
-
-
195
join_list = join_nodes + custom_join_ast(manager, string_joins)
-
-
195
join_dependency = ActiveRecord::Associations::JoinDependency.new(
-
@klass,
-
association_joins,
-
join_list
-
)
-
-
195
joins = join_dependency.join_constraints stashed_association_joins
-
-
195
joins.each { |join| manager.from(join) }
-
-
195
manager.join_sources.concat(join_list)
-
-
195
manager
-
end
-
-
2
def build_select(arel, selects)
-
478
if !selects.empty?
-
195
expanded_select = selects.map do |field|
-
195
columns_hash.key?(field.to_s) ? arel_table[field] : field
-
end
-
195
arel.project(*expanded_select)
-
else
-
283
arel.project(@klass.arel_table[Arel.star])
-
end
-
end
-
-
2
def reverse_sql_order(order_query)
-
order_query = ["#{quoted_table_name}.#{quoted_primary_key} ASC"] if order_query.empty?
-
-
order_query.flat_map do |o|
-
case o
-
when Arel::Nodes::Ordering
-
o.reverse
-
when String
-
o.to_s.split(',').map! do |s|
-
s.strip!
-
s.gsub!(/\sasc\Z/i, ' DESC') || s.gsub!(/\sdesc\Z/i, ' ASC') || s.concat(' DESC')
-
end
-
else
-
o
-
end
-
end
-
end
-
-
2
def array_of_strings?(o)
-
o.is_a?(Array) && o.all? { |obj| obj.is_a?(String) }
-
end
-
-
2
def build_order(arel)
-
478
orders = order_values.uniq
-
478
orders.reject!(&:blank?)
-
478
orders = reverse_sql_order(orders) if reverse_order_value
-
-
478
arel.order(*orders) unless orders.empty?
-
end
-
-
2
def validate_order_args(args)
-
args.grep(Hash) do |h|
-
unless (h.values - [:asc, :desc]).empty?
-
raise ArgumentError, 'Direction should be :asc or :desc'
-
end
-
end
-
end
-
-
2
def preprocess_order_args(order_args)
-
order_args.flatten!
-
validate_order_args(order_args)
-
-
references = order_args.grep(String)
-
references.map! { |arg| arg =~ /^([a-zA-Z]\w*)\.(\w+)/ && $1 }.compact!
-
references!(references) if references.any?
-
-
# if a symbol is given we prepend the quoted table name
-
order_args.map! do |arg|
-
case arg
-
when Symbol
-
arg = klass.attribute_alias(arg) if klass.attribute_alias?(arg)
-
table[arg].asc
-
when Hash
-
arg.map { |field, dir|
-
field = klass.attribute_alias(field) if klass.attribute_alias?(field)
-
table[field].send(dir)
-
}
-
else
-
arg
-
end
-
end.flatten!
-
end
-
-
# Checks to make sure that the arguments are not blank. Note that if some
-
# blank-like object were initially passed into the query method, then this
-
# method will not raise an error.
-
#
-
# Example:
-
#
-
# Post.references() # => raises an error
-
# Post.references([]) # => does not raise an error
-
#
-
# This particular method should be called with a method_name and the args
-
# passed into that method as an input. For example:
-
#
-
# def references(*args)
-
# check_if_method_has_arguments!("references", args)
-
# ...
-
# end
-
2
def check_if_method_has_arguments!(method_name, args)
-
195
if args.blank?
-
raise ArgumentError, "The method .#{method_name}() must contain arguments."
-
end
-
end
-
-
# This function is recursive just for better readablity.
-
# #where argument doesn't support more than one level nested hash in real world.
-
2
def add_relations_to_bind_values(attributes)
-
30
if attributes.is_a?(Hash)
-
15
attributes.each_value do |value|
-
15
if value.is_a?(ActiveRecord::Relation)
-
self.bind_values += value.bind_values
-
else
-
15
add_relations_to_bind_values(value)
-
end
-
end
-
end
-
end
-
end
-
end
-
2
require 'active_support/core_ext/hash/except'
-
2
require 'active_support/core_ext/hash/slice'
-
2
require 'active_record/relation/merger'
-
-
2
module ActiveRecord
-
2
module SpawnMethods
-
-
# This is overridden by Associations::CollectionProxy
-
2
def spawn #:nodoc:
-
1098
clone
-
end
-
-
# Merges in the conditions from <tt>other</tt>, if <tt>other</tt> is an <tt>ActiveRecord::Relation</tt>.
-
# Returns an array representing the intersection of the resulting records with <tt>other</tt>, if <tt>other</tt> is an array.
-
# Post.where(published: true).joins(:comments).merge( Comment.where(spam: false) )
-
# # Performs a single join query with both where conditions.
-
#
-
# recent_posts = Post.order('created_at DESC').first(5)
-
# Post.where(published: true).merge(recent_posts)
-
# # Returns the intersection of all published posts with the 5 most recently created posts.
-
# # (This is just an example. You'd probably want to do this with a single query!)
-
#
-
# Procs will be evaluated by merge:
-
#
-
# Post.where(published: true).merge(-> { joins(:comments) })
-
# # => Post.where(published: true).joins(:comments)
-
#
-
# This is mainly intended for sharing common conditions between multiple associations.
-
2
def merge(other)
-
304
if other.is_a?(Array)
-
to_a & other
-
304
elsif other
-
144
spawn.merge!(other)
-
else
-
160
self
-
end
-
end
-
-
2
def merge!(other) # :nodoc:
-
360
if !other.is_a?(Relation) && other.respond_to?(:to_proc)
-
instance_exec(&other)
-
else
-
360
klass = other.is_a?(Hash) ? Relation::HashMerger : Relation::Merger
-
360
klass.new(self, other).merge
-
end
-
end
-
-
# Removes from the query the condition(s) specified in +skips+.
-
#
-
# Post.order('id asc').except(:order) # discards the order condition
-
# Post.where('id > 10').order('id asc').except(:where) # discards the where condition but keeps the order
-
2
def except(*skips)
-
390
relation_with values.except(*skips)
-
end
-
-
# Removes any condition from the query other than the one(s) specified in +onlies+.
-
#
-
# Post.order('id asc').only(:where) # discards the order condition
-
# Post.order('id asc').only(:where, :order) # uses the specified order
-
2
def only(*onlies)
-
relation_with values.slice(*onlies)
-
end
-
-
2
private
-
-
2
def relation_with(values) # :nodoc:
-
390
result = Relation.create(klass, table, values)
-
390
result.extend(*extending_values) if extending_values.any?
-
390
result
-
end
-
end
-
end
-
2
module ActiveRecord
-
###
-
# This class encapsulates a Result returned from calling +exec_query+ on any
-
# database connection adapter. For example:
-
#
-
# result = ActiveRecord::Base.connection.exec_query('SELECT id, title, body FROM posts')
-
# result # => #<ActiveRecord::Result:0xdeadbeef>
-
#
-
# # Get the column names of the result:
-
# result.columns
-
# # => ["id", "title", "body"]
-
#
-
# # Get the record values of the result:
-
# result.rows
-
# # => [[1, "title_1", "body_1"],
-
# [2, "title_2", "body_2"],
-
# ...
-
# ]
-
#
-
# # Get an array of hashes representing the result (column => value):
-
# result.to_hash
-
# # => [{"id" => 1, "title" => "title_1", "body" => "body_1"},
-
# {"id" => 2, "title" => "title_2", "body" => "body_2"},
-
# ...
-
# ]
-
#
-
# # ActiveRecord::Result also includes Enumerable.
-
# result.each do |row|
-
# puts row['title'] + " " + row['body']
-
# end
-
2
class Result
-
2
include Enumerable
-
-
4
IDENTITY_TYPE = Class.new { def type_cast(v); v; end }.new # :nodoc:
-
-
2
attr_reader :columns, :rows, :column_types
-
-
2
def initialize(columns, rows, column_types = {})
-
507
@columns = columns
-
507
@rows = rows
-
507
@hash_rows = nil
-
507
@column_types = column_types
-
end
-
-
2
def identity_type # :nodoc:
-
IDENTITY_TYPE
-
end
-
-
2
def column_type(name)
-
@column_types[name] || identity_type
-
end
-
-
2
def each
-
221
if block_given?
-
263
hash_rows.each { |row| yield row }
-
else
-
hash_rows.to_enum { @rows.size }
-
end
-
end
-
-
2
def to_hash
-
19
hash_rows
-
end
-
-
2
alias :map! :map
-
2
alias :collect! :map
-
-
# Returns true if there are no records.
-
2
def empty?
-
rows.empty?
-
end
-
-
2
def to_ary
-
hash_rows
-
end
-
-
2
def [](idx)
-
hash_rows[idx]
-
end
-
-
2
def last
-
hash_rows.last
-
end
-
-
2
def initialize_copy(other)
-
17
@columns = columns.dup
-
17
@rows = rows.dup
-
17
@column_types = column_types.dup
-
17
@hash_rows = nil
-
end
-
-
2
private
-
-
2
def hash_rows
-
@hash_rows ||=
-
begin
-
# We freeze the strings to prevent them getting duped when
-
# used as keys in ActiveRecord::Base's @attributes hash
-
830
columns = @columns.map { |c| c.dup.freeze }
-
240
@rows.map { |row|
-
# In the past we used Hash[columns.zip(row)]
-
# though elegant, the verbose way is much more efficient
-
# both time and memory wise cause it avoids a big array allocation
-
# this method is called a lot and needs to be micro optimised
-
241
hash = {}
-
-
241
index = 0
-
241
length = columns.length
-
-
241
while index < length
-
1236
hash[columns[index]] = row[index]
-
1236
index += 1
-
end
-
-
241
hash
-
}
-
240
end
-
end
-
end
-
end
-
2
require 'active_support/per_thread_registry'
-
-
2
module ActiveRecord
-
# This is a thread locals registry for Active Record. For example:
-
#
-
# ActiveRecord::RuntimeRegistry.connection_handler
-
#
-
# returns the connection handler local to the current thread.
-
#
-
# See the documentation of <tt>ActiveSupport::PerThreadRegistry</tt>
-
# for further details.
-
2
class RuntimeRegistry # :nodoc:
-
2
extend ActiveSupport::PerThreadRegistry
-
-
2
attr_accessor :connection_handler, :sql_runtime, :connection_id
-
-
2
[:connection_handler, :sql_runtime, :connection_id].each do |val|
-
6
class_eval %{ def self.#{val}; instance.#{val}; end }, __FILE__, __LINE__
-
6
class_eval %{ def self.#{val}=(x); instance.#{val}=x; end }, __FILE__, __LINE__
-
end
-
end
-
end
-
2
module ActiveRecord
-
2
module Sanitization
-
2
extend ActiveSupport::Concern
-
-
2
module ClassMethods
-
2
def quote_value(value, column) #:nodoc:
-
connection.quote(value, column)
-
end
-
-
# Used to sanitize objects before they're used in an SQL SELECT statement. Delegates to <tt>connection.quote</tt>.
-
2
def sanitize(object) #:nodoc:
-
connection.quote(object)
-
end
-
-
2
protected
-
-
# Accepts an array, hash, or string of SQL conditions and sanitizes
-
# them into a valid SQL fragment for a WHERE clause.
-
# ["name='%s' and group_id='%s'", "foo'bar", 4] returns "name='foo''bar' and group_id='4'"
-
# { name: "foo'bar", group_id: 4 } returns "name='foo''bar' and group_id='4'"
-
# "name='foo''bar' and group_id='4'" returns "name='foo''bar' and group_id='4'"
-
2
def sanitize_sql_for_conditions(condition, table_name = self.table_name)
-
16
return nil if condition.blank?
-
-
16
case condition
-
when Array; sanitize_sql_array(condition)
-
when Hash; sanitize_sql_hash_for_conditions(condition, table_name)
-
16
else condition
-
end
-
end
-
2
alias_method :sanitize_sql, :sanitize_sql_for_conditions
-
2
alias_method :sanitize_conditions, :sanitize_sql
-
-
# Accepts an array, hash, or string of SQL conditions and sanitizes
-
# them into a valid SQL fragment for a SET clause.
-
# { name: nil, group_id: 4 } returns "name = NULL , group_id='4'"
-
2
def sanitize_sql_for_assignment(assignments, default_table_name = self.table_name)
-
case assignments
-
when Array; sanitize_sql_array(assignments)
-
when Hash; sanitize_sql_hash_for_assignment(assignments, default_table_name)
-
else assignments
-
end
-
end
-
-
# Accepts a hash of SQL conditions and replaces those attributes
-
# that correspond to a +composed_of+ relationship with their expanded
-
# aggregate attribute values.
-
# Given:
-
# class Person < ActiveRecord::Base
-
# composed_of :address, class_name: "Address",
-
# mapping: [%w(address_street street), %w(address_city city)]
-
# end
-
# Then:
-
# { address: Address.new("813 abc st.", "chicago") }
-
# # => { address_street: "813 abc st.", address_city: "chicago" }
-
2
def expand_hash_conditions_for_aggregates(attrs)
-
15
expanded_attrs = {}
-
15
attrs.each do |attr, value|
-
15
if aggregation = reflect_on_aggregation(attr.to_sym)
-
mapping = aggregation.mapping
-
mapping.each do |field_attr, aggregate_attr|
-
if mapping.size == 1 && !value.respond_to?(aggregate_attr)
-
expanded_attrs[field_attr] = value
-
else
-
expanded_attrs[field_attr] = value.send(aggregate_attr)
-
end
-
end
-
else
-
15
expanded_attrs[attr] = value
-
end
-
end
-
15
expanded_attrs
-
end
-
-
# Sanitizes a hash of attribute/value pairs into SQL conditions for a WHERE clause.
-
# { name: "foo'bar", group_id: 4 }
-
# # => "name='foo''bar' and group_id= 4"
-
# { status: nil, group_id: [1,2,3] }
-
# # => "status IS NULL and group_id IN (1,2,3)"
-
# { age: 13..18 }
-
# # => "age BETWEEN 13 AND 18"
-
# { 'other_records.id' => 7 }
-
# # => "`other_records`.`id` = 7"
-
# { other_records: { id: 7 } }
-
# # => "`other_records`.`id` = 7"
-
# And for value objects on a composed_of relationship:
-
# { address: Address.new("123 abc st.", "chicago") }
-
# # => "address_street='123 abc st.' and address_city='chicago'"
-
2
def sanitize_sql_hash_for_conditions(attrs, default_table_name = self.table_name)
-
attrs = PredicateBuilder.resolve_column_aliases self, attrs
-
attrs = expand_hash_conditions_for_aggregates(attrs)
-
-
table = Arel::Table.new(table_name, arel_engine).alias(default_table_name)
-
PredicateBuilder.build_from_hash(self, attrs, table).map { |b|
-
connection.visitor.accept b
-
}.join(' AND ')
-
end
-
2
alias_method :sanitize_sql_hash, :sanitize_sql_hash_for_conditions
-
-
# Sanitizes a hash of attribute/value pairs into SQL conditions for a SET clause.
-
# { status: nil, group_id: 1 }
-
# # => "status = NULL , group_id = 1"
-
2
def sanitize_sql_hash_for_assignment(attrs, table)
-
c = connection
-
attrs.map do |attr, value|
-
"#{c.quote_table_name_for_assignment(table, attr)} = #{quote_bound_value(value, c, columns_hash[attr.to_s])}"
-
end.join(', ')
-
end
-
-
# Accepts an array of conditions. The array has each value
-
# sanitized and interpolated into the SQL statement.
-
# ["name='%s' and group_id='%s'", "foo'bar", 4] returns "name='foo''bar' and group_id='4'"
-
2
def sanitize_sql_array(ary)
-
statement, *values = ary
-
if values.first.is_a?(Hash) && statement =~ /:\w+/
-
replace_named_bind_variables(statement, values.first)
-
elsif statement.include?('?')
-
replace_bind_variables(statement, values)
-
elsif statement.blank?
-
statement
-
else
-
statement % values.collect { |value| connection.quote_string(value.to_s) }
-
end
-
end
-
-
2
def replace_bind_variables(statement, values) #:nodoc:
-
raise_if_bind_arity_mismatch(statement, statement.count('?'), values.size)
-
bound = values.dup
-
c = connection
-
statement.gsub('?') do
-
replace_bind_variable(bound.shift, c)
-
end
-
end
-
-
2
def replace_bind_variable(value, c = connection) #:nodoc:
-
if ActiveRecord::Relation === value
-
value.to_sql
-
else
-
quote_bound_value(value, c)
-
end
-
end
-
-
2
def replace_named_bind_variables(statement, bind_vars) #:nodoc:
-
statement.gsub(/(:?):([a-zA-Z]\w*)/) do
-
if $1 == ':' # skip postgresql casts
-
$& # return the whole match
-
elsif bind_vars.include?(match = $2.to_sym)
-
replace_bind_variable(bind_vars[match])
-
else
-
raise PreparedStatementInvalid, "missing value for :#{match} in #{statement}"
-
end
-
end
-
end
-
-
2
def quote_bound_value(value, c = connection, column = nil) #:nodoc:
-
if column
-
c.quote(value, column)
-
elsif value.respond_to?(:map) && !value.acts_like?(:string)
-
if value.respond_to?(:empty?) && value.empty?
-
c.quote(nil)
-
else
-
value.map { |v| c.quote(v) }.join(',')
-
end
-
else
-
c.quote(value)
-
end
-
end
-
-
2
def raise_if_bind_arity_mismatch(statement, expected, provided) #:nodoc:
-
unless expected == provided
-
raise PreparedStatementInvalid, "wrong number of bind variables (#{provided} for #{expected}) in: #{statement}"
-
end
-
end
-
end
-
-
# TODO: Deprecate this
-
2
def quoted_id
-
self.class.quote_value(id, column_for_attribute(self.class.primary_key))
-
end
-
end
-
end
-
1
require 'active_record/scoping/default'
-
1
require 'active_record/scoping/named'
-
1
require 'active_record/base'
-
-
1
module ActiveRecord
-
1
class SchemaMigration < ActiveRecord::Base
-
1
class << self
-
1
def primary_key
-
nil
-
end
-
-
1
def table_name
-
4
"#{table_name_prefix}#{ActiveRecord::Base.schema_migrations_table_name}#{table_name_suffix}"
-
end
-
-
1
def index_name
-
"#{table_name_prefix}unique_#{ActiveRecord::Base.schema_migrations_table_name}#{table_name_suffix}"
-
end
-
-
1
def table_exists?
-
connection.table_exists?(table_name)
-
end
-
-
1
def create_table(limit=nil)
-
unless table_exists?
-
version_options = {null: false}
-
version_options[:limit] = limit if limit
-
-
connection.create_table(table_name, id: false) do |t|
-
t.column :version, :string, version_options
-
end
-
connection.add_index table_name, :version, unique: true, name: index_name
-
end
-
end
-
-
1
def drop_table
-
if table_exists?
-
connection.remove_index table_name, name: index_name
-
connection.drop_table(table_name)
-
end
-
end
-
-
1
def normalize_migration_number(number)
-
"%.3d" % number.to_i
-
end
-
end
-
-
1
def version
-
32
super.to_i
-
end
-
end
-
end
-
2
require 'active_support/per_thread_registry'
-
-
2
module ActiveRecord
-
2
module Scoping
-
2
extend ActiveSupport::Concern
-
-
2
included do
-
2
include Default
-
2
include Named
-
end
-
-
2
module ClassMethods
-
2
def current_scope #:nodoc:
-
634
ScopeRegistry.value_for(:current_scope, base_class.to_s)
-
end
-
-
2
def current_scope=(scope) #:nodoc:
-
390
ScopeRegistry.set_value_for(:current_scope, base_class.to_s, scope)
-
end
-
end
-
-
2
def populate_with_current_scope_attributes
-
279
return unless self.class.scope_attributes?
-
-
self.class.scope_attributes.each do |att,value|
-
send("#{att}=", value) if respond_to?("#{att}=")
-
end
-
end
-
-
2
def initialize_internals_callback
-
279
super
-
279
populate_with_current_scope_attributes
-
end
-
-
# This class stores the +:current_scope+ and +:ignore_default_scope+ values
-
# for different classes. The registry is stored as a thread local, which is
-
# accessed through +ScopeRegistry.current+.
-
#
-
# This class allows you to store and get the scope values on different
-
# classes and different types of scopes. For example, if you are attempting
-
# to get the current_scope for the +Board+ model, then you would use the
-
# following code:
-
#
-
# registry = ActiveRecord::Scoping::ScopeRegistry
-
# registry.set_value_for(:current_scope, "Board", some_new_scope)
-
#
-
# Now when you run:
-
#
-
# registry.value_for(:current_scope, "Board")
-
#
-
# You will obtain whatever was defined in +some_new_scope+. The +value_for+
-
# and +set_value_for+ methods are delegated to the current +ScopeRegistry+
-
# object, so the above example code can also be called as:
-
#
-
# ActiveRecord::Scoping::ScopeRegistry.set_value_for(:current_scope,
-
# "Board", some_new_scope)
-
2
class ScopeRegistry # :nodoc:
-
2
extend ActiveSupport::PerThreadRegistry
-
-
2
VALID_SCOPE_TYPES = [:current_scope, :ignore_default_scope]
-
-
2
def initialize
-
4
@registry = Hash.new { |hash, key| hash[key] = {} }
-
end
-
-
# Obtains the value for a given +scope_name+ and +variable_name+.
-
2
def value_for(scope_type, variable_name)
-
634
raise_invalid_scope_type!(scope_type)
-
634
@registry[scope_type][variable_name]
-
end
-
-
# Sets the +value+ for a given +scope_type+ and +variable_name+.
-
2
def set_value_for(scope_type, variable_name, value)
-
390
raise_invalid_scope_type!(scope_type)
-
390
@registry[scope_type][variable_name] = value
-
end
-
-
2
private
-
-
2
def raise_invalid_scope_type!(scope_type)
-
1024
if !VALID_SCOPE_TYPES.include?(scope_type)
-
raise ArgumentError, "Invalid scope type '#{scope_type}' sent to the registry. Scope types must be included in VALID_SCOPE_TYPES"
-
end
-
end
-
end
-
end
-
end
-
2
module ActiveRecord
-
2
module Scoping
-
2
module Default
-
2
extend ActiveSupport::Concern
-
-
2
included do
-
# Stores the default scope for the class.
-
2
class_attribute :default_scopes, instance_writer: false, instance_predicate: false
-
-
2
self.default_scopes = []
-
end
-
-
2
module ClassMethods
-
# Returns a scope for the model without the +default_scope+.
-
#
-
# class Post < ActiveRecord::Base
-
# def self.default_scope
-
# where published: true
-
# end
-
# end
-
#
-
# Post.all # Fires "SELECT * FROM posts WHERE published = true"
-
# Post.unscoped.all # Fires "SELECT * FROM posts"
-
#
-
# This method also accepts a block. All queries inside the block will
-
# not use the +default_scope+:
-
#
-
# Post.unscoped {
-
# Post.limit(10) # Fires "SELECT * FROM posts LIMIT 10"
-
# }
-
2
def unscoped
-
534
block_given? ? relation.scoping { yield } : relation
-
end
-
-
2
def before_remove_const #:nodoc:
-
self.current_scope = nil
-
end
-
-
2
protected
-
-
# Use this macro in your model to set a default scope for all operations on
-
# the model.
-
#
-
# class Article < ActiveRecord::Base
-
# default_scope { where(published: true) }
-
# end
-
#
-
# Article.all # => SELECT * FROM articles WHERE published = true
-
#
-
# The +default_scope+ is also applied while creating/building a record.
-
# It is not applied while updating a record.
-
#
-
# Article.new.published # => true
-
# Article.create.published # => true
-
#
-
# (You can also pass any object which responds to +call+ to the
-
# +default_scope+ macro, and it will be called when building the
-
# default scope.)
-
#
-
# If you use multiple +default_scope+ declarations in your model then
-
# they will be merged together:
-
#
-
# class Article < ActiveRecord::Base
-
# default_scope { where(published: true) }
-
# default_scope { where(rating: 'G') }
-
# end
-
#
-
# Article.all # => SELECT * FROM articles WHERE published = true AND rating = 'G'
-
#
-
# This is also the case with inheritance and module includes where the
-
# parent or module defines a +default_scope+ and the child or including
-
# class defines a second one.
-
#
-
# If you need to do more complex things with a default scope, you can
-
# alternatively define it as a class method:
-
#
-
# class Article < ActiveRecord::Base
-
# def self.default_scope
-
# # Should return a scope, you can call 'super' here etc.
-
# end
-
# end
-
2
def default_scope(scope = nil)
-
scope = Proc.new if block_given?
-
-
if scope.is_a?(Relation) || !scope.respond_to?(:call)
-
raise ArgumentError,
-
"Support for calling #default_scope without a block is removed. For example instead " \
-
"of `default_scope where(color: 'red')`, please use " \
-
"`default_scope { where(color: 'red') }`. (Alternatively you can just redefine " \
-
"self.default_scope.)"
-
end
-
-
self.default_scopes += [scope]
-
end
-
-
2
def build_default_scope(base_rel = relation) # :nodoc:
-
160
if !Base.is_a?(method(:default_scope).owner)
-
# The user has defined their own default scope method, so call that
-
evaluate_default_scope { default_scope }
-
160
elsif default_scopes.any?
-
evaluate_default_scope do
-
default_scopes.inject(base_rel) do |default_scope, scope|
-
default_scope.merge(base_rel.scoping { scope.call })
-
end
-
end
-
end
-
end
-
-
2
def ignore_default_scope? # :nodoc:
-
ScopeRegistry.value_for(:ignore_default_scope, self)
-
end
-
-
2
def ignore_default_scope=(ignore) # :nodoc:
-
ScopeRegistry.set_value_for(:ignore_default_scope, self, ignore)
-
end
-
-
# The ignore_default_scope flag is used to prevent an infinite recursion
-
# situation where a default scope references a scope which has a default
-
# scope which references a scope...
-
2
def evaluate_default_scope # :nodoc:
-
return if ignore_default_scope?
-
-
begin
-
self.ignore_default_scope = true
-
yield
-
ensure
-
self.ignore_default_scope = false
-
end
-
end
-
end
-
end
-
end
-
end
-
2
require 'active_support/core_ext/array'
-
2
require 'active_support/core_ext/hash/except'
-
2
require 'active_support/core_ext/kernel/singleton_class'
-
-
2
module ActiveRecord
-
# = Active Record \Named \Scopes
-
2
module Scoping
-
2
module Named
-
2
extend ActiveSupport::Concern
-
-
2
module ClassMethods
-
# Returns an <tt>ActiveRecord::Relation</tt> scope object.
-
#
-
# posts = Post.all
-
# posts.size # Fires "select count(*) from posts" and returns the count
-
# posts.each {|p| puts p.name } # Fires "select * from posts" and loads post objects
-
#
-
# fruits = Fruit.all
-
# fruits = fruits.where(color: 'red') if options[:red_only]
-
# fruits = fruits.limit(10) if limited?
-
#
-
# You can define a scope that applies to all finders using
-
# <tt>ActiveRecord::Base.default_scope</tt>.
-
2
def all
-
160
if current_scope
-
current_scope.clone
-
else
-
160
default_scoped
-
end
-
end
-
-
2
def default_scoped # :nodoc:
-
160
relation.merge(build_default_scope)
-
end
-
-
# Collects attributes from scopes that should be applied when creating
-
# an AR instance for the particular class this is called on.
-
2
def scope_attributes # :nodoc:
-
all.scope_for_create
-
end
-
-
# Are there default attributes associated with this scope?
-
2
def scope_attributes? # :nodoc:
-
279
current_scope || default_scopes.any?
-
end
-
-
# Adds a class method for retrieving and querying objects. A \scope
-
# represents a narrowing of a database query, such as
-
# <tt>where(color: :red).select('shirts.*').includes(:washing_instructions)</tt>.
-
#
-
# class Shirt < ActiveRecord::Base
-
# scope :red, -> { where(color: 'red') }
-
# scope :dry_clean_only, -> { joins(:washing_instructions).where('washing_instructions.dry_clean_only = ?', true) }
-
# end
-
#
-
# The above calls to +scope+ define class methods <tt>Shirt.red</tt> and
-
# <tt>Shirt.dry_clean_only</tt>. <tt>Shirt.red</tt>, in effect,
-
# represents the query <tt>Shirt.where(color: 'red')</tt>.
-
#
-
# You should always pass a callable object to the scopes defined
-
# with +scope+. This ensures that the scope is re-evaluated each
-
# time it is called.
-
#
-
# Note that this is simply 'syntactic sugar' for defining an actual
-
# class method:
-
#
-
# class Shirt < ActiveRecord::Base
-
# def self.red
-
# where(color: 'red')
-
# end
-
# end
-
#
-
# Unlike <tt>Shirt.find(...)</tt>, however, the object returned by
-
# <tt>Shirt.red</tt> is not an Array; it resembles the association object
-
# constructed by a +has_many+ declaration. For instance, you can invoke
-
# <tt>Shirt.red.first</tt>, <tt>Shirt.red.count</tt>,
-
# <tt>Shirt.red.where(size: 'small')</tt>. Also, just as with the
-
# association objects, named \scopes act like an Array, implementing
-
# Enumerable; <tt>Shirt.red.each(&block)</tt>, <tt>Shirt.red.first</tt>,
-
# and <tt>Shirt.red.inject(memo, &block)</tt> all behave as if
-
# <tt>Shirt.red</tt> really was an Array.
-
#
-
# These named \scopes are composable. For instance,
-
# <tt>Shirt.red.dry_clean_only</tt> will produce all shirts that are
-
# both red and dry clean only. Nested finds and calculations also work
-
# with these compositions: <tt>Shirt.red.dry_clean_only.count</tt>
-
# returns the number of garments for which these criteria obtain.
-
# Similarly with <tt>Shirt.red.dry_clean_only.average(:thread_count)</tt>.
-
#
-
# All scopes are available as class methods on the ActiveRecord::Base
-
# descendant upon which the \scopes were defined. But they are also
-
# available to +has_many+ associations. If,
-
#
-
# class Person < ActiveRecord::Base
-
# has_many :shirts
-
# end
-
#
-
# then <tt>elton.shirts.red.dry_clean_only</tt> will return all of
-
# Elton's red, dry clean only shirts.
-
#
-
# \Named scopes can also have extensions, just as with +has_many+
-
# declarations:
-
#
-
# class Shirt < ActiveRecord::Base
-
# scope :red, -> { where(color: 'red') } do
-
# def dom_id
-
# 'red_shirts'
-
# end
-
# end
-
# end
-
#
-
# Scopes can also be used while creating/building a record.
-
#
-
# class Article < ActiveRecord::Base
-
# scope :published, -> { where(published: true) }
-
# end
-
#
-
# Article.published.new.published # => true
-
# Article.published.create.published # => true
-
#
-
# \Class methods on your model are automatically available
-
# on scopes. Assuming the following setup:
-
#
-
# class Article < ActiveRecord::Base
-
# scope :published, -> { where(published: true) }
-
# scope :featured, -> { where(featured: true) }
-
#
-
# def self.latest_article
-
# order('published_at desc').first
-
# end
-
#
-
# def self.titles
-
# pluck(:title)
-
# end
-
# end
-
#
-
# We are able to call the methods like this:
-
#
-
# Article.published.featured.latest_article
-
# Article.featured.titles
-
2
def scope(name, body, &block)
-
if dangerous_class_method?(name)
-
raise ArgumentError, "You tried to define a scope named \"#{name}\" " \
-
"on the model \"#{self.name}\", but Active Record already defined " \
-
"a class method with the same name."
-
end
-
-
extension = Module.new(&block) if block
-
-
singleton_class.send(:define_method, name) do |*args|
-
scope = all.scoping { body.call(*args) }
-
scope = scope.extending(extension) if extension
-
-
scope || all
-
end
-
end
-
end
-
end
-
end
-
end
-
2
module ActiveRecord #:nodoc:
-
# = Active Record Serialization
-
2
module Serialization
-
2
extend ActiveSupport::Concern
-
2
include ActiveModel::Serializers::JSON
-
-
2
included do
-
2
self.include_root_in_json = false
-
end
-
-
2
def serializable_hash(options = nil)
-
options = options.try(:clone) || {}
-
-
options[:except] = Array(options[:except]).map { |n| n.to_s }
-
options[:except] |= Array(self.class.inheritance_column)
-
-
super(options)
-
end
-
end
-
end
-
-
2
require 'active_record/serializers/xml_serializer'
-
2
require 'active_support/core_ext/hash/conversions'
-
-
2
module ActiveRecord #:nodoc:
-
2
module Serialization
-
2
include ActiveModel::Serializers::Xml
-
-
# Builds an XML document to represent the model. Some configuration is
-
# available through +options+. However more complicated cases should
-
# override ActiveRecord::Base#to_xml.
-
#
-
# By default the generated XML document will include the processing
-
# instruction and all the object's attributes. For example:
-
#
-
# <?xml version="1.0" encoding="UTF-8"?>
-
# <topic>
-
# <title>The First Topic</title>
-
# <author-name>David</author-name>
-
# <id type="integer">1</id>
-
# <approved type="boolean">false</approved>
-
# <replies-count type="integer">0</replies-count>
-
# <bonus-time type="dateTime">2000-01-01T08:28:00+12:00</bonus-time>
-
# <written-on type="dateTime">2003-07-16T09:28:00+1200</written-on>
-
# <content>Have a nice day</content>
-
# <author-email-address>david@loudthinking.com</author-email-address>
-
# <parent-id></parent-id>
-
# <last-read type="date">2004-04-15</last-read>
-
# </topic>
-
#
-
# This behavior can be controlled with <tt>:only</tt>, <tt>:except</tt>,
-
# <tt>:skip_instruct</tt>, <tt>:skip_types</tt>, <tt>:dasherize</tt> and <tt>:camelize</tt> .
-
# The <tt>:only</tt> and <tt>:except</tt> options are the same as for the
-
# +attributes+ method. The default is to dasherize all column names, but you
-
# can disable this setting <tt>:dasherize</tt> to +false+. Setting <tt>:camelize</tt>
-
# to +true+ will camelize all column names - this also overrides <tt>:dasherize</tt>.
-
# To not have the column type included in the XML output set <tt>:skip_types</tt> to +true+.
-
#
-
# For instance:
-
#
-
# topic.to_xml(skip_instruct: true, except: [ :id, :bonus_time, :written_on, :replies_count ])
-
#
-
# <topic>
-
# <title>The First Topic</title>
-
# <author-name>David</author-name>
-
# <approved type="boolean">false</approved>
-
# <content>Have a nice day</content>
-
# <author-email-address>david@loudthinking.com</author-email-address>
-
# <parent-id></parent-id>
-
# <last-read type="date">2004-04-15</last-read>
-
# </topic>
-
#
-
# To include first level associations use <tt>:include</tt>:
-
#
-
# firm.to_xml include: [ :account, :clients ]
-
#
-
# <?xml version="1.0" encoding="UTF-8"?>
-
# <firm>
-
# <id type="integer">1</id>
-
# <rating type="integer">1</rating>
-
# <name>37signals</name>
-
# <clients type="array">
-
# <client>
-
# <rating type="integer">1</rating>
-
# <name>Summit</name>
-
# </client>
-
# <client>
-
# <rating type="integer">1</rating>
-
# <name>Microsoft</name>
-
# </client>
-
# </clients>
-
# <account>
-
# <id type="integer">1</id>
-
# <credit-limit type="integer">50</credit-limit>
-
# </account>
-
# </firm>
-
#
-
# Additionally, the record being serialized will be passed to a Proc's second
-
# parameter. This allows for ad hoc additions to the resultant document that
-
# incorporate the context of the record being serialized. And by leveraging the
-
# closure created by a Proc, to_xml can be used to add elements that normally fall
-
# outside of the scope of the model -- for example, generating and appending URLs
-
# associated with models.
-
#
-
# proc = Proc.new { |options, record| options[:builder].tag!('name-reverse', record.name.reverse) }
-
# firm.to_xml procs: [ proc ]
-
#
-
# <firm>
-
# # ... normal attributes as shown above ...
-
# <name-reverse>slangis73</name-reverse>
-
# </firm>
-
#
-
# To include deeper levels of associations pass a hash like this:
-
#
-
# firm.to_xml include: {account: {}, clients: {include: :address}}
-
# <?xml version="1.0" encoding="UTF-8"?>
-
# <firm>
-
# <id type="integer">1</id>
-
# <rating type="integer">1</rating>
-
# <name>37signals</name>
-
# <clients type="array">
-
# <client>
-
# <rating type="integer">1</rating>
-
# <name>Summit</name>
-
# <address>
-
# ...
-
# </address>
-
# </client>
-
# <client>
-
# <rating type="integer">1</rating>
-
# <name>Microsoft</name>
-
# <address>
-
# ...
-
# </address>
-
# </client>
-
# </clients>
-
# <account>
-
# <id type="integer">1</id>
-
# <credit-limit type="integer">50</credit-limit>
-
# </account>
-
# </firm>
-
#
-
# To include any methods on the model being called use <tt>:methods</tt>:
-
#
-
# firm.to_xml methods: [ :calculated_earnings, :real_earnings ]
-
#
-
# <firm>
-
# # ... normal attributes as shown above ...
-
# <calculated-earnings>100000000000000000</calculated-earnings>
-
# <real-earnings>5</real-earnings>
-
# </firm>
-
#
-
# To call any additional Procs use <tt>:procs</tt>. The Procs are passed a
-
# modified version of the options hash that was given to +to_xml+:
-
#
-
# proc = Proc.new { |options| options[:builder].tag!('abc', 'def') }
-
# firm.to_xml procs: [ proc ]
-
#
-
# <firm>
-
# # ... normal attributes as shown above ...
-
# <abc>def</abc>
-
# </firm>
-
#
-
# Alternatively, you can yield the builder object as part of the +to_xml+ call:
-
#
-
# firm.to_xml do |xml|
-
# xml.creator do
-
# xml.first_name "David"
-
# xml.last_name "Heinemeier Hansson"
-
# end
-
# end
-
#
-
# <firm>
-
# # ... normal attributes as shown above ...
-
# <creator>
-
# <first_name>David</first_name>
-
# <last_name>Heinemeier Hansson</last_name>
-
# </creator>
-
# </firm>
-
#
-
# As noted above, you may override +to_xml+ in your ActiveRecord::Base
-
# subclasses to have complete control about what's generated. The general
-
# form of doing this is:
-
#
-
# class IHaveMyOwnXML < ActiveRecord::Base
-
# def to_xml(options = {})
-
# require 'builder'
-
# options[:indent] ||= 2
-
# xml = options[:builder] ||= ::Builder::XmlMarkup.new(indent: options[:indent])
-
# xml.instruct! unless options[:skip_instruct]
-
# xml.level_one do
-
# xml.tag!(:second_level, 'content')
-
# end
-
# end
-
# end
-
2
def to_xml(options = {}, &block)
-
XmlSerializer.new(self, options).serialize(&block)
-
end
-
end
-
-
2
class XmlSerializer < ActiveModel::Serializers::Xml::Serializer #:nodoc:
-
2
class Attribute < ActiveModel::Serializers::Xml::Serializer::Attribute #:nodoc:
-
2
def compute_type
-
klass = @serializable.class
-
type = if klass.serialized_attributes.key?(name)
-
super
-
elsif klass.columns_hash.key?(name)
-
klass.columns_hash[name].type
-
else
-
NilClass
-
end
-
-
{ :text => :string,
-
:time => :datetime }[type] || type
-
end
-
2
protected :compute_type
-
end
-
end
-
end
-
2
require 'active_support/core_ext/hash/indifferent_access'
-
-
2
module ActiveRecord
-
# Store gives you a thin wrapper around serialize for the purpose of storing hashes in a single column.
-
# It's like a simple key/value store baked into your record when you don't care about being able to
-
# query that store outside the context of a single record.
-
#
-
# You can then declare accessors to this store that are then accessible just like any other attribute
-
# of the model. This is very helpful for easily exposing store keys to a form or elsewhere that's
-
# already built around just accessing attributes on the model.
-
#
-
# Make sure that you declare the database column used for the serialized store as a text, so there's
-
# plenty of room.
-
#
-
# You can set custom coder to encode/decode your serialized attributes to/from different formats.
-
# JSON, YAML, Marshal are supported out of the box. Generally it can be any wrapper that provides +load+ and +dump+.
-
#
-
# NOTE - If you are using PostgreSQL specific columns like +hstore+ or +json+ there is no need for
-
# the serialization provided by +store+. Simply use +store_accessor+ instead to generate
-
# the accessor methods. Be aware that these columns use a string keyed hash and do not allow access
-
# using a symbol.
-
#
-
# Examples:
-
#
-
# class User < ActiveRecord::Base
-
# store :settings, accessors: [ :color, :homepage ], coder: JSON
-
# end
-
#
-
# u = User.new(color: 'black', homepage: '37signals.com')
-
# u.color # Accessor stored attribute
-
# u.settings[:country] = 'Denmark' # Any attribute, even if not specified with an accessor
-
#
-
# # There is no difference between strings and symbols for accessing custom attributes
-
# u.settings[:country] # => 'Denmark'
-
# u.settings['country'] # => 'Denmark'
-
#
-
# # Add additional accessors to an existing store through store_accessor
-
# class SuperUser < User
-
# store_accessor :settings, :privileges, :servants
-
# end
-
#
-
# The stored attribute names can be retrieved using +stored_attributes+.
-
#
-
# User.stored_attributes[:settings] # [:color, :homepage]
-
#
-
# == Overwriting default accessors
-
#
-
# All stored values are automatically available through accessors on the Active Record
-
# object, but sometimes you want to specialize this behavior. This can be done by overwriting
-
# the default accessors (using the same name as the attribute) and calling <tt>super</tt>
-
# to actually change things.
-
#
-
# class Song < ActiveRecord::Base
-
# # Uses a stored integer to hold the volume adjustment of the song
-
# store :settings, accessors: [:volume_adjustment]
-
#
-
# def volume_adjustment=(decibels)
-
# super(decibels.to_i)
-
# end
-
#
-
# def volume_adjustment
-
# super.to_i
-
# end
-
# end
-
2
module Store
-
2
extend ActiveSupport::Concern
-
-
2
included do
-
2
class << self
-
2
attr_accessor :local_stored_attributes
-
end
-
end
-
-
2
module ClassMethods
-
2
def store(store_attribute, options = {})
-
serialize store_attribute, IndifferentCoder.new(options[:coder])
-
store_accessor(store_attribute, options[:accessors]) if options.has_key? :accessors
-
end
-
-
2
def store_accessor(store_attribute, *keys)
-
keys = keys.flatten
-
-
_store_accessors_module.module_eval do
-
keys.each do |key|
-
define_method("#{key}=") do |value|
-
write_store_attribute(store_attribute, key, value)
-
end
-
-
define_method(key) do
-
read_store_attribute(store_attribute, key)
-
end
-
end
-
end
-
-
# assign new store attribute and create new hash to ensure that each class in the hierarchy
-
# has its own hash of stored attributes.
-
self.local_stored_attributes ||= {}
-
self.local_stored_attributes[store_attribute] ||= []
-
self.local_stored_attributes[store_attribute] |= keys
-
end
-
-
2
def _store_accessors_module
-
@_store_accessors_module ||= begin
-
mod = Module.new
-
include mod
-
mod
-
end
-
end
-
-
2
def stored_attributes
-
parent = superclass.respond_to?(:stored_attributes) ? superclass.stored_attributes : {}
-
if self.local_stored_attributes
-
parent.merge!(self.local_stored_attributes) { |k, a, b| a | b }
-
end
-
parent
-
end
-
end
-
-
2
protected
-
2
def read_store_attribute(store_attribute, key)
-
accessor = store_accessor_for(store_attribute)
-
accessor.read(self, store_attribute, key)
-
end
-
-
2
def write_store_attribute(store_attribute, key, value)
-
accessor = store_accessor_for(store_attribute)
-
accessor.write(self, store_attribute, key, value)
-
end
-
-
2
private
-
2
def store_accessor_for(store_attribute)
-
@column_types[store_attribute.to_s].accessor
-
end
-
-
2
class HashAccessor
-
2
def self.read(object, attribute, key)
-
prepare(object, attribute)
-
object.public_send(attribute)[key]
-
end
-
-
2
def self.write(object, attribute, key, value)
-
prepare(object, attribute)
-
if value != read(object, attribute, key)
-
object.public_send :"#{attribute}_will_change!"
-
object.public_send(attribute)[key] = value
-
end
-
end
-
-
2
def self.prepare(object, attribute)
-
object.public_send :"#{attribute}=", {} unless object.send(attribute)
-
end
-
end
-
-
2
class StringKeyedHashAccessor < HashAccessor
-
2
def self.read(object, attribute, key)
-
super object, attribute, key.to_s
-
end
-
-
2
def self.write(object, attribute, key, value)
-
super object, attribute, key.to_s, value
-
end
-
end
-
-
2
class IndifferentHashAccessor < ActiveRecord::Store::HashAccessor
-
2
def self.prepare(object, store_attribute)
-
attribute = object.send(store_attribute)
-
unless attribute.is_a?(ActiveSupport::HashWithIndifferentAccess)
-
attribute = IndifferentCoder.as_indifferent_hash(attribute)
-
object.send :"#{store_attribute}=", attribute
-
end
-
attribute
-
end
-
end
-
-
2
class IndifferentCoder # :nodoc:
-
2
def initialize(coder_or_class_name)
-
@coder =
-
if coder_or_class_name.respond_to?(:load) && coder_or_class_name.respond_to?(:dump)
-
coder_or_class_name
-
else
-
ActiveRecord::Coders::YAMLColumn.new(coder_or_class_name || Object)
-
end
-
end
-
-
2
def dump(obj)
-
@coder.dump self.class.as_indifferent_hash(obj)
-
end
-
-
2
def load(yaml)
-
self.class.as_indifferent_hash(@coder.load(yaml || ''))
-
end
-
-
2
def self.as_indifferent_hash(obj)
-
case obj
-
when ActiveSupport::HashWithIndifferentAccess
-
obj
-
when Hash
-
obj.with_indifferent_access
-
else
-
ActiveSupport::HashWithIndifferentAccess.new
-
end
-
end
-
end
-
end
-
end
-
2
require 'thread'
-
-
2
module ActiveRecord
-
# See ActiveRecord::Transactions::ClassMethods for documentation.
-
2
module Transactions
-
2
extend ActiveSupport::Concern
-
2
ACTIONS = [:create, :destroy, :update]
-
-
2
included do
-
2
define_callbacks :commit, :rollback,
-
terminator: ->(_, result) { result == false },
-
scope: [:kind, :name]
-
end
-
-
# = Active Record Transactions
-
#
-
# Transactions are protective blocks where SQL statements are only permanent
-
# if they can all succeed as one atomic action. The classic example is a
-
# transfer between two accounts where you can only have a deposit if the
-
# withdrawal succeeded and vice versa. Transactions enforce the integrity of
-
# the database and guard the data against program errors or database
-
# break-downs. So basically you should use transaction blocks whenever you
-
# have a number of statements that must be executed together or not at all.
-
#
-
# For example:
-
#
-
# ActiveRecord::Base.transaction do
-
# david.withdrawal(100)
-
# mary.deposit(100)
-
# end
-
#
-
# This example will only take money from David and give it to Mary if neither
-
# +withdrawal+ nor +deposit+ raise an exception. Exceptions will force a
-
# ROLLBACK that returns the database to the state before the transaction
-
# began. Be aware, though, that the objects will _not_ have their instance
-
# data returned to their pre-transactional state.
-
#
-
# == Different Active Record classes in a single transaction
-
#
-
# Though the transaction class method is called on some Active Record class,
-
# the objects within the transaction block need not all be instances of
-
# that class. This is because transactions are per-database connection, not
-
# per-model.
-
#
-
# In this example a +balance+ record is transactionally saved even
-
# though +transaction+ is called on the +Account+ class:
-
#
-
# Account.transaction do
-
# balance.save!
-
# account.save!
-
# end
-
#
-
# The +transaction+ method is also available as a model instance method.
-
# For example, you can also do this:
-
#
-
# balance.transaction do
-
# balance.save!
-
# account.save!
-
# end
-
#
-
# == Transactions are not distributed across database connections
-
#
-
# A transaction acts on a single database connection. If you have
-
# multiple class-specific databases, the transaction will not protect
-
# interaction among them. One workaround is to begin a transaction
-
# on each class whose models you alter:
-
#
-
# Student.transaction do
-
# Course.transaction do
-
# course.enroll(student)
-
# student.units += course.units
-
# end
-
# end
-
#
-
# This is a poor solution, but fully distributed transactions are beyond
-
# the scope of Active Record.
-
#
-
# == +save+ and +destroy+ are automatically wrapped in a transaction
-
#
-
# Both +save+ and +destroy+ come wrapped in a transaction that ensures
-
# that whatever you do in validations or callbacks will happen under its
-
# protected cover. So you can use validations to check for values that
-
# the transaction depends on or you can raise exceptions in the callbacks
-
# to rollback, including <tt>after_*</tt> callbacks.
-
#
-
# As a consequence changes to the database are not seen outside your connection
-
# until the operation is complete. For example, if you try to update the index
-
# of a search engine in +after_save+ the indexer won't see the updated record.
-
# The +after_commit+ callback is the only one that is triggered once the update
-
# is committed. See below.
-
#
-
# == Exception handling and rolling back
-
#
-
# Also have in mind that exceptions thrown within a transaction block will
-
# be propagated (after triggering the ROLLBACK), so you should be ready to
-
# catch those in your application code.
-
#
-
# One exception is the <tt>ActiveRecord::Rollback</tt> exception, which will trigger
-
# a ROLLBACK when raised, but not be re-raised by the transaction block.
-
#
-
# *Warning*: one should not catch <tt>ActiveRecord::StatementInvalid</tt> exceptions
-
# inside a transaction block. <tt>ActiveRecord::StatementInvalid</tt> exceptions indicate that an
-
# error occurred at the database level, for example when a unique constraint
-
# is violated. On some database systems, such as PostgreSQL, database errors
-
# inside a transaction cause the entire transaction to become unusable
-
# until it's restarted from the beginning. Here is an example which
-
# demonstrates the problem:
-
#
-
# # Suppose that we have a Number model with a unique column called 'i'.
-
# Number.transaction do
-
# Number.create(i: 0)
-
# begin
-
# # This will raise a unique constraint error...
-
# Number.create(i: 0)
-
# rescue ActiveRecord::StatementInvalid
-
# # ...which we ignore.
-
# end
-
#
-
# # On PostgreSQL, the transaction is now unusable. The following
-
# # statement will cause a PostgreSQL error, even though the unique
-
# # constraint is no longer violated:
-
# Number.create(i: 1)
-
# # => "PGError: ERROR: current transaction is aborted, commands
-
# # ignored until end of transaction block"
-
# end
-
#
-
# One should restart the entire transaction if an
-
# <tt>ActiveRecord::StatementInvalid</tt> occurred.
-
#
-
# == Nested transactions
-
#
-
# +transaction+ calls can be nested. By default, this makes all database
-
# statements in the nested transaction block become part of the parent
-
# transaction. For example, the following behavior may be surprising:
-
#
-
# User.transaction do
-
# User.create(username: 'Kotori')
-
# User.transaction do
-
# User.create(username: 'Nemu')
-
# raise ActiveRecord::Rollback
-
# end
-
# end
-
#
-
# creates both "Kotori" and "Nemu". Reason is the <tt>ActiveRecord::Rollback</tt>
-
# exception in the nested block does not issue a ROLLBACK. Since these exceptions
-
# are captured in transaction blocks, the parent block does not see it and the
-
# real transaction is committed.
-
#
-
# In order to get a ROLLBACK for the nested transaction you may ask for a real
-
# sub-transaction by passing <tt>requires_new: true</tt>. If anything goes wrong,
-
# the database rolls back to the beginning of the sub-transaction without rolling
-
# back the parent transaction. If we add it to the previous example:
-
#
-
# User.transaction do
-
# User.create(username: 'Kotori')
-
# User.transaction(requires_new: true) do
-
# User.create(username: 'Nemu')
-
# raise ActiveRecord::Rollback
-
# end
-
# end
-
#
-
# only "Kotori" is created. This works on MySQL and PostgreSQL. SQLite3 version >= '3.6.8' also supports it.
-
#
-
# Most databases don't support true nested transactions. At the time of
-
# writing, the only database that we're aware of that supports true nested
-
# transactions, is MS-SQL. Because of this, Active Record emulates nested
-
# transactions by using savepoints on MySQL and PostgreSQL. See
-
# http://dev.mysql.com/doc/refman/5.6/en/savepoint.html
-
# for more information about savepoints.
-
#
-
# === Callbacks
-
#
-
# There are two types of callbacks associated with committing and rolling back transactions:
-
# +after_commit+ and +after_rollback+.
-
#
-
# +after_commit+ callbacks are called on every record saved or destroyed within a
-
# transaction immediately after the transaction is committed. +after_rollback+ callbacks
-
# are called on every record saved or destroyed within a transaction immediately after the
-
# transaction or savepoint is rolled back.
-
#
-
# These callbacks are useful for interacting with other systems since you will be guaranteed
-
# that the callback is only executed when the database is in a permanent state. For example,
-
# +after_commit+ is a good spot to put in a hook to clearing a cache since clearing it from
-
# within a transaction could trigger the cache to be regenerated before the database is updated.
-
#
-
# === Caveats
-
#
-
# If you're on MySQL, then do not use DDL operations in nested transactions
-
# blocks that are emulated with savepoints. That is, do not execute statements
-
# like 'CREATE TABLE' inside such blocks. This is because MySQL automatically
-
# releases all savepoints upon executing a DDL operation. When +transaction+
-
# is finished and tries to release the savepoint it created earlier, a
-
# database error will occur because the savepoint has already been
-
# automatically released. The following example demonstrates the problem:
-
#
-
# Model.connection.transaction do # BEGIN
-
# Model.connection.transaction(requires_new: true) do # CREATE SAVEPOINT active_record_1
-
# Model.connection.create_table(...) # active_record_1 now automatically released
-
# end # RELEASE savepoint active_record_1
-
# # ^^^^ BOOM! database error!
-
# end
-
#
-
# Note that "TRUNCATE" is also a MySQL DDL statement!
-
2
module ClassMethods
-
# See ActiveRecord::Transactions::ClassMethods for detailed documentation.
-
2
def transaction(options = {}, &block)
-
# See the ConnectionAdapters::DatabaseStatements#transaction API docs.
-
341
connection.transaction(options, &block)
-
end
-
-
# This callback is called after a record has been created, updated, or destroyed.
-
#
-
# You can specify that the callback should only be fired by a certain action with
-
# the +:on+ option:
-
#
-
# after_commit :do_foo, on: :create
-
# after_commit :do_bar, on: :update
-
# after_commit :do_baz, on: :destroy
-
#
-
# after_commit :do_foo_bar, on: [:create, :update]
-
# after_commit :do_bar_baz, on: [:update, :destroy]
-
#
-
# Note that transactional fixtures do not play well with this feature. Please
-
# use the +test_after_commit+ gem to have these hooks fired in tests.
-
2
def after_commit(*args, &block)
-
8
set_options_for_callbacks!(args)
-
8
set_callback(:commit, :after, *args, &block)
-
end
-
-
# This callback is called after a create, update, or destroy are rolled back.
-
#
-
# Please check the documentation of +after_commit+ for options.
-
2
def after_rollback(*args, &block)
-
set_options_for_callbacks!(args)
-
set_callback(:rollback, :after, *args, &block)
-
end
-
-
2
private
-
-
2
def set_options_for_callbacks!(args)
-
8
options = args.last
-
8
if options.is_a?(Hash) && options[:on]
-
8
fire_on = Array(options[:on])
-
8
assert_valid_transaction_action(fire_on)
-
8
options[:if] = Array(options[:if])
-
8
options[:if] << "transaction_include_any_action?(#{fire_on})"
-
end
-
end
-
-
2
def assert_valid_transaction_action(actions)
-
8
if (actions - ACTIONS).any?
-
raise ArgumentError, ":on conditions for after_commit and after_rollback callbacks have to be one of #{ACTIONS.join(",")}"
-
end
-
end
-
end
-
-
# See ActiveRecord::Transactions::ClassMethods for detailed documentation.
-
2
def transaction(options = {}, &block)
-
self.class.transaction(options, &block)
-
end
-
-
2
def destroy #:nodoc:
-
with_transaction_returning_status { super }
-
end
-
-
2
def save(*) #:nodoc:
-
74
rollback_active_record_state! do
-
148
with_transaction_returning_status { super }
-
end
-
end
-
-
2
def save!(*) #:nodoc:
-
390
with_transaction_returning_status { super }
-
end
-
-
2
def touch(*) #:nodoc:
-
with_transaction_returning_status { super }
-
end
-
-
# Reset id and @new_record if the transaction rolls back.
-
2
def rollback_active_record_state!
-
74
remember_transaction_record_state
-
74
yield
-
rescue Exception
-
restore_transaction_record_state
-
raise
-
ensure
-
74
clear_transaction_record_state
-
end
-
-
# Call the +after_commit+ callbacks.
-
#
-
# Ensure that it is not called if the object was never persisted (failed create),
-
# but call it after the commit of a destroyed object.
-
2
def committed! #:nodoc:
-
run_callbacks :commit if destroyed? || persisted?
-
ensure
-
@_start_transaction_state.clear
-
end
-
-
# Call the +after_rollback+ callbacks. The +force_restore_state+ argument indicates if the record
-
# state should be rolled back to the beginning or just to the last savepoint.
-
2
def rolledback!(force_restore_state = false) #:nodoc:
-
195
run_callbacks :rollback
-
ensure
-
195
restore_transaction_record_state(force_restore_state)
-
195
clear_transaction_record_state
-
end
-
-
# Add the record to the current transaction so that the +after_rollback+ and +after_commit+ callbacks
-
# can be called.
-
2
def add_to_transaction
-
269
if self.class.connection.add_transaction_record(self)
-
269
remember_transaction_record_state
-
end
-
end
-
-
# Executes +method+ within a transaction and captures its return value as a
-
# status flag. If the status is true the transaction is committed, otherwise
-
# a ROLLBACK is issued. In any case the status flag is returned.
-
#
-
# This method is available within the context of an ActiveRecord::Base
-
# instance.
-
2
def with_transaction_returning_status
-
269
status = nil
-
269
self.class.transaction do
-
269
add_to_transaction
-
269
begin
-
269
status = yield
-
rescue ActiveRecord::Rollback
-
@_start_transaction_state[:level] = (@_start_transaction_state[:level] || 0) - 1
-
status = nil
-
end
-
-
269
raise ActiveRecord::Rollback unless status
-
end
-
269
status
-
end
-
-
2
protected
-
-
# Save the new record state and id of a record so it can be restored later if a transaction fails.
-
2
def remember_transaction_record_state #:nodoc:
-
343
@_start_transaction_state[:id] = id if has_attribute?(self.class.primary_key)
-
343
unless @_start_transaction_state.include?(:new_record)
-
269
@_start_transaction_state[:new_record] = @new_record
-
end
-
343
unless @_start_transaction_state.include?(:destroyed)
-
269
@_start_transaction_state[:destroyed] = @destroyed
-
end
-
343
@_start_transaction_state[:level] = (@_start_transaction_state[:level] || 0) + 1
-
343
@_start_transaction_state[:frozen?] = @attributes.frozen?
-
end
-
-
# Clear the new record state and id of a record.
-
2
def clear_transaction_record_state #:nodoc:
-
269
@_start_transaction_state[:level] = (@_start_transaction_state[:level] || 0) - 1
-
269
@_start_transaction_state.clear if @_start_transaction_state[:level] < 1
-
end
-
-
# Restore the new record state and id of a record that was previously saved by a call to save_record_state.
-
2
def restore_transaction_record_state(force = false) #:nodoc:
-
195
unless @_start_transaction_state.empty?
-
195
transaction_level = (@_start_transaction_state[:level] || 0) - 1
-
195
if transaction_level < 1 || force
-
193
restore_state = @_start_transaction_state
-
193
was_frozen = restore_state[:frozen?]
-
193
@attributes = @attributes.dup if @attributes.frozen?
-
193
@new_record = restore_state[:new_record]
-
193
@destroyed = restore_state[:destroyed]
-
193
if restore_state.has_key?(:id)
-
193
write_attribute(self.class.primary_key, restore_state[:id])
-
else
-
@attributes.delete(self.class.primary_key)
-
@attributes_cache.delete(self.class.primary_key)
-
end
-
193
@attributes.freeze if was_frozen
-
end
-
end
-
end
-
-
# Determine if a record was created or destroyed in a transaction. State should be one of :new_record or :destroyed.
-
2
def transaction_record_state(state) #:nodoc:
-
@_start_transaction_state[state]
-
end
-
-
# Determine if a transaction included an action for :create, :update, or :destroy. Used in filtering callbacks.
-
2
def transaction_include_any_action?(actions) #:nodoc:
-
actions.any? do |action|
-
case action
-
when :create
-
transaction_record_state(:new_record)
-
when :destroy
-
destroyed?
-
when :update
-
!(transaction_record_state(:new_record) || destroyed?)
-
end
-
end
-
end
-
end
-
end
-
2
module ActiveRecord
-
2
module Translation
-
2
include ActiveModel::Translation
-
-
# Set the lookup ancestors for ActiveModel.
-
2
def lookup_ancestors #:nodoc:
-
36
klass = self
-
36
classes = [klass]
-
36
return classes if klass == ActiveRecord::Base
-
-
36
while klass != klass.base_class
-
classes << klass = klass.superclass
-
end
-
36
classes
-
end
-
-
# Set the i18n scope to overwrite ActiveModel.
-
2
def i18n_scope #:nodoc:
-
60
:activerecord
-
end
-
end
-
end
-
2
module ActiveRecord
-
# = Active Record RecordInvalid
-
#
-
# Raised by <tt>save!</tt> and <tt>create!</tt> when the record is invalid. Use the
-
# +record+ method to retrieve the record which did not validate.
-
#
-
# begin
-
# complex_operation_that_calls_save!_internally
-
# rescue ActiveRecord::RecordInvalid => invalid
-
# puts invalid.record.errors
-
# end
-
2
class RecordInvalid < ActiveRecordError
-
2
attr_reader :record # :nodoc:
-
2
def initialize(record) # :nodoc:
-
@record = record
-
errors = @record.errors.full_messages.join(", ")
-
super(I18n.t(:"#{@record.class.i18n_scope}.errors.messages.record_invalid", :errors => errors, :default => :"errors.messages.record_invalid"))
-
end
-
end
-
-
# = Active Record Validations
-
#
-
# Active Record includes the majority of its validations from <tt>ActiveModel::Validations</tt>
-
# all of which accept the <tt>:on</tt> argument to define the context where the
-
# validations are active. Active Record will always supply either the context of
-
# <tt>:create</tt> or <tt>:update</tt> dependent on whether the model is a
-
# <tt>new_record?</tt>.
-
2
module Validations
-
2
extend ActiveSupport::Concern
-
2
include ActiveModel::Validations
-
-
2
module ClassMethods
-
# Creates an object just like Base.create but calls <tt>save!</tt> instead of +save+
-
# so an exception is raised if the record is invalid.
-
2
def create!(attributes = nil, &block)
-
195
if attributes.is_a?(Array)
-
attributes.collect { |attr| create!(attr, &block) }
-
else
-
195
object = new(attributes)
-
195
yield(object) if block_given?
-
195
object.save!
-
195
object
-
end
-
end
-
end
-
-
# The validation process on save can be skipped by passing <tt>validate: false</tt>.
-
# The regular Base#save method is replaced with this when the validations
-
# module is mixed in, which it is by default.
-
2
def save(options={})
-
74
perform_validations(options) ? super : false
-
end
-
-
# Attempts to save the record just like Base#save but will raise a +RecordInvalid+
-
# exception instead of returning +false+ if the record is not valid.
-
2
def save!(options={})
-
195
perform_validations(options) ? super : raise(RecordInvalid.new(self))
-
end
-
-
# Runs all the validations within the specified context. Returns +true+ if
-
# no errors are found, +false+ otherwise.
-
#
-
# If the argument is +false+ (default is +nil+), the context is set to <tt>:create</tt> if
-
# <tt>new_record?</tt> is +true+, and to <tt>:update</tt> if it is not.
-
#
-
# Validations with no <tt>:on</tt> option will run no matter the context. Validations with
-
# some <tt>:on</tt> option will only run in the specified context.
-
2
def valid?(context = nil)
-
269
context ||= (new_record? ? :create : :update)
-
269
output = super(context)
-
269
errors.empty? && output
-
end
-
-
2
protected
-
-
2
def perform_validations(options={}) # :nodoc:
-
269
options[:validate] == false || valid?(options[:context])
-
end
-
end
-
end
-
-
2
require "active_record/validations/associated"
-
2
require "active_record/validations/uniqueness"
-
2
require "active_record/validations/presence"
-
2
module ActiveRecord
-
2
module Validations
-
2
class AssociatedValidator < ActiveModel::EachValidator #:nodoc:
-
2
def validate_each(record, attribute, value)
-
if Array.wrap(value).reject {|r| r.marked_for_destruction? || r.valid?}.any?
-
record.errors.add(attribute, :invalid, options.merge(:value => value))
-
end
-
end
-
end
-
-
2
module ClassMethods
-
# Validates whether the associated object or objects are all valid.
-
# Works with any kind of association.
-
#
-
# class Book < ActiveRecord::Base
-
# has_many :pages
-
# belongs_to :library
-
#
-
# validates_associated :pages, :library
-
# end
-
#
-
# WARNING: This validation must not be used on both ends of an association.
-
# Doing so will lead to a circular dependency and cause infinite recursion.
-
#
-
# NOTE: This validation will not fail if the association hasn't been
-
# assigned. If you want to ensure that the association is both present and
-
# guaranteed to be valid, you also need to use +validates_presence_of+.
-
#
-
# Configuration options:
-
#
-
# * <tt>:message</tt> - A custom error message (default is: "is invalid").
-
# * <tt>:on</tt> - Specifies when this validation is active. Runs in all
-
# validation contexts by default (+nil+), other options are <tt>:create</tt>
-
# and <tt>:update</tt>.
-
# * <tt>:if</tt> - Specifies a method, proc or string to call to determine
-
# if the validation should occur (e.g. <tt>if: :allow_validation</tt>,
-
# or <tt>if: Proc.new { |user| user.signup_step > 2 }</tt>). The method,
-
# proc or string should return or evaluate to a +true+ or +false+ value.
-
# * <tt>:unless</tt> - Specifies a method, proc or string to call to
-
# determine if the validation should not occur (e.g. <tt>unless: :skip_validation</tt>,
-
# or <tt>unless: Proc.new { |user| user.signup_step <= 2 }</tt>). The
-
# method, proc or string should return or evaluate to a +true+ or +false+
-
# value.
-
2
def validates_associated(*attr_names)
-
validates_with AssociatedValidator, _merge_attributes(attr_names)
-
end
-
end
-
end
-
end
-
2
module ActiveRecord
-
2
module Validations
-
2
class PresenceValidator < ActiveModel::Validations::PresenceValidator # :nodoc:
-
2
def validate(record)
-
585
super
-
585
attributes.each do |attribute|
-
585
next unless record.class._reflect_on_association(attribute)
-
associated_records = Array.wrap(record.send(attribute))
-
-
# Superclass validates presence. Ensure present records aren't about to be destroyed.
-
if associated_records.present? && associated_records.all? { |r| r.marked_for_destruction? }
-
record.errors.add(attribute, :blank, options)
-
end
-
end
-
end
-
end
-
-
2
module ClassMethods
-
# Validates that the specified attributes are not blank (as defined by
-
# Object#blank?), and, if the attribute is an association, that the
-
# associated object is not marked for destruction. Happens by default
-
# on save.
-
#
-
# class Person < ActiveRecord::Base
-
# has_one :face
-
# validates_presence_of :face
-
# end
-
#
-
# The face attribute must be in the object and it cannot be blank or marked
-
# for destruction.
-
#
-
# If you want to validate the presence of a boolean field (where the real values
-
# are true and false), you will want to use
-
# <tt>validates_inclusion_of :field_name, in: [true, false]</tt>.
-
#
-
# This is due to the way Object#blank? handles boolean values:
-
# <tt>false.blank? # => true</tt>.
-
#
-
# This validator defers to the ActiveModel validation for presence, adding the
-
# check to see that an associated object is not marked for destruction. This
-
# prevents the parent object from validating successfully and saving, which then
-
# deletes the associated object, thus putting the parent object into an invalid
-
# state.
-
#
-
# Configuration options:
-
# * <tt>:message</tt> - A custom error message (default is: "can't be blank").
-
# * <tt>:on</tt> - Specifies when this validation is active. Runs in all
-
# validation contexts by default (+nil+), other options are <tt>:create</tt>
-
# and <tt>:update</tt>.
-
# * <tt>:if</tt> - Specifies a method, proc or string to call to determine if
-
# the validation should occur (e.g. <tt>if: :allow_validation</tt>, or
-
# <tt>if: Proc.new { |user| user.signup_step > 2 }</tt>). The method, proc
-
# or string should return or evaluate to a +true+ or +false+ value.
-
# * <tt>:unless</tt> - Specifies a method, proc or string to call to determine
-
# if the validation should not occur (e.g. <tt>unless: :skip_validation</tt>,
-
# or <tt>unless: Proc.new { |user| user.signup_step <= 2 }</tt>). The method,
-
# proc or string should return or evaluate to a +true+ or +false+ value.
-
# * <tt>:strict</tt> - Specifies whether validation should be strict.
-
# See <tt>ActiveModel::Validation#validates!</tt> for more information.
-
2
def validates_presence_of(*attr_names)
-
validates_with PresenceValidator, _merge_attributes(attr_names)
-
end
-
end
-
end
-
end
-
2
module ActiveRecord
-
2
module Validations
-
2
class UniquenessValidator < ActiveModel::EachValidator # :nodoc:
-
2
def initialize(options)
-
6
if options[:conditions] && !options[:conditions].respond_to?(:call)
-
raise ArgumentError, "#{options[:conditions]} was passed as :conditions but is not callable. " \
-
"Pass a callable instead: `conditions: -> { where(approved: true) }`"
-
end
-
6
super({ case_sensitive: true }.merge!(options))
-
6
@klass = options[:class]
-
end
-
-
2
def validate_each(record, attribute, value)
-
195
finder_class = find_finder_class_for(record)
-
195
table = finder_class.arel_table
-
195
value = map_enum_attribute(finder_class,attribute,value)
-
195
value = deserialize_attribute(record, attribute, value)
-
-
195
relation = build_relation(finder_class, table, attribute, value)
-
195
relation = relation.and(table[finder_class.primary_key.to_sym].not_eq(record.id)) if record.persisted?
-
195
relation = scope_relation(record, table, relation)
-
195
relation = finder_class.unscoped.where(relation)
-
195
relation = relation.merge(options[:conditions]) if options[:conditions]
-
-
195
if relation.exists?
-
error_options = options.except(:case_sensitive, :scope, :conditions)
-
error_options[:value] = value
-
-
record.errors.add(attribute, :taken, error_options)
-
end
-
end
-
-
2
protected
-
# The check for an existing value should be run from a class that
-
# isn't abstract. This means working down from the current class
-
# (self), to the first non-abstract class. Since classes don't know
-
# their subclasses, we have to build the hierarchy between self and
-
# the record's class.
-
2
def find_finder_class_for(record) #:nodoc:
-
195
class_hierarchy = [record.class]
-
-
195
while class_hierarchy.first != @klass
-
class_hierarchy.unshift(class_hierarchy.first.superclass)
-
end
-
-
390
class_hierarchy.detect { |klass| !klass.abstract_class? }
-
end
-
-
2
def build_relation(klass, table, attribute, value) #:nodoc:
-
195
if reflection = klass._reflect_on_association(attribute)
-
attribute = reflection.foreign_key
-
value = value.attributes[reflection.primary_key_column.name] unless value.nil?
-
end
-
-
195
attribute_name = attribute.to_s
-
-
# the attribute may be an aliased attribute
-
195
if klass.attribute_aliases[attribute_name]
-
attribute = klass.attribute_aliases[attribute_name]
-
attribute_name = attribute.to_s
-
end
-
-
195
column = klass.columns_hash[attribute_name]
-
195
value = klass.connection.type_cast(value, column)
-
195
value = value.to_s[0, column.limit] if value && column.limit && column.text?
-
-
195
if !options[:case_sensitive] && value && column.text?
-
# will use SQL LOWER function before comparison, unless it detects a case insensitive collation
-
klass.connection.case_insensitive_comparison(table, attribute, column, value)
-
else
-
195
value = klass.connection.case_sensitive_modifier(value) unless value.nil?
-
195
table[attribute].eq(value)
-
end
-
end
-
-
2
def scope_relation(record, table, relation)
-
195
Array(options[:scope]).each do |scope_item|
-
if reflection = record.class._reflect_on_association(scope_item)
-
scope_value = record.send(reflection.foreign_key)
-
scope_item = reflection.foreign_key
-
else
-
scope_value = record.read_attribute(scope_item)
-
end
-
relation = relation.and(table[scope_item].eq(scope_value))
-
end
-
-
195
relation
-
end
-
-
2
def deserialize_attribute(record, attribute, value)
-
195
coder = record.class.serialized_attributes[attribute.to_s]
-
195
value = coder.dump value if value && coder
-
195
value
-
end
-
-
2
def map_enum_attribute(klass, attribute, value)
-
195
mapping = klass.defined_enums[attribute.to_s]
-
195
value = mapping[value] if value && mapping
-
195
value
-
end
-
end
-
-
2
module ClassMethods
-
# Validates whether the value of the specified attributes are unique
-
# across the system. Useful for making sure that only one user
-
# can be named "davidhh".
-
#
-
# class Person < ActiveRecord::Base
-
# validates_uniqueness_of :user_name
-
# end
-
#
-
# It can also validate whether the value of the specified attributes are
-
# unique based on a <tt>:scope</tt> parameter:
-
#
-
# class Person < ActiveRecord::Base
-
# validates_uniqueness_of :user_name, scope: :account_id
-
# end
-
#
-
# Or even multiple scope parameters. For example, making sure that a
-
# teacher can only be on the schedule once per semester for a particular
-
# class.
-
#
-
# class TeacherSchedule < ActiveRecord::Base
-
# validates_uniqueness_of :teacher_id, scope: [:semester_id, :class_id]
-
# end
-
#
-
# It is also possible to limit the uniqueness constraint to a set of
-
# records matching certain conditions. In this example archived articles
-
# are not being taken into consideration when validating uniqueness
-
# of the title attribute:
-
#
-
# class Article < ActiveRecord::Base
-
# validates_uniqueness_of :title, conditions: -> { where.not(status: 'archived') }
-
# end
-
#
-
# When the record is created, a check is performed to make sure that no
-
# record exists in the database with the given value for the specified
-
# attribute (that maps to a column). When the record is updated,
-
# the same check is made but disregarding the record itself.
-
#
-
# Configuration options:
-
#
-
# * <tt>:message</tt> - Specifies a custom error message (default is:
-
# "has already been taken").
-
# * <tt>:scope</tt> - One or more columns by which to limit the scope of
-
# the uniqueness constraint.
-
# * <tt>:conditions</tt> - Specify the conditions to be included as a
-
# <tt>WHERE</tt> SQL fragment to limit the uniqueness constraint lookup
-
# (e.g. <tt>conditions: -> { where(status: 'active') }</tt>).
-
# * <tt>:case_sensitive</tt> - Looks for an exact match. Ignored by
-
# non-text columns (+true+ by default).
-
# * <tt>:allow_nil</tt> - If set to +true+, skips this validation if the
-
# attribute is +nil+ (default is +false+).
-
# * <tt>:allow_blank</tt> - If set to +true+, skips this validation if the
-
# attribute is blank (default is +false+).
-
# * <tt>:if</tt> - Specifies a method, proc or string to call to determine
-
# if the validation should occur (e.g. <tt>if: :allow_validation</tt>,
-
# or <tt>if: Proc.new { |user| user.signup_step > 2 }</tt>). The method,
-
# proc or string should return or evaluate to a +true+ or +false+ value.
-
# * <tt>:unless</tt> - Specifies a method, proc or string to call to
-
# determine if the validation should ot occur (e.g. <tt>unless: :skip_validation</tt>,
-
# or <tt>unless: Proc.new { |user| user.signup_step <= 2 }</tt>). The
-
# method, proc or string should return or evaluate to a +true+ or +false+
-
# value.
-
#
-
# === Concurrency and integrity
-
#
-
# Using this validation method in conjunction with ActiveRecord::Base#save
-
# does not guarantee the absence of duplicate record insertions, because
-
# uniqueness checks on the application level are inherently prone to race
-
# conditions. For example, suppose that two users try to post a Comment at
-
# the same time, and a Comment's title must be unique. At the database-level,
-
# the actions performed by these users could be interleaved in the following manner:
-
#
-
# User 1 | User 2
-
# ------------------------------------+--------------------------------------
-
# # User 1 checks whether there's |
-
# # already a comment with the title |
-
# # 'My Post'. This is not the case. |
-
# SELECT * FROM comments |
-
# WHERE title = 'My Post' |
-
# |
-
# | # User 2 does the same thing and also
-
# | # infers that their title is unique.
-
# | SELECT * FROM comments
-
# | WHERE title = 'My Post'
-
# |
-
# # User 1 inserts their comment. |
-
# INSERT INTO comments |
-
# (title, content) VALUES |
-
# ('My Post', 'hi!') |
-
# |
-
# | # User 2 does the same thing.
-
# | INSERT INTO comments
-
# | (title, content) VALUES
-
# | ('My Post', 'hello!')
-
# |
-
# | # ^^^^^^
-
# | # Boom! We now have a duplicate
-
# | # title!
-
#
-
# This could even happen if you use transactions with the 'serializable'
-
# isolation level. The best way to work around this problem is to add a unique
-
# index to the database table using
-
# ActiveRecord::ConnectionAdapters::SchemaStatements#add_index. In the
-
# rare case that a race condition occurs, the database will guarantee
-
# the field's uniqueness.
-
#
-
# When the database catches such a duplicate insertion,
-
# ActiveRecord::Base#save will raise an ActiveRecord::StatementInvalid
-
# exception. You can either choose to let this error propagate (which
-
# will result in the default Rails exception page being shown), or you
-
# can catch it and restart the transaction (e.g. by telling the user
-
# that the title already exists, and asking them to re-enter the title).
-
# This technique is also known as
-
# {optimistic concurrency control}[http://en.wikipedia.org/wiki/Optimistic_concurrency_control].
-
#
-
# The bundled ActiveRecord::ConnectionAdapters distinguish unique index
-
# constraint errors from other types of database errors by throwing an
-
# ActiveRecord::RecordNotUnique exception. For other adapters you will
-
# have to parse the (database-specific) exception message to detect such
-
# a case.
-
#
-
# The following bundled adapters throw the ActiveRecord::RecordNotUnique exception:
-
#
-
# * ActiveRecord::ConnectionAdapters::MysqlAdapter.
-
# * ActiveRecord::ConnectionAdapters::Mysql2Adapter.
-
# * ActiveRecord::ConnectionAdapters::SQLite3Adapter.
-
# * ActiveRecord::ConnectionAdapters::PostgreSQLAdapter.
-
2
def validates_uniqueness_of(*attr_names)
-
validates_with UniquenessValidator, _merge_attributes(attr_names)
-
end
-
end
-
end
-
end
-
2
require_relative 'gem_version'
-
-
2
module ActiveRecord
-
# Returns the version of the currently loaded ActiveRecord as a <tt>Gem::Version</tt>
-
2
def self.version
-
gem_version
-
end
-
end
-
#--
-
# Copyright (c) 2005-2014 David Heinemeier Hansson
-
#
-
# Permission is hereby granted, free of charge, to any person obtaining
-
# a copy of this software and associated documentation files (the
-
# "Software"), to deal in the Software without restriction, including
-
# without limitation the rights to use, copy, modify, merge, publish,
-
# distribute, sublicense, and/or sell copies of the Software, and to
-
# permit persons to whom the Software is furnished to do so, subject to
-
# the following conditions:
-
#
-
# The above copyright notice and this permission notice shall be
-
# included in all copies or substantial portions of the Software.
-
#
-
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
-
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
-
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
-
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-
#++
-
-
2
require 'securerandom'
-
2
require "active_support/dependencies/autoload"
-
2
require "active_support/version"
-
2
require "active_support/logger"
-
2
require "active_support/lazy_load_hooks"
-
-
2
module ActiveSupport
-
2
extend ActiveSupport::Autoload
-
-
2
autoload :Concern
-
2
autoload :Dependencies
-
2
autoload :DescendantsTracker
-
2
autoload :FileUpdateChecker
-
2
autoload :LogSubscriber
-
2
autoload :Notifications
-
-
2
eager_autoload do
-
2
autoload :BacktraceCleaner
-
2
autoload :ProxyObject
-
2
autoload :Benchmarkable
-
2
autoload :Cache
-
2
autoload :Callbacks
-
2
autoload :Configurable
-
2
autoload :Deprecation
-
2
autoload :Gzip
-
2
autoload :Inflector
-
2
autoload :JSON
-
2
autoload :KeyGenerator
-
2
autoload :MessageEncryptor
-
2
autoload :MessageVerifier
-
2
autoload :Multibyte
-
2
autoload :NumberHelper
-
2
autoload :OptionMerger
-
2
autoload :OrderedHash
-
2
autoload :OrderedOptions
-
2
autoload :StringInquirer
-
2
autoload :TaggedLogging
-
2
autoload :XmlMini
-
end
-
-
2
autoload :Rescuable
-
2
autoload :SafeBuffer, "active_support/core_ext/string/output_safety"
-
2
autoload :TestCase
-
-
2
def self.eager_load!
-
super
-
-
NumberHelper.eager_load!
-
end
-
end
-
-
2
autoload :I18n, "active_support/i18n"
-
2
require 'active_support'
-
2
require 'active_support/time'
-
2
require 'active_support/core_ext'
-
2
module ActiveSupport
-
# Backtraces often include many lines that are not relevant for the context
-
# under review. This makes it hard to find the signal amongst the backtrace
-
# noise, and adds debugging time. With a BacktraceCleaner, filters and
-
# silencers are used to remove the noisy lines, so that only the most relevant
-
# lines remain.
-
#
-
# Filters are used to modify lines of data, while silencers are used to remove
-
# lines entirely. The typical filter use case is to remove lengthy path
-
# information from the start of each line, and view file paths relevant to the
-
# app directory instead of the file system root. The typical silencer use case
-
# is to exclude the output of a noisy library from the backtrace, so that you
-
# can focus on the rest.
-
#
-
# bc = BacktraceCleaner.new
-
# bc.add_filter { |line| line.gsub(Rails.root, '') } # strip the Rails.root prefix
-
# bc.add_silencer { |line| line =~ /mongrel|rubygems/ } # skip any lines from mongrel or rubygems
-
# bc.clean(exception.backtrace) # perform the cleanup
-
#
-
# To reconfigure an existing BacktraceCleaner (like the default one in Rails)
-
# and show as much data as possible, you can always call
-
# <tt>BacktraceCleaner#remove_silencers!</tt>, which will restore the
-
# backtrace to a pristine state. If you need to reconfigure an existing
-
# BacktraceCleaner so that it does not filter or modify the paths of any lines
-
# of the backtrace, you can call <tt>BacktraceCleaner#remove_filters!</tt>
-
# These two methods will give you a completely untouched backtrace.
-
#
-
# Inspired by the Quiet Backtrace gem by Thoughtbot.
-
2
class BacktraceCleaner
-
2
def initialize
-
2
@filters, @silencers = [], []
-
end
-
-
# Returns the backtrace after all filters and silencers have been run
-
# against it. Filters run first, then silencers.
-
2
def clean(backtrace, kind = :silent)
-
filtered = filter_backtrace(backtrace)
-
-
case kind
-
when :silent
-
silence(filtered)
-
when :noise
-
noise(filtered)
-
else
-
filtered
-
end
-
end
-
2
alias :filter :clean
-
-
# Adds a filter from the block provided. Each line in the backtrace will be
-
# mapped against this filter.
-
#
-
# # Will turn "/my/rails/root/app/models/person.rb" into "/app/models/person.rb"
-
# backtrace_cleaner.add_filter { |line| line.gsub(Rails.root, '') }
-
2
def add_filter(&block)
-
8
@filters << block
-
end
-
-
# Adds a silencer from the block provided. If the silencer returns +true+
-
# for a given line, it will be excluded from the clean backtrace.
-
#
-
# # Will reject all lines that include the word "mongrel", like "/gems/mongrel/server.rb" or "/app/my_mongrel_server/rb"
-
# backtrace_cleaner.add_silencer { |line| line =~ /mongrel/ }
-
2
def add_silencer(&block)
-
4
@silencers << block
-
end
-
-
# Will remove all silencers, but leave in the filters. This is useful if
-
# your context of debugging suddenly expands as you suspect a bug in one of
-
# the libraries you use.
-
2
def remove_silencers!
-
@silencers = []
-
end
-
-
# Removes all filters, but leaves in silencers. Useful if you suddenly
-
# need to see entire filepaths in the backtrace that you had already
-
# filtered out.
-
2
def remove_filters!
-
@filters = []
-
end
-
-
2
private
-
2
def filter_backtrace(backtrace)
-
@filters.each do |f|
-
backtrace = backtrace.map { |line| f.call(line) }
-
end
-
-
backtrace
-
end
-
-
2
def silence(backtrace)
-
@silencers.each do |s|
-
backtrace = backtrace.reject { |line| s.call(line) }
-
end
-
-
backtrace
-
end
-
-
2
def noise(backtrace)
-
backtrace - silence(backtrace)
-
end
-
end
-
end
-
2
require 'active_support/core_ext/benchmark'
-
2
require 'active_support/core_ext/hash/keys'
-
-
2
module ActiveSupport
-
2
module Benchmarkable
-
# Allows you to measure the execution time of a block in a template and
-
# records the result to the log. Wrap this block around expensive operations
-
# or possible bottlenecks to get a time reading for the operation. For
-
# example, let's say you thought your file processing method was taking too
-
# long; you could wrap it in a benchmark block.
-
#
-
# <% benchmark 'Process data files' do %>
-
# <%= expensive_files_operation %>
-
# <% end %>
-
#
-
# That would add something like "Process data files (345.2ms)" to the log,
-
# which you can then use to compare timings when optimizing your code.
-
#
-
# You may give an optional logger level (<tt>:debug</tt>, <tt>:info</tt>,
-
# <tt>:warn</tt>, <tt>:error</tt>) as the <tt>:level</tt> option. The
-
# default logger level value is <tt>:info</tt>.
-
#
-
# <% benchmark 'Low-level files', level: :debug do %>
-
# <%= lowlevel_files_operation %>
-
# <% end %>
-
#
-
# Finally, you can pass true as the third argument to silence all log
-
# activity (other than the timing information) from inside the block. This
-
# is great for boiling down a noisy block to just a single statement that
-
# produces one log line:
-
#
-
# <% benchmark 'Process data files', level: :info, silence: true do %>
-
# <%= expensive_and_chatty_files_operation %>
-
# <% end %>
-
2
def benchmark(message = "Benchmarking", options = {})
-
if logger
-
options.assert_valid_keys(:level, :silence)
-
options[:level] ||= :info
-
-
result = nil
-
ms = Benchmark.ms { result = options[:silence] ? silence { yield } : yield }
-
logger.send(options[:level], '%s (%.1fms)' % [ message, ms ])
-
result
-
else
-
yield
-
end
-
end
-
end
-
end
-
2
require 'benchmark'
-
2
require 'zlib'
-
2
require 'active_support/core_ext/array/extract_options'
-
2
require 'active_support/core_ext/array/wrap'
-
2
require 'active_support/core_ext/benchmark'
-
2
require 'active_support/core_ext/module/attribute_accessors'
-
2
require 'active_support/core_ext/numeric/bytes'
-
2
require 'active_support/core_ext/numeric/time'
-
2
require 'active_support/core_ext/object/to_param'
-
2
require 'active_support/core_ext/string/inflections'
-
-
2
module ActiveSupport
-
# See ActiveSupport::Cache::Store for documentation.
-
2
module Cache
-
2
autoload :FileStore, 'active_support/cache/file_store'
-
2
autoload :MemoryStore, 'active_support/cache/memory_store'
-
2
autoload :MemCacheStore, 'active_support/cache/mem_cache_store'
-
2
autoload :NullStore, 'active_support/cache/null_store'
-
-
# These options mean something to all cache implementations. Individual cache
-
# implementations may support additional options.
-
2
UNIVERSAL_OPTIONS = [:namespace, :compress, :compress_threshold, :expires_in, :race_condition_ttl]
-
-
2
module Strategy
-
2
autoload :LocalCache, 'active_support/cache/strategy/local_cache'
-
end
-
-
2
class << self
-
# Creates a new CacheStore object according to the given options.
-
#
-
# If no arguments are passed to this method, then a new
-
# ActiveSupport::Cache::MemoryStore object will be returned.
-
#
-
# If you pass a Symbol as the first argument, then a corresponding cache
-
# store class under the ActiveSupport::Cache namespace will be created.
-
# For example:
-
#
-
# ActiveSupport::Cache.lookup_store(:memory_store)
-
# # => returns a new ActiveSupport::Cache::MemoryStore object
-
#
-
# ActiveSupport::Cache.lookup_store(:mem_cache_store)
-
# # => returns a new ActiveSupport::Cache::MemCacheStore object
-
#
-
# Any additional arguments will be passed to the corresponding cache store
-
# class's constructor:
-
#
-
# ActiveSupport::Cache.lookup_store(:file_store, '/tmp/cache')
-
# # => same as: ActiveSupport::Cache::FileStore.new('/tmp/cache')
-
#
-
# If the first argument is not a Symbol, then it will simply be returned:
-
#
-
# ActiveSupport::Cache.lookup_store(MyOwnCacheStore.new)
-
# # => returns MyOwnCacheStore.new
-
2
def lookup_store(*store_option)
-
4
store, *parameters = *Array.wrap(store_option).flatten
-
-
4
case store
-
when Symbol
-
2
retrieve_store_class(store).new(*parameters)
-
when nil
-
ActiveSupport::Cache::MemoryStore.new
-
else
-
2
store
-
end
-
end
-
-
# Expands out the +key+ argument into a key that can be used for the
-
# cache store. Optionally accepts a namespace, and all keys will be
-
# scoped within that namespace.
-
#
-
# If the +key+ argument provided is an array, or responds to +to_a+, then
-
# each of elements in the array will be turned into parameters/keys and
-
# concatenated into a single key. For example:
-
#
-
# expand_cache_key([:foo, :bar]) # => "foo/bar"
-
# expand_cache_key([:foo, :bar], "namespace") # => "namespace/foo/bar"
-
#
-
# The +key+ argument can also respond to +cache_key+ or +to_param+.
-
2
def expand_cache_key(key, namespace = nil)
-
expanded_cache_key = namespace ? "#{namespace}/" : ""
-
-
if prefix = ENV["RAILS_CACHE_ID"] || ENV["RAILS_APP_VERSION"]
-
expanded_cache_key << "#{prefix}/"
-
end
-
-
expanded_cache_key << retrieve_cache_key(key)
-
expanded_cache_key
-
end
-
-
2
private
-
2
def retrieve_cache_key(key)
-
case
-
when key.respond_to?(:cache_key) then key.cache_key
-
when key.is_a?(Array) then key.map { |element| retrieve_cache_key(element) }.to_param
-
when key.respond_to?(:to_a) then retrieve_cache_key(key.to_a)
-
else key.to_param
-
end.to_s
-
end
-
-
# Obtains the specified cache store class, given the name of the +store+.
-
# Raises an error when the store class cannot be found.
-
2
def retrieve_store_class(store)
-
2
require "active_support/cache/#{store}"
-
rescue LoadError => e
-
raise "Could not find cache store adapter for #{store} (#{e})"
-
else
-
2
ActiveSupport::Cache.const_get(store.to_s.camelize)
-
end
-
end
-
-
# An abstract cache store class. There are multiple cache store
-
# implementations, each having its own additional features. See the classes
-
# under the ActiveSupport::Cache module, e.g.
-
# ActiveSupport::Cache::MemCacheStore. MemCacheStore is currently the most
-
# popular cache store for large production websites.
-
#
-
# Some implementations may not support all methods beyond the basic cache
-
# methods of +fetch+, +write+, +read+, +exist?+, and +delete+.
-
#
-
# ActiveSupport::Cache::Store can store any serializable Ruby object.
-
#
-
# cache = ActiveSupport::Cache::MemoryStore.new
-
#
-
# cache.read('city') # => nil
-
# cache.write('city', "Duckburgh")
-
# cache.read('city') # => "Duckburgh"
-
#
-
# Keys are always translated into Strings and are case sensitive. When an
-
# object is specified as a key and has a +cache_key+ method defined, this
-
# method will be called to define the key. Otherwise, the +to_param+
-
# method will be called. Hashes and Arrays can also be used as keys. The
-
# elements will be delimited by slashes, and the elements within a Hash
-
# will be sorted by key so they are consistent.
-
#
-
# cache.read('city') == cache.read(:city) # => true
-
#
-
# Nil values can be cached.
-
#
-
# If your cache is on a shared infrastructure, you can define a namespace
-
# for your cache entries. If a namespace is defined, it will be prefixed on
-
# to every key. The namespace can be either a static value or a Proc. If it
-
# is a Proc, it will be invoked when each key is evaluated so that you can
-
# use application logic to invalidate keys.
-
#
-
# cache.namespace = -> { @last_mod_time } # Set the namespace to a variable
-
# @last_mod_time = Time.now # Invalidate the entire cache by changing namespace
-
#
-
# Caches can also store values in a compressed format to save space and
-
# reduce time spent sending data. Since there is overhead, values must be
-
# large enough to warrant compression. To turn on compression either pass
-
# <tt>compress: true</tt> in the initializer or as an option to +fetch+
-
# or +write+. To specify the threshold at which to compress values, set the
-
# <tt>:compress_threshold</tt> option. The default threshold is 16K.
-
2
class Store
-
2
cattr_accessor :logger, :instance_writer => true
-
-
2
attr_reader :silence, :options
-
2
alias :silence? :silence
-
-
# Create a new cache. The options will be passed to any write method calls
-
# except for <tt>:namespace</tt> which can be used to set the global
-
# namespace for the cache.
-
2
def initialize(options = nil)
-
15
@options = options ? options.dup : {}
-
end
-
-
# Silence the logger.
-
2
def silence!
-
@silence = true
-
self
-
end
-
-
# Silence the logger within a block.
-
2
def mute
-
previous_silence, @silence = defined?(@silence) && @silence, true
-
yield
-
ensure
-
@silence = previous_silence
-
end
-
-
# Set to +true+ if cache stores should be instrumented.
-
# Default is +false+.
-
2
def self.instrument=(boolean)
-
Thread.current[:instrument_cache_store] = boolean
-
end
-
-
2
def self.instrument
-
Thread.current[:instrument_cache_store] || false
-
end
-
-
# Fetches data from the cache, using the given key. If there is data in
-
# the cache with the given key, then that data is returned.
-
#
-
# If there is no such data in the cache (a cache miss), then +nil+ will be
-
# returned. However, if a block has been passed, that block will be passed
-
# the key and executed in the event of a cache miss. The return value of the
-
# block will be written to the cache under the given cache key, and that
-
# return value will be returned.
-
#
-
# cache.write('today', 'Monday')
-
# cache.fetch('today') # => "Monday"
-
#
-
# cache.fetch('city') # => nil
-
# cache.fetch('city') do
-
# 'Duckburgh'
-
# end
-
# cache.fetch('city') # => "Duckburgh"
-
#
-
# You may also specify additional options via the +options+ argument.
-
# Setting <tt>force: true</tt> will force a cache miss:
-
#
-
# cache.write('today', 'Monday')
-
# cache.fetch('today', force: true) # => nil
-
#
-
# Setting <tt>:compress</tt> will store a large cache entry set by the call
-
# in a compressed format.
-
#
-
# Setting <tt>:expires_in</tt> will set an expiration time on the cache.
-
# All caches support auto-expiring content after a specified number of
-
# seconds. This value can be specified as an option to the constructor
-
# (in which case all entries will be affected), or it can be supplied to
-
# the +fetch+ or +write+ method to effect just one entry.
-
#
-
# cache = ActiveSupport::Cache::MemoryStore.new(expires_in: 5.minutes)
-
# cache.write(key, value, expires_in: 1.minute) # Set a lower value for one entry
-
#
-
# Setting <tt>:race_condition_ttl</tt> is very useful in situations where
-
# a cache entry is used very frequently and is under heavy load. If a
-
# cache expires and due to heavy load several different processes will try
-
# to read data natively and then they all will try to write to cache. To
-
# avoid that case the first process to find an expired cache entry will
-
# bump the cache expiration time by the value set in <tt>:race_condition_ttl</tt>.
-
# Yes, this process is extending the time for a stale value by another few
-
# seconds. Because of extended life of the previous cache, other processes
-
# will continue to use slightly stale data for a just a bit longer. In the
-
# meantime that first process will go ahead and will write into cache the
-
# new value. After that all the processes will start getting new value.
-
# The key is to keep <tt>:race_condition_ttl</tt> small.
-
#
-
# If the process regenerating the entry errors out, the entry will be
-
# regenerated after the specified number of seconds. Also note that the
-
# life of stale cache is extended only if it expired recently. Otherwise
-
# a new value is generated and <tt>:race_condition_ttl</tt> does not play
-
# any role.
-
#
-
# # Set all values to expire after one minute.
-
# cache = ActiveSupport::Cache::MemoryStore.new(expires_in: 1.minute)
-
#
-
# cache.write('foo', 'original value')
-
# val_1 = nil
-
# val_2 = nil
-
# sleep 60
-
#
-
# Thread.new do
-
# val_1 = cache.fetch('foo', race_condition_ttl: 10) do
-
# sleep 1
-
# 'new value 1'
-
# end
-
# end
-
#
-
# Thread.new do
-
# val_2 = cache.fetch('foo', race_condition_ttl: 10) do
-
# 'new value 2'
-
# end
-
# end
-
#
-
# # val_1 => "new value 1"
-
# # val_2 => "original value"
-
# # sleep 10 # First thread extend the life of cache by another 10 seconds
-
# # cache.fetch('foo') => "new value 1"
-
#
-
# Other options will be handled by the specific cache store implementation.
-
# Internally, #fetch calls #read_entry, and calls #write_entry on a cache
-
# miss. +options+ will be passed to the #read and #write calls.
-
#
-
# For example, MemCacheStore's #write method supports the +:raw+
-
# option, which tells the memcached server to store all values as strings.
-
# We can use this option with #fetch too:
-
#
-
# cache = ActiveSupport::Cache::MemCacheStore.new
-
# cache.fetch("foo", force: true, raw: true) do
-
# :bar
-
# end
-
# cache.fetch('foo') # => "bar"
-
2
def fetch(name, options = nil)
-
if block_given?
-
options = merged_options(options)
-
key = namespaced_key(name, options)
-
-
cached_entry = find_cached_entry(key, name, options) unless options[:force]
-
entry = handle_expired_entry(cached_entry, key, options)
-
-
if entry
-
get_entry_value(entry, name, options)
-
else
-
save_block_result_to_cache(name, options) { |_name| yield _name }
-
end
-
else
-
read(name, options)
-
end
-
end
-
-
# Fetches data from the cache, using the given key. If there is data in
-
# the cache with the given key, then that data is returned. Otherwise,
-
# +nil+ is returned.
-
#
-
# Options are passed to the underlying cache implementation.
-
2
def read(name, options = nil)
-
options = merged_options(options)
-
key = namespaced_key(name, options)
-
instrument(:read, name, options) do |payload|
-
entry = read_entry(key, options)
-
if entry
-
if entry.expired?
-
delete_entry(key, options)
-
payload[:hit] = false if payload
-
nil
-
else
-
payload[:hit] = true if payload
-
entry.value
-
end
-
else
-
payload[:hit] = false if payload
-
nil
-
end
-
end
-
end
-
-
# Read multiple values at once from the cache. Options can be passed
-
# in the last argument.
-
#
-
# Some cache implementation may optimize this method.
-
#
-
# Returns a hash mapping the names provided to the values found.
-
2
def read_multi(*names)
-
options = names.extract_options!
-
options = merged_options(options)
-
results = {}
-
names.each do |name|
-
key = namespaced_key(name, options)
-
entry = read_entry(key, options)
-
if entry
-
if entry.expired?
-
delete_entry(key, options)
-
else
-
results[name] = entry.value
-
end
-
end
-
end
-
results
-
end
-
-
# Fetches data from the cache, using the given keys. If there is data in
-
# the cache with the given keys, then that data is returned. Otherwise,
-
# the supplied block is called for each key for which there was no data,
-
# and the result will be written to the cache and returned.
-
#
-
# Options are passed to the underlying cache implementation.
-
#
-
# Returns an array with the data for each of the names. For example:
-
#
-
# cache.write("bim", "bam")
-
# cache.fetch_multi("bim", "boom") {|key| key * 2 }
-
# # => ["bam", "boomboom"]
-
#
-
2
def fetch_multi(*names)
-
options = names.extract_options!
-
options = merged_options(options)
-
-
results = read_multi(*names, options)
-
-
names.map do |name|
-
results.fetch(name) do
-
value = yield name
-
write(name, value, options)
-
value
-
end
-
end
-
end
-
-
# Writes the value to the cache, with the key.
-
#
-
# Options are passed to the underlying cache implementation.
-
2
def write(name, value, options = nil)
-
options = merged_options(options)
-
-
instrument(:write, name, options) do
-
entry = Entry.new(value, options)
-
write_entry(namespaced_key(name, options), entry, options)
-
end
-
end
-
-
# Deletes an entry in the cache. Returns +true+ if an entry is deleted.
-
#
-
# Options are passed to the underlying cache implementation.
-
2
def delete(name, options = nil)
-
options = merged_options(options)
-
-
instrument(:delete, name) do
-
delete_entry(namespaced_key(name, options), options)
-
end
-
end
-
-
# Returns +true+ if the cache contains an entry for the given key.
-
#
-
# Options are passed to the underlying cache implementation.
-
2
def exist?(name, options = nil)
-
options = merged_options(options)
-
-
instrument(:exist?, name) do
-
entry = read_entry(namespaced_key(name, options), options)
-
(entry && !entry.expired?) || false
-
end
-
end
-
-
# Delete all entries with keys matching the pattern.
-
#
-
# Options are passed to the underlying cache implementation.
-
#
-
# All implementations may not support this method.
-
2
def delete_matched(matcher, options = nil)
-
raise NotImplementedError.new("#{self.class.name} does not support delete_matched")
-
end
-
-
# Increment an integer value in the cache.
-
#
-
# Options are passed to the underlying cache implementation.
-
#
-
# All implementations may not support this method.
-
2
def increment(name, amount = 1, options = nil)
-
raise NotImplementedError.new("#{self.class.name} does not support increment")
-
end
-
-
# Decrement an integer value in the cache.
-
#
-
# Options are passed to the underlying cache implementation.
-
#
-
# All implementations may not support this method.
-
2
def decrement(name, amount = 1, options = nil)
-
raise NotImplementedError.new("#{self.class.name} does not support decrement")
-
end
-
-
# Cleanup the cache by removing expired entries.
-
#
-
# Options are passed to the underlying cache implementation.
-
#
-
# All implementations may not support this method.
-
2
def cleanup(options = nil)
-
raise NotImplementedError.new("#{self.class.name} does not support cleanup")
-
end
-
-
# Clear the entire cache. Be careful with this method since it could
-
# affect other processes if shared cache is being used.
-
#
-
# The options hash is passed to the underlying cache implementation.
-
#
-
# All implementations may not support this method.
-
2
def clear(options = nil)
-
raise NotImplementedError.new("#{self.class.name} does not support clear")
-
end
-
-
2
protected
-
# Add the namespace defined in the options to a pattern designed to
-
# match keys. Implementations that support delete_matched should call
-
# this method to translate a pattern that matches names into one that
-
# matches namespaced keys.
-
2
def key_matcher(pattern, options)
-
prefix = options[:namespace].is_a?(Proc) ? options[:namespace].call : options[:namespace]
-
if prefix
-
source = pattern.source
-
if source.start_with?('^')
-
source = source[1, source.length]
-
else
-
source = ".*#{source[0, source.length]}"
-
end
-
Regexp.new("^#{Regexp.escape(prefix)}:#{source}", pattern.options)
-
else
-
pattern
-
end
-
end
-
-
# Read an entry from the cache implementation. Subclasses must implement
-
# this method.
-
2
def read_entry(key, options) # :nodoc:
-
raise NotImplementedError.new
-
end
-
-
# Write an entry to the cache implementation. Subclasses must implement
-
# this method.
-
2
def write_entry(key, entry, options) # :nodoc:
-
raise NotImplementedError.new
-
end
-
-
# Delete an entry from the cache implementation. Subclasses must
-
# implement this method.
-
2
def delete_entry(key, options) # :nodoc:
-
raise NotImplementedError.new
-
end
-
-
2
private
-
# Merge the default options with ones specific to a method call.
-
2
def merged_options(call_options) # :nodoc:
-
if call_options
-
options.merge(call_options)
-
else
-
options.dup
-
end
-
end
-
-
# Expand key to be a consistent string value. Invoke +cache_key+ if
-
# object responds to +cache_key+. Otherwise, +to_param+ method will be
-
# called. If the key is a Hash, then keys will be sorted alphabetically.
-
2
def expanded_key(key) # :nodoc:
-
return key.cache_key.to_s if key.respond_to?(:cache_key)
-
-
case key
-
when Array
-
if key.size > 1
-
key = key.collect{|element| expanded_key(element)}
-
else
-
key = key.first
-
end
-
when Hash
-
key = key.sort_by { |k,_| k.to_s }.collect{|k,v| "#{k}=#{v}"}
-
end
-
-
key.to_param
-
end
-
-
# Prefix a key with the namespace. Namespace and key will be delimited
-
# with a colon.
-
2
def namespaced_key(key, options)
-
key = expanded_key(key)
-
namespace = options[:namespace] if options
-
prefix = namespace.is_a?(Proc) ? namespace.call : namespace
-
key = "#{prefix}:#{key}" if prefix
-
key
-
end
-
-
2
def instrument(operation, key, options = nil)
-
log(operation, key, options)
-
-
if self.class.instrument
-
payload = { :key => key }
-
payload.merge!(options) if options.is_a?(Hash)
-
ActiveSupport::Notifications.instrument("cache_#{operation}.active_support", payload){ yield(payload) }
-
else
-
yield(nil)
-
end
-
end
-
-
2
def log(operation, key, options = nil)
-
return unless logger && logger.debug? && !silence?
-
logger.debug("Cache #{operation}: #{key}#{options.blank? ? "" : " (#{options.inspect})"}")
-
end
-
-
2
def find_cached_entry(key, name, options)
-
instrument(:read, name, options) do |payload|
-
payload[:super_operation] = :fetch if payload
-
read_entry(key, options)
-
end
-
end
-
-
2
def handle_expired_entry(entry, key, options)
-
if entry && entry.expired?
-
race_ttl = options[:race_condition_ttl].to_i
-
if race_ttl && (Time.now.to_f - entry.expires_at <= race_ttl)
-
# When an entry has :race_condition_ttl defined, put the stale entry back into the cache
-
# for a brief period while the entry is begin recalculated.
-
entry.expires_at = Time.now + race_ttl
-
write_entry(key, entry, :expires_in => race_ttl * 2)
-
else
-
delete_entry(key, options)
-
end
-
entry = nil
-
end
-
entry
-
end
-
-
2
def get_entry_value(entry, name, options)
-
instrument(:fetch_hit, name, options) { |payload| }
-
entry.value
-
end
-
-
2
def save_block_result_to_cache(name, options)
-
result = instrument(:generate, name, options) do |payload|
-
yield(name)
-
end
-
-
write(name, result, options)
-
result
-
end
-
end
-
-
# This class is used to represent cache entries. Cache entries have a value and an optional
-
# expiration time. The expiration time is used to support the :race_condition_ttl option
-
# on the cache.
-
#
-
# Since cache entries in most instances will be serialized, the internals of this class are highly optimized
-
# using short instance variable names that are lazily defined.
-
2
class Entry # :nodoc:
-
2
DEFAULT_COMPRESS_LIMIT = 16.kilobytes
-
-
# Create a new cache entry for the specified value. Options supported are
-
# +:compress+, +:compress_threshold+, and +:expires_in+.
-
2
def initialize(value, options = {})
-
if should_compress?(value, options)
-
@value = compress(value)
-
@compressed = true
-
else
-
@value = value
-
end
-
-
@created_at = Time.now.to_f
-
@expires_in = options[:expires_in]
-
@expires_in = @expires_in.to_f if @expires_in
-
end
-
-
2
def value
-
convert_version_4beta1_entry! if defined?(@v)
-
compressed? ? uncompress(@value) : @value
-
end
-
-
# Check if the entry is expired. The +expires_in+ parameter can override
-
# the value set when the entry was created.
-
2
def expired?
-
convert_version_4beta1_entry! if defined?(@value)
-
@expires_in && @created_at + @expires_in <= Time.now.to_f
-
end
-
-
2
def expires_at
-
@expires_in ? @created_at + @expires_in : nil
-
end
-
-
2
def expires_at=(value)
-
if value
-
@expires_in = value.to_f - @created_at
-
else
-
@expires_in = nil
-
end
-
end
-
-
# Returns the size of the cached value. This could be less than
-
# <tt>value.size</tt> if the data is compressed.
-
2
def size
-
if defined?(@s)
-
@s
-
else
-
case value
-
when NilClass
-
0
-
when String
-
@value.bytesize
-
else
-
@s = Marshal.dump(@value).bytesize
-
end
-
end
-
end
-
-
# Duplicate the value in a class. This is used by cache implementations that don't natively
-
# serialize entries to protect against accidental cache modifications.
-
2
def dup_value!
-
convert_version_4beta1_entry! if defined?(@v)
-
-
if @value && !compressed? && !(@value.is_a?(Numeric) || @value == true || @value == false)
-
if @value.is_a?(String)
-
@value = @value.dup
-
else
-
@value = Marshal.load(Marshal.dump(@value))
-
end
-
end
-
end
-
-
2
private
-
2
def should_compress?(value, options)
-
if value && options[:compress]
-
compress_threshold = options[:compress_threshold] || DEFAULT_COMPRESS_LIMIT
-
serialized_value_size = (value.is_a?(String) ? value : Marshal.dump(value)).bytesize
-
-
return true if serialized_value_size >= compress_threshold
-
end
-
-
false
-
end
-
-
2
def compressed?
-
defined?(@compressed) ? @compressed : false
-
end
-
-
2
def compress(value)
-
Zlib::Deflate.deflate(Marshal.dump(value))
-
end
-
-
2
def uncompress(value)
-
Marshal.load(Zlib::Inflate.inflate(value))
-
end
-
-
# The internals of this method changed between Rails 3.x and 4.0. This method provides the glue
-
# to ensure that cache entries created under the old version still work with the new class definition.
-
2
def convert_version_4beta1_entry!
-
if defined?(@v)
-
@value = @v
-
remove_instance_variable(:@v)
-
end
-
-
if defined?(@c)
-
@compressed = @c
-
remove_instance_variable(:@c)
-
end
-
-
if defined?(@x) && @x
-
@created_at ||= Time.now.to_f
-
@expires_in = @x - @created_at
-
remove_instance_variable(:@x)
-
end
-
end
-
end
-
end
-
end
-
2
require 'active_support/core_ext/marshal'
-
2
require 'active_support/core_ext/file/atomic'
-
2
require 'active_support/core_ext/string/conversions'
-
2
require 'uri/common'
-
-
2
module ActiveSupport
-
2
module Cache
-
# A cache store implementation which stores everything on the filesystem.
-
#
-
# FileStore implements the Strategy::LocalCache strategy which implements
-
# an in-memory cache inside of a block.
-
2
class FileStore < Store
-
2
attr_reader :cache_path
-
-
2
DIR_FORMATTER = "%03X"
-
2
FILENAME_MAX_SIZE = 228 # max filename size on file system is 255, minus room for timestamp and random characters appended by Tempfile (used by atomic write)
-
2
EXCLUDED_DIRS = ['.', '..'].freeze
-
-
2
def initialize(cache_path, options = nil)
-
2
super(options)
-
2
@cache_path = cache_path.to_s
-
2
extend Strategy::LocalCache
-
end
-
-
# Deletes all items from the cache. In this case it deletes all the entries in the specified
-
# file store directory except for .gitkeep. Be careful which directory is specified in your
-
# config file when using +FileStore+ because everything in that directory will be deleted.
-
2
def clear(options = nil)
-
root_dirs = Dir.entries(cache_path).reject {|f| (EXCLUDED_DIRS + [".gitkeep"]).include?(f)}
-
FileUtils.rm_r(root_dirs.collect{|f| File.join(cache_path, f)})
-
end
-
-
# Preemptively iterates through all stored keys and removes the ones which have expired.
-
2
def cleanup(options = nil)
-
options = merged_options(options)
-
search_dir(cache_path) do |fname|
-
key = file_path_key(fname)
-
entry = read_entry(key, options)
-
delete_entry(key, options) if entry && entry.expired?
-
end
-
end
-
-
# Increments an already existing integer value that is stored in the cache.
-
# If the key is not found nothing is done.
-
2
def increment(name, amount = 1, options = nil)
-
modify_value(name, amount, options)
-
end
-
-
# Decrements an already existing integer value that is stored in the cache.
-
# If the key is not found nothing is done.
-
2
def decrement(name, amount = 1, options = nil)
-
modify_value(name, -amount, options)
-
end
-
-
2
def delete_matched(matcher, options = nil)
-
options = merged_options(options)
-
instrument(:delete_matched, matcher.inspect) do
-
matcher = key_matcher(matcher, options)
-
search_dir(cache_path) do |path|
-
key = file_path_key(path)
-
delete_entry(key, options) if key.match(matcher)
-
end
-
end
-
end
-
-
2
protected
-
-
2
def read_entry(key, options)
-
file_name = key_file_path(key)
-
if File.exist?(file_name)
-
File.open(file_name) { |f| Marshal.load(f) }
-
end
-
rescue => e
-
logger.error("FileStoreError (#{e}): #{e.message}") if logger
-
nil
-
end
-
-
2
def write_entry(key, entry, options)
-
file_name = key_file_path(key)
-
return false if options[:unless_exist] && File.exist?(file_name)
-
ensure_cache_path(File.dirname(file_name))
-
File.atomic_write(file_name, cache_path) {|f| Marshal.dump(entry, f)}
-
true
-
end
-
-
2
def delete_entry(key, options)
-
file_name = key_file_path(key)
-
if File.exist?(file_name)
-
begin
-
File.delete(file_name)
-
delete_empty_directories(File.dirname(file_name))
-
true
-
rescue => e
-
# Just in case the error was caused by another process deleting the file first.
-
raise e if File.exist?(file_name)
-
false
-
end
-
end
-
end
-
-
2
private
-
# Lock a file for a block so only one process can modify it at a time.
-
2
def lock_file(file_name, &block) # :nodoc:
-
if File.exist?(file_name)
-
File.open(file_name, 'r+') do |f|
-
begin
-
f.flock File::LOCK_EX
-
yield
-
ensure
-
f.flock File::LOCK_UN
-
end
-
end
-
else
-
yield
-
end
-
end
-
-
# Translate a key into a file path.
-
2
def key_file_path(key)
-
fname = URI.encode_www_form_component(key)
-
hash = Zlib.adler32(fname)
-
hash, dir_1 = hash.divmod(0x1000)
-
dir_2 = hash.modulo(0x1000)
-
fname_paths = []
-
-
# Make sure file name doesn't exceed file system limits.
-
begin
-
fname_paths << fname[0, FILENAME_MAX_SIZE]
-
fname = fname[FILENAME_MAX_SIZE..-1]
-
end until fname.blank?
-
-
File.join(cache_path, DIR_FORMATTER % dir_1, DIR_FORMATTER % dir_2, *fname_paths)
-
end
-
-
# Translate a file path into a key.
-
2
def file_path_key(path)
-
fname = path[cache_path.to_s.size..-1].split(File::SEPARATOR, 4).last
-
URI.decode_www_form_component(fname, Encoding::UTF_8)
-
end
-
-
# Delete empty directories in the cache.
-
2
def delete_empty_directories(dir)
-
return if File.realpath(dir) == File.realpath(cache_path)
-
if Dir.entries(dir).reject {|f| EXCLUDED_DIRS.include?(f)}.empty?
-
Dir.delete(dir) rescue nil
-
delete_empty_directories(File.dirname(dir))
-
end
-
end
-
-
# Make sure a file path's directories exist.
-
2
def ensure_cache_path(path)
-
FileUtils.makedirs(path) unless File.exist?(path)
-
end
-
-
2
def search_dir(dir, &callback)
-
return if !File.exist?(dir)
-
Dir.foreach(dir) do |d|
-
next if EXCLUDED_DIRS.include?(d)
-
name = File.join(dir, d)
-
if File.directory?(name)
-
search_dir(name, &callback)
-
else
-
callback.call name
-
end
-
end
-
end
-
-
# Modifies the amount of an already existing integer value that is stored in the cache.
-
# If the key is not found nothing is done.
-
2
def modify_value(name, amount, options)
-
file_name = key_file_path(namespaced_key(name, options))
-
-
lock_file(file_name) do
-
options = merged_options(options)
-
-
if num = read(name, options)
-
num = num.to_i + amount
-
write(name, num, options)
-
num
-
end
-
end
-
end
-
end
-
end
-
end
-
2
require 'active_support/core_ext/object/duplicable'
-
2
require 'active_support/core_ext/string/inflections'
-
2
require 'active_support/per_thread_registry'
-
-
2
module ActiveSupport
-
2
module Cache
-
2
module Strategy
-
# Caches that implement LocalCache will be backed by an in-memory cache for the
-
# duration of a block. Repeated calls to the cache for the same key will hit the
-
# in-memory cache for faster access.
-
2
module LocalCache
-
2
autoload :Middleware, 'active_support/cache/strategy/local_cache_middleware'
-
-
# Class for storing and registering the local caches.
-
2
class LocalCacheRegistry # :nodoc:
-
2
extend ActiveSupport::PerThreadRegistry
-
-
2
def initialize
-
1
@registry = {}
-
end
-
-
2
def cache_for(local_cache_key)
-
@registry[local_cache_key]
-
end
-
-
2
def set_cache_for(local_cache_key, value)
-
26
@registry[local_cache_key] = value
-
end
-
-
28
def self.set_cache_for(l, v); instance.set_cache_for l, v; end
-
2
def self.cache_for(l); instance.cache_for l; end
-
end
-
-
# Simple memory backed cache. This cache is not thread safe and is intended only
-
# for serving as a temporary memory cache for a single thread.
-
2
class LocalStore < Store
-
2
def initialize
-
13
super
-
13
@data = {}
-
end
-
-
# Don't allow synchronizing since it isn't thread safe,
-
2
def synchronize # :nodoc:
-
yield
-
end
-
-
2
def clear(options = nil)
-
@data.clear
-
end
-
-
2
def read_entry(key, options)
-
@data[key]
-
end
-
-
2
def write_entry(key, value, options)
-
@data[key] = value
-
true
-
end
-
-
2
def delete_entry(key, options)
-
!!@data.delete(key)
-
end
-
end
-
-
# Use a local cache for the duration of block.
-
2
def with_local_cache
-
use_temporary_local_cache(LocalStore.new) { yield }
-
end
-
# Middleware class can be inserted as a Rack handler to be local cache for the
-
# duration of request.
-
2
def middleware
-
@middleware ||= Middleware.new(
-
"ActiveSupport::Cache::Strategy::LocalCache",
-
2
local_cache_key)
-
end
-
-
2
def clear(options = nil) # :nodoc:
-
local_cache.clear(options) if local_cache
-
super
-
end
-
-
2
def cleanup(options = nil) # :nodoc:
-
local_cache.clear(options) if local_cache
-
super
-
end
-
-
2
def increment(name, amount = 1, options = nil) # :nodoc:
-
value = bypass_local_cache{super}
-
increment_or_decrement(value, name, amount, options)
-
value
-
end
-
-
2
def decrement(name, amount = 1, options = nil) # :nodoc:
-
value = bypass_local_cache{super}
-
increment_or_decrement(value, name, amount, options)
-
value
-
end
-
-
2
protected
-
2
def read_entry(key, options) # :nodoc:
-
if local_cache
-
entry = local_cache.read_entry(key, options)
-
unless entry
-
entry = super
-
local_cache.write_entry(key, entry, options)
-
end
-
entry
-
else
-
super
-
end
-
end
-
-
2
def write_entry(key, entry, options) # :nodoc:
-
local_cache.write_entry(key, entry, options) if local_cache
-
super
-
end
-
-
2
def delete_entry(key, options) # :nodoc:
-
local_cache.delete_entry(key, options) if local_cache
-
super
-
end
-
-
2
private
-
2
def increment_or_decrement(value, name, amount, options)
-
if local_cache
-
local_cache.mute do
-
if value
-
local_cache.write(name, value, options)
-
else
-
local_cache.delete(name, options)
-
end
-
end
-
end
-
end
-
-
2
def local_cache_key
-
2
@local_cache_key ||= "#{self.class.name.underscore}_local_cache_#{object_id}".gsub(/[\/-]/, '_').to_sym
-
end
-
-
2
def local_cache
-
LocalCacheRegistry.cache_for(local_cache_key)
-
end
-
-
2
def bypass_local_cache
-
use_temporary_local_cache(nil) { yield }
-
end
-
-
2
def use_temporary_local_cache(temporary_cache)
-
save_cache = LocalCacheRegistry.cache_for(local_cache_key)
-
begin
-
LocalCacheRegistry.set_cache_for(local_cache_key, temporary_cache)
-
yield
-
ensure
-
LocalCacheRegistry.set_cache_for(local_cache_key, save_cache)
-
end
-
end
-
end
-
end
-
end
-
end
-
2
require 'rack/body_proxy'
-
2
module ActiveSupport
-
2
module Cache
-
2
module Strategy
-
2
module LocalCache
-
-
#--
-
# This class wraps up local storage for middlewares. Only the middleware method should
-
# construct them.
-
2
class Middleware # :nodoc:
-
2
attr_reader :name, :local_cache_key
-
-
2
def initialize(name, local_cache_key)
-
2
@name = name
-
2
@local_cache_key = local_cache_key
-
2
@app = nil
-
end
-
-
2
def new(app)
-
2
@app = app
-
2
self
-
end
-
-
2
def call(env)
-
13
LocalCacheRegistry.set_cache_for(local_cache_key, LocalStore.new)
-
13
response = @app.call(env)
-
13
response[2] = ::Rack::BodyProxy.new(response[2]) do
-
13
LocalCacheRegistry.set_cache_for(local_cache_key, nil)
-
end
-
13
response
-
rescue Exception
-
LocalCacheRegistry.set_cache_for(local_cache_key, nil)
-
raise
-
end
-
end
-
end
-
end
-
end
-
end
-
2
require 'active_support/concern'
-
2
require 'active_support/descendants_tracker'
-
2
require 'active_support/core_ext/array/extract_options'
-
2
require 'active_support/core_ext/class/attribute'
-
2
require 'active_support/core_ext/kernel/reporting'
-
2
require 'active_support/core_ext/kernel/singleton_class'
-
2
require 'thread'
-
-
2
module ActiveSupport
-
# Callbacks are code hooks that are run at key points in an object's life cycle.
-
# The typical use case is to have a base class define a set of callbacks
-
# relevant to the other functionality it supplies, so that subclasses can
-
# install callbacks that enhance or modify the base functionality without
-
# needing to override or redefine methods of the base class.
-
#
-
# Mixing in this module allows you to define the events in the object's
-
# life cycle that will support callbacks (via +ClassMethods.define_callbacks+),
-
# set the instance methods, procs, or callback objects to be called (via
-
# +ClassMethods.set_callback+), and run the installed callbacks at the
-
# appropriate times (via +run_callbacks+).
-
#
-
# Three kinds of callbacks are supported: before callbacks, run before a
-
# certain event; after callbacks, run after the event; and around callbacks,
-
# blocks that surround the event, triggering it when they yield. Callback code
-
# can be contained in instance methods, procs or lambdas, or callback objects
-
# that respond to certain predetermined methods. See +ClassMethods.set_callback+
-
# for details.
-
#
-
# class Record
-
# include ActiveSupport::Callbacks
-
# define_callbacks :save
-
#
-
# def save
-
# run_callbacks :save do
-
# puts "- save"
-
# end
-
# end
-
# end
-
#
-
# class PersonRecord < Record
-
# set_callback :save, :before, :saving_message
-
# def saving_message
-
# puts "saving..."
-
# end
-
#
-
# set_callback :save, :after do |object|
-
# puts "saved"
-
# end
-
# end
-
#
-
# person = PersonRecord.new
-
# person.save
-
#
-
# Output:
-
# saving...
-
# - save
-
# saved
-
2
module Callbacks
-
2
extend Concern
-
-
2
included do
-
14
extend ActiveSupport::DescendantsTracker
-
end
-
-
2
CALLBACK_FILTER_TYPES = [:before, :after, :around]
-
-
# Runs the callbacks for the given event.
-
#
-
# Calls the before and around callbacks in the order they were set, yields
-
# the block (if given one), and then runs the after callbacks in reverse
-
# order.
-
#
-
# If the callback chain was halted, returns +false+. Otherwise returns the
-
# result of the block, or +true+ if no block is given.
-
#
-
# run_callbacks :save do
-
# save
-
# end
-
2
def run_callbacks(kind, &block)
-
1413
cbs = send("_#{kind}_callbacks")
-
1413
if cbs.empty?
-
732
yield if block_given?
-
else
-
681
runner = cbs.compile
-
681
e = Filters::Environment.new(self, false, nil, block)
-
681
runner.call(e).value
-
end
-
end
-
-
2
private
-
-
# A hook invoked every time a before callback is halted.
-
# This can be overridden in AS::Callback implementors in order
-
# to provide better debugging/logging.
-
2
def halted_callback_hook(filter)
-
end
-
-
2
module Conditionals # :nodoc:
-
2
class Value
-
2
def initialize(&block)
-
72
@block = block
-
end
-
1762
def call(target, value); @block.call(value); end
-
end
-
end
-
-
2
module Filters
-
2
Environment = Struct.new(:target, :halted, :value, :run_block)
-
-
2
class End
-
2
def call(env)
-
681
block = env.run_block
-
681
env.value = !env.halted && (!block || block.call)
-
681
env
-
end
-
end
-
2
ENDING = End.new
-
-
2
class Before
-
2
def self.build(next_callback, user_callback, user_conditions, chain_config, filter)
-
91
halted_lambda = chain_config[:terminator]
-
-
91
if chain_config.key?(:terminator) && user_conditions.any?
-
halting_and_conditional(next_callback, user_callback, user_conditions, halted_lambda, filter)
-
91
elsif chain_config.key? :terminator
-
20
halting(next_callback, user_callback, halted_lambda, filter)
-
71
elsif user_conditions.any?
-
3
conditional(next_callback, user_callback, user_conditions)
-
else
-
68
simple next_callback, user_callback
-
end
-
end
-
-
2
private
-
-
2
def self.halting_and_conditional(next_callback, user_callback, user_conditions, halted_lambda, filter)
-
lambda { |env|
-
target = env.target
-
value = env.value
-
halted = env.halted
-
-
if !halted && user_conditions.all? { |c| c.call(target, value) }
-
result = user_callback.call target, value
-
env.halted = halted_lambda.call(target, result)
-
if env.halted
-
target.send :halted_callback_hook, filter
-
end
-
end
-
next_callback.call env
-
}
-
end
-
-
2
def self.halting(next_callback, user_callback, halted_lambda, filter)
-
20
lambda { |env|
-
871
target = env.target
-
871
value = env.value
-
871
halted = env.halted
-
-
871
unless halted
-
871
result = user_callback.call target, value
-
871
env.halted = halted_lambda.call(target, result)
-
871
if env.halted
-
target.send :halted_callback_hook, filter
-
end
-
end
-
871
next_callback.call env
-
}
-
end
-
-
2
def self.conditional(next_callback, user_callback, user_conditions)
-
3
lambda { |env|
-
195
target = env.target
-
195
value = env.value
-
-
390
if user_conditions.all? { |c| c.call(target, value) }
-
193
user_callback.call target, value
-
end
-
195
next_callback.call env
-
}
-
end
-
-
2
def self.simple(next_callback, user_callback)
-
68
lambda { |env|
-
3548
user_callback.call env.target, env.value
-
3548
next_callback.call env
-
}
-
end
-
end
-
-
2
class After
-
2
def self.build(next_callback, user_callback, user_conditions, chain_config)
-
31
if chain_config[:skip_after_callbacks_if_terminated]
-
31
if chain_config.key?(:terminator) && user_conditions.any?
-
27
halting_and_conditional(next_callback, user_callback, user_conditions)
-
4
elsif chain_config.key?(:terminator)
-
4
halting(next_callback, user_callback)
-
elsif user_conditions.any?
-
conditional next_callback, user_callback, user_conditions
-
else
-
simple next_callback, user_callback
-
end
-
else
-
if user_conditions.any?
-
conditional next_callback, user_callback, user_conditions
-
else
-
simple next_callback, user_callback
-
end
-
end
-
end
-
-
2
private
-
-
2
def self.halting_and_conditional(next_callback, user_callback, user_conditions)
-
27
lambda { |env|
-
1760
env = next_callback.call env
-
1760
target = env.target
-
1760
value = env.value
-
1760
halted = env.halted
-
-
3520
if !halted && user_conditions.all? { |c| c.call(target, value) }
-
1760
user_callback.call target, value
-
end
-
1760
env
-
}
-
end
-
-
2
def self.halting(next_callback, user_callback)
-
4
lambda { |env|
-
48
env = next_callback.call env
-
48
unless env.halted
-
48
user_callback.call env.target, env.value
-
end
-
48
env
-
}
-
end
-
-
2
def self.conditional(next_callback, user_callback, user_conditions)
-
lambda { |env|
-
env = next_callback.call env
-
target = env.target
-
value = env.value
-
-
if user_conditions.all? { |c| c.call(target, value) }
-
user_callback.call target, value
-
end
-
env
-
}
-
end
-
-
2
def self.simple(next_callback, user_callback)
-
lambda { |env|
-
env = next_callback.call env
-
user_callback.call env.target, env.value
-
env
-
}
-
end
-
end
-
-
2
class Around
-
2
def self.build(next_callback, user_callback, user_conditions, chain_config)
-
2
if chain_config.key?(:terminator) && user_conditions.any?
-
halting_and_conditional(next_callback, user_callback, user_conditions)
-
2
elsif chain_config.key? :terminator
-
2
halting(next_callback, user_callback)
-
elsif user_conditions.any?
-
conditional(next_callback, user_callback, user_conditions)
-
else
-
simple(next_callback, user_callback)
-
end
-
end
-
-
2
private
-
-
2
def self.halting_and_conditional(next_callback, user_callback, user_conditions)
-
lambda { |env|
-
target = env.target
-
value = env.value
-
halted = env.halted
-
-
if !halted && user_conditions.all? { |c| c.call(target, value) }
-
user_callback.call(target, value) {
-
env = next_callback.call env
-
env.value
-
}
-
env
-
else
-
next_callback.call env
-
end
-
}
-
end
-
-
2
def self.halting(next_callback, user_callback)
-
2
lambda { |env|
-
24
target = env.target
-
24
value = env.value
-
-
24
unless env.halted
-
24
user_callback.call(target, value) {
-
24
env = next_callback.call env
-
24
env.value
-
}
-
24
env
-
else
-
next_callback.call env
-
end
-
}
-
end
-
-
2
def self.conditional(next_callback, user_callback, user_conditions)
-
lambda { |env|
-
target = env.target
-
value = env.value
-
-
if user_conditions.all? { |c| c.call(target, value) }
-
user_callback.call(target, value) {
-
env = next_callback.call env
-
env.value
-
}
-
env
-
else
-
next_callback.call env
-
end
-
}
-
end
-
-
2
def self.simple(next_callback, user_callback)
-
lambda { |env|
-
user_callback.call(env.target, env.value) {
-
env = next_callback.call env
-
env.value
-
}
-
env
-
}
-
end
-
end
-
end
-
-
2
class Callback #:nodoc:#
-
2
def self.build(chain, filter, kind, options)
-
284
new chain.name, filter, kind, options, chain.config
-
end
-
-
2
attr_accessor :kind, :name
-
2
attr_reader :chain_config
-
-
2
def initialize(name, filter, kind, options, chain_config)
-
284
@chain_config = chain_config
-
284
@name = name
-
284
@kind = kind
-
284
@filter = filter
-
284
@key = compute_identifier filter
-
284
@if = Array(options[:if])
-
284
@unless = Array(options[:unless])
-
end
-
-
984
def filter; @key; end
-
2
def raw_filter; @filter; end
-
-
2
def merge(chain, new_options)
-
options = {
-
:if => @if.dup,
-
:unless => @unless.dup
-
}
-
-
options[:if].concat Array(new_options.fetch(:unless, []))
-
options[:unless].concat Array(new_options.fetch(:if, []))
-
-
self.class.build chain, @filter, @kind, options
-
end
-
-
2
def matches?(_kind, _filter)
-
547
@kind == _kind && filter == _filter
-
end
-
-
2
def duplicates?(other)
-
1324
case @filter
-
when Symbol, String
-
547
matches?(other.kind, other.filter)
-
else
-
777
false
-
end
-
end
-
-
# Wraps code with filter
-
2
def apply(next_callback)
-
124
user_conditions = conditions_lambdas
-
124
user_callback = make_lambda @filter
-
-
124
case kind
-
when :before
-
91
Filters::Before.build(next_callback, user_callback, user_conditions, chain_config, @filter)
-
when :after
-
31
Filters::After.build(next_callback, user_callback, user_conditions, chain_config)
-
when :around
-
2
Filters::Around.build(next_callback, user_callback, user_conditions, chain_config)
-
end
-
end
-
-
2
private
-
-
2
def invert_lambda(l)
-
lambda { |*args, &blk| !l.call(*args, &blk) }
-
end
-
-
# Filters support:
-
#
-
# Symbols:: A method to call.
-
# Strings:: Some content to evaluate.
-
# Procs:: A proc to call with the object.
-
# Objects:: An object with a <tt>before_foo</tt> method on it to call.
-
#
-
# All of these objects are compiled into methods and handled
-
# the same after this point:
-
#
-
# Symbols:: Already methods.
-
# Strings:: class_eval'd into methods.
-
# Procs:: using define_method compiled into methods.
-
# Objects::
-
# a method is created that calls the before_foo method
-
# on the object.
-
2
def make_lambda(filter)
-
154
case filter
-
when Symbol
-
3772
lambda { |target, _, &blk| target.send filter, &blk }
-
when String
-
l = eval "lambda { |value| #{filter} }"
-
lambda { |target, value| target.instance_exec(value, &l) }
-
27
when Conditionals::Value then filter
-
when ::Proc
-
23
if filter.arity > 1
-
return lambda { |target, _, &block|
-
raise ArgumentError unless block
-
target.instance_exec(target, block, &filter)
-
}
-
end
-
-
23
if filter.arity <= 0
-
422
lambda { |target, _| target.instance_exec(&filter) }
-
else
-
198
lambda { |target, _| target.instance_exec(target, &filter) }
-
end
-
else
-
36
scopes = Array(chain_config[:scope])
-
72
method_to_call = scopes.map{ |s| public_send(s) }.join("_")
-
-
36
lambda { |target, _, &blk|
-
2338
filter.public_send method_to_call, target, &blk
-
}
-
end
-
end
-
-
2
def compute_identifier(filter)
-
284
case filter
-
when String, ::Proc
-
34
filter.object_id
-
else
-
250
filter
-
end
-
end
-
-
2
def conditions_lambdas
-
30
@if.map { |c| make_lambda c } +
-
124
@unless.map { |c| invert_lambda make_lambda c }
-
end
-
end
-
-
# An Array with a compile method.
-
2
class CallbackChain #:nodoc:#
-
2
include Enumerable
-
-
2
attr_reader :name, :config
-
-
2
def initialize(name, config)
-
40
@name = name
-
40
@config = {
-
:scope => [ :kind ]
-
}.merge!(config)
-
40
@chain = []
-
40
@callbacks = nil
-
40
@mutex = Mutex.new
-
end
-
-
2
def each(&block); @chain.each(&block); end
-
2
def index(o); @chain.index(o); end
-
2692
def empty?; @chain.empty?; end
-
-
2
def insert(index, o)
-
@callbacks = nil
-
@chain.insert(index, o)
-
end
-
-
2
def delete(o)
-
@callbacks = nil
-
@chain.delete(o)
-
end
-
-
2
def clear
-
@callbacks = nil
-
@chain.clear
-
self
-
end
-
-
2
def initialize_copy(other)
-
284
@callbacks = nil
-
284
@chain = other.chain.dup
-
284
@mutex = Mutex.new
-
end
-
-
2
def compile
-
@callbacks || @mutex.synchronize do
-
@callbacks ||= @chain.reverse.inject(Filters::ENDING) do |chain, callback|
-
124
callback.apply chain
-
15
end
-
681
end
-
end
-
-
2
def append(*callbacks)
-
416
callbacks.each { |c| append_one(c) }
-
end
-
-
2
def prepend(*callbacks)
-
152
callbacks.each { |c| prepend_one(c) }
-
end
-
-
2
protected
-
286
def chain; @chain; end
-
-
2
private
-
-
2
def append_one(callback)
-
208
@callbacks = nil
-
208
remove_duplicates(callback)
-
208
@chain.push(callback)
-
end
-
-
2
def prepend_one(callback)
-
76
@callbacks = nil
-
76
remove_duplicates(callback)
-
76
@chain.unshift(callback)
-
end
-
-
2
def remove_duplicates(callback)
-
284
@callbacks = nil
-
1608
@chain.delete_if { |c| callback.duplicates?(c) }
-
end
-
end
-
-
2
module ClassMethods
-
2
def normalize_callback_params(filters, block) # :nodoc:
-
284
type = CALLBACK_FILTER_TYPES.include?(filters.first) ? filters.shift : :before
-
284
options = filters.extract_options!
-
284
filters.unshift(block) if block
-
284
[type, filters, options.dup]
-
end
-
-
# This is used internally to append, prepend and skip callbacks to the
-
# CallbackChain.
-
2
def __update_callbacks(name) #:nodoc:
-
284
([self] + ActiveSupport::DescendantsTracker.descendants(self)).reverse.each do |target|
-
284
chain = target.get_callbacks name
-
284
yield target, chain.dup
-
end
-
end
-
-
# Install a callback for the given event.
-
#
-
# set_callback :save, :before, :before_meth
-
# set_callback :save, :after, :after_meth, if: :condition
-
# set_callback :save, :around, ->(r, &block) { stuff; result = block.call; stuff }
-
#
-
# The second arguments indicates whether the callback is to be run +:before+,
-
# +:after+, or +:around+ the event. If omitted, +:before+ is assumed. This
-
# means the first example above can also be written as:
-
#
-
# set_callback :save, :before_meth
-
#
-
# The callback can be specified as a symbol naming an instance method; as a
-
# proc, lambda, or block; as a string to be instance evaluated; or as an
-
# object that responds to a certain method determined by the <tt>:scope</tt>
-
# argument to +define_callbacks+.
-
#
-
# If a proc, lambda, or block is given, its body is evaluated in the context
-
# of the current object. It can also optionally accept the current object as
-
# an argument.
-
#
-
# Before and around callbacks are called in the order that they are set;
-
# after callbacks are called in the reverse order.
-
#
-
# Around callbacks can access the return value from the event, if it
-
# wasn't halted, from the +yield+ call.
-
#
-
# ===== Options
-
#
-
# * <tt>:if</tt> - A symbol naming an instance method or a proc; the
-
# callback will be called only when it returns a +true+ value.
-
# * <tt>:unless</tt> - A symbol naming an instance method or a proc; the
-
# callback will be called only when it returns a +false+ value.
-
# * <tt>:prepend</tt> - If +true+, the callback will be prepended to the
-
# existing chain rather than appended.
-
2
def set_callback(name, *filter_list, &block)
-
284
type, filters, options = normalize_callback_params(filter_list, block)
-
284
self_chain = get_callbacks name
-
284
mapped = filters.map do |filter|
-
284
Callback.build(self_chain, filter, type, options)
-
end
-
-
284
__update_callbacks(name) do |target, chain|
-
284
options[:prepend] ? chain.prepend(*mapped) : chain.append(*mapped)
-
284
target.set_callbacks name, chain
-
end
-
end
-
-
# Skip a previously set callback. Like +set_callback+, <tt>:if</tt> or
-
# <tt>:unless</tt> options may be passed in order to control when the
-
# callback is skipped.
-
#
-
# class Writer < Person
-
# skip_callback :validate, :before, :check_membership, if: -> { self.age > 18 }
-
# end
-
2
def skip_callback(name, *filter_list, &block)
-
type, filters, options = normalize_callback_params(filter_list, block)
-
-
__update_callbacks(name) do |target, chain|
-
filters.each do |filter|
-
filter = chain.find {|c| c.matches?(type, filter) }
-
-
if filter && options.any?
-
new_filter = filter.merge(chain, options)
-
chain.insert(chain.index(filter), new_filter)
-
end
-
-
chain.delete(filter)
-
end
-
target.set_callbacks name, chain
-
end
-
end
-
-
# Remove all set callbacks for the given event.
-
2
def reset_callbacks(name)
-
callbacks = get_callbacks name
-
-
ActiveSupport::DescendantsTracker.descendants(self).each do |target|
-
chain = target.get_callbacks(name).dup
-
callbacks.each { |c| chain.delete(c) }
-
target.set_callbacks name, chain
-
end
-
-
self.set_callbacks name, callbacks.dup.clear
-
end
-
-
# Define sets of events in the object life cycle that support callbacks.
-
#
-
# define_callbacks :validate
-
# define_callbacks :initialize, :save, :destroy
-
#
-
# ===== Options
-
#
-
# * <tt>:terminator</tt> - Determines when a before filter will halt the
-
# callback chain, preventing following callbacks from being called and
-
# the event from being triggered. This should be a lambda to be executed.
-
# The current object and the return result of the callback will be called
-
# with the lambda.
-
#
-
# define_callbacks :validate, terminator: ->(target, result) { result == false }
-
#
-
# In this example, if any before validate callbacks returns +false+,
-
# other callbacks are not executed. Defaults to +false+, meaning no value
-
# halts the chain.
-
#
-
# * <tt>:skip_after_callbacks_if_terminated</tt> - Determines if after
-
# callbacks should be terminated by the <tt>:terminator</tt> option. By
-
# default after callbacks executed no matter if callback chain was
-
# terminated or not. Option makes sense only when <tt>:terminator</tt>
-
# option is specified.
-
#
-
# * <tt>:scope</tt> - Indicates which methods should be executed when an
-
# object is used as a callback.
-
#
-
# class Audit
-
# def before(caller)
-
# puts 'Audit: before is called'
-
# end
-
#
-
# def before_save(caller)
-
# puts 'Audit: before_save is called'
-
# end
-
# end
-
#
-
# class Account
-
# include ActiveSupport::Callbacks
-
#
-
# define_callbacks :save
-
# set_callback :save, :before, Audit.new
-
#
-
# def save
-
# run_callbacks :save do
-
# puts 'save in main'
-
# end
-
# end
-
# end
-
#
-
# In the above case whenever you save an account the method
-
# <tt>Audit#before</tt> will be called. On the other hand
-
#
-
# define_callbacks :save, scope: [:kind, :name]
-
#
-
# would trigger <tt>Audit#before_save</tt> instead. That's constructed
-
# by calling <tt>#{kind}_#{name}</tt> on the given instance. In this
-
# case "kind" is "before" and "name" is "save". In this context +:kind+
-
# and +:name+ have special meanings: +:kind+ refers to the kind of
-
# callback (before/after/around) and +:name+ refers to the method on
-
# which callbacks are being defined.
-
#
-
# A declaration like
-
#
-
# define_callbacks :save, scope: [:name]
-
#
-
# would call <tt>Audit#save</tt>.
-
2
def define_callbacks(*names)
-
34
options = names.extract_options!
-
34
if options.key?(:terminator) && String === options[:terminator]
-
ActiveSupport::Deprecation.warn "String based terminators are deprecated, please use a lambda"
-
value = options[:terminator]
-
line = class_eval "lambda { |result| #{value} }", __FILE__, __LINE__
-
options[:terminator] = lambda { |target, result| target.instance_exec(result, &line) }
-
end
-
-
34
names.each do |name|
-
40
class_attribute "_#{name}_callbacks"
-
40
set_callbacks name, CallbackChain.new(name, options)
-
end
-
end
-
-
2
protected
-
-
2
def get_callbacks(name)
-
568
send "_#{name}_callbacks"
-
end
-
-
2
def set_callbacks(name, callbacks)
-
324
send "_#{name}_callbacks=", callbacks
-
end
-
end
-
end
-
end
-
2
module ActiveSupport
-
# A typical module looks like this:
-
#
-
# module M
-
# def self.included(base)
-
# base.extend ClassMethods
-
# base.class_eval do
-
# scope :disabled, -> { where(disabled: true) }
-
# end
-
# end
-
#
-
# module ClassMethods
-
# ...
-
# end
-
# end
-
#
-
# By using <tt>ActiveSupport::Concern</tt> the above module could instead be
-
# written as:
-
#
-
# require 'active_support/concern'
-
#
-
# module M
-
# extend ActiveSupport::Concern
-
#
-
# included do
-
# scope :disabled, -> { where(disabled: true) }
-
# end
-
#
-
# module ClassMethods
-
# ...
-
# end
-
# end
-
#
-
# Moreover, it gracefully handles module dependencies. Given a +Foo+ module
-
# and a +Bar+ module which depends on the former, we would typically write the
-
# following:
-
#
-
# module Foo
-
# def self.included(base)
-
# base.class_eval do
-
# def self.method_injected_by_foo
-
# ...
-
# end
-
# end
-
# end
-
# end
-
#
-
# module Bar
-
# def self.included(base)
-
# base.method_injected_by_foo
-
# end
-
# end
-
#
-
# class Host
-
# include Foo # We need to include this dependency for Bar
-
# include Bar # Bar is the module that Host really needs
-
# end
-
#
-
# But why should +Host+ care about +Bar+'s dependencies, namely +Foo+? We
-
# could try to hide these from +Host+ directly including +Foo+ in +Bar+:
-
#
-
# module Bar
-
# include Foo
-
# def self.included(base)
-
# base.method_injected_by_foo
-
# end
-
# end
-
#
-
# class Host
-
# include Bar
-
# end
-
#
-
# Unfortunately this won't work, since when +Foo+ is included, its <tt>base</tt>
-
# is the +Bar+ module, not the +Host+ class. With <tt>ActiveSupport::Concern</tt>,
-
# module dependencies are properly resolved:
-
#
-
# require 'active_support/concern'
-
#
-
# module Foo
-
# extend ActiveSupport::Concern
-
# included do
-
# def self.method_injected_by_foo
-
# ...
-
# end
-
# end
-
# end
-
#
-
# module Bar
-
# extend ActiveSupport::Concern
-
# include Foo
-
#
-
# included do
-
# self.method_injected_by_foo
-
# end
-
# end
-
#
-
# class Host
-
# include Bar # works, Bar takes care now of its dependencies
-
# end
-
2
module Concern
-
2
class MultipleIncludedBlocks < StandardError #:nodoc:
-
2
def initialize
-
super "Cannot define multiple 'included' blocks for a Concern"
-
end
-
end
-
-
2
def self.extended(base) #:nodoc:
-
286
base.instance_variable_set(:@_dependencies, [])
-
end
-
-
2
def append_features(base)
-
866
if base.instance_variable_defined?(:@_dependencies)
-
148
base.instance_variable_get(:@_dependencies) << self
-
148
return false
-
else
-
718
return false if base < self
-
851
@_dependencies.each { |dep| base.send(:include, dep) }
-
546
super
-
546
base.extend const_get(:ClassMethods) if const_defined?(:ClassMethods)
-
546
base.class_eval(&@_included_block) if instance_variable_defined?(:@_included_block)
-
end
-
end
-
-
2
def included(base = nil, &block)
-
1044
if base.nil?
-
178
raise MultipleIncludedBlocks if instance_variable_defined?(:@_included_block)
-
-
178
@_included_block = block
-
else
-
866
super
-
end
-
end
-
end
-
end
-
2
require 'active_support/concern'
-
2
require 'active_support/ordered_options'
-
2
require 'active_support/core_ext/array/extract_options'
-
-
2
module ActiveSupport
-
# Configurable provides a <tt>config</tt> method to store and retrieve
-
# configuration options as an <tt>OrderedHash</tt>.
-
2
module Configurable
-
2
extend ActiveSupport::Concern
-
-
2
class Configuration < ActiveSupport::InheritableOptions
-
2
def compile_methods!
-
4
self.class.compile_methods!(keys)
-
end
-
-
# Compiles reader methods so we don't have to go through method_missing.
-
2
def self.compile_methods!(keys)
-
40
keys.reject { |m| method_defined?(m) }.each do |key|
-
24
class_eval <<-RUBY, __FILE__, __LINE__ + 1
-
def #{key}; _get(#{key.inspect}); end
-
RUBY
-
end
-
end
-
end
-
-
2
module ClassMethods
-
2
def config
-
@_config ||= if respond_to?(:superclass) && superclass.respond_to?(:config)
-
16
superclass.config.inheritable_copy
-
else
-
# create a new "anonymous" class that will host the compiled reader methods
-
2
Class.new(Configuration).new
-
396
end
-
end
-
-
2
def configure
-
yield config
-
end
-
-
# Allows you to add shortcut so that you don't have to refer to attribute
-
# through config. Also look at the example for config to contrast.
-
#
-
# Defines both class and instance config accessors.
-
#
-
# class User
-
# include ActiveSupport::Configurable
-
# config_accessor :allowed_access
-
# end
-
#
-
# User.allowed_access # => nil
-
# User.allowed_access = false
-
# User.allowed_access # => false
-
#
-
# user = User.new
-
# user.allowed_access # => false
-
# user.allowed_access = true
-
# user.allowed_access # => true
-
#
-
# User.allowed_access # => false
-
#
-
# The attribute name must be a valid method name in Ruby.
-
#
-
# class User
-
# include ActiveSupport::Configurable
-
# config_accessor :"1_Badname"
-
# end
-
# # => NameError: invalid config attribute name
-
#
-
# To opt out of the instance writer method, pass <tt>instance_writer: false</tt>.
-
# To opt out of the instance reader method, pass <tt>instance_reader: false</tt>.
-
#
-
# class User
-
# include ActiveSupport::Configurable
-
# config_accessor :allowed_access, instance_reader: false, instance_writer: false
-
# end
-
#
-
# User.allowed_access = false
-
# User.allowed_access # => false
-
#
-
# User.new.allowed_access = true # => NoMethodError
-
# User.new.allowed_access # => NoMethodError
-
#
-
# Or pass <tt>instance_accessor: false</tt>, to opt out both instance methods.
-
#
-
# class User
-
# include ActiveSupport::Configurable
-
# config_accessor :allowed_access, instance_accessor: false
-
# end
-
#
-
# User.allowed_access = false
-
# User.allowed_access # => false
-
#
-
# User.new.allowed_access = true # => NoMethodError
-
# User.new.allowed_access # => NoMethodError
-
#
-
# Also you can pass a block to set up the attribute with a default value.
-
#
-
# class User
-
# include ActiveSupport::Configurable
-
# config_accessor :hair_colors do
-
# [:brown, :black, :blonde, :red]
-
# end
-
# end
-
#
-
# User.hair_colors # => [:brown, :black, :blonde, :red]
-
2
def config_accessor(*names)
-
18
options = names.extract_options!
-
-
18
names.each do |name|
-
38
raise NameError.new('invalid config attribute name') unless name =~ /\A[_A-Za-z]\w*\z/
-
-
38
reader, reader_line = "def #{name}; config.#{name}; end", __LINE__
-
38
writer, writer_line = "def #{name}=(value); config.#{name} = value; end", __LINE__
-
-
38
singleton_class.class_eval reader, __FILE__, reader_line
-
38
singleton_class.class_eval writer, __FILE__, writer_line
-
-
38
unless options[:instance_accessor] == false
-
38
class_eval reader, __FILE__, reader_line unless options[:instance_reader] == false
-
38
class_eval writer, __FILE__, writer_line unless options[:instance_writer] == false
-
end
-
38
send("#{name}=", yield) if block_given?
-
end
-
end
-
end
-
-
# Reads and writes attributes from a configuration <tt>OrderedHash</tt>.
-
#
-
# require 'active_support/configurable'
-
#
-
# class User
-
# include ActiveSupport::Configurable
-
# end
-
#
-
# user = User.new
-
#
-
# user.config.allowed_access = true
-
# user.config.level = 1
-
#
-
# user.config.allowed_access # => true
-
# user.config.level # => 1
-
2
def config
-
94
@_config ||= self.class.config.inheritable_copy
-
end
-
end
-
end
-
-
2
Dir["#{File.dirname(__FILE__)}/core_ext/*.rb"].each do |path|
-
48
require path
-
end
-
2
require 'active_support/core_ext/array/wrap'
-
2
require 'active_support/core_ext/array/access'
-
2
require 'active_support/core_ext/array/conversions'
-
2
require 'active_support/core_ext/array/extract_options'
-
2
require 'active_support/core_ext/array/grouping'
-
2
require 'active_support/core_ext/array/prepend_and_append'
-
2
class Array
-
# Returns the tail of the array from +position+.
-
#
-
# %w( a b c d ).from(0) # => ["a", "b", "c", "d"]
-
# %w( a b c d ).from(2) # => ["c", "d"]
-
# %w( a b c d ).from(10) # => []
-
# %w().from(0) # => []
-
2
def from(position)
-
self[position, length] || []
-
end
-
-
# Returns the beginning of the array up to +position+.
-
#
-
# %w( a b c d ).to(0) # => ["a"]
-
# %w( a b c d ).to(2) # => ["a", "b", "c"]
-
# %w( a b c d ).to(10) # => ["a", "b", "c", "d"]
-
# %w().to(0) # => []
-
2
def to(position)
-
first position + 1
-
end
-
-
# Equal to <tt>self[1]</tt>.
-
#
-
# %w( a b c d e ).second # => "b"
-
2
def second
-
self[1]
-
end
-
-
# Equal to <tt>self[2]</tt>.
-
#
-
# %w( a b c d e ).third # => "c"
-
2
def third
-
self[2]
-
end
-
-
# Equal to <tt>self[3]</tt>.
-
#
-
# %w( a b c d e ).fourth # => "d"
-
2
def fourth
-
self[3]
-
end
-
-
# Equal to <tt>self[4]</tt>.
-
#
-
# %w( a b c d e ).fifth # => "e"
-
2
def fifth
-
self[4]
-
end
-
-
# Equal to <tt>self[41]</tt>. Also known as accessing "the reddit".
-
#
-
# (1..42).to_a.forty_two # => 42
-
2
def forty_two
-
self[41]
-
end
-
end
-
2
require 'active_support/xml_mini'
-
2
require 'active_support/core_ext/hash/keys'
-
2
require 'active_support/core_ext/string/inflections'
-
2
require 'active_support/core_ext/object/to_param'
-
2
require 'active_support/core_ext/object/to_query'
-
-
2
class Array
-
# Converts the array to a comma-separated sentence where the last element is
-
# joined by the connector word.
-
#
-
# You can pass the following options to change the default behavior. If you
-
# pass an option key that doesn't exist in the list below, it will raise an
-
# <tt>ArgumentError</tt>.
-
#
-
# ==== Options
-
#
-
# * <tt>:words_connector</tt> - The sign or word used to join the elements
-
# in arrays with two or more elements (default: ", ").
-
# * <tt>:two_words_connector</tt> - The sign or word used to join the elements
-
# in arrays with two elements (default: " and ").
-
# * <tt>:last_word_connector</tt> - The sign or word used to join the last element
-
# in arrays with three or more elements (default: ", and ").
-
# * <tt>:locale</tt> - If +i18n+ is available, you can set a locale and use
-
# the connector options defined on the 'support.array' namespace in the
-
# corresponding dictionary file.
-
#
-
# ==== Examples
-
#
-
# [].to_sentence # => ""
-
# ['one'].to_sentence # => "one"
-
# ['one', 'two'].to_sentence # => "one and two"
-
# ['one', 'two', 'three'].to_sentence # => "one, two, and three"
-
#
-
# ['one', 'two'].to_sentence(passing: 'invalid option')
-
# # => ArgumentError: Unknown key :passing
-
#
-
# ['one', 'two'].to_sentence(two_words_connector: '-')
-
# # => "one-two"
-
#
-
# ['one', 'two', 'three'].to_sentence(words_connector: ' or ', last_word_connector: ' or at least ')
-
# # => "one or two or at least three"
-
#
-
# Using <tt>:locale</tt> option:
-
#
-
# # Given this locale dictionary:
-
# #
-
# # es:
-
# # support:
-
# # array:
-
# # words_connector: " o "
-
# # two_words_connector: " y "
-
# # last_word_connector: " o al menos "
-
#
-
# ['uno', 'dos'].to_sentence(locale: :es)
-
# # => "uno y dos"
-
#
-
# ['uno', 'dos', 'tres'].to_sentence(locale: :es)
-
# # => "uno o dos o al menos tres"
-
2
def to_sentence(options = {})
-
options.assert_valid_keys(:words_connector, :two_words_connector, :last_word_connector, :locale)
-
-
default_connectors = {
-
:words_connector => ', ',
-
:two_words_connector => ' and ',
-
:last_word_connector => ', and '
-
}
-
if defined?(I18n)
-
i18n_connectors = I18n.translate(:'support.array', locale: options[:locale], default: {})
-
default_connectors.merge!(i18n_connectors)
-
end
-
options = default_connectors.merge!(options)
-
-
case length
-
when 0
-
''
-
when 1
-
self[0].to_s.dup
-
when 2
-
"#{self[0]}#{options[:two_words_connector]}#{self[1]}"
-
else
-
"#{self[0...-1].join(options[:words_connector])}#{options[:last_word_connector]}#{self[-1]}"
-
end
-
end
-
-
# Extends <tt>Array#to_s</tt> to convert a collection of elements into a
-
# comma separated id list if <tt>:db</tt> argument is given as the format.
-
#
-
# Blog.all.to_formatted_s(:db) # => "1,2,3"
-
2
def to_formatted_s(format = :default)
-
8
case format
-
when :db
-
if empty?
-
'null'
-
else
-
collect { |element| element.id }.join(',')
-
end
-
else
-
8
to_default_s
-
end
-
end
-
2
alias_method :to_default_s, :to_s
-
2
alias_method :to_s, :to_formatted_s
-
-
# Returns a string that represents the array in XML by invoking +to_xml+
-
# on each element. Active Record collections delegate their representation
-
# in XML to this method.
-
#
-
# All elements are expected to respond to +to_xml+, if any of them does
-
# not then an exception is raised.
-
#
-
# The root node reflects the class name of the first element in plural
-
# if all elements belong to the same type and that's not Hash:
-
#
-
# customer.projects.to_xml
-
#
-
# <?xml version="1.0" encoding="UTF-8"?>
-
# <projects type="array">
-
# <project>
-
# <amount type="decimal">20000.0</amount>
-
# <customer-id type="integer">1567</customer-id>
-
# <deal-date type="date">2008-04-09</deal-date>
-
# ...
-
# </project>
-
# <project>
-
# <amount type="decimal">57230.0</amount>
-
# <customer-id type="integer">1567</customer-id>
-
# <deal-date type="date">2008-04-15</deal-date>
-
# ...
-
# </project>
-
# </projects>
-
#
-
# Otherwise the root element is "objects":
-
#
-
# [{ foo: 1, bar: 2}, { baz: 3}].to_xml
-
#
-
# <?xml version="1.0" encoding="UTF-8"?>
-
# <objects type="array">
-
# <object>
-
# <bar type="integer">2</bar>
-
# <foo type="integer">1</foo>
-
# </object>
-
# <object>
-
# <baz type="integer">3</baz>
-
# </object>
-
# </objects>
-
#
-
# If the collection is empty the root element is "nil-classes" by default:
-
#
-
# [].to_xml
-
#
-
# <?xml version="1.0" encoding="UTF-8"?>
-
# <nil-classes type="array"/>
-
#
-
# To ensure a meaningful root element use the <tt>:root</tt> option:
-
#
-
# customer_with_no_projects.projects.to_xml(root: 'projects')
-
#
-
# <?xml version="1.0" encoding="UTF-8"?>
-
# <projects type="array"/>
-
#
-
# By default name of the node for the children of root is <tt>root.singularize</tt>.
-
# You can change it with the <tt>:children</tt> option.
-
#
-
# The +options+ hash is passed downwards:
-
#
-
# Message.all.to_xml(skip_types: true)
-
#
-
# <?xml version="1.0" encoding="UTF-8"?>
-
# <messages>
-
# <message>
-
# <created-at>2008-03-07T09:58:18+01:00</created-at>
-
# <id>1</id>
-
# <name>1</name>
-
# <updated-at>2008-03-07T09:58:18+01:00</updated-at>
-
# <user-id>1</user-id>
-
# </message>
-
# </messages>
-
#
-
2
def to_xml(options = {})
-
require 'active_support/builder' unless defined?(Builder)
-
-
options = options.dup
-
options[:indent] ||= 2
-
options[:builder] ||= Builder::XmlMarkup.new(indent: options[:indent])
-
options[:root] ||= \
-
if first.class != Hash && all? { |e| e.is_a?(first.class) }
-
underscored = ActiveSupport::Inflector.underscore(first.class.name)
-
ActiveSupport::Inflector.pluralize(underscored).tr('/', '_')
-
else
-
'objects'
-
end
-
-
builder = options[:builder]
-
builder.instruct! unless options.delete(:skip_instruct)
-
-
root = ActiveSupport::XmlMini.rename_key(options[:root].to_s, options)
-
children = options.delete(:children) || root.singularize
-
attributes = options[:skip_types] ? {} : { type: 'array' }
-
-
if empty?
-
builder.tag!(root, attributes)
-
else
-
builder.tag!(root, attributes) do
-
each { |value| ActiveSupport::XmlMini.to_tag(children, value, options) }
-
yield builder if block_given?
-
end
-
end
-
end
-
end
-
2
class Hash
-
# By default, only instances of Hash itself are extractable.
-
# Subclasses of Hash may implement this method and return
-
# true to declare themselves as extractable. If a Hash
-
# is extractable, Array#extract_options! pops it from
-
# the Array when it is the last element of the Array.
-
2
def extractable_options?
-
640
instance_of?(Hash)
-
end
-
end
-
-
2
class Array
-
# Extracts options from a set of arguments. Removes and returns the last
-
# element in the array if it's a hash, otherwise returns a blank hash.
-
#
-
# def options(*args)
-
# args.extract_options!
-
# end
-
#
-
# options(1, 2) # => {}
-
# options(1, 2, a: :b) # => {:a=>:b}
-
2
def extract_options!
-
2131
if last.is_a?(Hash) && last.extractable_options?
-
640
pop
-
else
-
1491
{}
-
end
-
end
-
end
-
2
class Array
-
# Splits or iterates over the array in groups of size +number+,
-
# padding any remaining slots with +fill_with+ unless it is +false+.
-
#
-
# %w(1 2 3 4 5 6 7 8 9 10).in_groups_of(3) {|group| p group}
-
# ["1", "2", "3"]
-
# ["4", "5", "6"]
-
# ["7", "8", "9"]
-
# ["10", nil, nil]
-
#
-
# %w(1 2 3 4 5).in_groups_of(2, ' ') {|group| p group}
-
# ["1", "2"]
-
# ["3", "4"]
-
# ["5", " "]
-
#
-
# %w(1 2 3 4 5).in_groups_of(2, false) {|group| p group}
-
# ["1", "2"]
-
# ["3", "4"]
-
# ["5"]
-
2
def in_groups_of(number, fill_with = nil)
-
if fill_with == false
-
collection = self
-
else
-
# size % number gives how many extra we have;
-
# subtracting from number gives how many to add;
-
# modulo number ensures we don't add group of just fill.
-
padding = (number - size % number) % number
-
collection = dup.concat(Array.new(padding, fill_with))
-
end
-
-
if block_given?
-
collection.each_slice(number) { |slice| yield(slice) }
-
else
-
collection.each_slice(number).to_a
-
end
-
end
-
-
# Splits or iterates over the array in +number+ of groups, padding any
-
# remaining slots with +fill_with+ unless it is +false+.
-
#
-
# %w(1 2 3 4 5 6 7 8 9 10).in_groups(3) {|group| p group}
-
# ["1", "2", "3", "4"]
-
# ["5", "6", "7", nil]
-
# ["8", "9", "10", nil]
-
#
-
# %w(1 2 3 4 5 6 7 8 9 10).in_groups(3, ' ') {|group| p group}
-
# ["1", "2", "3", "4"]
-
# ["5", "6", "7", " "]
-
# ["8", "9", "10", " "]
-
#
-
# %w(1 2 3 4 5 6 7).in_groups(3, false) {|group| p group}
-
# ["1", "2", "3"]
-
# ["4", "5"]
-
# ["6", "7"]
-
2
def in_groups(number, fill_with = nil)
-
# size.div number gives minor group size;
-
# size % number gives how many objects need extra accommodation;
-
# each group hold either division or division + 1 items.
-
division = size.div number
-
modulo = size % number
-
-
# create a new array avoiding dup
-
groups = []
-
start = 0
-
-
number.times do |index|
-
length = division + (modulo > 0 && modulo > index ? 1 : 0)
-
groups << last_group = slice(start, length)
-
last_group << fill_with if fill_with != false &&
-
modulo > 0 && length == division
-
start += length
-
end
-
-
if block_given?
-
groups.each { |g| yield(g) }
-
else
-
groups
-
end
-
end
-
-
# Divides the array into one or more subarrays based on a delimiting +value+
-
# or the result of an optional block.
-
#
-
# [1, 2, 3, 4, 5].split(3) # => [[1, 2], [4, 5]]
-
# (1..10).to_a.split { |i| i % 3 == 0 } # => [[1, 2], [4, 5], [7, 8], [10]]
-
2
def split(value = nil)
-
if block_given?
-
inject([[]]) do |results, element|
-
if yield(element)
-
results << []
-
else
-
results.last << element
-
end
-
-
results
-
end
-
else
-
results, arr = [[]], self.dup
-
until arr.empty?
-
if (idx = arr.index(value))
-
results.last.concat(arr.shift(idx))
-
arr.shift
-
results << []
-
else
-
results.last.concat(arr.shift(arr.size))
-
end
-
end
-
results
-
end
-
end
-
end
-
2
class Array
-
# The human way of thinking about adding stuff to the end of a list is with append.
-
2
alias_method :append, :<<
-
-
# The human way of thinking about adding stuff to the beginning of a list is with prepend.
-
2
alias_method :prepend, :unshift
-
end
-
2
class Array
-
# Wraps its argument in an array unless it is already an array (or array-like).
-
#
-
# Specifically:
-
#
-
# * If the argument is +nil+ an empty list is returned.
-
# * Otherwise, if the argument responds to +to_ary+ it is invoked, and its result returned.
-
# * Otherwise, returns an array with the argument as its single element.
-
#
-
# Array.wrap(nil) # => []
-
# Array.wrap([1, 2, 3]) # => [1, 2, 3]
-
# Array.wrap(0) # => [0]
-
#
-
# This method is similar in purpose to <tt>Kernel#Array</tt>, but there are some differences:
-
#
-
# * If the argument responds to +to_ary+ the method is invoked. <tt>Kernel#Array</tt>
-
# moves on to try +to_a+ if the returned value is +nil+, but <tt>Array.wrap</tt> returns
-
# +nil+ right away.
-
# * If the returned value from +to_ary+ is neither +nil+ nor an +Array+ object, <tt>Kernel#Array</tt>
-
# raises an exception, while <tt>Array.wrap</tt> does not, it just returns the value.
-
# * It does not call +to_a+ on the argument, but returns an empty array if argument is +nil+.
-
#
-
# The second point is easily explained with some enumerables:
-
#
-
# Array(foo: :bar) # => [[:foo, :bar]]
-
# Array.wrap(foo: :bar) # => [{:foo=>:bar}]
-
#
-
# There's also a related idiom that uses the splat operator:
-
#
-
# [*object]
-
#
-
# which returns <tt>[]</tt> for +nil+, but calls to <tt>Array(object)</tt> otherwise.
-
#
-
# The differences with <tt>Kernel#Array</tt> explained above
-
# apply to the rest of <tt>object</tt>s.
-
2
def self.wrap(object)
-
20
if object.nil?
-
4
[]
-
16
elsif object.respond_to?(:to_ary)
-
4
object.to_ary || [object]
-
else
-
12
[object]
-
end
-
end
-
end
-
2
require 'benchmark'
-
-
2
class << Benchmark
-
# Benchmark realtime in milliseconds.
-
#
-
# Benchmark.realtime { User.all }
-
# # => 8.0e-05
-
#
-
# Benchmark.ms { User.all }
-
# # => 0.074
-
2
def ms
-
48
1000 * realtime { yield }
-
end
-
end
-
2
require 'active_support/core_ext/big_decimal/conversions'
-
2
require 'bigdecimal'
-
2
require 'bigdecimal/util'
-
-
2
class BigDecimal
-
2
DEFAULT_STRING_FORMAT = 'F'
-
2
def to_formatted_s(*args)
-
if args[0].is_a?(Symbol)
-
super
-
else
-
format = args[0] || DEFAULT_STRING_FORMAT
-
_original_to_s(format)
-
end
-
end
-
2
alias_method :_original_to_s, :to_s
-
2
alias_method :to_s, :to_formatted_s
-
end
-
2
require 'active_support/core_ext/class/attribute'
-
2
require 'active_support/core_ext/class/delegating_attributes'
-
2
require 'active_support/core_ext/class/subclasses'
-
2
require 'active_support/core_ext/kernel/singleton_class'
-
2
require 'active_support/core_ext/module/remove_method'
-
2
require 'active_support/core_ext/array/extract_options'
-
-
2
class Class
-
# Declare a class-level attribute whose value is inheritable by subclasses.
-
# Subclasses can change their own value and it will not impact parent class.
-
#
-
# class Base
-
# class_attribute :setting
-
# end
-
#
-
# class Subclass < Base
-
# end
-
#
-
# Base.setting = true
-
# Subclass.setting # => true
-
# Subclass.setting = false
-
# Subclass.setting # => false
-
# Base.setting # => true
-
#
-
# In the above case as long as Subclass does not assign a value to setting
-
# by performing <tt>Subclass.setting = _something_ </tt>, <tt>Subclass.setting</tt>
-
# would read value assigned to parent class. Once Subclass assigns a value then
-
# the value assigned by Subclass would be returned.
-
#
-
# This matches normal Ruby method inheritance: think of writing an attribute
-
# on a subclass as overriding the reader method. However, you need to be aware
-
# when using +class_attribute+ with mutable structures as +Array+ or +Hash+.
-
# In such cases, you don't want to do changes in places but use setters:
-
#
-
# Base.setting = []
-
# Base.setting # => []
-
# Subclass.setting # => []
-
#
-
# # Appending in child changes both parent and child because it is the same object:
-
# Subclass.setting << :foo
-
# Base.setting # => [:foo]
-
# Subclass.setting # => [:foo]
-
#
-
# # Use setters to not propagate changes:
-
# Base.setting = []
-
# Subclass.setting += [:foo]
-
# Base.setting # => []
-
# Subclass.setting # => [:foo]
-
#
-
# For convenience, an instance predicate method is defined as well.
-
# To skip it, pass <tt>instance_predicate: false</tt>.
-
#
-
# Subclass.setting? # => false
-
#
-
# Instances may overwrite the class value in the same way:
-
#
-
# Base.setting = true
-
# object = Base.new
-
# object.setting # => true
-
# object.setting = false
-
# object.setting # => false
-
# Base.setting # => true
-
#
-
# To opt out of the instance reader method, pass <tt>instance_reader: false</tt>.
-
#
-
# object.setting # => NoMethodError
-
# object.setting? # => NoMethodError
-
#
-
# To opt out of the instance writer method, pass <tt>instance_writer: false</tt>.
-
#
-
# object.setting = false # => NoMethodError
-
#
-
# To opt out of both instance methods, pass <tt>instance_accessor: false</tt>.
-
2
def class_attribute(*attrs)
-
399
options = attrs.extract_options!
-
399
instance_reader = options.fetch(:instance_accessor, true) && options.fetch(:instance_reader, true)
-
399
instance_writer = options.fetch(:instance_accessor, true) && options.fetch(:instance_writer, true)
-
399
instance_predicate = options.fetch(:instance_predicate, true)
-
-
399
attrs.each do |name|
-
4678
define_singleton_method(name) { nil }
-
444
define_singleton_method("#{name}?") { !!public_send(name) } if instance_predicate
-
-
444
ivar = "@#{name}"
-
-
444
define_singleton_method("#{name}=") do |val|
-
999
singleton_class.class_eval do
-
999
remove_possible_method(name)
-
18591
define_method(name) { val }
-
end
-
-
999
if singleton_class?
-
class_eval do
-
remove_possible_method(name)
-
define_method(name) do
-
if instance_variable_defined? ivar
-
instance_variable_get ivar
-
else
-
singleton_class.send name
-
end
-
end
-
end
-
end
-
999
val
-
end
-
-
444
if instance_reader
-
424
remove_possible_method name
-
424
define_method(name) do
-
3650
if instance_variable_defined?(ivar)
-
instance_variable_get ivar
-
else
-
3650
self.class.public_send name
-
end
-
end
-
691
define_method("#{name}?") { !!public_send(name) } if instance_predicate
-
end
-
-
444
attr_writer name if instance_writer
-
end
-
end
-
-
2
private
-
-
2
unless respond_to?(:singleton_class?)
-
def singleton_class?
-
ancestors.first != self
-
end
-
end
-
end
-
2
require 'active_support/core_ext/kernel/singleton_class'
-
2
require 'active_support/core_ext/module/remove_method'
-
-
2
class Class
-
2
def superclass_delegating_accessor(name, options = {})
-
# Create private _name and _name= methods that can still be used if the public
-
# methods are overridden.
-
_superclass_delegating_accessor("_#{name}", options)
-
-
# Generate the public methods name, name=, and name?.
-
# These methods dispatch to the private _name, and _name= methods, making them
-
# overridable.
-
singleton_class.send(:define_method, name) { send("_#{name}") }
-
singleton_class.send(:define_method, "#{name}?") { !!send("_#{name}") }
-
singleton_class.send(:define_method, "#{name}=") { |value| send("_#{name}=", value) }
-
-
# If an instance_reader is needed, generate public instance methods name and name?.
-
if options[:instance_reader] != false
-
define_method(name) { send("_#{name}") }
-
define_method("#{name}?") { !!send("#{name}") }
-
end
-
end
-
-
2
private
-
# Take the object being set and store it in a method. This gives us automatic
-
# inheritance behavior, without having to store the object in an instance
-
# variable and look up the superclass chain manually.
-
2
def _stash_object_in_method(object, method, instance_reader = true)
-
singleton_class.remove_possible_method(method)
-
singleton_class.send(:define_method, method) { object }
-
remove_possible_method(method)
-
define_method(method) { object } if instance_reader
-
end
-
-
2
def _superclass_delegating_accessor(name, options = {})
-
singleton_class.send(:define_method, "#{name}=") do |value|
-
_stash_object_in_method(value, name, options[:instance_reader] != false)
-
end
-
send("#{name}=", nil)
-
end
-
end
-
2
require 'active_support/core_ext/module/anonymous'
-
2
require 'active_support/core_ext/module/reachable'
-
-
2
class Class
-
2
begin
-
2
ObjectSpace.each_object(Class.new) {}
-
-
2
def descendants # :nodoc:
-
descendants = []
-
ObjectSpace.each_object(singleton_class) do |k|
-
descendants.unshift k unless k == self
-
end
-
descendants
-
end
-
rescue StandardError # JRuby
-
def descendants # :nodoc:
-
descendants = []
-
ObjectSpace.each_object(Class) do |k|
-
descendants.unshift k if k < self
-
end
-
descendants.uniq!
-
descendants
-
end
-
end
-
-
# Returns an array with the direct children of +self+.
-
#
-
# Integer.subclasses # => [Fixnum, Bignum]
-
#
-
# class Foo; end
-
# class Bar < Foo; end
-
# class Baz < Bar; end
-
#
-
# Foo.subclasses # => [Bar]
-
2
def subclasses
-
subclasses, chain = [], descendants
-
chain.each do |k|
-
subclasses << k unless chain.any? { |c| c > k }
-
end
-
subclasses
-
end
-
end
-
2
require 'active_support/core_ext/date/acts_like'
-
2
require 'active_support/core_ext/date/calculations'
-
2
require 'active_support/core_ext/date/conversions'
-
2
require 'active_support/core_ext/date/zones'
-
-
2
require 'active_support/core_ext/object/acts_like'
-
-
2
class Date
-
# Duck-types as a Date-like class. See Object#acts_like?.
-
2
def acts_like_date?
-
true
-
end
-
end
-
2
require 'date'
-
2
require 'active_support/duration'
-
2
require 'active_support/core_ext/object/acts_like'
-
2
require 'active_support/core_ext/date/zones'
-
2
require 'active_support/core_ext/time/zones'
-
2
require 'active_support/core_ext/date_and_time/calculations'
-
-
2
class Date
-
2
include DateAndTime::Calculations
-
-
2
class << self
-
2
attr_accessor :beginning_of_week_default
-
-
# Returns the week start (e.g. :monday) for the current request, if this has been set (via Date.beginning_of_week=).
-
# If <tt>Date.beginning_of_week</tt> has not been set for the current request, returns the week start specified in <tt>config.beginning_of_week</tt>.
-
# If no config.beginning_of_week was specified, returns :monday.
-
2
def beginning_of_week
-
Thread.current[:beginning_of_week] || beginning_of_week_default || :monday
-
end
-
-
# Sets <tt>Date.beginning_of_week</tt> to a week start (e.g. :monday) for current request/thread.
-
#
-
# This method accepts any of the following day symbols:
-
# :monday, :tuesday, :wednesday, :thursday, :friday, :saturday, :sunday
-
2
def beginning_of_week=(week_start)
-
Thread.current[:beginning_of_week] = find_beginning_of_week!(week_start)
-
end
-
-
# Returns week start day symbol (e.g. :monday), or raises an ArgumentError for invalid day symbol.
-
2
def find_beginning_of_week!(week_start)
-
2
raise ArgumentError, "Invalid beginning of week: #{week_start}" unless ::Date::DAYS_INTO_WEEK.key?(week_start)
-
2
week_start
-
end
-
-
# Returns a new Date representing the date 1 day ago (i.e. yesterday's date).
-
2
def yesterday
-
::Date.current.yesterday
-
end
-
-
# Returns a new Date representing the date 1 day after today (i.e. tomorrow's date).
-
2
def tomorrow
-
::Date.current.tomorrow
-
end
-
-
# Returns Time.zone.today when <tt>Time.zone</tt> or <tt>config.time_zone</tt> are set, otherwise just returns Date.today.
-
2
def current
-
::Time.zone ? ::Time.zone.today : ::Date.today
-
end
-
end
-
-
# Converts Date to a Time (or DateTime if necessary) with the time portion set to the beginning of the day (0:00)
-
# and then subtracts the specified number of seconds.
-
2
def ago(seconds)
-
in_time_zone.since(-seconds)
-
end
-
-
# Converts Date to a Time (or DateTime if necessary) with the time portion set to the beginning of the day (0:00)
-
# and then adds the specified number of seconds
-
2
def since(seconds)
-
in_time_zone.since(seconds)
-
end
-
2
alias :in :since
-
-
# Converts Date to a Time (or DateTime if necessary) with the time portion set to the beginning of the day (0:00)
-
2
def beginning_of_day
-
in_time_zone
-
end
-
2
alias :midnight :beginning_of_day
-
2
alias :at_midnight :beginning_of_day
-
2
alias :at_beginning_of_day :beginning_of_day
-
-
# Converts Date to a Time (or DateTime if necessary) with the time portion set to the middle of the day (12:00)
-
2
def middle_of_day
-
in_time_zone.middle_of_day
-
end
-
2
alias :midday :middle_of_day
-
2
alias :noon :middle_of_day
-
2
alias :at_midday :middle_of_day
-
2
alias :at_noon :middle_of_day
-
2
alias :at_middle_of_day :middle_of_day
-
-
# Converts Date to a Time (or DateTime if necessary) with the time portion set to the end of the day (23:59:59)
-
2
def end_of_day
-
in_time_zone.end_of_day
-
end
-
2
alias :at_end_of_day :end_of_day
-
-
2
def plus_with_duration(other) #:nodoc:
-
if ActiveSupport::Duration === other
-
other.since(self)
-
else
-
plus_without_duration(other)
-
end
-
end
-
2
alias_method :plus_without_duration, :+
-
2
alias_method :+, :plus_with_duration
-
-
2
def minus_with_duration(other) #:nodoc:
-
if ActiveSupport::Duration === other
-
plus_with_duration(-other)
-
else
-
minus_without_duration(other)
-
end
-
end
-
2
alias_method :minus_without_duration, :-
-
2
alias_method :-, :minus_with_duration
-
-
# Provides precise Date calculations for years, months, and days. The +options+ parameter takes a hash with
-
# any of these keys: <tt>:years</tt>, <tt>:months</tt>, <tt>:weeks</tt>, <tt>:days</tt>.
-
2
def advance(options)
-
options = options.dup
-
d = self
-
d = d >> options.delete(:years) * 12 if options[:years]
-
d = d >> options.delete(:months) if options[:months]
-
d = d + options.delete(:weeks) * 7 if options[:weeks]
-
d = d + options.delete(:days) if options[:days]
-
d
-
end
-
-
# Returns a new Date where one or more of the elements have been changed according to the +options+ parameter.
-
# The +options+ parameter is a hash with a combination of these keys: <tt>:year</tt>, <tt>:month</tt>, <tt>:day</tt>.
-
#
-
# Date.new(2007, 5, 12).change(day: 1) # => Date.new(2007, 5, 1)
-
# Date.new(2007, 5, 12).change(year: 2005, month: 1) # => Date.new(2005, 1, 12)
-
2
def change(options)
-
::Date.new(
-
options.fetch(:year, year),
-
options.fetch(:month, month),
-
options.fetch(:day, day)
-
)
-
end
-
-
# Allow Date to be compared with Time by converting to DateTime and relying on the <=> from there.
-
2
def compare_with_coercion(other)
-
if other.is_a?(Time)
-
self.to_datetime <=> other
-
else
-
compare_without_coercion(other)
-
end
-
end
-
2
alias_method :compare_without_coercion, :<=>
-
2
alias_method :<=>, :compare_with_coercion
-
end
-
2
require 'date'
-
2
require 'active_support/inflector/methods'
-
2
require 'active_support/core_ext/date/zones'
-
2
require 'active_support/core_ext/module/remove_method'
-
-
2
class Date
-
2
DATE_FORMATS = {
-
:short => '%e %b',
-
:long => '%B %e, %Y',
-
:db => '%Y-%m-%d',
-
:number => '%Y%m%d',
-
:long_ordinal => lambda { |date|
-
day_format = ActiveSupport::Inflector.ordinalize(date.day)
-
date.strftime("%B #{day_format}, %Y") # => "April 25th, 2007"
-
},
-
:rfc822 => '%e %b %Y',
-
:iso8601 => lambda { |date| date.iso8601 }
-
}
-
-
# Ruby 1.9 has Date#to_time which converts to localtime only.
-
2
remove_method :to_time
-
-
# Ruby 1.9 has Date#xmlschema which converts to a string without the time
-
# component. This removal may generate an issue on FreeBSD, that's why we
-
# need to use remove_possible_method here
-
2
remove_possible_method :xmlschema
-
-
# Convert to a formatted string. See DATE_FORMATS for predefined formats.
-
#
-
# This method is aliased to <tt>to_s</tt>.
-
#
-
# date = Date.new(2007, 11, 10) # => Sat, 10 Nov 2007
-
#
-
# date.to_formatted_s(:db) # => "2007-11-10"
-
# date.to_s(:db) # => "2007-11-10"
-
#
-
# date.to_formatted_s(:short) # => "10 Nov"
-
# date.to_formatted_s(:long) # => "November 10, 2007"
-
# date.to_formatted_s(:long_ordinal) # => "November 10th, 2007"
-
# date.to_formatted_s(:rfc822) # => "10 Nov 2007"
-
# date.to_formatted_s(:iso8601) # => "2007-11-10"
-
#
-
# == Adding your own date formats to to_formatted_s
-
# You can add your own formats to the Date::DATE_FORMATS hash.
-
# Use the format name as the hash key and either a strftime string
-
# or Proc instance that takes a date argument as the value.
-
#
-
# # config/initializers/date_formats.rb
-
# Date::DATE_FORMATS[:month_and_year] = '%B %Y'
-
# Date::DATE_FORMATS[:short_ordinal] = ->(date) { date.strftime("%B #{date.day.ordinalize}") }
-
2
def to_formatted_s(format = :default)
-
if formatter = DATE_FORMATS[format]
-
if formatter.respond_to?(:call)
-
formatter.call(self).to_s
-
else
-
strftime(formatter)
-
end
-
else
-
to_default_s
-
end
-
end
-
2
alias_method :to_default_s, :to_s
-
2
alias_method :to_s, :to_formatted_s
-
-
# Overrides the default inspect method with a human readable one, e.g., "Mon, 21 Feb 2005"
-
2
def readable_inspect
-
strftime('%a, %d %b %Y')
-
end
-
2
alias_method :default_inspect, :inspect
-
2
alias_method :inspect, :readable_inspect
-
-
# Converts a Date instance to a Time, where the time is set to the beginning of the day.
-
# The timezone can be either :local or :utc (default :local).
-
#
-
# date = Date.new(2007, 11, 10) # => Sat, 10 Nov 2007
-
#
-
# date.to_time # => Sat Nov 10 00:00:00 0800 2007
-
# date.to_time(:local) # => Sat Nov 10 00:00:00 0800 2007
-
#
-
# date.to_time(:utc) # => Sat Nov 10 00:00:00 UTC 2007
-
2
def to_time(form = :local)
-
::Time.send(form, year, month, day)
-
end
-
-
2
def xmlschema
-
in_time_zone.xmlschema
-
end
-
end
-
2
require 'date'
-
2
require 'active_support/core_ext/date_and_time/zones'
-
-
2
class Date
-
2
include DateAndTime::Zones
-
end
-
2
module DateAndTime
-
2
module Calculations
-
2
DAYS_INTO_WEEK = {
-
:monday => 0,
-
:tuesday => 1,
-
:wednesday => 2,
-
:thursday => 3,
-
:friday => 4,
-
:saturday => 5,
-
:sunday => 6
-
}
-
-
# Returns a new date/time representing yesterday.
-
2
def yesterday
-
advance(:days => -1)
-
end
-
-
# Returns a new date/time representing tomorrow.
-
2
def tomorrow
-
advance(:days => 1)
-
end
-
-
# Returns true if the date/time is today.
-
2
def today?
-
to_date == ::Date.current
-
end
-
-
# Returns true if the date/time is in the past.
-
2
def past?
-
self < self.class.current
-
end
-
-
# Returns true if the date/time is in the future.
-
2
def future?
-
self > self.class.current
-
end
-
-
# Returns a new date/time the specified number of days ago.
-
2
def days_ago(days)
-
advance(:days => -days)
-
end
-
-
# Returns a new date/time the specified number of days in the future.
-
2
def days_since(days)
-
advance(:days => days)
-
end
-
-
# Returns a new date/time the specified number of weeks ago.
-
2
def weeks_ago(weeks)
-
advance(:weeks => -weeks)
-
end
-
-
# Returns a new date/time the specified number of weeks in the future.
-
2
def weeks_since(weeks)
-
advance(:weeks => weeks)
-
end
-
-
# Returns a new date/time the specified number of months ago.
-
2
def months_ago(months)
-
advance(:months => -months)
-
end
-
-
# Returns a new date/time the specified number of months in the future.
-
2
def months_since(months)
-
advance(:months => months)
-
end
-
-
# Returns a new date/time the specified number of years ago.
-
2
def years_ago(years)
-
advance(:years => -years)
-
end
-
-
# Returns a new date/time the specified number of years in the future.
-
2
def years_since(years)
-
advance(:years => years)
-
end
-
-
# Returns a new date/time at the start of the month.
-
# DateTime objects will have a time set to 0:00.
-
2
def beginning_of_month
-
first_hour(change(:day => 1))
-
end
-
2
alias :at_beginning_of_month :beginning_of_month
-
-
# Returns a new date/time at the start of the quarter.
-
# Example: 1st January, 1st July, 1st October.
-
# DateTime objects will have a time set to 0:00.
-
2
def beginning_of_quarter
-
first_quarter_month = [10, 7, 4, 1].detect { |m| m <= month }
-
beginning_of_month.change(:month => first_quarter_month)
-
end
-
2
alias :at_beginning_of_quarter :beginning_of_quarter
-
-
# Returns a new date/time at the end of the quarter.
-
# Example: 31st March, 30th June, 30th September.
-
# DateTime objects will have a time set to 23:59:59.
-
2
def end_of_quarter
-
last_quarter_month = [3, 6, 9, 12].detect { |m| m >= month }
-
beginning_of_month.change(:month => last_quarter_month).end_of_month
-
end
-
2
alias :at_end_of_quarter :end_of_quarter
-
-
# Return a new date/time at the beginning of the year.
-
# Example: 1st January.
-
# DateTime objects will have a time set to 0:00.
-
2
def beginning_of_year
-
change(:month => 1).beginning_of_month
-
end
-
2
alias :at_beginning_of_year :beginning_of_year
-
-
# Returns a new date/time representing the given day in the next week.
-
# The +given_day_in_next_week+ defaults to the beginning of the week
-
# which is determined by +Date.beginning_of_week+ or +config.beginning_of_week+
-
# when set. +DateTime+ objects have their time set to 0:00.
-
2
def next_week(given_day_in_next_week = Date.beginning_of_week)
-
first_hour(weeks_since(1).beginning_of_week.days_since(days_span(given_day_in_next_week)))
-
end
-
-
# Short-hand for months_since(1).
-
2
def next_month
-
months_since(1)
-
end
-
-
# Short-hand for months_since(3)
-
2
def next_quarter
-
months_since(3)
-
end
-
-
# Short-hand for years_since(1).
-
2
def next_year
-
years_since(1)
-
end
-
-
# Returns a new date/time representing the given day in the previous week.
-
# Week is assumed to start on +start_day+, default is
-
# +Date.beginning_of_week+ or +config.beginning_of_week+ when set.
-
# DateTime objects have their time set to 0:00.
-
2
def prev_week(start_day = Date.beginning_of_week)
-
first_hour(weeks_ago(1).beginning_of_week.days_since(days_span(start_day)))
-
end
-
2
alias_method :last_week, :prev_week
-
-
# Short-hand for months_ago(1).
-
2
def prev_month
-
months_ago(1)
-
end
-
2
alias_method :last_month, :prev_month
-
-
# Short-hand for months_ago(3).
-
2
def prev_quarter
-
months_ago(3)
-
end
-
2
alias_method :last_quarter, :prev_quarter
-
-
# Short-hand for years_ago(1).
-
2
def prev_year
-
years_ago(1)
-
end
-
2
alias_method :last_year, :prev_year
-
-
# Returns the number of days to the start of the week on the given day.
-
# Week is assumed to start on +start_day+, default is
-
# +Date.beginning_of_week+ or +config.beginning_of_week+ when set.
-
2
def days_to_week_start(start_day = Date.beginning_of_week)
-
start_day_number = DAYS_INTO_WEEK[start_day]
-
current_day_number = wday != 0 ? wday - 1 : 6
-
(current_day_number - start_day_number) % 7
-
end
-
-
# Returns a new date/time representing the start of this week on the given day.
-
# Week is assumed to start on +start_day+, default is
-
# +Date.beginning_of_week+ or +config.beginning_of_week+ when set.
-
# +DateTime+ objects have their time set to 0:00.
-
2
def beginning_of_week(start_day = Date.beginning_of_week)
-
result = days_ago(days_to_week_start(start_day))
-
acts_like?(:time) ? result.midnight : result
-
end
-
2
alias :at_beginning_of_week :beginning_of_week
-
-
# Returns Monday of this week assuming that week starts on Monday.
-
# +DateTime+ objects have their time set to 0:00.
-
2
def monday
-
beginning_of_week(:monday)
-
end
-
-
# Returns a new date/time representing the end of this week on the given day.
-
# Week is assumed to start on +start_day+, default is
-
# +Date.beginning_of_week+ or +config.beginning_of_week+ when set.
-
# DateTime objects have their time set to 23:59:59.
-
2
def end_of_week(start_day = Date.beginning_of_week)
-
last_hour(days_since(6 - days_to_week_start(start_day)))
-
end
-
2
alias :at_end_of_week :end_of_week
-
-
# Returns Sunday of this week assuming that week starts on Monday.
-
# +DateTime+ objects have their time set to 23:59:59.
-
2
def sunday
-
end_of_week(:monday)
-
end
-
-
# Returns a new date/time representing the end of the month.
-
# DateTime objects will have a time set to 23:59:59.
-
2
def end_of_month
-
last_day = ::Time.days_in_month(month, year)
-
last_hour(days_since(last_day - day))
-
end
-
2
alias :at_end_of_month :end_of_month
-
-
# Returns a new date/time representing the end of the year.
-
# DateTime objects will have a time set to 23:59:59.
-
2
def end_of_year
-
change(:month => 12).end_of_month
-
end
-
2
alias :at_end_of_year :end_of_year
-
-
# Returns a Range representing the whole week of the current date/time.
-
# Week starts on start_day, default is <tt>Date.week_start</tt> or <tt>config.week_start</tt> when set.
-
2
def all_week(start_day = Date.beginning_of_week)
-
beginning_of_week(start_day)..end_of_week(start_day)
-
end
-
-
# Returns a Range representing the whole month of the current date/time.
-
2
def all_month
-
beginning_of_month..end_of_month
-
end
-
-
# Returns a Range representing the whole quarter of the current date/time.
-
2
def all_quarter
-
beginning_of_quarter..end_of_quarter
-
end
-
-
# Returns a Range representing the whole year of the current date/time.
-
2
def all_year
-
beginning_of_year..end_of_year
-
end
-
-
2
private
-
-
2
def first_hour(date_or_time)
-
date_or_time.acts_like?(:time) ? date_or_time.beginning_of_day : date_or_time
-
end
-
-
2
def last_hour(date_or_time)
-
date_or_time.acts_like?(:time) ? date_or_time.end_of_day : date_or_time
-
end
-
-
2
def days_span(day)
-
(DAYS_INTO_WEEK[day] - DAYS_INTO_WEEK[Date.beginning_of_week]) % 7
-
end
-
end
-
end
-
2
module DateAndTime
-
2
module Zones
-
# Returns the simultaneous time in <tt>Time.zone</tt> if a zone is given or
-
# if Time.zone_default is set. Otherwise, it returns the current time.
-
#
-
# Time.zone = 'Hawaii' # => 'Hawaii'
-
# DateTime.utc(2000).in_time_zone # => Fri, 31 Dec 1999 14:00:00 HST -10:00
-
# Date.new(2000).in_time_zone # => Sat, 01 Jan 2000 00:00:00 HST -10:00
-
#
-
# This method is similar to Time#localtime, except that it uses <tt>Time.zone</tt> as the local zone
-
# instead of the operating system's time zone.
-
#
-
# You can also pass in a TimeZone instance or string that identifies a TimeZone as an argument,
-
# and the conversion will be based on that zone instead of <tt>Time.zone</tt>.
-
#
-
# Time.utc(2000).in_time_zone('Alaska') # => Fri, 31 Dec 1999 15:00:00 AKST -09:00
-
# DateTime.utc(2000).in_time_zone('Alaska') # => Fri, 31 Dec 1999 15:00:00 AKST -09:00
-
# Date.new(2000).in_time_zone('Alaska') # => Sat, 01 Jan 2000 00:00:00 AKST -09:00
-
2
def in_time_zone(zone = ::Time.zone)
-
534
time_zone = ::Time.find_zone! zone
-
534
time = acts_like?(:time) ? self : nil
-
-
534
if time_zone
-
534
time_with_zone(time, time_zone)
-
else
-
time || self.to_time
-
end
-
end
-
-
2
private
-
-
2
def time_with_zone(time, zone)
-
534
if time
-
534
ActiveSupport::TimeWithZone.new(time.utc? ? time : time.getutc, zone)
-
else
-
ActiveSupport::TimeWithZone.new(nil, zone, to_time(:utc))
-
end
-
end
-
end
-
end
-
-
2
require 'active_support/core_ext/date_time/acts_like'
-
2
require 'active_support/core_ext/date_time/calculations'
-
2
require 'active_support/core_ext/date_time/conversions'
-
2
require 'active_support/core_ext/date_time/zones'
-
2
require 'date'
-
2
require 'active_support/core_ext/object/acts_like'
-
-
2
class DateTime
-
# Duck-types as a Date-like class. See Object#acts_like?.
-
2
def acts_like_date?
-
true
-
end
-
-
# Duck-types as a Time-like class. See Object#acts_like?.
-
2
def acts_like_time?
-
true
-
end
-
end
-
2
require 'date'
-
-
2
class DateTime
-
2
class << self
-
# Returns <tt>Time.zone.now.to_datetime</tt> when <tt>Time.zone</tt> or
-
# <tt>config.time_zone</tt> are set, otherwise returns
-
# <tt>Time.now.to_datetime</tt>.
-
2
def current
-
::Time.zone ? ::Time.zone.now.to_datetime : ::Time.now.to_datetime
-
end
-
end
-
-
# Seconds since midnight: DateTime.now.seconds_since_midnight.
-
2
def seconds_since_midnight
-
sec + (min * 60) + (hour * 3600)
-
end
-
-
# Returns the number of seconds until 23:59:59.
-
#
-
# DateTime.new(2012, 8, 29, 0, 0, 0).seconds_until_end_of_day # => 86399
-
# DateTime.new(2012, 8, 29, 12, 34, 56).seconds_until_end_of_day # => 41103
-
# DateTime.new(2012, 8, 29, 23, 59, 59).seconds_until_end_of_day # => 0
-
2
def seconds_until_end_of_day
-
end_of_day.to_i - to_i
-
end
-
-
# Returns a new DateTime where one or more of the elements have been changed
-
# according to the +options+ parameter. The time options (<tt>:hour</tt>,
-
# <tt>:min</tt>, <tt>:sec</tt>) reset cascadingly, so if only the hour is
-
# passed, then minute and sec is set to 0. If the hour and minute is passed,
-
# then sec is set to 0. The +options+ parameter takes a hash with any of these
-
# keys: <tt>:year</tt>, <tt>:month</tt>, <tt>:day</tt>, <tt>:hour</tt>,
-
# <tt>:min</tt>, <tt>:sec</tt>, <tt>:offset</tt>, <tt>:start</tt>.
-
#
-
# DateTime.new(2012, 8, 29, 22, 35, 0).change(day: 1) # => DateTime.new(2012, 8, 1, 22, 35, 0)
-
# DateTime.new(2012, 8, 29, 22, 35, 0).change(year: 1981, day: 1) # => DateTime.new(1981, 8, 1, 22, 35, 0)
-
# DateTime.new(2012, 8, 29, 22, 35, 0).change(year: 1981, hour: 0) # => DateTime.new(1981, 8, 29, 0, 0, 0)
-
2
def change(options)
-
::DateTime.civil(
-
options.fetch(:year, year),
-
options.fetch(:month, month),
-
options.fetch(:day, day),
-
options.fetch(:hour, hour),
-
options.fetch(:min, options[:hour] ? 0 : min),
-
options.fetch(:sec, (options[:hour] || options[:min]) ? 0 : sec + sec_fraction),
-
options.fetch(:offset, offset),
-
options.fetch(:start, start)
-
)
-
end
-
-
# Uses Date to provide precise Time calculations for years, months, and days.
-
# The +options+ parameter takes a hash with any of these keys: <tt>:years</tt>,
-
# <tt>:months</tt>, <tt>:weeks</tt>, <tt>:days</tt>, <tt>:hours</tt>,
-
# <tt>:minutes</tt>, <tt>:seconds</tt>.
-
2
def advance(options)
-
d = to_date.advance(options)
-
datetime_advanced_by_date = change(:year => d.year, :month => d.month, :day => d.day)
-
seconds_to_advance = \
-
options.fetch(:seconds, 0) +
-
options.fetch(:minutes, 0) * 60 +
-
options.fetch(:hours, 0) * 3600
-
-
if seconds_to_advance.zero?
-
datetime_advanced_by_date
-
else
-
datetime_advanced_by_date.since seconds_to_advance
-
end
-
end
-
-
# Returns a new DateTime representing the time a number of seconds ago.
-
# Do not use this method in combination with x.months, use months_ago instead!
-
2
def ago(seconds)
-
since(-seconds)
-
end
-
-
# Returns a new DateTime representing the time a number of seconds since the
-
# instance time. Do not use this method in combination with x.months, use
-
# months_since instead!
-
2
def since(seconds)
-
self + Rational(seconds.round, 86400)
-
end
-
2
alias :in :since
-
-
# Returns a new DateTime representing the start of the day (0:00).
-
2
def beginning_of_day
-
change(:hour => 0)
-
end
-
2
alias :midnight :beginning_of_day
-
2
alias :at_midnight :beginning_of_day
-
2
alias :at_beginning_of_day :beginning_of_day
-
-
# Returns a new DateTime representing the middle of the day (12:00)
-
2
def middle_of_day
-
change(:hour => 12)
-
end
-
2
alias :midday :middle_of_day
-
2
alias :noon :middle_of_day
-
2
alias :at_midday :middle_of_day
-
2
alias :at_noon :middle_of_day
-
2
alias :at_middle_of_day :middle_of_day
-
-
# Returns a new DateTime representing the end of the day (23:59:59).
-
2
def end_of_day
-
change(:hour => 23, :min => 59, :sec => 59)
-
end
-
2
alias :at_end_of_day :end_of_day
-
-
# Returns a new DateTime representing the start of the hour (hh:00:00).
-
2
def beginning_of_hour
-
change(:min => 0)
-
end
-
2
alias :at_beginning_of_hour :beginning_of_hour
-
-
# Returns a new DateTime representing the end of the hour (hh:59:59).
-
2
def end_of_hour
-
change(:min => 59, :sec => 59)
-
end
-
2
alias :at_end_of_hour :end_of_hour
-
-
# Returns a new DateTime representing the start of the minute (hh:mm:00).
-
2
def beginning_of_minute
-
change(:sec => 0)
-
end
-
2
alias :at_beginning_of_minute :beginning_of_minute
-
-
# Returns a new DateTime representing the end of the minute (hh:mm:59).
-
2
def end_of_minute
-
change(:sec => 59)
-
end
-
2
alias :at_end_of_minute :end_of_minute
-
-
# Adjusts DateTime to UTC by adding its offset value; offset is set to 0.
-
#
-
# DateTime.civil(2005, 2, 21, 10, 11, 12, Rational(-6, 24)) # => Mon, 21 Feb 2005 10:11:12 -0600
-
# DateTime.civil(2005, 2, 21, 10, 11, 12, Rational(-6, 24)).utc # => Mon, 21 Feb 2005 16:11:12 +0000
-
2
def utc
-
new_offset(0)
-
end
-
2
alias_method :getutc, :utc
-
-
# Returns +true+ if <tt>offset == 0</tt>.
-
2
def utc?
-
offset == 0
-
end
-
-
# Returns the offset value in seconds.
-
2
def utc_offset
-
(offset * 86400).to_i
-
end
-
-
# Layers additional behavior on DateTime#<=> so that Time and
-
# ActiveSupport::TimeWithZone instances can be compared with a DateTime.
-
2
def <=>(other)
-
if other.kind_of?(Infinity)
-
super
-
elsif other.respond_to? :to_datetime
-
super other.to_datetime
-
else
-
nil
-
end
-
end
-
-
end
-
2
require 'date'
-
2
require 'active_support/inflector/methods'
-
2
require 'active_support/core_ext/time/conversions'
-
2
require 'active_support/core_ext/date_time/calculations'
-
2
require 'active_support/values/time_zone'
-
-
2
class DateTime
-
# Convert to a formatted string. See Time::DATE_FORMATS for predefined formats.
-
#
-
# This method is aliased to <tt>to_s</tt>.
-
#
-
# === Examples
-
# datetime = DateTime.civil(2007, 12, 4, 0, 0, 0, 0) # => Tue, 04 Dec 2007 00:00:00 +0000
-
#
-
# datetime.to_formatted_s(:db) # => "2007-12-04 00:00:00"
-
# datetime.to_s(:db) # => "2007-12-04 00:00:00"
-
# datetime.to_s(:number) # => "20071204000000"
-
# datetime.to_formatted_s(:short) # => "04 Dec 00:00"
-
# datetime.to_formatted_s(:long) # => "December 04, 2007 00:00"
-
# datetime.to_formatted_s(:long_ordinal) # => "December 4th, 2007 00:00"
-
# datetime.to_formatted_s(:rfc822) # => "Tue, 04 Dec 2007 00:00:00 +0000"
-
# datetime.to_formatted_s(:iso8601) # => "2007-12-04T00:00:00+00:00"
-
#
-
# == Adding your own datetime formats to to_formatted_s
-
# DateTime formats are shared with Time. You can add your own to the
-
# Time::DATE_FORMATS hash. Use the format name as the hash key and
-
# either a strftime string or Proc instance that takes a time or
-
# datetime argument as the value.
-
#
-
# # config/initializers/time_formats.rb
-
# Time::DATE_FORMATS[:month_and_year] = '%B %Y'
-
# Time::DATE_FORMATS[:short_ordinal] = lambda { |time| time.strftime("%B #{time.day.ordinalize}") }
-
2
def to_formatted_s(format = :default)
-
if formatter = ::Time::DATE_FORMATS[format]
-
formatter.respond_to?(:call) ? formatter.call(self).to_s : strftime(formatter)
-
else
-
to_default_s
-
end
-
end
-
2
alias_method :to_default_s, :to_s if instance_methods(false).include?(:to_s)
-
2
alias_method :to_s, :to_formatted_s
-
-
#
-
# datetime = DateTime.civil(2000, 1, 1, 0, 0, 0, Rational(-6, 24))
-
# datetime.formatted_offset # => "-06:00"
-
# datetime.formatted_offset(false) # => "-0600"
-
2
def formatted_offset(colon = true, alternate_utc_string = nil)
-
utc? && alternate_utc_string || ActiveSupport::TimeZone.seconds_to_utc_offset(utc_offset, colon)
-
end
-
-
# Overrides the default inspect method with a human readable one, e.g., "Mon, 21 Feb 2005 14:30:00 +0000".
-
2
def readable_inspect
-
to_s(:rfc822)
-
end
-
2
alias_method :default_inspect, :inspect
-
2
alias_method :inspect, :readable_inspect
-
-
# Returns DateTime with local offset for given year if format is local else
-
# offset is zero.
-
#
-
# DateTime.civil_from_format :local, 2012
-
# # => Sun, 01 Jan 2012 00:00:00 +0300
-
# DateTime.civil_from_format :local, 2012, 12, 17
-
# # => Mon, 17 Dec 2012 00:00:00 +0000
-
2
def self.civil_from_format(utc_or_local, year, month=1, day=1, hour=0, min=0, sec=0)
-
if utc_or_local.to_sym == :local
-
offset = ::Time.local(year, month, day).utc_offset.to_r / 86400
-
else
-
offset = 0
-
end
-
civil(year, month, day, hour, min, sec, offset)
-
end
-
-
# Converts +self+ to a floating-point number of seconds since the Unix epoch.
-
2
def to_f
-
seconds_since_unix_epoch.to_f
-
end
-
-
# Converts +self+ to an integer number of seconds since the Unix epoch.
-
2
def to_i
-
seconds_since_unix_epoch.to_i
-
end
-
-
# Returns the fraction of a second as microseconds
-
2
def usec
-
(sec_fraction * 1_000_000).to_i
-
end
-
-
# Returns the fraction of a second as nanoseconds
-
2
def nsec
-
(sec_fraction * 1_000_000_000).to_i
-
end
-
-
2
private
-
-
2
def offset_in_seconds
-
(offset * 86400).to_i
-
end
-
-
2
def seconds_since_unix_epoch
-
(jd - 2440588) * 86400 - offset_in_seconds + seconds_since_midnight
-
end
-
end
-
2
require 'date'
-
2
require 'active_support/core_ext/date_and_time/zones'
-
-
2
class DateTime
-
2
include DateAndTime::Zones
-
end
-
2
module Enumerable
-
# Calculates a sum from the elements.
-
#
-
# payments.sum { |p| p.price * p.tax_rate }
-
# payments.sum(&:price)
-
#
-
# The latter is a shortcut for:
-
#
-
# payments.inject(0) { |sum, p| sum + p.price }
-
#
-
# It can also calculate the sum without the use of a block.
-
#
-
# [5, 15, 10].sum # => 30
-
# ['foo', 'bar'].sum # => "foobar"
-
# [[1, 2], [3, 1, 5]].sum => [1, 2, 3, 1, 5]
-
#
-
# The default sum of an empty list is zero. You can override this default:
-
#
-
# [].sum(Payment.new(0)) { |i| i.amount } # => Payment.new(0)
-
2
def sum(identity = 0, &block)
-
if block_given?
-
map(&block).sum(identity)
-
else
-
inject { |sum, element| sum + element } || identity
-
end
-
end
-
-
# Convert an enumerable to a hash.
-
#
-
# people.index_by(&:login)
-
# => { "nextangle" => <Person ...>, "chade-" => <Person ...>, ...}
-
# people.index_by { |person| "#{person.first_name} #{person.last_name}" }
-
# => { "Chade- Fowlersburg-e" => <Person ...>, "David Heinemeier Hansson" => <Person ...>, ...}
-
2
def index_by
-
if block_given?
-
Hash[map { |elem| [yield(elem), elem] }]
-
else
-
to_enum(:index_by) { size if respond_to?(:size) }
-
end
-
end
-
-
# Returns +true+ if the enumerable has more than 1 element. Functionally
-
# equivalent to <tt>enum.to_a.size > 1</tt>. Can be called with a block too,
-
# much like any?, so <tt>people.many? { |p| p.age > 26 }</tt> returns +true+
-
# if more than one person is over 26.
-
2
def many?
-
cnt = 0
-
if block_given?
-
any? do |element|
-
cnt += 1 if yield element
-
cnt > 1
-
end
-
else
-
any? { (cnt += 1) > 1 }
-
end
-
end
-
-
# The negative of the <tt>Enumerable#include?</tt>. Returns +true+ if the
-
# collection does not include the object.
-
2
def exclude?(object)
-
!include?(object)
-
end
-
end
-
-
2
class Range #:nodoc:
-
# Optimize range sum to use arithmetic progression if a block is not given and
-
# we have a range of numeric values.
-
2
def sum(identity = 0)
-
if block_given? || !(first.is_a?(Integer) && last.is_a?(Integer))
-
super
-
else
-
actual_last = exclude_end? ? (last - 1) : last
-
if actual_last >= first
-
(actual_last - first + 1) * (actual_last + first) / 2
-
else
-
identity
-
end
-
end
-
end
-
end
-
2
require 'active_support/core_ext/file/atomic'
-
2
require 'fileutils'
-
-
2
class File
-
# Write to a file atomically. Useful for situations where you don't
-
# want other processes or threads to see half-written files.
-
#
-
# File.atomic_write('important.file') do |file|
-
# file.write('hello')
-
# end
-
#
-
# If your temp directory is not on the same filesystem as the file you're
-
# trying to write, you can provide a different temporary directory.
-
#
-
# File.atomic_write('/data/something.important', '/data/tmp') do |file|
-
# file.write('hello')
-
# end
-
2
def self.atomic_write(file_name, temp_dir = Dir.tmpdir)
-
require 'tempfile' unless defined?(Tempfile)
-
require 'fileutils' unless defined?(FileUtils)
-
-
temp_file = Tempfile.new(basename(file_name), temp_dir)
-
temp_file.binmode
-
yield temp_file
-
temp_file.close
-
-
if File.exist?(file_name)
-
# Get original file permissions
-
old_stat = stat(file_name)
-
else
-
# If not possible, probe which are the default permissions in the
-
# destination directory.
-
old_stat = probe_stat_in(dirname(file_name))
-
end
-
-
# Overwrite original file with temp file
-
FileUtils.mv(temp_file.path, file_name)
-
-
# Set correct permissions on new file
-
begin
-
chown(old_stat.uid, old_stat.gid, file_name)
-
# This operation will affect filesystem ACL's
-
chmod(old_stat.mode, file_name)
-
rescue Errno::EPERM
-
# Changing file ownership failed, moving on.
-
end
-
end
-
-
# Private utility method.
-
2
def self.probe_stat_in(dir) #:nodoc:
-
basename = [
-
'.permissions_check',
-
Thread.current.object_id,
-
Process.pid,
-
rand(1000000)
-
].join('.')
-
-
file_name = join(dir, basename)
-
FileUtils.touch(file_name)
-
stat(file_name)
-
ensure
-
FileUtils.rm_f(file_name) if file_name
-
end
-
end
-
2
require 'active_support/core_ext/hash/compact'
-
2
require 'active_support/core_ext/hash/conversions'
-
2
require 'active_support/core_ext/hash/deep_merge'
-
2
require 'active_support/core_ext/hash/except'
-
2
require 'active_support/core_ext/hash/indifferent_access'
-
2
require 'active_support/core_ext/hash/keys'
-
2
require 'active_support/core_ext/hash/reverse_merge'
-
2
require 'active_support/core_ext/hash/slice'
-
2
class Hash
-
# Returns a hash with non +nil+ values.
-
#
-
# hash = { a: true, b: false, c: nil}
-
# hash.compact # => { a: true, b: false}
-
# hash # => { a: true, b: false, c: nil}
-
# { c: nil }.compact # => {}
-
2
def compact
-
self.select { |_, value| !value.nil? }
-
end
-
-
# Replaces current hash with non +nil+ values.
-
#
-
# hash = { a: true, b: false, c: nil}
-
# hash.compact! # => { a: true, b: false}
-
# hash # => { a: true, b: false}
-
2
def compact!
-
self.reject! { |_, value| value.nil? }
-
end
-
end
-
2
require 'active_support/xml_mini'
-
2
require 'active_support/time'
-
2
require 'active_support/core_ext/object/blank'
-
2
require 'active_support/core_ext/object/to_param'
-
2
require 'active_support/core_ext/object/to_query'
-
2
require 'active_support/core_ext/array/wrap'
-
2
require 'active_support/core_ext/hash/reverse_merge'
-
2
require 'active_support/core_ext/string/inflections'
-
-
2
class Hash
-
# Returns a string containing an XML representation of its receiver:
-
#
-
# { foo: 1, bar: 2 }.to_xml
-
# # =>
-
# # <?xml version="1.0" encoding="UTF-8"?>
-
# # <hash>
-
# # <foo type="integer">1</foo>
-
# # <bar type="integer">2</bar>
-
# # </hash>
-
#
-
# To do so, the method loops over the pairs and builds nodes that depend on
-
# the _values_. Given a pair +key+, +value+:
-
#
-
# * If +value+ is a hash there's a recursive call with +key+ as <tt>:root</tt>.
-
#
-
# * If +value+ is an array there's a recursive call with +key+ as <tt>:root</tt>,
-
# and +key+ singularized as <tt>:children</tt>.
-
#
-
# * If +value+ is a callable object it must expect one or two arguments. Depending
-
# on the arity, the callable is invoked with the +options+ hash as first argument
-
# with +key+ as <tt>:root</tt>, and +key+ singularized as second argument. The
-
# callable can add nodes by using <tt>options[:builder]</tt>.
-
#
-
# 'foo'.to_xml(lambda { |options, key| options[:builder].b(key) })
-
# # => "<b>foo</b>"
-
#
-
# * If +value+ responds to +to_xml+ the method is invoked with +key+ as <tt>:root</tt>.
-
#
-
# class Foo
-
# def to_xml(options)
-
# options[:builder].bar 'fooing!'
-
# end
-
# end
-
#
-
# { foo: Foo.new }.to_xml(skip_instruct: true)
-
# # =>
-
# # <hash>
-
# # <bar>fooing!</bar>
-
# # </hash>
-
#
-
# * Otherwise, a node with +key+ as tag is created with a string representation of
-
# +value+ as text node. If +value+ is +nil+ an attribute "nil" set to "true" is added.
-
# Unless the option <tt>:skip_types</tt> exists and is true, an attribute "type" is
-
# added as well according to the following mapping:
-
#
-
# XML_TYPE_NAMES = {
-
# "Symbol" => "symbol",
-
# "Fixnum" => "integer",
-
# "Bignum" => "integer",
-
# "BigDecimal" => "decimal",
-
# "Float" => "float",
-
# "TrueClass" => "boolean",
-
# "FalseClass" => "boolean",
-
# "Date" => "date",
-
# "DateTime" => "dateTime",
-
# "Time" => "dateTime"
-
# }
-
#
-
# By default the root node is "hash", but that's configurable via the <tt>:root</tt> option.
-
#
-
# The default XML builder is a fresh instance of <tt>Builder::XmlMarkup</tt>. You can
-
# configure your own builder with the <tt>:builder</tt> option. The method also accepts
-
# options like <tt>:dasherize</tt> and friends, they are forwarded to the builder.
-
2
def to_xml(options = {})
-
require 'active_support/builder' unless defined?(Builder)
-
-
options = options.dup
-
options[:indent] ||= 2
-
options[:root] ||= 'hash'
-
options[:builder] ||= Builder::XmlMarkup.new(indent: options[:indent])
-
-
builder = options[:builder]
-
builder.instruct! unless options.delete(:skip_instruct)
-
-
root = ActiveSupport::XmlMini.rename_key(options[:root].to_s, options)
-
-
builder.tag!(root) do
-
each { |key, value| ActiveSupport::XmlMini.to_tag(key, value, options) }
-
yield builder if block_given?
-
end
-
end
-
-
2
class << self
-
# Returns a Hash containing a collection of pairs when the key is the node name and the value is
-
# its content
-
#
-
# xml = <<-XML
-
# <?xml version="1.0" encoding="UTF-8"?>
-
# <hash>
-
# <foo type="integer">1</foo>
-
# <bar type="integer">2</bar>
-
# </hash>
-
# XML
-
#
-
# hash = Hash.from_xml(xml)
-
# # => {"hash"=>{"foo"=>1, "bar"=>2}}
-
#
-
# DisallowedType is raised if the XML contains attributes with <tt>type="yaml"</tt> or
-
# <tt>type="symbol"</tt>. Use <tt>Hash.from_trusted_xml</tt> to parse this XML.
-
2
def from_xml(xml, disallowed_types = nil)
-
ActiveSupport::XMLConverter.new(xml, disallowed_types).to_h
-
end
-
-
# Builds a Hash from XML just like <tt>Hash.from_xml</tt>, but also allows Symbol and YAML.
-
2
def from_trusted_xml(xml)
-
from_xml xml, []
-
end
-
end
-
end
-
-
2
module ActiveSupport
-
2
class XMLConverter # :nodoc:
-
2
class DisallowedType < StandardError
-
2
def initialize(type)
-
super "Disallowed type attribute: #{type.inspect}"
-
end
-
end
-
-
2
DISALLOWED_TYPES = %w(symbol yaml)
-
-
2
def initialize(xml, disallowed_types = nil)
-
@xml = normalize_keys(XmlMini.parse(xml))
-
@disallowed_types = disallowed_types || DISALLOWED_TYPES
-
end
-
-
2
def to_h
-
deep_to_h(@xml)
-
end
-
-
2
private
-
2
def normalize_keys(params)
-
case params
-
when Hash
-
Hash[params.map { |k,v| [k.to_s.tr('-', '_'), normalize_keys(v)] } ]
-
when Array
-
params.map { |v| normalize_keys(v) }
-
else
-
params
-
end
-
end
-
-
2
def deep_to_h(value)
-
case value
-
when Hash
-
process_hash(value)
-
when Array
-
process_array(value)
-
when String
-
value
-
else
-
raise "can't typecast #{value.class.name} - #{value.inspect}"
-
end
-
end
-
-
2
def process_hash(value)
-
if value.include?('type') && !value['type'].is_a?(Hash) && @disallowed_types.include?(value['type'])
-
raise DisallowedType, value['type']
-
end
-
-
if become_array?(value)
-
_, entries = Array.wrap(value.detect { |k,v| not v.is_a?(String) })
-
if entries.nil? || value['__content__'].try(:empty?)
-
[]
-
else
-
case entries
-
when Array
-
entries.collect { |v| deep_to_h(v) }
-
when Hash
-
[deep_to_h(entries)]
-
else
-
raise "can't typecast #{entries.inspect}"
-
end
-
end
-
elsif become_content?(value)
-
process_content(value)
-
-
elsif become_empty_string?(value)
-
''
-
elsif become_hash?(value)
-
xml_value = Hash[value.map { |k,v| [k, deep_to_h(v)] }]
-
-
# Turn { files: { file: #<StringIO> } } into { files: #<StringIO> } so it is compatible with
-
# how multipart uploaded files from HTML appear
-
xml_value['file'].is_a?(StringIO) ? xml_value['file'] : xml_value
-
end
-
end
-
-
2
def become_content?(value)
-
value['type'] == 'file' || (value['__content__'] && (value.keys.size == 1 || value['__content__'].present?))
-
end
-
-
2
def become_array?(value)
-
value['type'] == 'array'
-
end
-
-
2
def become_empty_string?(value)
-
# { "string" => true }
-
# No tests fail when the second term is removed.
-
value['type'] == 'string' && value['nil'] != 'true'
-
end
-
-
2
def become_hash?(value)
-
!nothing?(value) && !garbage?(value)
-
end
-
-
2
def nothing?(value)
-
# blank or nil parsed values are represented by nil
-
value.blank? || value['nil'] == 'true'
-
end
-
-
2
def garbage?(value)
-
# If the type is the only element which makes it then
-
# this still makes the value nil, except if type is
-
# a XML node(where type['value'] is a Hash)
-
value['type'] && !value['type'].is_a?(::Hash) && value.size == 1
-
end
-
-
2
def process_content(value)
-
content = value['__content__']
-
if parser = ActiveSupport::XmlMini::PARSING[value['type']]
-
parser.arity == 1 ? parser.call(content) : parser.call(content, value)
-
else
-
content
-
end
-
end
-
-
2
def process_array(value)
-
value.map! { |i| deep_to_h(i) }
-
value.length > 1 ? value : value.first
-
end
-
-
end
-
end
-
-
2
class Hash
-
# Returns a new hash with +self+ and +other_hash+ merged recursively.
-
#
-
# h1 = { a: true, b: { c: [1, 2, 3] } }
-
# h2 = { a: false, b: { x: [3, 4, 5] } }
-
#
-
# h1.deep_merge(h2) #=> { a: false, b: { c: [1, 2, 3], x: [3, 4, 5] } }
-
#
-
# Like with Hash#merge in the standard library, a block can be provided
-
# to merge values:
-
#
-
# h1 = { a: 100, b: 200, c: { c1: 100 } }
-
# h2 = { b: 250, c: { c1: 200 } }
-
# h1.deep_merge(h2) { |key, this_val, other_val| this_val + other_val }
-
# # => { a: 100, b: 450, c: { c1: 300 } }
-
2
def deep_merge(other_hash, &block)
-
48
dup.deep_merge!(other_hash, &block)
-
end
-
-
# Same as +deep_merge+, but modifies +self+.
-
2
def deep_merge!(other_hash, &block)
-
67
other_hash.each_pair do |current_key, other_value|
-
163
this_value = self[current_key]
-
-
163
self[current_key] = if this_value.is_a?(Hash) && other_value.is_a?(Hash)
-
30
this_value.deep_merge(other_value, &block)
-
else
-
133
if block_given? && key?(current_key)
-
block.call(current_key, this_value, other_value)
-
else
-
133
other_value
-
end
-
end
-
end
-
-
67
self
-
end
-
end
-
2
class Hash
-
# Returns a hash that includes everything but the given keys. This is useful for
-
# limiting a set of parameters to everything but a few known toggles:
-
#
-
# @person.update(params[:person].except(:admin))
-
2
def except(*keys)
-
2299
dup.except!(*keys)
-
end
-
-
# Replaces the hash without the given keys.
-
2
def except!(*keys)
-
13416
keys.each { |key| delete(key) }
-
2299
self
-
end
-
end
-
2
require 'active_support/hash_with_indifferent_access'
-
-
2
class Hash
-
-
# Returns an <tt>ActiveSupport::HashWithIndifferentAccess</tt> out of its receiver:
-
#
-
# { a: 1 }.with_indifferent_access['a'] # => 1
-
2
def with_indifferent_access
-
124
ActiveSupport::HashWithIndifferentAccess.new_from_hash_copying_default(self)
-
end
-
-
# Called when object is nested under an object that receives
-
# #with_indifferent_access. This method will be called on the current object
-
# by the enclosing object and is aliased to #with_indifferent_access by
-
# default. Subclasses of Hash may overwrite this method to return +self+ if
-
# converting to an <tt>ActiveSupport::HashWithIndifferentAccess</tt> would not be
-
# desirable.
-
#
-
# b = { b: 1 }
-
# { a: b }.with_indifferent_access['a'] # calls b.nested_under_indifferent_access
-
# # => {"b"=>32}
-
2
alias nested_under_indifferent_access with_indifferent_access
-
end
-
2
class Hash
-
# Returns a new hash with all keys converted using the block operation.
-
#
-
# hash = { name: 'Rob', age: '28' }
-
#
-
# hash.transform_keys{ |key| key.to_s.upcase }
-
# # => {"NAME"=>"Rob", "AGE"=>"28"}
-
2
def transform_keys
-
796
result = {}
-
796
each_key do |key|
-
1588
result[yield(key)] = self[key]
-
end
-
796
result
-
end
-
-
# Destructively convert all keys using the block operations.
-
# Same as transform_keys but modifies +self+.
-
2
def transform_keys!
-
4
keys.each do |key|
-
36
self[yield(key)] = delete(key)
-
end
-
4
self
-
end
-
-
# Returns a new hash with all keys converted to strings.
-
#
-
# hash = { name: 'Rob', age: '28' }
-
#
-
# hash.stringify_keys
-
# # => { "name" => "Rob", "age" => "28" }
-
2
def stringify_keys
-
2103
transform_keys{ |key| key.to_s }
-
end
-
-
# Destructively convert all keys to strings. Same as
-
# +stringify_keys+, but modifies +self+.
-
2
def stringify_keys!
-
transform_keys!{ |key| key.to_s }
-
end
-
-
# Returns a new hash with all keys converted to symbols, as long as
-
# they respond to +to_sym+.
-
#
-
# hash = { 'name' => 'Rob', 'age' => '28' }
-
#
-
# hash.symbolize_keys
-
# # => { name: "Rob", age: "28" }
-
2
def symbolize_keys
-
281
transform_keys{ |key| key.to_sym rescue key }
-
end
-
2
alias_method :to_options, :symbolize_keys
-
-
# Destructively convert all keys to symbols, as long as they respond
-
# to +to_sym+. Same as +symbolize_keys+, but modifies +self+.
-
2
def symbolize_keys!
-
40
transform_keys!{ |key| key.to_sym rescue key }
-
end
-
2
alias_method :to_options!, :symbolize_keys!
-
-
# Validate all keys in a hash match <tt>*valid_keys</tt>, raising ArgumentError
-
# on a mismatch. Note that keys are NOT treated indifferently, meaning if you
-
# use strings for keys but assert symbols as keys, this will fail.
-
#
-
# { name: 'Rob', years: '28' }.assert_valid_keys(:name, :age) # => raises "ArgumentError: Unknown key: :years. Valid keys are: :name, :age"
-
# { name: 'Rob', age: '28' }.assert_valid_keys('name', 'age') # => raises "ArgumentError: Unknown key: :name. Valid keys are: 'name', 'age'"
-
# { name: 'Rob', age: '28' }.assert_valid_keys(:name, :age) # => passes, raises nothing
-
2
def assert_valid_keys(*valid_keys)
-
408
valid_keys.flatten!
-
408
each_key do |k|
-
62
unless valid_keys.include?(k)
-
raise ArgumentError.new("Unknown key: #{k.inspect}. Valid keys are: #{valid_keys.map(&:inspect).join(', ')}")
-
end
-
end
-
end
-
-
# Returns a new hash with all keys converted by the block operation.
-
# This includes the keys from the root hash and from all
-
# nested hashes and arrays.
-
#
-
# hash = { person: { name: 'Rob', age: '28' } }
-
#
-
# hash.deep_transform_keys{ |key| key.to_s.upcase }
-
# # => {"PERSON"=>{"NAME"=>"Rob", "AGE"=>"28"}}
-
2
def deep_transform_keys(&block)
-
19
_deep_transform_keys_in_object(self, &block)
-
end
-
-
# Destructively convert all keys by using the block operation.
-
# This includes the keys from the root hash and from all
-
# nested hashes and arrays.
-
2
def deep_transform_keys!(&block)
-
_deep_transform_keys_in_object!(self, &block)
-
end
-
-
# Returns a new hash with all keys converted to strings.
-
# This includes the keys from the root hash and from all
-
# nested hashes and arrays.
-
#
-
# hash = { person: { name: 'Rob', age: '28' } }
-
#
-
# hash.deep_stringify_keys
-
# # => {"person"=>{"name"=>"Rob", "age"=>"28"}}
-
2
def deep_stringify_keys
-
deep_transform_keys{ |key| key.to_s }
-
end
-
-
# Destructively convert all keys to strings.
-
# This includes the keys from the root hash and from all
-
# nested hashes and arrays.
-
2
def deep_stringify_keys!
-
deep_transform_keys!{ |key| key.to_s }
-
end
-
-
# Returns a new hash with all keys converted to symbols, as long as
-
# they respond to +to_sym+. This includes the keys from the root hash
-
# and from all nested hashes and arrays.
-
#
-
# hash = { 'person' => { 'name' => 'Rob', 'age' => '28' } }
-
#
-
# hash.deep_symbolize_keys
-
# # => {:person=>{:name=>"Rob", :age=>"28"}}
-
2
def deep_symbolize_keys
-
466
deep_transform_keys{ |key| key.to_sym rescue key }
-
end
-
-
# Destructively convert all keys to symbols, as long as they respond
-
# to +to_sym+. This includes the keys from the root hash and from all
-
# nested hashes and arrays.
-
2
def deep_symbolize_keys!
-
deep_transform_keys!{ |key| key.to_sym rescue key }
-
end
-
-
2
private
-
# support methods for deep transforming nested hashes and arrays
-
2
def _deep_transform_keys_in_object(object, &block)
-
509
case object
-
when Hash
-
169
object.each_with_object({}) do |(key, value), result|
-
447
result[yield(key)] = _deep_transform_keys_in_object(value, &block)
-
end
-
when Array
-
48
object.map {|e| _deep_transform_keys_in_object(e, &block) }
-
else
-
335
object
-
end
-
end
-
-
2
def _deep_transform_keys_in_object!(object, &block)
-
case object
-
when Hash
-
object.keys.each do |key|
-
value = object.delete(key)
-
object[yield(key)] = _deep_transform_keys_in_object!(value, &block)
-
end
-
object
-
when Array
-
object.map! {|e| _deep_transform_keys_in_object!(e, &block)}
-
else
-
object
-
end
-
end
-
end
-
2
class Hash
-
# Merges the caller into +other_hash+. For example,
-
#
-
# options = options.reverse_merge(size: 25, velocity: 10)
-
#
-
# is equivalent to
-
#
-
# options = { size: 25, velocity: 10 }.merge(options)
-
#
-
# This is particularly useful for initializing an options hash
-
# with default values.
-
2
def reverse_merge(other_hash)
-
24
other_hash.merge(self)
-
end
-
-
# Destructive +reverse_merge+.
-
2
def reverse_merge!(other_hash)
-
# right wins if there is no left
-
318
merge!( other_hash ){|key,left,right| left }
-
end
-
2
alias_method :reverse_update, :reverse_merge!
-
end
-
2
class Hash
-
# Slice a hash to include only the given keys. This is useful for
-
# limiting an options hash to valid keys before passing to a method:
-
#
-
# def search(criteria = {})
-
# criteria.assert_valid_keys(:mass, :velocity, :time)
-
# end
-
#
-
# search(options.slice(:mass, :velocity, :time))
-
#
-
# If you have an array of keys you want to limit to, you should splat them:
-
#
-
# valid_keys = [:mass, :velocity, :time]
-
# search(options.slice(*valid_keys))
-
2
def slice(*keys)
-
152
keys.map! { |key| convert_key(key) } if respond_to?(:convert_key, true)
-
551
keys.each_with_object(self.class.new) { |k, hash| hash[k] = self[k] if has_key?(k) }
-
end
-
-
# Replaces the hash with only the given keys.
-
# Returns a hash containing the removed key/value pairs.
-
#
-
# { a: 1, b: 2, c: 3, d: 4 }.slice!(:a, :b)
-
# # => {:c=>3, :d=>4}
-
2
def slice!(*keys)
-
42
keys.map! { |key| convert_key(key) } if respond_to?(:convert_key, true)
-
42
omit = slice(*self.keys - keys)
-
42
hash = slice(*keys)
-
42
hash.default = default
-
42
hash.default_proc = default_proc if default_proc
-
42
replace(hash)
-
42
omit
-
end
-
-
# Removes and returns the key/value pairs matching the given keys.
-
#
-
# { a: 1, b: 2, c: 3, d: 4 }.extract!(:a, :b) # => {:a=>1, :b=>2}
-
# { a: 1, b: 2 }.extract!(:a, :x) # => {:a=>1}
-
2
def extract!(*keys)
-
65
keys.each_with_object(self.class.new) { |key, result| result[key] = delete(key) if has_key?(key) }
-
end
-
end
-
2
require 'active_support/core_ext/integer/multiple'
-
2
require 'active_support/core_ext/integer/inflections'
-
2
require 'active_support/core_ext/integer/time'
-
2
require 'active_support/inflector'
-
-
2
class Integer
-
# Ordinalize turns a number into an ordinal string used to denote the
-
# position in an ordered sequence such as 1st, 2nd, 3rd, 4th.
-
#
-
# 1.ordinalize # => "1st"
-
# 2.ordinalize # => "2nd"
-
# 1002.ordinalize # => "1002nd"
-
# 1003.ordinalize # => "1003rd"
-
# -11.ordinalize # => "-11th"
-
# -1001.ordinalize # => "-1001st"
-
2
def ordinalize
-
ActiveSupport::Inflector.ordinalize(self)
-
end
-
-
# Ordinal returns the suffix used to denote the position
-
# in an ordered sequence such as 1st, 2nd, 3rd, 4th.
-
#
-
# 1.ordinal # => "st"
-
# 2.ordinal # => "nd"
-
# 1002.ordinal # => "nd"
-
# 1003.ordinal # => "rd"
-
# -11.ordinal # => "th"
-
# -1001.ordinal # => "st"
-
2
def ordinal
-
ActiveSupport::Inflector.ordinal(self)
-
end
-
end
-
2
class Integer
-
# Check whether the integer is evenly divisible by the argument.
-
#
-
# 0.multiple_of?(0) # => true
-
# 6.multiple_of?(5) # => false
-
# 10.multiple_of?(2) # => true
-
2
def multiple_of?(number)
-
number != 0 ? self % number == 0 : zero?
-
end
-
end
-
2
require 'active_support/duration'
-
2
require 'active_support/core_ext/numeric/time'
-
-
2
class Integer
-
# Enables the use of time calculations and declarations, like <tt>45.minutes +
-
# 2.hours + 4.years</tt>.
-
#
-
# These methods use Time#advance for precise date calculations when using
-
# <tt>from_now</tt>, +ago+, etc. as well as adding or subtracting their
-
# results from a Time object.
-
#
-
# # equivalent to Time.now.advance(months: 1)
-
# 1.month.from_now
-
#
-
# # equivalent to Time.now.advance(years: 2)
-
# 2.years.from_now
-
#
-
# # equivalent to Time.now.advance(months: 4, years: 5)
-
# (4.months + 5.years).from_now
-
#
-
# While these methods provide precise calculation when used as in the examples
-
# above, care should be taken to note that this is not true if the result of
-
# +months+, +years+, etc is converted before use:
-
#
-
# # equivalent to 30.days.to_i.from_now
-
# 1.month.to_i.from_now
-
#
-
# # equivalent to 365.25.days.to_f.from_now
-
# 1.year.to_f.from_now
-
#
-
# In such cases, Ruby's core
-
# Date[http://ruby-doc.org/stdlib/libdoc/date/rdoc/Date.html] and
-
# Time[http://ruby-doc.org/stdlib/libdoc/time/rdoc/Time.html] should be used for precision
-
# date and time arithmetic.
-
2
def months
-
ActiveSupport::Duration.new(self * 30.days, [[:months, self]])
-
end
-
2
alias :month :months
-
-
2
def years
-
ActiveSupport::Duration.new(self * 365.25.days, [[:years, self]])
-
end
-
2
alias :year :years
-
end
-
2
require 'active_support/core_ext/kernel/reporting'
-
2
require 'active_support/core_ext/kernel/agnostics'
-
2
require 'active_support/core_ext/kernel/debugger'
-
2
require 'active_support/core_ext/kernel/singleton_class'
-
2
class Object
-
# Makes backticks behave (somewhat more) similarly on all platforms.
-
# On win32 `nonexistent_command` raises Errno::ENOENT; on Unix, the
-
# spawned shell prints a message to stderr and sets $?. We emulate
-
# Unix on the former but not the latter.
-
2
def `(command) #:nodoc:
-
super
-
rescue Errno::ENOENT => e
-
STDERR.puts "#$0: #{e}"
-
end
-
end
-
2
module Kernel
-
2
unless respond_to?(:debugger)
-
# Starts a debugging session if the +debugger+ gem has been loaded (call rails server --debugger to do load it).
-
def debugger
-
message = "\n***** Debugger requested, but was not available (ensure the debugger gem is listed in Gemfile/installed as gem): Start server with --debugger to enable *****\n"
-
defined?(Rails) ? Rails.logger.info(message) : $stderr.puts(message)
-
end
-
alias breakpoint debugger unless respond_to?(:breakpoint)
-
end
-
end
-
2
module Kernel
-
# class_eval on an object acts like singleton_class.class_eval.
-
2
def class_eval(*args, &block)
-
singleton_class.class_eval(*args, &block)
-
end
-
end
-
2
class LoadError
-
2
REGEXPS = [
-
/^no such file to load -- (.+)$/i,
-
/^Missing \w+ (?:file\s*)?([^\s]+.rb)$/i,
-
/^Missing API definition file in (.+)$/i,
-
/^cannot load such file -- (.+)$/i,
-
]
-
-
2
unless method_defined?(:path)
-
def path
-
@path ||= begin
-
REGEXPS.find do |regex|
-
message =~ regex
-
end
-
$1
-
end
-
end
-
end
-
-
2
def is_missing?(location)
-
1
location.sub(/\.rb$/, '') == path.sub(/\.rb$/, '')
-
end
-
end
-
-
2
MissingSourceFile = LoadError
-
2
require 'active_support/core_ext/module/aliasing'
-
-
2
module Marshal
-
2
class << self
-
2
def load_with_autoloading(source)
-
171
load_without_autoloading(source)
-
rescue ArgumentError, NameError => exc
-
if exc.message.match(%r|undefined class/module (.+)|)
-
# try loading the class/module
-
$1.constantize
-
# if it is a IO we need to go back to read the object
-
source.rewind if source.respond_to?(:rewind)
-
retry
-
else
-
raise exc
-
end
-
end
-
-
2
alias_method_chain :load, :autoloading
-
end
-
end
-
2
require 'active_support/core_ext/module/aliasing'
-
2
require 'active_support/core_ext/module/introspection'
-
2
require 'active_support/core_ext/module/anonymous'
-
2
require 'active_support/core_ext/module/reachable'
-
2
require 'active_support/core_ext/module/attribute_accessors'
-
2
require 'active_support/core_ext/module/attr_internal'
-
2
require 'active_support/core_ext/module/concerning'
-
2
require 'active_support/core_ext/module/delegation'
-
2
require 'active_support/core_ext/module/deprecation'
-
2
require 'active_support/core_ext/module/remove_method'
-
2
require 'active_support/core_ext/module/qualified_const'
-
2
class Module
-
# Encapsulates the common pattern of:
-
#
-
# alias_method :foo_without_feature, :foo
-
# alias_method :foo, :foo_with_feature
-
#
-
# With this, you simply do:
-
#
-
# alias_method_chain :foo, :feature
-
#
-
# And both aliases are set up for you.
-
#
-
# Query and bang methods (foo?, foo!) keep the same punctuation:
-
#
-
# alias_method_chain :foo?, :feature
-
#
-
# is equivalent to
-
#
-
# alias_method :foo_without_feature?, :foo?
-
# alias_method :foo?, :foo_with_feature?
-
#
-
# so you can safely chain foo, foo?, and foo! with the same feature.
-
2
def alias_method_chain(target, feature)
-
# Strip out punctuation on predicates or bang methods since
-
# e.g. target?_without_feature is not a valid method name.
-
30
aliased_target, punctuation = target.to_s.sub(/([?!=])$/, ''), $1
-
30
yield(aliased_target, punctuation) if block_given?
-
-
30
with_method = "#{aliased_target}_with_#{feature}#{punctuation}"
-
30
without_method = "#{aliased_target}_without_#{feature}#{punctuation}"
-
-
30
alias_method without_method, target
-
30
alias_method target, with_method
-
-
case
-
when public_method_defined?(without_method)
-
30
public target
-
when protected_method_defined?(without_method)
-
protected target
-
when private_method_defined?(without_method)
-
private target
-
30
end
-
end
-
-
# Allows you to make aliases for attributes, which includes
-
# getter, setter, and query methods.
-
#
-
# class Content < ActiveRecord::Base
-
# # has a title attribute
-
# end
-
#
-
# class Email < Content
-
# alias_attribute :subject, :title
-
# end
-
#
-
# e = Email.find(1)
-
# e.title # => "Superstars"
-
# e.subject # => "Superstars"
-
# e.subject? # => true
-
# e.subject = "Megastars"
-
# e.title # => "Megastars"
-
2
def alias_attribute(new_name, old_name)
-
module_eval <<-STR, __FILE__, __LINE__ + 1
-
def #{new_name}; self.#{old_name}; end # def subject; self.title; end
-
def #{new_name}?; self.#{old_name}?; end # def subject?; self.title?; end
-
def #{new_name}=(v); self.#{old_name} = v; end # def subject=(v); self.title = v; end
-
STR
-
end
-
end
-
2
class Module
-
# A module may or may not have a name.
-
#
-
# module M; end
-
# M.name # => "M"
-
#
-
# m = Module.new
-
# m.name # => nil
-
#
-
# A module gets a name when it is first assigned to a constant. Either
-
# via the +module+ or +class+ keyword or by an explicit assignment:
-
#
-
# m = Module.new # creates an anonymous module
-
# M = m # => m gets a name here as a side-effect
-
# m.name # => "M"
-
2
def anonymous?
-
145
name.nil?
-
end
-
end
-
2
class Module
-
# Declares an attribute reader backed by an internally-named instance variable.
-
2
def attr_internal_reader(*attrs)
-
44
attrs.each {|attr_name| attr_internal_define(attr_name, :reader)}
-
end
-
-
# Declares an attribute writer backed by an internally-named instance variable.
-
2
def attr_internal_writer(*attrs)
-
56
attrs.each {|attr_name| attr_internal_define(attr_name, :writer)}
-
end
-
-
# Declares an attribute reader and writer backed by an internally-named instance
-
# variable.
-
2
def attr_internal_accessor(*attrs)
-
18
attr_internal_reader(*attrs)
-
18
attr_internal_writer(*attrs)
-
end
-
2
alias_method :attr_internal, :attr_internal_accessor
-
-
4
class << self; attr_accessor :attr_internal_naming_format end
-
2
self.attr_internal_naming_format = '@_%s'
-
-
2
private
-
2
def attr_internal_ivar_name(attr)
-
58
Module.attr_internal_naming_format % attr
-
end
-
-
2
def attr_internal_define(attr_name, type)
-
58
internal_name = attr_internal_ivar_name(attr_name).sub(/\A@/, '')
-
# class_eval is necessary on 1.9 or else the methods are made private
-
58
class_eval do
-
# use native attr_* methods as they are faster on some Ruby implementations
-
58
send("attr_#{type}", internal_name)
-
end
-
58
attr_name, internal_name = "#{attr_name}=", "#{internal_name}=" if type == :writer
-
58
alias_method attr_name, internal_name
-
58
remove_method internal_name
-
end
-
end
-
2
require 'active_support/core_ext/array/extract_options'
-
-
# Extends the module object with class/module and instance accessors for
-
# class/module attributes, just like the native attr* accessors for instance
-
# attributes.
-
2
class Module
-
# Defines a class attribute and creates a class and instance reader methods.
-
# The underlying the class variable is set to +nil+, if it is not previously
-
# defined.
-
#
-
# module HairColors
-
# mattr_reader :hair_colors
-
# end
-
#
-
# HairColors.hair_colors # => nil
-
# HairColors.class_variable_set("@@hair_colors", [:brown, :black])
-
# HairColors.hair_colors # => [:brown, :black]
-
#
-
# The attribute name must be a valid method name in Ruby.
-
#
-
# module Foo
-
# mattr_reader :"1_Badname "
-
# end
-
# # => NameError: invalid attribute name
-
#
-
# If you want to opt out the creation on the instance reader method, pass
-
# <tt>instance_reader: false</tt> or <tt>instance_accessor: false</tt>.
-
#
-
# module HairColors
-
# mattr_writer :hair_colors, instance_reader: false
-
# end
-
#
-
# class Person
-
# include HairColors
-
# end
-
#
-
# Person.new.hair_colors # => NoMethodError
-
#
-
#
-
# Also, you can pass a block to set up the attribute with a default value.
-
#
-
# module HairColors
-
# cattr_reader :hair_colors do
-
# [:brown, :black, :blonde, :red]
-
# end
-
# end
-
#
-
# class Person
-
# include HairColors
-
# end
-
#
-
# Person.hair_colors # => [:brown, :black, :blonde, :red]
-
2
def mattr_reader(*syms)
-
280
options = syms.extract_options!
-
280
syms.each do |sym|
-
280
raise NameError.new("invalid attribute name: #{sym}") unless sym =~ /^[_A-Za-z]\w*$/
-
280
class_eval(<<-EOS, __FILE__, __LINE__ + 1)
-
@@#{sym} = nil unless defined? @@#{sym}
-
-
def self.#{sym}
-
@@#{sym}
-
end
-
EOS
-
-
280
unless options[:instance_reader] == false || options[:instance_accessor] == false
-
274
class_eval(<<-EOS, __FILE__, __LINE__ + 1)
-
def #{sym}
-
@@#{sym}
-
end
-
EOS
-
end
-
280
class_variable_set("@@#{sym}", yield) if block_given?
-
end
-
end
-
2
alias :cattr_reader :mattr_reader
-
-
# Defines a class attribute and creates a class and instance writer methods to
-
# allow assignment to the attribute.
-
#
-
# module HairColors
-
# mattr_writer :hair_colors
-
# end
-
#
-
# class Person
-
# include HairColors
-
# end
-
#
-
# HairColors.hair_colors = [:brown, :black]
-
# Person.class_variable_get("@@hair_colors") # => [:brown, :black]
-
# Person.new.hair_colors = [:blonde, :red]
-
# HairColors.class_variable_get("@@hair_colors") # => [:blonde, :red]
-
#
-
# If you want to opt out the instance writer method, pass
-
# <tt>instance_writer: false</tt> or <tt>instance_accessor: false</tt>.
-
#
-
# module HairColors
-
# mattr_writer :hair_colors, instance_writer: false
-
# end
-
#
-
# class Person
-
# include HairColors
-
# end
-
#
-
# Person.new.hair_colors = [:blonde, :red] # => NoMethodError
-
#
-
# Also, you can pass a block to set up the attribute with a default value.
-
#
-
# class HairColors
-
# mattr_writer :hair_colors do
-
# [:brown, :black, :blonde, :red]
-
# end
-
# end
-
#
-
# class Person
-
# include HairColors
-
# end
-
#
-
# Person.class_variable_get("@@hair_colors") # => [:brown, :black, :blonde, :red]
-
2
def mattr_writer(*syms)
-
272
options = syms.extract_options!
-
272
syms.each do |sym|
-
272
raise NameError.new("invalid attribute name: #{sym}") unless sym =~ /^[_A-Za-z]\w*$/
-
272
class_eval(<<-EOS, __FILE__, __LINE__ + 1)
-
@@#{sym} = nil unless defined? @@#{sym}
-
-
def self.#{sym}=(obj)
-
@@#{sym} = obj
-
end
-
EOS
-
-
272
unless options[:instance_writer] == false || options[:instance_accessor] == false
-
248
class_eval(<<-EOS, __FILE__, __LINE__ + 1)
-
def #{sym}=(obj)
-
@@#{sym} = obj
-
end
-
EOS
-
end
-
272
send("#{sym}=", yield) if block_given?
-
end
-
end
-
2
alias :cattr_writer :mattr_writer
-
-
# Defines both class and instance accessors for class attributes.
-
#
-
# module HairColors
-
# mattr_accessor :hair_colors
-
# end
-
#
-
# class Person
-
# include HairColors
-
# end
-
#
-
# Person.hair_colors = [:brown, :black, :blonde, :red]
-
# Person.hair_colors # => [:brown, :black, :blonde, :red]
-
# Person.new.hair_colors # => [:brown, :black, :blonde, :red]
-
#
-
# If a subclass changes the value then that would also change the value for
-
# parent class. Similarly if parent class changes the value then that would
-
# change the value of subclasses too.
-
#
-
# class Male < Person
-
# end
-
#
-
# Male.hair_colors << :blue
-
# Person.hair_colors # => [:brown, :black, :blonde, :red, :blue]
-
#
-
# To opt out of the instance writer method, pass <tt>instance_writer: false</tt>.
-
# To opt out of the instance reader method, pass <tt>instance_reader: false</tt>.
-
#
-
# module HairColors
-
# mattr_accessor :hair_colors, instance_writer: false, instance_reader: false
-
# end
-
#
-
# class Person
-
# include HairColors
-
# end
-
#
-
# Person.new.hair_colors = [:brown] # => NoMethodError
-
# Person.new.hair_colors # => NoMethodError
-
#
-
# Or pass <tt>instance_accessor: false</tt>, to opt out both instance methods.
-
#
-
# module HairColors
-
# mattr_accessor :hair_colors, instance_accessor: false
-
# end
-
#
-
# class Person
-
# include HairColors
-
# end
-
#
-
# Person.new.hair_colors = [:brown] # => NoMethodError
-
# Person.new.hair_colors # => NoMethodError
-
#
-
# Also you can pass a block to set up the attribute with a default value.
-
#
-
# module HairColors
-
# mattr_accessor :hair_colors do
-
# [:brown, :black, :blonde, :red]
-
# end
-
# end
-
#
-
# class Person
-
# include HairColors
-
# end
-
#
-
# Person.class_variable_get("@@hair_colors") #=> [:brown, :black, :blonde, :red]
-
2
def mattr_accessor(*syms, &blk)
-
270
mattr_reader(*syms, &blk)
-
270
mattr_writer(*syms, &blk)
-
end
-
2
alias :cattr_accessor :mattr_accessor
-
end
-
2
require 'active_support/concern'
-
-
2
class Module
-
# = Bite-sized separation of concerns
-
#
-
# We often find ourselves with a medium-sized chunk of behavior that we'd
-
# like to extract, but only mix in to a single class.
-
#
-
# Extracting a plain old Ruby object to encapsulate it and collaborate or
-
# delegate to the original object is often a good choice, but when there's
-
# no additional state to encapsulate or we're making DSL-style declarations
-
# about the parent class, introducing new collaborators can obfuscate rather
-
# than simplify.
-
#
-
# The typical route is to just dump everything in a monolithic class, perhaps
-
# with a comment, as a least-bad alternative. Using modules in separate files
-
# means tedious sifting to get a big-picture view.
-
#
-
# = Dissatisfying ways to separate small concerns
-
#
-
# == Using comments:
-
#
-
# class Todo
-
# # Other todo implementation
-
# # ...
-
#
-
# ## Event tracking
-
# has_many :events
-
#
-
# before_create :track_creation
-
# after_destroy :track_deletion
-
#
-
# private
-
# def track_creation
-
# # ...
-
# end
-
# end
-
#
-
# == With an inline module:
-
#
-
# Noisy syntax.
-
#
-
# class Todo
-
# # Other todo implementation
-
# # ...
-
#
-
# module EventTracking
-
# extend ActiveSupport::Concern
-
#
-
# included do
-
# has_many :events
-
# before_create :track_creation
-
# after_destroy :track_deletion
-
# end
-
#
-
# private
-
# def track_creation
-
# # ...
-
# end
-
# end
-
# include EventTracking
-
# end
-
#
-
# == Mix-in noise exiled to its own file:
-
#
-
# Once our chunk of behavior starts pushing the scroll-to-understand it's
-
# boundary, we give in and move it to a separate file. At this size, the
-
# overhead feels in good proportion to the size of our extraction, despite
-
# diluting our at-a-glance sense of how things really work.
-
#
-
# class Todo
-
# # Other todo implementation
-
# # ...
-
#
-
# include TodoEventTracking
-
# end
-
#
-
# = Introducing Module#concerning
-
#
-
# By quieting the mix-in noise, we arrive at a natural, low-ceremony way to
-
# separate bite-sized concerns.
-
#
-
# class Todo
-
# # Other todo implementation
-
# # ...
-
#
-
# concerning :EventTracking do
-
# included do
-
# has_many :events
-
# before_create :track_creation
-
# after_destroy :track_deletion
-
# end
-
#
-
# private
-
# def track_creation
-
# # ...
-
# end
-
# end
-
# end
-
#
-
# Todo.ancestors
-
# # => Todo, Todo::EventTracking, Object
-
#
-
# This small step has some wonderful ripple effects. We can
-
# * grok the behavior of our class in one glance,
-
# * clean up monolithic junk-drawer classes by separating their concerns, and
-
# * stop leaning on protected/private for crude "this is internal stuff" modularity.
-
2
module Concerning
-
# Define a new concern and mix it in.
-
2
def concerning(topic, &block)
-
include concern(topic, &block)
-
end
-
-
# A low-cruft shortcut to define a concern.
-
#
-
# concern :EventTracking do
-
# ...
-
# end
-
#
-
# is equivalent to
-
#
-
# module EventTracking
-
# extend ActiveSupport::Concern
-
#
-
# ...
-
# end
-
2
def concern(topic, &module_definition)
-
const_set topic, Module.new {
-
extend ::ActiveSupport::Concern
-
module_eval(&module_definition)
-
}
-
end
-
end
-
2
include Concerning
-
end
-
2
class Module
-
# Error generated by +delegate+ when a method is called on +nil+ and +allow_nil+
-
# option is not used.
-
2
class DelegationError < NoMethodError; end
-
-
# Provides a +delegate+ class method to easily expose contained objects'
-
# public methods as your own.
-
#
-
# ==== Options
-
# * <tt>:to</tt> - Specifies the target object
-
# * <tt>:prefix</tt> - Prefixes the new method with the target name or a custom prefix
-
# * <tt>:allow_nil</tt> - if set to true, prevents a +NoMethodError+ to be raised
-
#
-
# The macro receives one or more method names (specified as symbols or
-
# strings) and the name of the target object via the <tt>:to</tt> option
-
# (also a symbol or string).
-
#
-
# Delegation is particularly useful with Active Record associations:
-
#
-
# class Greeter < ActiveRecord::Base
-
# def hello
-
# 'hello'
-
# end
-
#
-
# def goodbye
-
# 'goodbye'
-
# end
-
# end
-
#
-
# class Foo < ActiveRecord::Base
-
# belongs_to :greeter
-
# delegate :hello, to: :greeter
-
# end
-
#
-
# Foo.new.hello # => "hello"
-
# Foo.new.goodbye # => NoMethodError: undefined method `goodbye' for #<Foo:0x1af30c>
-
#
-
# Multiple delegates to the same target are allowed:
-
#
-
# class Foo < ActiveRecord::Base
-
# belongs_to :greeter
-
# delegate :hello, :goodbye, to: :greeter
-
# end
-
#
-
# Foo.new.goodbye # => "goodbye"
-
#
-
# Methods can be delegated to instance variables, class variables, or constants
-
# by providing them as a symbols:
-
#
-
# class Foo
-
# CONSTANT_ARRAY = [0,1,2,3]
-
# @@class_array = [4,5,6,7]
-
#
-
# def initialize
-
# @instance_array = [8,9,10,11]
-
# end
-
# delegate :sum, to: :CONSTANT_ARRAY
-
# delegate :min, to: :@@class_array
-
# delegate :max, to: :@instance_array
-
# end
-
#
-
# Foo.new.sum # => 6
-
# Foo.new.min # => 4
-
# Foo.new.max # => 11
-
#
-
# It's also possible to delegate a method to the class by using +:class+:
-
#
-
# class Foo
-
# def self.hello
-
# "world"
-
# end
-
#
-
# delegate :hello, to: :class
-
# end
-
#
-
# Foo.new.hello # => "world"
-
#
-
# Delegates can optionally be prefixed using the <tt>:prefix</tt> option. If the value
-
# is <tt>true</tt>, the delegate methods are prefixed with the name of the object being
-
# delegated to.
-
#
-
# Person = Struct.new(:name, :address)
-
#
-
# class Invoice < Struct.new(:client)
-
# delegate :name, :address, to: :client, prefix: true
-
# end
-
#
-
# john_doe = Person.new('John Doe', 'Vimmersvej 13')
-
# invoice = Invoice.new(john_doe)
-
# invoice.client_name # => "John Doe"
-
# invoice.client_address # => "Vimmersvej 13"
-
#
-
# It is also possible to supply a custom prefix.
-
#
-
# class Invoice < Struct.new(:client)
-
# delegate :name, :address, to: :client, prefix: :customer
-
# end
-
#
-
# invoice = Invoice.new(john_doe)
-
# invoice.customer_name # => 'John Doe'
-
# invoice.customer_address # => 'Vimmersvej 13'
-
#
-
# If the target is +nil+ and does not respond to the delegated method a
-
# +NoMethodError+ is raised, as with any other value. Sometimes, however, it
-
# makes sense to be robust to that situation and that is the purpose of the
-
# <tt>:allow_nil</tt> option: If the target is not +nil+, or it is and
-
# responds to the method, everything works as usual. But if it is +nil+ and
-
# does not respond to the delegated method, +nil+ is returned.
-
#
-
# class User < ActiveRecord::Base
-
# has_one :profile
-
# delegate :age, to: :profile
-
# end
-
#
-
# User.new.age # raises NoMethodError: undefined method `age'
-
#
-
# But if not having a profile yet is fine and should not be an error
-
# condition:
-
#
-
# class User < ActiveRecord::Base
-
# has_one :profile
-
# delegate :age, to: :profile, allow_nil: true
-
# end
-
#
-
# User.new.age # nil
-
#
-
# Note that if the target is not +nil+ then the call is attempted regardless of the
-
# <tt>:allow_nil</tt> option, and thus an exception is still raised if said object
-
# does not respond to the method:
-
#
-
# class Foo
-
# def initialize(bar)
-
# @bar = bar
-
# end
-
#
-
# delegate :name, to: :@bar, allow_nil: true
-
# end
-
#
-
# Foo.new("Bar").name # raises NoMethodError: undefined method `name'
-
#
-
# The target method must be public, otherwise it will raise +NoMethodError+.
-
#
-
2
def delegate(*methods)
-
148
options = methods.pop
-
148
unless options.is_a?(Hash) && to = options[:to]
-
raise ArgumentError, 'Delegation needs a target. Supply an options hash with a :to key as the last argument (e.g. delegate :hello, to: :greeter).'
-
end
-
-
148
prefix, allow_nil = options.values_at(:prefix, :allow_nil)
-
-
148
if prefix == true && to =~ /^[^a-z_]/
-
raise ArgumentError, 'Can only automatically set the delegation prefix when delegating to a method.'
-
end
-
-
148
method_prefix = \
-
if prefix
-
"#{prefix == true ? to : prefix}_"
-
else
-
148
''
-
end
-
-
148
file, line = caller.first.split(':', 2)
-
148
line = line.to_i
-
-
148
to = to.to_s
-
148
to = 'self.class' if to == 'class'
-
-
148
methods.each do |method|
-
# Attribute writer methods only accept one argument. Makes sure []=
-
# methods still accept two arguments.
-
484
definition = (method =~ /[^\]]=$/) ? 'arg' : '*args, &block'
-
-
# The following generated methods call the target exactly once, storing
-
# the returned value in a dummy variable.
-
#
-
# Reason is twofold: On one hand doing less calls is in general better.
-
# On the other hand it could be that the target has side-effects,
-
# whereas conceptually, from the user point of view, the delegator should
-
# be doing one call.
-
484
if allow_nil
-
12
method_def = [
-
"def #{method_prefix}#{method}(#{definition})", # def customer_name(*args, &block)
-
"_ = #{to}", # _ = client
-
"if !_.nil? || nil.respond_to?(:#{method})", # if !_.nil? || nil.respond_to?(:name)
-
" _.#{method}(#{definition})", # _.name(*args, &block)
-
"end", # end
-
"end" # end
-
].join ';'
-
else
-
472
exception = %(raise DelegationError, "#{self}##{method_prefix}#{method} delegated to #{to}.#{method}, but #{to} is nil: \#{self.inspect}")
-
-
472
method_def = [
-
"def #{method_prefix}#{method}(#{definition})", # def customer_name(*args, &block)
-
" _ = #{to}", # _ = client
-
" _.#{method}(#{definition})", # _.name(*args, &block)
-
"rescue NoMethodError => e", # rescue NoMethodError => e
-
" if _.nil? && e.name == :#{method}", # if _.nil? && e.name == :name
-
" #{exception}", # # add helpful message to the exception
-
" else", # else
-
" raise", # raise
-
" end", # end
-
"end" # end
-
].join ';'
-
end
-
-
484
module_eval(method_def, file, line)
-
end
-
end
-
end
-
2
class Module
-
# deprecate :foo
-
# deprecate bar: 'message'
-
# deprecate :foo, :bar, baz: 'warning!', qux: 'gone!'
-
#
-
# You can also use custom deprecator instance:
-
#
-
# deprecate :foo, deprecator: MyLib::Deprecator.new
-
# deprecate :foo, bar: "warning!", deprecator: MyLib::Deprecator.new
-
#
-
# \Custom deprecators must respond to <tt>deprecation_warning(deprecated_method_name, message, caller_backtrace)</tt>
-
# method where you can implement your custom warning behavior.
-
#
-
# class MyLib::Deprecator
-
# def deprecation_warning(deprecated_method_name, message, caller_backtrace = nil)
-
# message = "#{deprecated_method_name} is deprecated and will be removed from MyLibrary | #{message}"
-
# Kernel.warn message
-
# end
-
# end
-
2
def deprecate(*method_names)
-
ActiveSupport::Deprecation.deprecate_methods(self, *method_names)
-
end
-
end
-
2
require 'active_support/inflector'
-
-
2
class Module
-
# Returns the name of the module containing this one.
-
#
-
# M::N.parent_name # => "M"
-
2
def parent_name
-
100
if defined? @parent_name
-
65
@parent_name
-
else
-
35
@parent_name = name =~ /::[^:]+\Z/ ? $`.freeze : nil
-
end
-
end
-
-
# Returns the module which contains this one according to its name.
-
#
-
# module M
-
# module N
-
# end
-
# end
-
# X = M::N
-
#
-
# M::N.parent # => M
-
# X.parent # => M
-
#
-
# The parent of top-level and anonymous modules is Object.
-
#
-
# M.parent # => Object
-
# Module.new.parent # => Object
-
2
def parent
-
27
parent_name ? ActiveSupport::Inflector.constantize(parent_name) : Object
-
end
-
-
# Returns all the parents of this module according to its name, ordered from
-
# nested outwards. The receiver is not contained within the result.
-
#
-
# module M
-
# module N
-
# end
-
# end
-
# X = M::N
-
#
-
# M.parents # => [Object]
-
# M::N.parents # => [M, Object]
-
# X.parents # => [M, Object]
-
2
def parents
-
53
parents = []
-
53
if parent_name
-
11
parts = parent_name.split('::')
-
11
until parts.empty?
-
20
parents << ActiveSupport::Inflector.constantize(parts * '::')
-
20
parts.pop
-
end
-
end
-
53
parents << Object unless parents.include? Object
-
53
parents
-
end
-
-
2
def local_constants #:nodoc:
-
constants(false)
-
end
-
end
-
2
class Module
-
###
-
# TODO: remove this after 1.9 support is dropped
-
2
def methods_transplantable? # :nodoc:
-
8
x = Module.new { def foo; end }
-
8
Module.new { define_method :bar, x.instance_method(:foo) }
-
4
true
-
rescue TypeError
-
false
-
end
-
end
-
2
require 'active_support/core_ext/string/inflections'
-
-
#--
-
# Allows code reuse in the methods below without polluting Module.
-
#++
-
2
module QualifiedConstUtils
-
2
def self.raise_if_absolute(path)
-
44
raise NameError.new("wrong constant name #$&") if path =~ /\A::[^:]+/
-
end
-
-
2
def self.names(path)
-
44
path.split('::')
-
end
-
end
-
-
##
-
# Extends the API for constants to be able to deal with qualified names. Arguments
-
# are assumed to be relative to the receiver.
-
#
-
#--
-
# Qualified names are required to be relative because we are extending existing
-
# methods that expect constant names, ie, relative paths of length 1. For example,
-
# Object.const_get('::String') raises NameError and so does qualified_const_get.
-
#++
-
2
class Module
-
2
def qualified_const_defined?(path, search_parents=true)
-
44
QualifiedConstUtils.raise_if_absolute(path)
-
-
44
QualifiedConstUtils.names(path).inject(self) do |mod, name|
-
60
return unless mod.const_defined?(name, search_parents)
-
60
mod.const_get(name)
-
end
-
44
return true
-
end
-
-
2
def qualified_const_get(path)
-
QualifiedConstUtils.raise_if_absolute(path)
-
-
QualifiedConstUtils.names(path).inject(self) do |mod, name|
-
mod.const_get(name)
-
end
-
end
-
-
2
def qualified_const_set(path, value)
-
QualifiedConstUtils.raise_if_absolute(path)
-
-
const_name = path.demodulize
-
mod_name = path.deconstantize
-
mod = mod_name.empty? ? self : qualified_const_get(mod_name)
-
mod.const_set(const_name, value)
-
end
-
end
-
2
require 'active_support/core_ext/module/anonymous'
-
2
require 'active_support/core_ext/string/inflections'
-
-
2
class Module
-
2
def reachable? #:nodoc:
-
!anonymous? && name.safe_constantize.equal?(self)
-
end
-
end
-
2
class Module
-
2
def remove_possible_method(method)
-
1771
if method_defined?(method) || private_method_defined?(method)
-
1045
undef_method(method)
-
end
-
end
-
-
2
def redefine_method(method, &block)
-
17
remove_possible_method(method)
-
17
define_method(method, &block)
-
end
-
end
-
2
class NameError
-
# Extract the name of the missing constant from the exception message.
-
2
def missing_name
-
5
if /undefined local variable or method/ !~ message
-
5
$1 if /((::)?([A-Z]\w*)(::[A-Z]\w*)*)$/ =~ message
-
end
-
end
-
-
# Was this exception raised because the given name was missing?
-
2
def missing_name?(name)
-
5
if name.is_a? Symbol
-
last_name = (missing_name || '').split('::').last
-
last_name == name.to_s
-
else
-
5
missing_name == name.to_s
-
end
-
end
-
end
-
2
require 'active_support/core_ext/numeric/bytes'
-
2
require 'active_support/core_ext/numeric/time'
-
2
require 'active_support/core_ext/numeric/conversions'
-
2
class Numeric
-
2
KILOBYTE = 1024
-
2
MEGABYTE = KILOBYTE * 1024
-
2
GIGABYTE = MEGABYTE * 1024
-
2
TERABYTE = GIGABYTE * 1024
-
2
PETABYTE = TERABYTE * 1024
-
2
EXABYTE = PETABYTE * 1024
-
-
# Enables the use of byte calculations and declarations, like 45.bytes + 2.6.megabytes
-
2
def bytes
-
self
-
end
-
2
alias :byte :bytes
-
-
2
def kilobytes
-
2
self * KILOBYTE
-
end
-
2
alias :kilobyte :kilobytes
-
-
2
def megabytes
-
self * MEGABYTE
-
end
-
2
alias :megabyte :megabytes
-
-
2
def gigabytes
-
self * GIGABYTE
-
end
-
2
alias :gigabyte :gigabytes
-
-
2
def terabytes
-
self * TERABYTE
-
end
-
2
alias :terabyte :terabytes
-
-
2
def petabytes
-
self * PETABYTE
-
end
-
2
alias :petabyte :petabytes
-
-
2
def exabytes
-
self * EXABYTE
-
end
-
2
alias :exabyte :exabytes
-
end
-
2
require 'active_support/core_ext/big_decimal/conversions'
-
2
require 'active_support/number_helper'
-
-
2
class Numeric
-
-
# Provides options for converting numbers into formatted strings.
-
# Options are provided for phone numbers, currency, percentage,
-
# precision, positional notation, file size and pretty printing.
-
#
-
# ==== Options
-
#
-
# For details on which formats use which options, see ActiveSupport::NumberHelper
-
#
-
# ==== Examples
-
#
-
# Phone Numbers:
-
# 5551234.to_s(:phone) # => 555-1234
-
# 1235551234.to_s(:phone) # => 123-555-1234
-
# 1235551234.to_s(:phone, area_code: true) # => (123) 555-1234
-
# 1235551234.to_s(:phone, delimiter: ' ') # => 123 555 1234
-
# 1235551234.to_s(:phone, area_code: true, extension: 555) # => (123) 555-1234 x 555
-
# 1235551234.to_s(:phone, country_code: 1) # => +1-123-555-1234
-
# 1235551234.to_s(:phone, country_code: 1, extension: 1343, delimiter: '.')
-
# # => +1.123.555.1234 x 1343
-
#
-
# Currency:
-
# 1234567890.50.to_s(:currency) # => $1,234,567,890.50
-
# 1234567890.506.to_s(:currency) # => $1,234,567,890.51
-
# 1234567890.506.to_s(:currency, precision: 3) # => $1,234,567,890.506
-
# 1234567890.506.to_s(:currency, locale: :fr) # => 1 234 567 890,51 €
-
# -1234567890.50.to_s(:currency, negative_format: '(%u%n)')
-
# # => ($1,234,567,890.50)
-
# 1234567890.50.to_s(:currency, unit: '£', separator: ',', delimiter: '')
-
# # => £1234567890,50
-
# 1234567890.50.to_s(:currency, unit: '£', separator: ',', delimiter: '', format: '%n %u')
-
# # => 1234567890,50 £
-
#
-
# Percentage:
-
# 100.to_s(:percentage) # => 100.000%
-
# 100.to_s(:percentage, precision: 0) # => 100%
-
# 1000.to_s(:percentage, delimiter: '.', separator: ',') # => 1.000,000%
-
# 302.24398923423.to_s(:percentage, precision: 5) # => 302.24399%
-
# 1000.to_s(:percentage, locale: :fr) # => 1 000,000%
-
# 100.to_s(:percentage, format: '%n %') # => 100 %
-
#
-
# Delimited:
-
# 12345678.to_s(:delimited) # => 12,345,678
-
# 12345678.05.to_s(:delimited) # => 12,345,678.05
-
# 12345678.to_s(:delimited, delimiter: '.') # => 12.345.678
-
# 12345678.to_s(:delimited, delimiter: ',') # => 12,345,678
-
# 12345678.05.to_s(:delimited, separator: ' ') # => 12,345,678 05
-
# 12345678.05.to_s(:delimited, locale: :fr) # => 12 345 678,05
-
# 98765432.98.to_s(:delimited, delimiter: ' ', separator: ',')
-
# # => 98 765 432,98
-
#
-
# Rounded:
-
# 111.2345.to_s(:rounded) # => 111.235
-
# 111.2345.to_s(:rounded, precision: 2) # => 111.23
-
# 13.to_s(:rounded, precision: 5) # => 13.00000
-
# 389.32314.to_s(:rounded, precision: 0) # => 389
-
# 111.2345.to_s(:rounded, significant: true) # => 111
-
# 111.2345.to_s(:rounded, precision: 1, significant: true) # => 100
-
# 13.to_s(:rounded, precision: 5, significant: true) # => 13.000
-
# 111.234.to_s(:rounded, locale: :fr) # => 111,234
-
# 13.to_s(:rounded, precision: 5, significant: true, strip_insignificant_zeros: true)
-
# # => 13
-
# 389.32314.to_s(:rounded, precision: 4, significant: true) # => 389.3
-
# 1111.2345.to_s(:rounded, precision: 2, separator: ',', delimiter: '.')
-
# # => 1.111,23
-
#
-
# Human-friendly size in Bytes:
-
# 123.to_s(:human_size) # => 123 Bytes
-
# 1234.to_s(:human_size) # => 1.21 KB
-
# 12345.to_s(:human_size) # => 12.1 KB
-
# 1234567.to_s(:human_size) # => 1.18 MB
-
# 1234567890.to_s(:human_size) # => 1.15 GB
-
# 1234567890123.to_s(:human_size) # => 1.12 TB
-
# 1234567.to_s(:human_size, precision: 2) # => 1.2 MB
-
# 483989.to_s(:human_size, precision: 2) # => 470 KB
-
# 1234567.to_s(:human_size, precision: 2, separator: ',') # => 1,2 MB
-
# 1234567890123.to_s(:human_size, precision: 5) # => "1.1229 TB"
-
# 524288000.to_s(:human_size, precision: 5) # => "500 MB"
-
#
-
# Human-friendly format:
-
# 123.to_s(:human) # => "123"
-
# 1234.to_s(:human) # => "1.23 Thousand"
-
# 12345.to_s(:human) # => "12.3 Thousand"
-
# 1234567.to_s(:human) # => "1.23 Million"
-
# 1234567890.to_s(:human) # => "1.23 Billion"
-
# 1234567890123.to_s(:human) # => "1.23 Trillion"
-
# 1234567890123456.to_s(:human) # => "1.23 Quadrillion"
-
# 1234567890123456789.to_s(:human) # => "1230 Quadrillion"
-
# 489939.to_s(:human, precision: 2) # => "490 Thousand"
-
# 489939.to_s(:human, precision: 4) # => "489.9 Thousand"
-
# 1234567.to_s(:human, precision: 4,
-
# significant: false) # => "1.2346 Million"
-
# 1234567.to_s(:human, precision: 1,
-
# separator: ',',
-
# significant: false) # => "1,2 Million"
-
2
def to_formatted_s(format = :default, options = {})
-
case format
-
when :phone
-
return ActiveSupport::NumberHelper.number_to_phone(self, options)
-
when :currency
-
return ActiveSupport::NumberHelper.number_to_currency(self, options)
-
when :percentage
-
return ActiveSupport::NumberHelper.number_to_percentage(self, options)
-
when :delimited
-
return ActiveSupport::NumberHelper.number_to_delimited(self, options)
-
when :rounded
-
return ActiveSupport::NumberHelper.number_to_rounded(self, options)
-
when :human
-
return ActiveSupport::NumberHelper.number_to_human(self, options)
-
when :human_size
-
return ActiveSupport::NumberHelper.number_to_human_size(self, options)
-
else
-
self.to_default_s
-
end
-
end
-
-
2
[Float, Fixnum, Bignum, BigDecimal].each do |klass|
-
8
klass.send(:alias_method, :to_default_s, :to_s)
-
-
8
klass.send(:define_method, :to_s) do |*args|
-
14569
if args[0].is_a?(Symbol)
-
format = args[0]
-
options = args[1] || {}
-
-
self.to_formatted_s(format, options)
-
else
-
14569
to_default_s(*args)
-
end
-
end
-
end
-
end
-
2
require 'active_support/duration'
-
2
require 'active_support/core_ext/time/calculations'
-
2
require 'active_support/core_ext/time/acts_like'
-
-
2
class Numeric
-
# Enables the use of time calculations and declarations, like 45.minutes + 2.hours + 4.years.
-
#
-
# These methods use Time#advance for precise date calculations when using from_now, ago, etc.
-
# as well as adding or subtracting their results from a Time object. For example:
-
#
-
# # equivalent to Time.current.advance(months: 1)
-
# 1.month.from_now
-
#
-
# # equivalent to Time.current.advance(years: 2)
-
# 2.years.from_now
-
#
-
# # equivalent to Time.current.advance(months: 4, years: 5)
-
# (4.months + 5.years).from_now
-
#
-
# While these methods provide precise calculation when used as in the examples above, care
-
# should be taken to note that this is not true if the result of `months', `years', etc is
-
# converted before use:
-
#
-
# # equivalent to 30.days.to_i.from_now
-
# 1.month.to_i.from_now
-
#
-
# # equivalent to 365.25.days.to_f.from_now
-
# 1.year.to_f.from_now
-
#
-
# In such cases, Ruby's core
-
# Date[http://ruby-doc.org/stdlib/libdoc/date/rdoc/Date.html] and
-
# Time[http://ruby-doc.org/stdlib/libdoc/time/rdoc/Time.html] should be used for precision
-
# date and time arithmetic.
-
2
def seconds
-
ActiveSupport::Duration.new(self, [[:seconds, self]])
-
end
-
2
alias :second :seconds
-
-
2
def minutes
-
2
ActiveSupport::Duration.new(self * 60, [[:seconds, self * 60]])
-
end
-
2
alias :minute :minutes
-
-
2
def hours
-
10
ActiveSupport::Duration.new(self * 3600, [[:seconds, self * 3600]])
-
end
-
2
alias :hour :hours
-
-
2
def days
-
4
ActiveSupport::Duration.new(self * 24.hours, [[:days, self]])
-
end
-
2
alias :day :days
-
-
2
def weeks
-
2
ActiveSupport::Duration.new(self * 7.days, [[:days, self * 7]])
-
end
-
2
alias :week :weeks
-
-
2
def fortnights
-
ActiveSupport::Duration.new(self * 2.weeks, [[:days, self * 14]])
-
end
-
2
alias :fortnight :fortnights
-
-
# Reads best without arguments: 10.minutes.ago
-
2
def ago(time = ::Time.current)
-
ActiveSupport::Deprecation.warn "Calling #ago or #until on a number (e.g. 5.ago) is deprecated and will be removed in the future, use 5.seconds.ago instead"
-
time - self
-
end
-
-
# Reads best with argument: 10.minutes.until(time)
-
2
alias :until :ago
-
-
# Reads best with argument: 10.minutes.since(time)
-
2
def since(time = ::Time.current)
-
ActiveSupport::Deprecation.warn "Calling #since or #from_now on a number (e.g. 5.since) is deprecated and will be removed in the future, use 5.seconds.since instead"
-
time + self
-
end
-
-
# Reads best without arguments: 10.minutes.from_now
-
2
alias :from_now :since
-
-
# Used with the standard time durations, like 1.hour.in_milliseconds --
-
# so we can feed them to JavaScript functions like getTime().
-
2
def in_milliseconds
-
self * 1000
-
end
-
end
-
2
require 'active_support/core_ext/object/acts_like'
-
2
require 'active_support/core_ext/object/blank'
-
2
require 'active_support/core_ext/object/duplicable'
-
2
require 'active_support/core_ext/object/deep_dup'
-
2
require 'active_support/core_ext/object/try'
-
2
require 'active_support/core_ext/object/inclusion'
-
-
2
require 'active_support/core_ext/object/conversions'
-
2
require 'active_support/core_ext/object/instance_variables'
-
-
2
require 'active_support/core_ext/object/json'
-
2
require 'active_support/core_ext/object/to_param'
-
2
require 'active_support/core_ext/object/to_query'
-
2
require 'active_support/core_ext/object/with_options'
-
2
class Object
-
# A duck-type assistant method. For example, Active Support extends Date
-
# to define an <tt>acts_like_date?</tt> method, and extends Time to define
-
# <tt>acts_like_time?</tt>. As a result, we can do <tt>x.acts_like?(:time)</tt> and
-
# <tt>x.acts_like?(:date)</tt> to do duck-type-safe comparisons, since classes that
-
# we want to act like Time simply need to define an <tt>acts_like_time?</tt> method.
-
2
def acts_like?(duck)
-
2136
respond_to? :"acts_like_#{duck}?"
-
end
-
end
-
# encoding: utf-8
-
-
2
class Object
-
# An object is blank if it's false, empty, or a whitespace string.
-
# For example, '', ' ', +nil+, [], and {} are all blank.
-
#
-
# This simplifies
-
#
-
# address.nil? || address.empty?
-
#
-
# to
-
#
-
# address.blank?
-
#
-
# @return [true, false]
-
2
def blank?
-
645
respond_to?(:empty?) ? !!empty? : !self
-
end
-
-
# An object is present if it's not blank.
-
#
-
# @return [true, false]
-
2
def present?
-
4334
!blank?
-
end
-
-
# Returns the receiver if it's present otherwise returns +nil+.
-
# <tt>object.presence</tt> is equivalent to
-
#
-
# object.present? ? object : nil
-
#
-
# For example, something like
-
#
-
# state = params[:state] if params[:state].present?
-
# country = params[:country] if params[:country].present?
-
# region = state || country || 'US'
-
#
-
# becomes
-
#
-
# region = params[:state].presence || params[:country].presence || 'US'
-
#
-
# @return [Object]
-
2
def presence
-
492
self if present?
-
end
-
end
-
-
2
class NilClass
-
# +nil+ is blank:
-
#
-
# nil.blank? # => true
-
#
-
# @return [true]
-
2
def blank?
-
6190
true
-
end
-
end
-
-
2
class FalseClass
-
# +false+ is blank:
-
#
-
# false.blank? # => true
-
#
-
# @return [true]
-
2
def blank?
-
true
-
end
-
end
-
-
2
class TrueClass
-
# +true+ is not blank:
-
#
-
# true.blank? # => false
-
#
-
# @return [false]
-
2
def blank?
-
false
-
end
-
end
-
-
2
class Array
-
# An array is blank if it's empty:
-
#
-
# [].blank? # => true
-
# [1,2,3].blank? # => false
-
#
-
# @return [true, false]
-
2
alias_method :blank?, :empty?
-
end
-
-
2
class Hash
-
# A hash is blank if it's empty:
-
#
-
# {}.blank? # => true
-
# { key: 'value' }.blank? # => false
-
#
-
# @return [true, false]
-
2
alias_method :blank?, :empty?
-
end
-
-
2
class String
-
2
BLANK_RE = /\A[[:space:]]*\z/
-
-
# A string is blank if it's empty or contains whitespaces only:
-
#
-
# ''.blank? # => true
-
# ' '.blank? # => true
-
# "\t\n\r".blank? # => true
-
# ' blah '.blank? # => false
-
#
-
# Unicode whitespace is supported:
-
#
-
# "\u00a0".blank? # => true
-
#
-
# @return [true, false]
-
2
def blank?
-
5329
BLANK_RE === self
-
end
-
end
-
-
2
class Numeric #:nodoc:
-
# No number is blank:
-
#
-
# 1.blank? # => false
-
# 0.blank? # => false
-
#
-
# @return [false]
-
2
def blank?
-
149
false
-
end
-
end
-
2
require 'active_support/core_ext/object/to_param'
-
2
require 'active_support/core_ext/object/to_query'
-
2
require 'active_support/core_ext/array/conversions'
-
2
require 'active_support/core_ext/hash/conversions'
-
2
require 'active_support/core_ext/object/duplicable'
-
-
2
class Object
-
# Returns a deep copy of object if it's duplicable. If it's
-
# not duplicable, returns +self+.
-
#
-
# object = Object.new
-
# dup = object.deep_dup
-
# dup.instance_variable_set(:@a, 1)
-
#
-
# object.instance_variable_defined?(:@a) # => false
-
# dup.instance_variable_defined?(:@a) # => true
-
2
def deep_dup
-
522
duplicable? ? dup : self
-
end
-
end
-
-
2
class Array
-
# Returns a deep copy of array.
-
#
-
# array = [1, [2, 3]]
-
# dup = array.deep_dup
-
# dup[1][2] = 4
-
#
-
# array[1][2] # => nil
-
# dup[1][2] # => 4
-
2
def deep_dup
-
map { |it| it.deep_dup }
-
end
-
end
-
-
2
class Hash
-
# Returns a deep copy of hash.
-
#
-
# hash = { a: { b: 'b' } }
-
# dup = hash.deep_dup
-
# dup[:a][:c] = 'c'
-
#
-
# hash[:a][:c] # => nil
-
# dup[:a][:c] # => "c"
-
2
def deep_dup
-
145
each_with_object(dup) do |(key, value), hash|
-
294
hash[key.deep_dup] = value.deep_dup
-
end
-
end
-
end
-
#--
-
# Most objects are cloneable, but not all. For example you can't dup +nil+:
-
#
-
# nil.dup # => TypeError: can't dup NilClass
-
#
-
# Classes may signal their instances are not duplicable removing +dup+/+clone+
-
# or raising exceptions from them. So, to dup an arbitrary object you normally
-
# use an optimistic approach and are ready to catch an exception, say:
-
#
-
# arbitrary_object.dup rescue object
-
#
-
# Rails dups objects in a few critical spots where they are not that arbitrary.
-
# That rescue is very expensive (like 40 times slower than a predicate), and it
-
# is often triggered.
-
#
-
# That's why we hardcode the following cases and check duplicable? instead of
-
# using that rescue idiom.
-
#++
-
2
class Object
-
# Can you safely dup this object?
-
#
-
# False for +nil+, +false+, +true+, symbol, and number objects;
-
# true otherwise.
-
2
def duplicable?
-
true
-
end
-
end
-
-
2
class NilClass
-
# +nil+ is not duplicable:
-
#
-
# nil.duplicable? # => false
-
# nil.dup # => TypeError: can't dup NilClass
-
2
def duplicable?
-
5782
false
-
end
-
end
-
-
2
class FalseClass
-
# +false+ is not duplicable:
-
#
-
# false.duplicable? # => false
-
# false.dup # => TypeError: can't dup FalseClass
-
2
def duplicable?
-
20
false
-
end
-
end
-
-
2
class TrueClass
-
# +true+ is not duplicable:
-
#
-
# true.duplicable? # => false
-
# true.dup # => TypeError: can't dup TrueClass
-
2
def duplicable?
-
66
false
-
end
-
end
-
-
2
class Symbol
-
# Symbols are not duplicable:
-
#
-
# :my_symbol.duplicable? # => false
-
# :my_symbol.dup # => TypeError: can't dup Symbol
-
2
def duplicable?
-
414
false
-
end
-
end
-
-
2
class Numeric
-
# Numbers are not duplicable:
-
#
-
# 3.duplicable? # => false
-
# 3.dup # => TypeError: can't dup Fixnum
-
2
def duplicable?
-
193
false
-
end
-
end
-
-
2
require 'bigdecimal'
-
2
class BigDecimal
-
2
begin
-
2
BigDecimal.new('4.56').dup
-
-
2
def duplicable?
-
true
-
end
-
rescue TypeError
-
# can't dup, so use superclass implementation
-
end
-
end
-
-
2
class Method
-
# Methods are not duplicable:
-
#
-
# method(:puts).duplicable? # => false
-
# method(:puts).dup # => TypeError: allocator undefined for Method
-
2
def duplicable?
-
false
-
end
-
end
-
2
class Object
-
# Returns true if this object is included in the argument. Argument must be
-
# any object which responds to +#include?+. Usage:
-
#
-
# characters = ["Konata", "Kagami", "Tsukasa"]
-
# "Konata".in?(characters) # => true
-
#
-
# This will throw an ArgumentError if the argument doesn't respond
-
# to +#include?+.
-
2
def in?(another_object)
-
another_object.include?(self)
-
rescue NoMethodError
-
raise ArgumentError.new("The parameter passed to #in? must respond to #include?")
-
end
-
-
# Returns the receiver if it's included in the argument otherwise returns +nil+.
-
# Argument must be any object which responds to +#include?+. Usage:
-
#
-
# params[:bucket_type].presence_in %w( project calendar )
-
#
-
# This will throw an ArgumentError if the argument doesn't respond to +#include?+.
-
#
-
# @return [Object]
-
2
def presence_in(another_object)
-
self.in?(another_object) ? self : nil
-
end
-
end
-
2
class Object
-
# Returns a hash with string keys that maps instance variable names without "@" to their
-
# corresponding values.
-
#
-
# class C
-
# def initialize(x, y)
-
# @x, @y = x, y
-
# end
-
# end
-
#
-
# C.new(0, 1).instance_values # => {"x" => 0, "y" => 1}
-
2
def instance_values
-
Hash[instance_variables.map { |name| [name[1..-1], instance_variable_get(name)] }]
-
end
-
-
# Returns an array of instance variable names as strings including "@".
-
#
-
# class C
-
# def initialize(x, y)
-
# @x, @y = x, y
-
# end
-
# end
-
#
-
# C.new(0, 1).instance_variable_names # => ["@y", "@x"]
-
2
def instance_variable_names
-
instance_variables.map { |var| var.to_s }
-
end
-
end
-
# Hack to load json gem first so we can overwrite its to_json.
-
2
require 'json'
-
2
require 'bigdecimal'
-
2
require 'active_support/core_ext/big_decimal/conversions' # for #to_s
-
2
require 'active_support/core_ext/hash/except'
-
2
require 'active_support/core_ext/hash/slice'
-
2
require 'active_support/core_ext/object/instance_variables'
-
2
require 'time'
-
2
require 'active_support/core_ext/time/conversions'
-
2
require 'active_support/core_ext/date_time/conversions'
-
2
require 'active_support/core_ext/date/conversions'
-
2
require 'active_support/core_ext/module/aliasing'
-
-
# The JSON gem adds a few modules to Ruby core classes containing :to_json definition, overwriting
-
# their default behavior. That said, we need to define the basic to_json method in all of them,
-
# otherwise they will always use to_json gem implementation, which is backwards incompatible in
-
# several cases (for instance, the JSON implementation for Hash does not work) with inheritance
-
# and consequently classes as ActiveSupport::OrderedHash cannot be serialized to json.
-
#
-
# On the other hand, we should avoid conflict with ::JSON.{generate,dump}(obj). Unfortunately, the
-
# JSON gem's encoder relies on its own to_json implementation to encode objects. Since it always
-
# passes a ::JSON::State object as the only argument to to_json, we can detect that and forward the
-
# calls to the original to_json method.
-
#
-
# It should be noted that when using ::JSON.{generate,dump} directly, ActiveSupport's encoder is
-
# bypassed completely. This means that as_json won't be invoked and the JSON gem will simply
-
# ignore any options it does not natively understand. This also means that ::JSON.{generate,dump}
-
# should give exactly the same results with or without active support.
-
2
[Object, Array, FalseClass, Float, Hash, Integer, NilClass, String, TrueClass].each do |klass|
-
18
klass.class_eval do
-
18
def to_json_with_active_support_encoder(options = nil)
-
if options.is_a?(::JSON::State)
-
# Called from JSON.{generate,dump}, forward it to JSON gem's to_json
-
self.to_json_without_active_support_encoder(options)
-
else
-
# to_json is being invoked directly, use ActiveSupport's encoder
-
ActiveSupport::JSON.encode(self, options)
-
end
-
end
-
-
18
alias_method_chain :to_json, :active_support_encoder
-
end
-
end
-
-
2
class Object
-
2
def as_json(options = nil) #:nodoc:
-
if respond_to?(:to_hash)
-
to_hash.as_json(options)
-
else
-
instance_values.as_json(options)
-
end
-
end
-
end
-
-
2
class Struct #:nodoc:
-
2
def as_json(options = nil)
-
Hash[members.zip(values)].as_json(options)
-
end
-
end
-
-
2
class TrueClass
-
2
def as_json(options = nil) #:nodoc:
-
self
-
end
-
end
-
-
2
class FalseClass
-
2
def as_json(options = nil) #:nodoc:
-
self
-
end
-
end
-
-
2
class NilClass
-
2
def as_json(options = nil) #:nodoc:
-
self
-
end
-
end
-
-
2
class String
-
2
def as_json(options = nil) #:nodoc:
-
self
-
end
-
end
-
-
2
class Symbol
-
2
def as_json(options = nil) #:nodoc:
-
to_s
-
end
-
end
-
-
2
class Numeric
-
2
def as_json(options = nil) #:nodoc:
-
self
-
end
-
end
-
-
2
class Float
-
# Encoding Infinity or NaN to JSON should return "null". The default returns
-
# "Infinity" or "NaN" which are not valid JSON.
-
2
def as_json(options = nil) #:nodoc:
-
finite? ? self : nil
-
end
-
end
-
-
2
class BigDecimal
-
# A BigDecimal would be naturally represented as a JSON number. Most libraries,
-
# however, parse non-integer JSON numbers directly as floats. Clients using
-
# those libraries would get in general a wrong number and no way to recover
-
# other than manually inspecting the string with the JSON code itself.
-
#
-
# That's why a JSON string is returned. The JSON literal is not numeric, but
-
# if the other end knows by contract that the data is supposed to be a
-
# BigDecimal, it still has the chance to post-process the string and get the
-
# real value.
-
2
def as_json(options = nil) #:nodoc:
-
finite? ? to_s : nil
-
end
-
end
-
-
2
class Regexp
-
2
def as_json(options = nil) #:nodoc:
-
to_s
-
end
-
end
-
-
2
module Enumerable
-
2
def as_json(options = nil) #:nodoc:
-
to_a.as_json(options)
-
end
-
end
-
-
2
class Range
-
2
def as_json(options = nil) #:nodoc:
-
to_s
-
end
-
end
-
-
2
class Array
-
2
def as_json(options = nil) #:nodoc:
-
map { |v| options ? v.as_json(options.dup) : v.as_json }
-
end
-
end
-
-
2
class Hash
-
2
def as_json(options = nil) #:nodoc:
-
# create a subset of the hash by applying :only or :except
-
subset = if options
-
if attrs = options[:only]
-
slice(*Array(attrs))
-
elsif attrs = options[:except]
-
except(*Array(attrs))
-
else
-
self
-
end
-
else
-
self
-
end
-
-
Hash[subset.map { |k, v| [k.to_s, options ? v.as_json(options.dup) : v.as_json] }]
-
end
-
end
-
-
2
class Time
-
2
def as_json(options = nil) #:nodoc:
-
if ActiveSupport::JSON::Encoding.use_standard_json_time_format
-
xmlschema(ActiveSupport::JSON::Encoding.time_precision)
-
else
-
%(#{strftime("%Y/%m/%d %H:%M:%S")} #{formatted_offset(false)})
-
end
-
end
-
end
-
-
2
class Date
-
2
def as_json(options = nil) #:nodoc:
-
if ActiveSupport::JSON::Encoding.use_standard_json_time_format
-
strftime("%Y-%m-%d")
-
else
-
strftime("%Y/%m/%d")
-
end
-
end
-
end
-
-
2
class DateTime
-
2
def as_json(options = nil) #:nodoc:
-
if ActiveSupport::JSON::Encoding.use_standard_json_time_format
-
xmlschema(ActiveSupport::JSON::Encoding.time_precision)
-
else
-
strftime('%Y/%m/%d %H:%M:%S %z')
-
end
-
end
-
end
-
-
2
class Process::Status #:nodoc:
-
2
def as_json(options = nil)
-
{ :exitstatus => exitstatus, :pid => pid }
-
end
-
end
-
2
require 'active_support/core_ext/object/to_query'
-
2
class Object
-
# Alias of <tt>to_s</tt>.
-
2
def to_param
-
38
to_s
-
end
-
-
# Converts an object into a string suitable for use as a URL query string,
-
# using the given <tt>key</tt> as the param name.
-
2
def to_query(key)
-
require 'cgi' unless defined?(CGI) && defined?(CGI::escape)
-
"#{CGI.escape(key.to_param)}=#{CGI.escape(to_param.to_s)}"
-
end
-
end
-
-
2
class NilClass
-
# Returns +self+.
-
2
def to_param
-
26
self
-
end
-
end
-
-
2
class TrueClass
-
# Returns +self+.
-
2
def to_param
-
self
-
end
-
end
-
-
2
class FalseClass
-
# Returns +self+.
-
2
def to_param
-
self
-
end
-
end
-
-
2
class Array
-
# Calls <tt>to_param</tt> on all its elements and joins the result with
-
# slashes. This is used by <tt>url_for</tt> in Action Pack.
-
2
def to_param
-
collect { |e| e.to_param }.join '/'
-
end
-
-
# Converts an array into a string suitable for use as a URL query string,
-
# using the given +key+ as the param name.
-
#
-
# ['Rails', 'coding'].to_query('hobbies') # => "hobbies%5B%5D=Rails&hobbies%5B%5D=coding"
-
2
def to_query(key)
-
prefix = "#{key}[]"
-
-
if empty?
-
nil.to_query(prefix)
-
else
-
collect { |value| value.to_query(prefix) }.join '&'
-
end
-
end
-
end
-
-
2
class Hash
-
# Returns a string representation of the receiver suitable for use as a URL
-
# query string:
-
#
-
# {name: 'David', nationality: 'Danish'}.to_query
-
# # => "name=David&nationality=Danish"
-
#
-
# An optional namespace can be passed to enclose key names:
-
#
-
# {name: 'David', nationality: 'Danish'}.to_query('user')
-
# # => "user%5Bname%5D=David&user%5Bnationality%5D=Danish"
-
#
-
# The string pairs "key=value" that conform the query string
-
# are sorted lexicographically in ascending order.
-
#
-
# This method is also aliased as +to_param+.
-
2
def to_query(namespace = nil)
-
collect do |key, value|
-
unless (value.is_a?(Hash) || value.is_a?(Array)) && value.empty?
-
value.to_query(namespace ? "#{namespace}[#{key}]" : key)
-
end
-
11
end.compact.sort! * '&'
-
end
-
-
2
alias_method :to_param, :to_query
-
end
-
2
class Object
-
# Invokes the public method whose name goes as first argument just like
-
# +public_send+ does, except that if the receiver does not respond to it the
-
# call returns +nil+ rather than raising an exception.
-
#
-
# This method is defined to be able to write
-
#
-
# @person.try(:name)
-
#
-
# instead of
-
#
-
# @person ? @person.name : nil
-
#
-
# +try+ returns +nil+ when called on +nil+ regardless of whether it responds
-
# to the method:
-
#
-
# nil.try(:to_i) # => nil, rather than 0
-
#
-
# Arguments and blocks are forwarded to the method if invoked:
-
#
-
# @posts.try(:each_slice, 2) do |a, b|
-
# ...
-
# end
-
#
-
# The number of arguments in the signature must match. If the object responds
-
# to the method the call is attempted and +ArgumentError+ is still raised
-
# otherwise.
-
#
-
# If +try+ is called without arguments it yields the receiver to a given
-
# block unless it is +nil+:
-
#
-
# @person.try do |p|
-
# ...
-
# end
-
#
-
# Please also note that +try+ is defined on +Object+, therefore it won't work
-
# with instances of classes that do not have +Object+ among their ancestors,
-
# like direct subclasses of +BasicObject+. For example, using +try+ with
-
# +SimpleDelegator+ will delegate +try+ to the target instead of calling it on
-
# delegator itself.
-
2
def try(*a, &b)
-
128
if a.empty? && block_given?
-
yield self
-
else
-
128
public_send(*a, &b) if respond_to?(a.first)
-
end
-
end
-
-
# Same as #try, but will raise a NoMethodError exception if the receiving is not nil and
-
# does not implement the tried method.
-
2
def try!(*a, &b)
-
if a.empty? && block_given?
-
yield self
-
else
-
public_send(*a, &b)
-
end
-
end
-
end
-
-
2
class NilClass
-
# Calling +try+ on +nil+ always returns +nil+.
-
# It becomes specially helpful when navigating through associations that may return +nil+.
-
#
-
# nil.try(:name) # => nil
-
#
-
# Without +try+
-
# @person && !@person.children.blank? && @person.children.first.name
-
#
-
# With +try+
-
# @person.try(:children).try(:first).try(:name)
-
2
def try(*args)
-
nil
-
end
-
-
2
def try!(*args)
-
nil
-
end
-
end
-
2
require 'active_support/option_merger'
-
-
2
class Object
-
# An elegant way to factor duplication out of options passed to a series of
-
# method calls. Each method called in the block, with the block variable as
-
# the receiver, will have its options merged with the default +options+ hash
-
# provided. Each method called on the block variable must take an options
-
# hash as its final argument.
-
#
-
# Without <tt>with_options></tt>, this code contains duplication:
-
#
-
# class Account < ActiveRecord::Base
-
# has_many :customers, dependent: :destroy
-
# has_many :products, dependent: :destroy
-
# has_many :invoices, dependent: :destroy
-
# has_many :expenses, dependent: :destroy
-
# end
-
#
-
# Using <tt>with_options</tt>, we can remove the duplication:
-
#
-
# class Account < ActiveRecord::Base
-
# with_options dependent: :destroy do |assoc|
-
# assoc.has_many :customers
-
# assoc.has_many :products
-
# assoc.has_many :invoices
-
# assoc.has_many :expenses
-
# end
-
# end
-
#
-
# It can also be used with an explicit receiver:
-
#
-
# I18n.with_options locale: user.locale, scope: 'newsletter' do |i18n|
-
# subject i18n.t :subject
-
# body i18n.t :body, user_name: user.name
-
# end
-
#
-
# <tt>with_options</tt> can also be nested since the call is forwarded to its receiver.
-
# Each nesting level will merge inherited defaults in addition to their own.
-
2
def with_options(options)
-
6
yield ActiveSupport::OptionMerger.new(self, options)
-
end
-
end
-
2
require 'active_support/core_ext/range/conversions'
-
2
require 'active_support/core_ext/range/include_range'
-
2
require 'active_support/core_ext/range/overlaps'
-
2
require 'active_support/core_ext/range/each'
-
2
class Range
-
2
RANGE_FORMATS = {
-
:db => Proc.new { |start, stop| "BETWEEN '#{start.to_s(:db)}' AND '#{stop.to_s(:db)}'" }
-
}
-
-
# Gives a human readable format of the range.
-
#
-
# (1..100).to_formatted_s # => "1..100"
-
2
def to_formatted_s(format = :default)
-
if formatter = RANGE_FORMATS[format]
-
formatter.call(first, last)
-
else
-
to_default_s
-
end
-
end
-
-
2
alias_method :to_default_s, :to_s
-
2
alias_method :to_s, :to_formatted_s
-
end
-
2
require 'active_support/core_ext/module/aliasing'
-
-
2
class Range #:nodoc:
-
-
2
def each_with_time_with_zone(&block)
-
6
ensure_iteration_allowed
-
6
each_without_time_with_zone(&block)
-
end
-
2
alias_method_chain :each, :time_with_zone
-
-
2
def step_with_time_with_zone(n = 1, &block)
-
ensure_iteration_allowed
-
step_without_time_with_zone(n, &block)
-
end
-
2
alias_method_chain :step, :time_with_zone
-
-
2
private
-
2
def ensure_iteration_allowed
-
6
if first.is_a?(Time)
-
raise TypeError, "can't iterate from #{first.class}"
-
end
-
end
-
end
-
2
require 'active_support/core_ext/module/aliasing'
-
-
2
class Range
-
# Extends the default Range#include? to support range comparisons.
-
# (1..5).include?(1..5) # => true
-
# (1..5).include?(2..3) # => true
-
# (1..5).include?(2..6) # => false
-
#
-
# The native Range#include? behavior is untouched.
-
# ('a'..'f').include?('c') # => true
-
# (5..9).include?(11) # => false
-
2
def include_with_range?(value)
-
6136
if value.is_a?(::Range)
-
# 1...10 includes 1..9 but it does not include 1..10.
-
operator = exclude_end? && !value.exclude_end? ? :< : :<=
-
include_without_range?(value.first) && value.last.send(operator, last)
-
else
-
6136
include_without_range?(value)
-
end
-
end
-
-
2
alias_method_chain :include?, :range
-
end
-
2
class Range
-
# Compare two ranges and see if they overlap each other
-
# (1..5).overlaps?(4..6) # => true
-
# (1..5).overlaps?(7..9) # => false
-
2
def overlaps?(other)
-
cover?(other.first) || other.cover?(first)
-
end
-
end
-
2
class Regexp #:nodoc:
-
2
def multiline?
-
options & MULTILINE == MULTILINE
-
end
-
end
-
2
require 'active_support/core_ext/string/conversions'
-
2
require 'active_support/core_ext/string/filters'
-
2
require 'active_support/core_ext/string/multibyte'
-
2
require 'active_support/core_ext/string/starts_ends_with'
-
2
require 'active_support/core_ext/string/inflections'
-
2
require 'active_support/core_ext/string/access'
-
2
require 'active_support/core_ext/string/behavior'
-
2
require 'active_support/core_ext/string/output_safety'
-
2
require 'active_support/core_ext/string/exclude'
-
2
require 'active_support/core_ext/string/strip'
-
2
require 'active_support/core_ext/string/inquiry'
-
2
require 'active_support/core_ext/string/indent'
-
2
require 'active_support/core_ext/string/zones'
-
2
class String
-
# If you pass a single Fixnum, returns a substring of one character at that
-
# position. The first character of the string is at position 0, the next at
-
# position 1, and so on. If a range is supplied, a substring containing
-
# characters at offsets given by the range is returned. In both cases, if an
-
# offset is negative, it is counted from the end of the string. Returns nil
-
# if the initial offset falls outside the string. Returns an empty string if
-
# the beginning of the range is greater than the end of the string.
-
#
-
# str = "hello"
-
# str.at(0) # => "h"
-
# str.at(1..3) # => "ell"
-
# str.at(-2) # => "l"
-
# str.at(-2..-1) # => "lo"
-
# str.at(5) # => nil
-
# str.at(5..-1) # => ""
-
#
-
# If a Regexp is given, the matching portion of the string is returned.
-
# If a String is given, that given string is returned if it occurs in
-
# the string. In both cases, nil is returned if there is no match.
-
#
-
# str = "hello"
-
# str.at(/lo/) # => "lo"
-
# str.at(/ol/) # => nil
-
# str.at("lo") # => "lo"
-
# str.at("ol") # => nil
-
2
def at(position)
-
self[position]
-
end
-
-
# Returns a substring from the given position to the end of the string.
-
# If the position is negative, it is counted from the end of the string.
-
#
-
# str = "hello"
-
# str.from(0) # => "hello"
-
# str.from(3) # => "lo"
-
# str.from(-2) # => "lo"
-
#
-
# You can mix it with +to+ method and do fun things like:
-
#
-
# str = "hello"
-
# str.from(0).to(-1) # => "hello"
-
# str.from(1).to(-2) # => "ell"
-
2
def from(position)
-
self[position..-1]
-
end
-
-
# Returns a substring from the beginning of the string to the given position.
-
# If the position is negative, it is counted from the end of the string.
-
#
-
# str = "hello"
-
# str.to(0) # => "h"
-
# str.to(3) # => "hell"
-
# str.to(-2) # => "hell"
-
#
-
# You can mix it with +from+ method and do fun things like:
-
#
-
# str = "hello"
-
# str.from(0).to(-1) # => "hello"
-
# str.from(1).to(-2) # => "ell"
-
2
def to(position)
-
8
self[0..position]
-
end
-
-
# Returns the first character. If a limit is supplied, returns a substring
-
# from the beginning of the string until it reaches the limit value. If the
-
# given limit is greater than or equal to the string length, returns self.
-
#
-
# str = "hello"
-
# str.first # => "h"
-
# str.first(1) # => "h"
-
# str.first(2) # => "he"
-
# str.first(0) # => ""
-
# str.first(6) # => "hello"
-
2
def first(limit = 1)
-
8
if limit == 0
-
''
-
8
elsif limit >= size
-
self
-
else
-
8
to(limit - 1)
-
end
-
end
-
-
# Returns the last character of the string. If a limit is supplied, returns a substring
-
# from the end of the string until it reaches the limit value (counting backwards). If
-
# the given limit is greater than or equal to the string length, returns self.
-
#
-
# str = "hello"
-
# str.last # => "o"
-
# str.last(1) # => "o"
-
# str.last(2) # => "lo"
-
# str.last(0) # => ""
-
# str.last(6) # => "hello"
-
2
def last(limit = 1)
-
4
if limit == 0
-
''
-
4
elsif limit >= size
-
4
self
-
else
-
from(-limit)
-
end
-
end
-
end
-
2
class String
-
# Enable more predictable duck-typing on String-like classes. See <tt>Object#acts_like?</tt>.
-
2
def acts_like_string?
-
true
-
end
-
end
-
2
require 'date'
-
2
require 'active_support/core_ext/time/calculations'
-
-
2
class String
-
# Converts a string to a Time value.
-
# The +form+ can be either :utc or :local (default :local).
-
#
-
# The time is parsed using Time.parse method.
-
# If +form+ is :local, then the time is in the system timezone.
-
# If the date part is missing then the current date is used and if
-
# the time part is missing then it is assumed to be 00:00:00.
-
#
-
# "13-12-2012".to_time # => 2012-12-13 00:00:00 +0100
-
# "06:12".to_time # => 2012-12-13 06:12:00 +0100
-
# "2012-12-13 06:12".to_time # => 2012-12-13 06:12:00 +0100
-
# "2012-12-13T06:12".to_time # => 2012-12-13 06:12:00 +0100
-
# "2012-12-13T06:12".to_time(:utc) # => 2012-12-13 05:12:00 UTC
-
# "12/13/2012".to_time # => ArgumentError: argument out of range
-
2
def to_time(form = :local)
-
parts = Date._parse(self, false)
-
return if parts.empty?
-
-
now = Time.now
-
time = Time.new(
-
parts.fetch(:year, now.year),
-
parts.fetch(:mon, now.month),
-
parts.fetch(:mday, now.day),
-
parts.fetch(:hour, 0),
-
parts.fetch(:min, 0),
-
parts.fetch(:sec, 0) + parts.fetch(:sec_fraction, 0),
-
parts.fetch(:offset, form == :utc ? 0 : nil)
-
)
-
-
form == :utc ? time.utc : time.getlocal
-
end
-
-
# Converts a string to a Date value.
-
#
-
# "1-1-2012".to_date # => Sun, 01 Jan 2012
-
# "01/01/2012".to_date # => Sun, 01 Jan 2012
-
# "2012-12-13".to_date # => Thu, 13 Dec 2012
-
# "12/13/2012".to_date # => ArgumentError: invalid date
-
2
def to_date
-
::Date.parse(self, false) unless blank?
-
end
-
-
# Converts a string to a DateTime value.
-
#
-
# "1-1-2012".to_datetime # => Sun, 01 Jan 2012 00:00:00 +0000
-
# "01/01/2012 23:59:59".to_datetime # => Sun, 01 Jan 2012 23:59:59 +0000
-
# "2012-12-13 12:50".to_datetime # => Thu, 13 Dec 2012 12:50:00 +0000
-
# "12/13/2012".to_datetime # => ArgumentError: invalid date
-
2
def to_datetime
-
::DateTime.parse(self, false) unless blank?
-
end
-
end
-
2
class String
-
# The inverse of <tt>String#include?</tt>. Returns true if the string
-
# does not include the other string.
-
#
-
# "hello".exclude? "lo" # => false
-
# "hello".exclude? "ol" # => true
-
# "hello".exclude? ?h # => false
-
2
def exclude?(string)
-
!include?(string)
-
end
-
end
-
2
class String
-
# Returns the string, first removing all whitespace on both ends of
-
# the string, and then changing remaining consecutive whitespace
-
# groups into one space each.
-
#
-
# Note that it handles both ASCII and Unicode whitespace like mongolian vowel separator (U+180E).
-
#
-
# %{ Multi-line
-
# string }.squish # => "Multi-line string"
-
# " foo bar \n \t boo".squish # => "foo bar boo"
-
2
def squish
-
1
dup.squish!
-
end
-
-
# Performs a destructive squish. See String#squish.
-
2
def squish!
-
1
gsub!(/\A[[:space:]]+/, '')
-
1
gsub!(/[[:space:]]+\z/, '')
-
1
gsub!(/[[:space:]]+/, ' ')
-
1
self
-
end
-
-
# Returns a new string with all occurrences of the pattern removed. Short-hand for String#gsub(pattern, '').
-
2
def remove(pattern)
-
gsub pattern, ''
-
end
-
-
# Alters the string by removing all occurrences of the pattern. Short-hand for String#gsub!(pattern, '').
-
2
def remove!(pattern)
-
gsub! pattern, ''
-
end
-
-
# Truncates a given +text+ after a given <tt>length</tt> if +text+ is longer than <tt>length</tt>:
-
#
-
# 'Once upon a time in a world far far away'.truncate(27)
-
# # => "Once upon a time in a wo..."
-
#
-
# Pass a string or regexp <tt>:separator</tt> to truncate +text+ at a natural break:
-
#
-
# 'Once upon a time in a world far far away'.truncate(27, separator: ' ')
-
# # => "Once upon a time in a..."
-
#
-
# 'Once upon a time in a world far far away'.truncate(27, separator: /\s/)
-
# # => "Once upon a time in a..."
-
#
-
# The last characters will be replaced with the <tt>:omission</tt> string (defaults to "...")
-
# for a total length not exceeding <tt>length</tt>:
-
#
-
# 'And they found that many people were sleeping better.'.truncate(25, omission: '... (continued)')
-
# # => "And they f... (continued)"
-
2
def truncate(truncate_at, options = {})
-
return dup unless length > truncate_at
-
-
omission = options[:omission] || '...'
-
length_with_room_for_omission = truncate_at - omission.length
-
stop = \
-
if options[:separator]
-
rindex(options[:separator], length_with_room_for_omission) || length_with_room_for_omission
-
else
-
length_with_room_for_omission
-
end
-
-
"#{self[0, stop]}#{omission}"
-
end
-
end
-
2
class String
-
# Same as +indent+, except it indents the receiver in-place.
-
#
-
# Returns the indented string, or +nil+ if there was nothing to indent.
-
2
def indent!(amount, indent_string=nil, indent_empty_lines=false)
-
153
indent_string = indent_string || self[/^[ \t]/] || ' '
-
153
re = indent_empty_lines ? /^/ : /^(?!$)/
-
153
gsub!(re, indent_string * amount)
-
end
-
-
# Indents the lines in the receiver:
-
#
-
# <<EOS.indent(2)
-
# def some_method
-
# some_code
-
# end
-
# EOS
-
# # =>
-
# def some_method
-
# some_code
-
# end
-
#
-
# The second argument, +indent_string+, specifies which indent string to
-
# use. The default is +nil+, which tells the method to make a guess by
-
# peeking at the first indented line, and fallback to a space if there is
-
# none.
-
#
-
# " foo".indent(2) # => " foo"
-
# "foo\n\t\tbar".indent(2) # => "\t\tfoo\n\t\t\t\tbar"
-
# "foo".indent(2, "\t") # => "\t\tfoo"
-
#
-
# While +indent_string+ is typically one space or tab, it may be any string.
-
#
-
# The third argument, +indent_empty_lines+, is a flag that says whether
-
# empty lines should be indented. Default is false.
-
#
-
# "foo\n\nbar".indent(2) # => " foo\n\n bar"
-
# "foo\n\nbar".indent(2, nil, true) # => " foo\n \n bar"
-
#
-
2
def indent(amount, indent_string=nil, indent_empty_lines=false)
-
306
dup.tap {|_| _.indent!(amount, indent_string, indent_empty_lines)}
-
end
-
end
-
2
require 'active_support/inflector/methods'
-
2
require 'active_support/inflector/transliterate'
-
-
# String inflections define new methods on the String class to transform names for different purposes.
-
# For instance, you can figure out the name of a table from the name of a class.
-
#
-
# 'ScaleScore'.tableize # => "scale_scores"
-
#
-
2
class String
-
# Returns the plural form of the word in the string.
-
#
-
# If the optional parameter +count+ is specified,
-
# the singular form will be returned if <tt>count == 1</tt>.
-
# For any other value of +count+ the plural will be returned.
-
#
-
# If the optional parameter +locale+ is specified,
-
# the word will be pluralized as a word of that language.
-
# By default, this parameter is set to <tt>:en</tt>.
-
# You must define your own inflection rules for languages other than English.
-
#
-
# 'post'.pluralize # => "posts"
-
# 'octopus'.pluralize # => "octopi"
-
# 'sheep'.pluralize # => "sheep"
-
# 'words'.pluralize # => "words"
-
# 'the blue mailman'.pluralize # => "the blue mailmen"
-
# 'CamelOctopus'.pluralize # => "CamelOctopi"
-
# 'apple'.pluralize(1) # => "apple"
-
# 'apple'.pluralize(2) # => "apples"
-
# 'ley'.pluralize(:es) # => "leyes"
-
# 'ley'.pluralize(1, :es) # => "ley"
-
2
def pluralize(count = nil, locale = :en)
-
49
locale = count if count.is_a?(Symbol)
-
49
if count == 1
-
self
-
else
-
49
ActiveSupport::Inflector.pluralize(self, locale)
-
end
-
end
-
-
# The reverse of +pluralize+, returns the singular form of a word in a string.
-
#
-
# If the optional parameter +locale+ is specified,
-
# the word will be singularized as a word of that language.
-
# By default, this parameter is set to <tt>:en</tt>.
-
# You must define your own inflection rules for languages other than English.
-
#
-
# 'posts'.singularize # => "post"
-
# 'octopi'.singularize # => "octopus"
-
# 'sheep'.singularize # => "sheep"
-
# 'word'.singularize # => "word"
-
# 'the blue mailmen'.singularize # => "the blue mailman"
-
# 'CamelOctopi'.singularize # => "CamelOctopus"
-
# 'leyes'.singularize(:es) # => "ley"
-
2
def singularize(locale = :en)
-
78
ActiveSupport::Inflector.singularize(self, locale)
-
end
-
-
# +constantize+ tries to find a declared constant with the name specified
-
# in the string. It raises a NameError when the name is not in CamelCase
-
# or is not initialized. See ActiveSupport::Inflector.constantize
-
#
-
# 'Module'.constantize # => Module
-
# 'Class'.constantize # => Class
-
# 'blargle'.constantize # => NameError: wrong constant name blargle
-
2
def constantize
-
104
ActiveSupport::Inflector.constantize(self)
-
end
-
-
# +safe_constantize+ tries to find a declared constant with the name specified
-
# in the string. It returns nil when the name is not in CamelCase
-
# or is not initialized. See ActiveSupport::Inflector.safe_constantize
-
#
-
# 'Module'.safe_constantize # => Module
-
# 'Class'.safe_constantize # => Class
-
# 'blargle'.safe_constantize # => nil
-
2
def safe_constantize
-
ActiveSupport::Inflector.safe_constantize(self)
-
end
-
-
# By default, +camelize+ converts strings to UpperCamelCase. If the argument to camelize
-
# is set to <tt>:lower</tt> then camelize produces lowerCamelCase.
-
#
-
# +camelize+ will also convert '/' to '::' which is useful for converting paths to namespaces.
-
#
-
# 'active_record'.camelize # => "ActiveRecord"
-
# 'active_record'.camelize(:lower) # => "activeRecord"
-
# 'active_record/errors'.camelize # => "ActiveRecord::Errors"
-
# 'active_record/errors'.camelize(:lower) # => "activeRecord::Errors"
-
2
def camelize(first_letter = :upper)
-
189
case first_letter
-
when :upper
-
189
ActiveSupport::Inflector.camelize(self, true)
-
when :lower
-
ActiveSupport::Inflector.camelize(self, false)
-
end
-
end
-
2
alias_method :camelcase, :camelize
-
-
# Capitalizes all the words and replaces some characters in the string to create
-
# a nicer looking title. +titleize+ is meant for creating pretty output. It is not
-
# used in the Rails internals.
-
#
-
# +titleize+ is also aliased as +titlecase+.
-
#
-
# 'man from the boondocks'.titleize # => "Man From The Boondocks"
-
# 'x-men: the last stand'.titleize # => "X Men: The Last Stand"
-
2
def titleize
-
ActiveSupport::Inflector.titleize(self)
-
end
-
2
alias_method :titlecase, :titleize
-
-
# The reverse of +camelize+. Makes an underscored, lowercase form from the expression in the string.
-
#
-
# +underscore+ will also change '::' to '/' to convert namespaces to paths.
-
#
-
# 'ActiveModel'.underscore # => "active_model"
-
# 'ActiveModel::Errors'.underscore # => "active_model/errors"
-
2
def underscore
-
328
ActiveSupport::Inflector.underscore(self)
-
end
-
-
# Replaces underscores with dashes in the string.
-
#
-
# 'puni_puni'.dasherize # => "puni-puni"
-
2
def dasherize
-
264
ActiveSupport::Inflector.dasherize(self)
-
end
-
-
# Removes the module part from the constant expression in the string.
-
#
-
# 'ActiveRecord::CoreExtensions::String::Inflections'.demodulize # => "Inflections"
-
# 'Inflections'.demodulize # => "Inflections"
-
#
-
# See also +deconstantize+.
-
2
def demodulize
-
8
ActiveSupport::Inflector.demodulize(self)
-
end
-
-
# Removes the rightmost segment from the constant expression in the string.
-
#
-
# 'Net::HTTP'.deconstantize # => "Net"
-
# '::Net::HTTP'.deconstantize # => "::Net"
-
# 'String'.deconstantize # => ""
-
# '::String'.deconstantize # => ""
-
# ''.deconstantize # => ""
-
#
-
# See also +demodulize+.
-
2
def deconstantize
-
ActiveSupport::Inflector.deconstantize(self)
-
end
-
-
# Replaces special characters in a string so that it may be used as part of a 'pretty' URL.
-
#
-
# class Person
-
# def to_param
-
# "#{id}-#{name.parameterize}"
-
# end
-
# end
-
#
-
# @person = Person.find(1)
-
# # => #<Person id: 1, name: "Donald E. Knuth">
-
#
-
# <%= link_to(@person.name, person_path) %>
-
# # => <a href="/person/1-donald-e-knuth">Donald E. Knuth</a>
-
2
def parameterize(sep = '-')
-
ActiveSupport::Inflector.parameterize(self, sep)
-
end
-
-
# Creates the name of a table like Rails does for models to table names. This method
-
# uses the +pluralize+ method on the last word in the string.
-
#
-
# 'RawScaledScorer'.tableize # => "raw_scaled_scorers"
-
# 'egg_and_ham'.tableize # => "egg_and_hams"
-
# 'fancyCategory'.tableize # => "fancy_categories"
-
2
def tableize
-
ActiveSupport::Inflector.tableize(self)
-
end
-
-
# Create a class name from a plural table name like Rails does for table names to models.
-
# Note that this returns a string and not a class. (To convert to an actual class
-
# follow +classify+ with +constantize+.)
-
#
-
# 'egg_and_hams'.classify # => "EggAndHam"
-
# 'posts'.classify # => "Post"
-
2
def classify
-
10
ActiveSupport::Inflector.classify(self)
-
end
-
-
# Capitalizes the first word, turns underscores into spaces, and strips a
-
# trailing '_id' if present.
-
# Like +titleize+, this is meant for creating pretty output.
-
#
-
# The capitalization of the first word can be turned off by setting the
-
# optional parameter +capitalize+ to false.
-
# By default, this parameter is true.
-
#
-
# 'employee_salary'.humanize # => "Employee salary"
-
# 'author_id'.humanize # => "Author"
-
# 'author_id'.humanize(capitalize: false) # => "author"
-
2
def humanize(options = {})
-
34
ActiveSupport::Inflector.humanize(self, options)
-
end
-
-
# Creates a foreign key name from a class name.
-
# +separate_class_name_and_id_with_underscore+ sets whether
-
# the method should put '_' between the name and 'id'.
-
#
-
# 'Message'.foreign_key # => "message_id"
-
# 'Message'.foreign_key(false) # => "messageid"
-
# 'Admin::Post'.foreign_key # => "post_id"
-
2
def foreign_key(separate_class_name_and_id_with_underscore = true)
-
ActiveSupport::Inflector.foreign_key(self, separate_class_name_and_id_with_underscore)
-
end
-
end
-
2
require 'active_support/string_inquirer'
-
-
2
class String
-
# Wraps the current string in the <tt>ActiveSupport::StringInquirer</tt> class,
-
# which gives you a prettier way to test for equality.
-
#
-
# env = 'production'.inquiry
-
# env.production? # => true
-
# env.development? # => false
-
2
def inquiry
-
ActiveSupport::StringInquirer.new(self)
-
end
-
end
-
# encoding: utf-8
-
2
require 'active_support/multibyte'
-
-
2
class String
-
# == Multibyte proxy
-
#
-
# +mb_chars+ is a multibyte safe proxy for string methods.
-
#
-
# It creates and returns an instance of the ActiveSupport::Multibyte::Chars class which
-
# encapsulates the original string. A Unicode safe version of all the String methods are defined on this proxy
-
# class. If the proxy class doesn't respond to a certain method, it's forwarded to the encapsulated string.
-
#
-
# name = 'Claus Müller'
-
# name.reverse # => "rell??M sualC"
-
# name.length # => 13
-
#
-
# name.mb_chars.reverse.to_s # => "rellüM sualC"
-
# name.mb_chars.length # => 12
-
#
-
# == Method chaining
-
#
-
# All the methods on the Chars proxy which normally return a string will return a Chars object. This allows
-
# method chaining on the result of any of these methods.
-
#
-
# name.mb_chars.reverse.length # => 12
-
#
-
# == Interoperability and configuration
-
#
-
# The Chars object tries to be as interchangeable with String objects as possible: sorting and comparing between
-
# String and Char work like expected. The bang! methods change the internal string representation in the Chars
-
# object. Interoperability problems can be resolved easily with a +to_s+ call.
-
#
-
# For more information about the methods defined on the Chars proxy see ActiveSupport::Multibyte::Chars. For
-
# information about how to change the default Multibyte behavior see ActiveSupport::Multibyte.
-
2
def mb_chars
-
ActiveSupport::Multibyte.proxy_class.new(self)
-
end
-
-
2
def is_utf8?
-
case encoding
-
when Encoding::UTF_8
-
valid_encoding?
-
when Encoding::ASCII_8BIT, Encoding::US_ASCII
-
dup.force_encoding(Encoding::UTF_8).valid_encoding?
-
else
-
false
-
end
-
end
-
end
-
2
require 'erb'
-
2
require 'active_support/core_ext/kernel/singleton_class'
-
-
2
class ERB
-
2
module Util
-
2
HTML_ESCAPE = { '&' => '&', '>' => '>', '<' => '<', '"' => '"', "'" => ''' }
-
2
JSON_ESCAPE = { '&' => '\u0026', '>' => '\u003e', '<' => '\u003c', "\u2028" => '\u2028', "\u2029" => '\u2029' }
-
2
HTML_ESCAPE_REGEXP = /[&"'><]/
-
2
HTML_ESCAPE_ONCE_REGEXP = /["><']|&(?!([a-zA-Z]+|(#\d+)|(#[xX][\dA-Fa-f]+));)/
-
2
JSON_ESCAPE_REGEXP = /[\u2028\u2029&><]/u
-
-
# A utility method for escaping HTML tag characters.
-
# This method is also aliased as <tt>h</tt>.
-
#
-
# In your ERB templates, use this method to escape any unsafe content. For example:
-
# <%=h @person.name %>
-
#
-
# puts html_escape('is a > 0 & a < 10?')
-
# # => is a > 0 & a < 10?
-
2
def html_escape(s)
-
659
s = s.to_s
-
659
if s.html_safe?
-
44
s
-
else
-
615
s.gsub(HTML_ESCAPE_REGEXP, HTML_ESCAPE).html_safe
-
end
-
end
-
-
# Aliasing twice issues a warning "discarding old...". Remove first to avoid it.
-
2
remove_method(:h)
-
2
alias h html_escape
-
-
2
module_function :h
-
-
2
singleton_class.send(:remove_method, :html_escape)
-
2
module_function :html_escape
-
-
# A utility method for escaping HTML without affecting existing escaped entities.
-
#
-
# html_escape_once('1 < 2 & 3')
-
# # => "1 < 2 & 3"
-
#
-
# html_escape_once('<< Accept & Checkout')
-
# # => "<< Accept & Checkout"
-
2
def html_escape_once(s)
-
result = s.to_s.gsub(HTML_ESCAPE_ONCE_REGEXP, HTML_ESCAPE)
-
s.html_safe? ? result.html_safe : result
-
end
-
-
2
module_function :html_escape_once
-
-
# A utility method for escaping HTML entities in JSON strings. Specifically, the
-
# &, > and < characters are replaced with their equivalent unicode escaped form -
-
# \u0026, \u003e, and \u003c. The Unicode sequences \u2028 and \u2029 are also
-
# escaped as they are treated as newline characters in some JavaScript engines.
-
# These sequences have identical meaning as the original characters inside the
-
# context of a JSON string, so assuming the input is a valid and well-formed
-
# JSON value, the output will have equivalent meaning when parsed:
-
#
-
# json = JSON.generate({ name: "</script><script>alert('PWNED!!!')</script>"})
-
# # => "{\"name\":\"</script><script>alert('PWNED!!!')</script>\"}"
-
#
-
# json_escape(json)
-
# # => "{\"name\":\"\\u003C/script\\u003E\\u003Cscript\\u003Ealert('PWNED!!!')\\u003C/script\\u003E\"}"
-
#
-
# JSON.parse(json) == JSON.parse(json_escape(json))
-
# # => true
-
#
-
# The intended use case for this method is to escape JSON strings before including
-
# them inside a script tag to avoid XSS vulnerability:
-
#
-
# <script>
-
# var currentUser = <%= raw json_escape(current_user.to_json) %>;
-
# </script>
-
#
-
# It is necessary to +raw+ the result of +json_escape+, so that quotation marks
-
# don't get converted to <tt>"</tt> entities. +json_escape+ doesn't
-
# automatically flag the result as HTML safe, since the raw value is unsafe to
-
# use inside HTML attributes.
-
#
-
# If you need to output JSON elsewhere in your HTML, you can just do something
-
# like this, as any unsafe characters (including quotation marks) will be
-
# automatically escaped for you:
-
#
-
# <div data-user-info="<%= current_user.to_json %>">...</div>
-
#
-
# WARNING: this helper only works with valid JSON. Using this on non-JSON values
-
# will open up serious XSS vulnerabilities. For example, if you replace the
-
# +current_user.to_json+ in the example above with user input instead, the browser
-
# will happily eval() that string as JavaScript.
-
#
-
# The escaping performed in this method is identical to those performed in the
-
# Active Support JSON encoder when +ActiveSupport.escape_html_entities_in_json+ is
-
# set to true. Because this transformation is idempotent, this helper can be
-
# applied even if +ActiveSupport.escape_html_entities_in_json+ is already true.
-
#
-
# Therefore, when you are unsure if +ActiveSupport.escape_html_entities_in_json+
-
# is enabled, or if you are unsure where your JSON string originated from, it
-
# is recommended that you always apply this helper (other libraries, such as the
-
# JSON gem, do not provide this kind of protection by default; also some gems
-
# might override +to_json+ to bypass Active Support's encoder).
-
2
def json_escape(s)
-
result = s.to_s.gsub(JSON_ESCAPE_REGEXP, JSON_ESCAPE)
-
s.html_safe? ? result.html_safe : result
-
end
-
-
2
module_function :json_escape
-
end
-
end
-
-
2
class Object
-
2
def html_safe?
-
624
false
-
end
-
end
-
-
2
class Numeric
-
2
def html_safe?
-
true
-
end
-
end
-
-
2
module ActiveSupport #:nodoc:
-
2
class SafeBuffer < String
-
2
UNSAFE_STRING_METHODS = %w(
-
capitalize chomp chop delete downcase gsub lstrip next reverse rstrip
-
slice squeeze strip sub succ swapcase tr tr_s upcase prepend
-
)
-
-
2
alias_method :original_concat, :concat
-
2
private :original_concat
-
-
2
class SafeConcatError < StandardError
-
2
def initialize
-
super 'Could not concatenate to the buffer because it is not html safe.'
-
end
-
end
-
-
2
def [](*args)
-
8
if args.size < 2
-
8
super
-
else
-
if html_safe?
-
new_safe_buffer = super
-
new_safe_buffer.instance_eval { @html_safe = true }
-
new_safe_buffer
-
else
-
to_str[*args]
-
end
-
end
-
end
-
-
2
def safe_concat(value)
-
388
raise SafeConcatError unless html_safe?
-
388
original_concat(value)
-
end
-
-
2
def initialize(*)
-
913
@html_safe = true
-
913
super
-
end
-
-
2
def initialize_copy(other)
-
9
super
-
9
@html_safe = other.html_safe?
-
end
-
-
2
def clone_empty
-
self[0, 0]
-
end
-
-
2
def concat(value)
-
210
if !html_safe? || value.html_safe?
-
201
super(value)
-
else
-
9
super(ERB::Util.h(value))
-
end
-
end
-
2
alias << concat
-
-
2
def +(other)
-
9
dup.concat(other)
-
end
-
-
2
def %(args)
-
case args
-
when Hash
-
escaped_args = Hash[args.map { |k,arg| [k, html_escape_interpolated_argument(arg)] }]
-
else
-
escaped_args = Array(args).map { |arg| html_escape_interpolated_argument(arg) }
-
end
-
-
self.class.new(super(escaped_args))
-
end
-
-
2
def html_safe?
-
852
defined?(@html_safe) && @html_safe
-
end
-
-
2
def to_s
-
292
self
-
end
-
-
2
def to_param
-
to_str
-
end
-
-
2
def encode_with(coder)
-
coder.represent_scalar nil, to_str
-
end
-
-
2
UNSAFE_STRING_METHODS.each do |unsafe_method|
-
40
if unsafe_method.respond_to?(unsafe_method)
-
40
class_eval <<-EOT, __FILE__, __LINE__ + 1
-
def #{unsafe_method}(*args, &block) # def capitalize(*args, &block)
-
to_str.#{unsafe_method}(*args, &block) # to_str.capitalize(*args, &block)
-
end # end
-
-
def #{unsafe_method}!(*args) # def capitalize!(*args)
-
@html_safe = false # @html_safe = false
-
super # super
-
end # end
-
EOT
-
end
-
end
-
-
2
private
-
-
2
def html_escape_interpolated_argument(arg)
-
(!html_safe? || arg.html_safe?) ? arg : ERB::Util.h(arg)
-
end
-
end
-
end
-
-
2
class String
-
2
def html_safe
-
856
ActiveSupport::SafeBuffer.new(self)
-
end
-
end
-
2
class String
-
2
alias_method :starts_with?, :start_with?
-
2
alias_method :ends_with?, :end_with?
-
end
-
2
require 'active_support/core_ext/object/try'
-
-
2
class String
-
# Strips indentation in heredocs.
-
#
-
# For example in
-
#
-
# if options[:usage]
-
# puts <<-USAGE.strip_heredoc
-
# This command does such and such.
-
#
-
# Supported options are:
-
# -h This message
-
# ...
-
# USAGE
-
# end
-
#
-
# the user would see the usage message aligned against the left margin.
-
#
-
# Technically, it looks for the least indented line in the whole string, and removes
-
# that amount of leading whitespace.
-
2
def strip_heredoc
-
indent = scan(/^[ \t]*(?=\S)/).min.try(:size) || 0
-
gsub(/^[ \t]{#{indent}}/, '')
-
end
-
end
-
2
require 'active_support/core_ext/string/conversions'
-
2
require 'active_support/core_ext/time/zones'
-
-
2
class String
-
# Converts String to a TimeWithZone in the current zone if Time.zone or Time.zone_default
-
# is set, otherwise converts String to a Time via String#to_time
-
2
def in_time_zone(zone = ::Time.zone)
-
if zone
-
::Time.find_zone!(zone).parse(self)
-
else
-
to_time
-
end
-
end
-
end
-
# Backport of Struct#to_h from Ruby 2.0
-
class Struct # :nodoc:
-
def to_h
-
Hash[members.zip(values)]
-
end
-
2
end unless Struct.instance_methods.include?(:to_h)
-
class Thread
-
LOCK = Mutex.new # :nodoc:
-
-
# Returns the value of a thread local variable that has been set. Note that
-
# these are different than fiber local values.
-
#
-
# Thread local values are carried along with threads, and do not respect
-
# fibers. For example:
-
#
-
# Thread.new {
-
# Thread.current.thread_variable_set("foo", "bar") # set a thread local
-
# Thread.current["foo"] = "bar" # set a fiber local
-
#
-
# Fiber.new {
-
# Fiber.yield [
-
# Thread.current.thread_variable_get("foo"), # get the thread local
-
# Thread.current["foo"], # get the fiber local
-
# ]
-
# }.resume
-
# }.join.value # => ['bar', nil]
-
#
-
# The value <tt>"bar"</tt> is returned for the thread local, where +nil+ is returned
-
# for the fiber local. The fiber is executed in the same thread, so the
-
# thread local values are available.
-
def thread_variable_get(key)
-
_locals[key.to_sym]
-
end
-
-
# Sets a thread local with +key+ to +value+. Note that these are local to
-
# threads, and not to fibers. Please see Thread#thread_variable_get for
-
# more information.
-
def thread_variable_set(key, value)
-
_locals[key.to_sym] = value
-
end
-
-
# Returns an array of the names of the thread-local variables (as Symbols).
-
#
-
# thr = Thread.new do
-
# Thread.current.thread_variable_set(:cat, 'meow')
-
# Thread.current.thread_variable_set("dog", 'woof')
-
# end
-
# thr.join # => #<Thread:0x401b3f10 dead>
-
# thr.thread_variables # => [:dog, :cat]
-
#
-
# Note that these are not fiber local variables. Please see Thread#thread_variable_get
-
# for more details.
-
def thread_variables
-
_locals.keys
-
end
-
-
# Returns <tt>true</tt> if the given string (or symbol) exists as a
-
# thread-local variable.
-
#
-
# me = Thread.current
-
# me.thread_variable_set(:oliver, "a")
-
# me.thread_variable?(:oliver) # => true
-
# me.thread_variable?(:stanley) # => false
-
#
-
# Note that these are not fiber local variables. Please see Thread#thread_variable_get
-
# for more details.
-
def thread_variable?(key)
-
_locals.has_key?(key.to_sym)
-
end
-
-
def freeze
-
_locals.freeze
-
super
-
end
-
-
private
-
-
def _locals
-
if defined?(@_locals)
-
@_locals
-
else
-
LOCK.synchronize { @_locals ||= {} }
-
end
-
end
-
2
end unless Thread.instance_methods.include?(:thread_variable_set)
-
2
require 'active_support/core_ext/time/acts_like'
-
2
require 'active_support/core_ext/time/calculations'
-
2
require 'active_support/core_ext/time/conversions'
-
2
require 'active_support/core_ext/time/marshal'
-
2
require 'active_support/core_ext/time/zones'
-
2
require 'active_support/core_ext/object/acts_like'
-
-
2
class Time
-
# Duck-types as a Time-like class. See Object#acts_like?.
-
2
def acts_like_time?
-
true
-
end
-
end
-
2
require 'active_support/duration'
-
2
require 'active_support/core_ext/time/conversions'
-
2
require 'active_support/time_with_zone'
-
2
require 'active_support/core_ext/time/zones'
-
2
require 'active_support/core_ext/date_and_time/calculations'
-
-
2
class Time
-
2
include DateAndTime::Calculations
-
-
2
COMMON_YEAR_DAYS_IN_MONTH = [nil, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
-
-
2
class << self
-
# Overriding case equality method so that it returns true for ActiveSupport::TimeWithZone instances
-
2
def ===(other)
-
534
super || (self == Time && other.is_a?(ActiveSupport::TimeWithZone))
-
end
-
-
# Return the number of days in the given month.
-
# If no year is specified, it will use the current year.
-
2
def days_in_month(month, year = now.year)
-
if month == 2 && ::Date.gregorian_leap?(year)
-
29
-
else
-
COMMON_YEAR_DAYS_IN_MONTH[month]
-
end
-
end
-
-
# Returns <tt>Time.zone.now</tt> when <tt>Time.zone</tt> or <tt>config.time_zone</tt> are set, otherwise just returns <tt>Time.now</tt>.
-
2
def current
-
::Time.zone ? ::Time.zone.now : ::Time.now
-
end
-
-
# Layers additional behavior on Time.at so that ActiveSupport::TimeWithZone and DateTime
-
# instances can be used when called with a single argument
-
2
def at_with_coercion(*args)
-
95
return at_without_coercion(*args) if args.size != 1
-
-
# Time.at can be called with a time or numerical value
-
95
time_or_number = args.first
-
-
95
if time_or_number.is_a?(ActiveSupport::TimeWithZone) || time_or_number.is_a?(DateTime)
-
at_without_coercion(time_or_number.to_f).getlocal
-
else
-
95
at_without_coercion(time_or_number)
-
end
-
end
-
2
alias_method :at_without_coercion, :at
-
2
alias_method :at, :at_with_coercion
-
end
-
-
# Seconds since midnight: Time.now.seconds_since_midnight
-
2
def seconds_since_midnight
-
to_i - change(:hour => 0).to_i + (usec / 1.0e+6)
-
end
-
-
# Returns the number of seconds until 23:59:59.
-
#
-
# Time.new(2012, 8, 29, 0, 0, 0).seconds_until_end_of_day # => 86399
-
# Time.new(2012, 8, 29, 12, 34, 56).seconds_until_end_of_day # => 41103
-
# Time.new(2012, 8, 29, 23, 59, 59).seconds_until_end_of_day # => 0
-
2
def seconds_until_end_of_day
-
end_of_day.to_i - to_i
-
end
-
-
# Returns a new Time where one or more of the elements have been changed according
-
# to the +options+ parameter. The time options (<tt>:hour</tt>, <tt>:min</tt>,
-
# <tt>:sec</tt>, <tt>:usec</tt>) reset cascadingly, so if only the hour is passed,
-
# then minute, sec, and usec is set to 0. If the hour and minute is passed, then
-
# sec and usec is set to 0. The +options+ parameter takes a hash with any of these
-
# keys: <tt>:year</tt>, <tt>:month</tt>, <tt>:day</tt>, <tt>:hour</tt>, <tt>:min</tt>,
-
# <tt>:sec</tt>, <tt>:usec</tt>.
-
#
-
# Time.new(2012, 8, 29, 22, 35, 0).change(day: 1) # => Time.new(2012, 8, 1, 22, 35, 0)
-
# Time.new(2012, 8, 29, 22, 35, 0).change(year: 1981, day: 1) # => Time.new(1981, 8, 1, 22, 35, 0)
-
# Time.new(2012, 8, 29, 22, 35, 0).change(year: 1981, hour: 0) # => Time.new(1981, 8, 29, 0, 0, 0)
-
2
def change(options)
-
new_year = options.fetch(:year, year)
-
new_month = options.fetch(:month, month)
-
new_day = options.fetch(:day, day)
-
new_hour = options.fetch(:hour, hour)
-
new_min = options.fetch(:min, options[:hour] ? 0 : min)
-
new_sec = options.fetch(:sec, (options[:hour] || options[:min]) ? 0 : sec)
-
new_usec = options.fetch(:usec, (options[:hour] || options[:min] || options[:sec]) ? 0 : Rational(nsec, 1000))
-
-
if utc?
-
::Time.utc(new_year, new_month, new_day, new_hour, new_min, new_sec, new_usec)
-
elsif zone
-
::Time.local(new_year, new_month, new_day, new_hour, new_min, new_sec, new_usec)
-
else
-
::Time.new(new_year, new_month, new_day, new_hour, new_min, new_sec + (new_usec.to_r / 1000000), utc_offset)
-
end
-
end
-
-
# Uses Date to provide precise Time calculations for years, months, and days
-
# according to the proleptic Gregorian calendar. The +options+ parameter
-
# takes a hash with any of these keys: <tt>:years</tt>, <tt>:months</tt>,
-
# <tt>:weeks</tt>, <tt>:days</tt>, <tt>:hours</tt>, <tt>:minutes</tt>,
-
# <tt>:seconds</tt>.
-
2
def advance(options)
-
unless options[:weeks].nil?
-
options[:weeks], partial_weeks = options[:weeks].divmod(1)
-
options[:days] = options.fetch(:days, 0) + 7 * partial_weeks
-
end
-
-
unless options[:days].nil?
-
options[:days], partial_days = options[:days].divmod(1)
-
options[:hours] = options.fetch(:hours, 0) + 24 * partial_days
-
end
-
-
d = to_date.advance(options)
-
d = d.gregorian if d.julian?
-
time_advanced_by_date = change(:year => d.year, :month => d.month, :day => d.day)
-
seconds_to_advance = \
-
options.fetch(:seconds, 0) +
-
options.fetch(:minutes, 0) * 60 +
-
options.fetch(:hours, 0) * 3600
-
-
if seconds_to_advance.zero?
-
time_advanced_by_date
-
else
-
time_advanced_by_date.since(seconds_to_advance)
-
end
-
end
-
-
# Returns a new Time representing the time a number of seconds ago, this is basically a wrapper around the Numeric extension
-
2
def ago(seconds)
-
since(-seconds)
-
end
-
-
# Returns a new Time representing the time a number of seconds since the instance time
-
2
def since(seconds)
-
self + seconds
-
rescue
-
to_datetime.since(seconds)
-
end
-
2
alias :in :since
-
-
# Returns a new Time representing the start of the day (0:00)
-
2
def beginning_of_day
-
#(self - seconds_since_midnight).change(usec: 0)
-
change(:hour => 0)
-
end
-
2
alias :midnight :beginning_of_day
-
2
alias :at_midnight :beginning_of_day
-
2
alias :at_beginning_of_day :beginning_of_day
-
-
# Returns a new Time representing the middle of the day (12:00)
-
2
def middle_of_day
-
change(:hour => 12)
-
end
-
2
alias :midday :middle_of_day
-
2
alias :noon :middle_of_day
-
2
alias :at_midday :middle_of_day
-
2
alias :at_noon :middle_of_day
-
2
alias :at_middle_of_day :middle_of_day
-
-
# Returns a new Time representing the end of the day, 23:59:59.999999 (.999999999 in ruby1.9)
-
2
def end_of_day
-
change(
-
:hour => 23,
-
:min => 59,
-
:sec => 59,
-
:usec => Rational(999999999, 1000)
-
)
-
end
-
2
alias :at_end_of_day :end_of_day
-
-
# Returns a new Time representing the start of the hour (x:00)
-
2
def beginning_of_hour
-
change(:min => 0)
-
end
-
2
alias :at_beginning_of_hour :beginning_of_hour
-
-
# Returns a new Time representing the end of the hour, x:59:59.999999 (.999999999 in ruby1.9)
-
2
def end_of_hour
-
change(
-
:min => 59,
-
:sec => 59,
-
:usec => Rational(999999999, 1000)
-
)
-
end
-
2
alias :at_end_of_hour :end_of_hour
-
-
# Returns a new Time representing the start of the minute (x:xx:00)
-
2
def beginning_of_minute
-
change(:sec => 0)
-
end
-
2
alias :at_beginning_of_minute :beginning_of_minute
-
-
# Returns a new Time representing the end of the minute, x:xx:59.999999 (.999999999 in ruby1.9)
-
2
def end_of_minute
-
change(
-
:sec => 59,
-
:usec => Rational(999999999, 1000)
-
)
-
end
-
2
alias :at_end_of_minute :end_of_minute
-
-
# Returns a Range representing the whole day of the current time.
-
2
def all_day
-
beginning_of_day..end_of_day
-
end
-
-
2
def plus_with_duration(other) #:nodoc:
-
if ActiveSupport::Duration === other
-
other.since(self)
-
else
-
plus_without_duration(other)
-
end
-
end
-
2
alias_method :plus_without_duration, :+
-
2
alias_method :+, :plus_with_duration
-
-
2
def minus_with_duration(other) #:nodoc:
-
1054
if ActiveSupport::Duration === other
-
other.until(self)
-
else
-
1054
minus_without_duration(other)
-
end
-
end
-
2
alias_method :minus_without_duration, :-
-
2
alias_method :-, :minus_with_duration
-
-
# Time#- can also be used to determine the number of seconds between two Time instances.
-
# We're layering on additional behavior so that ActiveSupport::TimeWithZone instances
-
# are coerced into values that Time#- will recognize
-
2
def minus_with_coercion(other)
-
1054
other = other.comparable_time if other.respond_to?(:comparable_time)
-
1054
other.is_a?(DateTime) ? to_f - other.to_f : minus_without_coercion(other)
-
end
-
2
alias_method :minus_without_coercion, :-
-
2
alias_method :-, :minus_with_coercion
-
-
# Layers additional behavior on Time#<=> so that DateTime and ActiveSupport::TimeWithZone instances
-
# can be chronologically compared with a Time
-
2
def compare_with_coercion(other)
-
# we're avoiding Time#to_datetime cause it's expensive
-
622
if other.is_a?(Time)
-
622
compare_without_coercion(other.to_time)
-
else
-
to_datetime <=> other
-
end
-
end
-
2
alias_method :compare_without_coercion, :<=>
-
2
alias_method :<=>, :compare_with_coercion
-
-
# Layers additional behavior on Time#eql? so that ActiveSupport::TimeWithZone instances
-
# can be eql? to an equivalent Time
-
2
def eql_with_coercion(other)
-
# if other is an ActiveSupport::TimeWithZone, coerce a Time instance from it so we can do eql? comparison
-
other = other.comparable_time if other.respond_to?(:comparable_time)
-
eql_without_coercion(other)
-
end
-
2
alias_method :eql_without_coercion, :eql?
-
2
alias_method :eql?, :eql_with_coercion
-
-
end
-
2
require 'active_support/inflector/methods'
-
2
require 'active_support/values/time_zone'
-
-
2
class Time
-
2
DATE_FORMATS = {
-
:db => '%Y-%m-%d %H:%M:%S',
-
:number => '%Y%m%d%H%M%S',
-
:nsec => '%Y%m%d%H%M%S%9N',
-
:time => '%H:%M',
-
:short => '%d %b %H:%M',
-
:long => '%B %d, %Y %H:%M',
-
:long_ordinal => lambda { |time|
-
day_format = ActiveSupport::Inflector.ordinalize(time.day)
-
time.strftime("%B #{day_format}, %Y %H:%M")
-
},
-
:rfc822 => lambda { |time|
-
offset_format = time.formatted_offset(false)
-
time.strftime("%a, %d %b %Y %H:%M:%S #{offset_format}")
-
},
-
:iso8601 => lambda { |time| time.iso8601 }
-
}
-
-
# Converts to a formatted string. See DATE_FORMATS for builtin formats.
-
#
-
# This method is aliased to <tt>to_s</tt>.
-
#
-
# time = Time.now # => Thu Jan 18 06:10:17 CST 2007
-
#
-
# time.to_formatted_s(:time) # => "06:10"
-
# time.to_s(:time) # => "06:10"
-
#
-
# time.to_formatted_s(:db) # => "2007-01-18 06:10:17"
-
# time.to_formatted_s(:number) # => "20070118061017"
-
# time.to_formatted_s(:short) # => "18 Jan 06:10"
-
# time.to_formatted_s(:long) # => "January 18, 2007 06:10"
-
# time.to_formatted_s(:long_ordinal) # => "January 18th, 2007 06:10"
-
# time.to_formatted_s(:rfc822) # => "Thu, 18 Jan 2007 06:10:17 -0600"
-
# time.to_formatted_s(:iso8601) # => "2007-01-18T06:10:17-06:00"
-
#
-
# == Adding your own time formats to +to_formatted_s+
-
# You can add your own formats to the Time::DATE_FORMATS hash.
-
# Use the format name as the hash key and either a strftime string
-
# or Proc instance that takes a time argument as the value.
-
#
-
# # config/initializers/time_formats.rb
-
# Time::DATE_FORMATS[:month_and_year] = '%B %Y'
-
# Time::DATE_FORMATS[:short_ordinal] = ->(time) { time.strftime("%B #{time.day.ordinalize}") }
-
2
def to_formatted_s(format = :default)
-
534
if formatter = DATE_FORMATS[format]
-
534
formatter.respond_to?(:call) ? formatter.call(self).to_s : strftime(formatter)
-
else
-
to_default_s
-
end
-
end
-
2
alias_method :to_default_s, :to_s
-
2
alias_method :to_s, :to_formatted_s
-
-
# Returns the UTC offset as an +HH:MM formatted string.
-
#
-
# Time.local(2000).formatted_offset # => "-06:00"
-
# Time.local(2000).formatted_offset(false) # => "-0600"
-
2
def formatted_offset(colon = true, alternate_utc_string = nil)
-
utc? && alternate_utc_string || ActiveSupport::TimeZone.seconds_to_utc_offset(utc_offset, colon)
-
end
-
end
-
# Ruby 1.9.2 adds utc_offset and zone to Time, but marshaling only
-
# preserves utc_offset. Preserve zone also, even though it may not
-
# work in some edge cases.
-
2
if Time.local(2010).zone != Marshal.load(Marshal.dump(Time.local(2010))).zone
-
class Time
-
class << self
-
alias_method :_load_without_zone, :_load
-
def _load(marshaled_time)
-
time = _load_without_zone(marshaled_time)
-
time.instance_eval do
-
if zone = defined?(@_zone) && remove_instance_variable('@_zone')
-
ary = to_a
-
ary[0] += subsec if ary[0] == sec
-
ary[-1] = zone
-
utc? ? Time.utc(*ary) : Time.local(*ary)
-
else
-
self
-
end
-
end
-
end
-
end
-
-
alias_method :_dump_without_zone, :_dump
-
def _dump(*args)
-
obj = dup
-
obj.instance_variable_set('@_zone', zone)
-
obj.send :_dump_without_zone, *args
-
end
-
end
-
end
-
2
require 'active_support/time_with_zone'
-
2
require 'active_support/core_ext/date_and_time/zones'
-
-
2
class Time
-
2
include DateAndTime::Zones
-
2
class << self
-
2
attr_accessor :zone_default
-
-
# Returns the TimeZone for the current request, if this has been set (via Time.zone=).
-
# If <tt>Time.zone</tt> has not been set for the current request, returns the TimeZone specified in <tt>config.time_zone</tt>.
-
2
def zone
-
534
Thread.current[:time_zone] || zone_default
-
end
-
-
# Sets <tt>Time.zone</tt> to a TimeZone object for the current request/thread.
-
#
-
# This method accepts any of the following:
-
#
-
# * A Rails TimeZone object.
-
# * An identifier for a Rails TimeZone object (e.g., "Eastern Time (US & Canada)", <tt>-5.hours</tt>).
-
# * A TZInfo::Timezone object.
-
# * An identifier for a TZInfo::Timezone object (e.g., "America/New_York").
-
#
-
# Here's an example of how you might set <tt>Time.zone</tt> on a per request basis and reset it when the request is done.
-
# <tt>current_user.time_zone</tt> just needs to return a string identifying the user's preferred time zone:
-
#
-
# class ApplicationController < ActionController::Base
-
# around_filter :set_time_zone
-
#
-
# def set_time_zone
-
# if logged_in?
-
# Time.use_zone(current_user.time_zone) { yield }
-
# else
-
# yield
-
# end
-
# end
-
# end
-
2
def zone=(time_zone)
-
Thread.current[:time_zone] = find_zone!(time_zone)
-
end
-
-
# Allows override of <tt>Time.zone</tt> locally inside supplied block; resets <tt>Time.zone</tt> to existing value when done.
-
2
def use_zone(time_zone)
-
new_zone = find_zone!(time_zone)
-
begin
-
old_zone, ::Time.zone = ::Time.zone, new_zone
-
yield
-
ensure
-
::Time.zone = old_zone
-
end
-
end
-
-
# Returns a TimeZone instance or nil, or raises an ArgumentError for invalid timezones.
-
2
def find_zone!(time_zone)
-
536
if !time_zone || time_zone.is_a?(ActiveSupport::TimeZone)
-
534
time_zone
-
else
-
# lookup timezone based on identifier (unless we've been passed a TZInfo::Timezone)
-
2
unless time_zone.respond_to?(:period_for_local)
-
2
time_zone = ActiveSupport::TimeZone[time_zone] || TZInfo::Timezone.get(time_zone)
-
end
-
-
# Return if a TimeZone instance, or wrap in a TimeZone instance if a TZInfo::Timezone
-
2
if time_zone.is_a?(ActiveSupport::TimeZone)
-
2
time_zone
-
else
-
ActiveSupport::TimeZone.create(time_zone.name, nil, time_zone)
-
end
-
end
-
rescue TZInfo::InvalidTimezoneIdentifier
-
raise ArgumentError, "Invalid Timezone: #{time_zone}"
-
end
-
-
2
def find_zone(time_zone)
-
find_zone!(time_zone) rescue nil
-
end
-
end
-
end
-
# encoding: utf-8
-
-
2
require 'uri'
-
2
str = "\xE6\x97\xA5\xE6\x9C\xAC\xE8\xAA\x9E" # Ni-ho-nn-go in UTF-8, means Japanese.
-
2
parser = URI::Parser.new
-
-
2
unless str == parser.unescape(parser.escape(str))
-
2
URI::Parser.class_eval do
-
2
remove_method :unescape
-
2
def unescape(str, escaped = /%[a-fA-F\d]{2}/)
-
# TODO: Are we actually sure that ASCII == UTF-8?
-
# YK: My initial experiments say yes, but let's be sure please
-
9
enc = str.encoding
-
9
enc = Encoding::UTF_8 if enc == Encoding::US_ASCII
-
9
str.gsub(escaped) { [$&[1, 2].hex].pack('C') }.force_encoding(enc)
-
end
-
end
-
end
-
-
2
module URI
-
2
class << self
-
2
def parser
-
275
@parser ||= URI::Parser.new
-
end
-
end
-
end
-
2
require 'set'
-
2
require 'thread'
-
2
require 'thread_safe'
-
2
require 'pathname'
-
2
require 'active_support/core_ext/module/aliasing'
-
2
require 'active_support/core_ext/module/attribute_accessors'
-
2
require 'active_support/core_ext/module/introspection'
-
2
require 'active_support/core_ext/module/anonymous'
-
2
require 'active_support/core_ext/module/qualified_const'
-
2
require 'active_support/core_ext/object/blank'
-
2
require 'active_support/core_ext/kernel/reporting'
-
2
require 'active_support/core_ext/load_error'
-
2
require 'active_support/core_ext/name_error'
-
2
require 'active_support/core_ext/string/starts_ends_with'
-
2
require 'active_support/inflector'
-
-
2
module ActiveSupport #:nodoc:
-
2
module Dependencies #:nodoc:
-
2
extend self
-
-
# Should we turn on Ruby warnings on the first load of dependent files?
-
2
mattr_accessor :warnings_on_first_load
-
2
self.warnings_on_first_load = false
-
-
# All files ever loaded.
-
2
mattr_accessor :history
-
2
self.history = Set.new
-
-
# All files currently loaded.
-
2
mattr_accessor :loaded
-
2
self.loaded = Set.new
-
-
# Should we load files or require them?
-
2
mattr_accessor :mechanism
-
2
self.mechanism = ENV['NO_RELOAD'] ? :require : :load
-
-
# The set of directories from which we may automatically load files. Files
-
# under these directories will be reloaded on each request in development mode,
-
# unless the directory also appears in autoload_once_paths.
-
2
mattr_accessor :autoload_paths
-
2
self.autoload_paths = []
-
-
# The set of directories from which automatically loaded constants are loaded
-
# only once. All directories in this set must also be present in +autoload_paths+.
-
2
mattr_accessor :autoload_once_paths
-
2
self.autoload_once_paths = []
-
-
# An array of qualified constant names that have been loaded. Adding a name
-
# to this array will cause it to be unloaded the next time Dependencies are
-
# cleared.
-
2
mattr_accessor :autoloaded_constants
-
2
self.autoloaded_constants = []
-
-
# An array of constant names that need to be unloaded on every request. Used
-
# to allow arbitrary constants to be marked for unloading.
-
2
mattr_accessor :explicitly_unloadable_constants
-
2
self.explicitly_unloadable_constants = []
-
-
# The logger is used for generating information on the action run-time
-
# (including benchmarking) if available. Can be set to nil for no logging.
-
# Compatible with both Ruby's own Logger and Log4r loggers.
-
2
mattr_accessor :logger
-
-
# Set to +true+ to enable logging of const_missing and file loads.
-
2
mattr_accessor :log_activity
-
2
self.log_activity = false
-
-
# The WatchStack keeps a stack of the modules being watched as files are
-
# loaded. If a file in the process of being loaded (parent.rb) triggers the
-
# load of another file (child.rb) the stack will ensure that child.rb
-
# handles the new constants.
-
#
-
# If child.rb is being autoloaded, its constants will be added to
-
# autoloaded_constants. If it was being `require`d, they will be discarded.
-
#
-
# This is handled by walking back up the watch stack and adding the constants
-
# found by child.rb to the list of original constants in parent.rb.
-
2
class WatchStack
-
2
include Enumerable
-
-
# @watching is a stack of lists of constants being watched. For instance,
-
# if parent.rb is autoloaded, the stack will look like [[Object]]. If
-
# parent.rb then requires namespace/child.rb, the stack will look like
-
# [[Object], [Namespace]].
-
-
2
def initialize
-
2
@watching = []
-
2
@stack = Hash.new { |h,k| h[k] = [] }
-
end
-
-
2
def each(&block)
-
@stack.each(&block)
-
end
-
-
2
def watching?
-
1747
!@watching.empty?
-
end
-
-
# Returns a list of new constants found since the last call to
-
# <tt>watch_namespaces</tt>.
-
2
def new_constants
-
constants = []
-
-
# Grab the list of namespaces that we're looking for new constants under
-
@watching.last.each do |namespace|
-
# Retrieve the constants that were present under the namespace when watch_namespaces
-
# was originally called
-
original_constants = @stack[namespace].last
-
-
mod = Inflector.constantize(namespace) if Dependencies.qualified_const_defined?(namespace)
-
next unless mod.is_a?(Module)
-
-
# Get a list of the constants that were added
-
new_constants = mod.local_constants - original_constants
-
-
# self[namespace] returns an Array of the constants that are being evaluated
-
# for that namespace. For instance, if parent.rb requires child.rb, the first
-
# element of self[Object] will be an Array of the constants that were present
-
# before parent.rb was required. The second element will be an Array of the
-
# constants that were present before child.rb was required.
-
@stack[namespace].each do |namespace_constants|
-
namespace_constants.concat(new_constants)
-
end
-
-
# Normalize the list of new constants, and add them to the list we will return
-
new_constants.each do |suffix|
-
constants << ([namespace, suffix] - ["Object"]).join("::")
-
end
-
end
-
constants
-
ensure
-
# A call to new_constants is always called after a call to watch_namespaces
-
pop_modules(@watching.pop)
-
end
-
-
# Add a set of modules to the watch stack, remembering the initial
-
# constants.
-
2
def watch_namespaces(namespaces)
-
@watching << namespaces.map do |namespace|
-
module_name = Dependencies.to_constant_name(namespace)
-
original_constants = Dependencies.qualified_const_defined?(module_name) ?
-
Inflector.constantize(module_name).local_constants : []
-
-
@stack[module_name] << original_constants
-
module_name
-
end
-
end
-
-
2
private
-
2
def pop_modules(modules)
-
modules.each { |mod| @stack[mod].pop }
-
end
-
end
-
-
# An internal stack used to record which constants are loaded by any block.
-
2
mattr_accessor :constant_watch_stack
-
2
self.constant_watch_stack = WatchStack.new
-
-
# Module includes this module.
-
2
module ModuleConstMissing #:nodoc:
-
2
def self.append_features(base)
-
2
base.class_eval do
-
# Emulate #exclude via an ivar
-
2
return if defined?(@_const_missing) && @_const_missing
-
2
@_const_missing = instance_method(:const_missing)
-
2
remove_method(:const_missing)
-
end
-
2
super
-
end
-
-
2
def self.exclude_from(base)
-
base.class_eval do
-
define_method :const_missing, @_const_missing
-
@_const_missing = nil
-
end
-
end
-
-
2
def const_missing(const_name)
-
44
from_mod = anonymous? ? guess_for_anonymous(const_name) : self
-
44
Dependencies.load_missing_constant(from_mod, const_name)
-
end
-
-
# Dependencies assumes the name of the module reflects the nesting (unless
-
# it can be proven that is not the case), and the path to the file that
-
# defines the constant. Anonymous modules cannot follow these conventions
-
# and we assume therefore the user wants to refer to a top-level constant.
-
2
def guess_for_anonymous(const_name)
-
if Object.const_defined?(const_name)
-
raise NameError.new "#{const_name} cannot be autoloaded from an anonymous class or module", const_name
-
else
-
Object
-
end
-
end
-
-
2
def unloadable(const_desc = self)
-
super(const_desc)
-
end
-
end
-
-
# Object includes this module.
-
2
module Loadable #:nodoc:
-
2
def self.exclude_from(base)
-
base.class_eval { define_method(:load, Kernel.instance_method(:load)) }
-
end
-
-
2
def require_or_load(file_name)
-
Dependencies.require_or_load(file_name)
-
end
-
-
# Interprets a file using <tt>mechanism</tt> and marks its defined
-
# constants as autoloaded. <tt>file_name</tt> can be either a string or
-
# respond to <tt>to_path</tt>.
-
#
-
# Use this method in code that absolutely needs a certain constant to be
-
# defined at that point. A typical use case is to make constant name
-
# resolution deterministic for constants with the same relative name in
-
# different namespaces whose evaluation would depend on load order
-
# otherwise.
-
2
def require_dependency(file_name, message = "No such file to load -- %s")
-
97
file_name = file_name.to_path if file_name.respond_to?(:to_path)
-
97
unless file_name.is_a?(String)
-
raise ArgumentError, "the file name must either be a String or implement #to_path -- you passed #{file_name.inspect}"
-
end
-
-
97
Dependencies.depend_on(file_name, message)
-
end
-
-
2
def load_dependency(file)
-
3429
if Dependencies.load? && ActiveSupport::Dependencies.constant_watch_stack.watching?
-
Dependencies.new_constants_in(Object) { yield }
-
else
-
3429
yield
-
end
-
rescue Exception => exception # errors from loading file
-
24
exception.blame_file! file if exception.respond_to? :blame_file!
-
24
raise
-
end
-
-
2
def load(file, wrap = false)
-
26
result = false
-
52
load_dependency(file) { result = super }
-
26
result
-
end
-
-
2
def require(file)
-
3403
result = false
-
6806
load_dependency(file) { result = super }
-
3379
result
-
end
-
-
# Mark the given constant as unloadable. Unloadable constants are removed
-
# each time dependencies are cleared.
-
#
-
# Note that marking a constant for unloading need only be done once. Setup
-
# or init scripts may list each unloadable constant that may need unloading;
-
# each constant will be removed for every subsequent clear, as opposed to
-
# for the first clear.
-
#
-
# The provided constant descriptor may be a (non-anonymous) module or class,
-
# or a qualified constant name as a string or symbol.
-
#
-
# Returns +true+ if the constant was not previously marked for unloading,
-
# +false+ otherwise.
-
2
def unloadable(const_desc)
-
Dependencies.mark_for_unload const_desc
-
end
-
end
-
-
# Exception file-blaming.
-
2
module Blamable #:nodoc:
-
2
def blame_file!(file)
-
24
(@blamed_files ||= []).unshift file
-
end
-
-
2
def blamed_files
-
1
@blamed_files ||= []
-
end
-
-
2
def describe_blame
-
return nil if blamed_files.empty?
-
"This error occurred while loading the following files:\n #{blamed_files.join "\n "}"
-
end
-
-
2
def copy_blame!(exc)
-
1
@blamed_files = exc.blamed_files.clone
-
1
self
-
end
-
end
-
-
2
def hook!
-
4
Object.class_eval { include Loadable }
-
4
Module.class_eval { include ModuleConstMissing }
-
4
Exception.class_eval { include Blamable }
-
end
-
-
2
def unhook!
-
ModuleConstMissing.exclude_from(Module)
-
Loadable.exclude_from(Object)
-
end
-
-
2
def load?
-
3509
mechanism == :load
-
end
-
-
2
def depend_on(file_name, message = "No such file to load -- %s.rb")
-
97
path = search_for_file(file_name)
-
97
require_or_load(path || file_name)
-
rescue LoadError => load_error
-
1
if file_name = load_error.message[/ -- (.*?)(\.rb)?$/, 1]
-
1
load_error.message.replace(message % file_name)
-
1
load_error.copy_blame!(load_error)
-
end
-
1
raise
-
end
-
-
2
def clear
-
log_call
-
loaded.clear
-
remove_unloadable_constants!
-
end
-
-
2
def require_or_load(file_name, const_path = nil)
-
122
log_call file_name, const_path
-
122
file_name = $` if file_name =~ /\.rb\z/
-
122
expanded = File.expand_path(file_name)
-
122
return if loaded.include?(expanded)
-
-
# Record that we've seen this file *before* loading it to avoid an
-
# infinite loop with mutual dependencies.
-
80
loaded << expanded
-
-
80
begin
-
80
if load?
-
log "loading #{file_name}"
-
-
# Enable warnings if this file has not been loaded before and
-
# warnings_on_first_load is set.
-
load_args = ["#{file_name}.rb"]
-
load_args << const_path unless const_path.nil?
-
-
if !warnings_on_first_load or history.include?(expanded)
-
result = load_file(*load_args)
-
else
-
enable_warnings { result = load_file(*load_args) }
-
end
-
else
-
80
log "requiring #{file_name}"
-
80
result = require file_name
-
end
-
rescue Exception
-
1
loaded.delete expanded
-
1
raise
-
end
-
-
# Record history *after* loading so first load gets warnings.
-
79
history << expanded
-
79
result
-
end
-
-
# Is the provided constant path defined?
-
2
def qualified_const_defined?(path)
-
44
Object.qualified_const_defined?(path.sub(/^::/, ''), false)
-
end
-
-
# Given +path+, a filesystem path to a ruby file, return an array of
-
# constant paths which would cause Dependencies to attempt to load this
-
# file.
-
2
def loadable_constants_for_path(path, bases = autoload_paths)
-
path = $` if path =~ /\.rb\z/
-
expanded_path = File.expand_path(path)
-
paths = []
-
-
bases.each do |root|
-
expanded_root = File.expand_path(root)
-
next unless %r{\A#{Regexp.escape(expanded_root)}(/|\\)} =~ expanded_path
-
-
nesting = expanded_path[(expanded_root.size)..-1]
-
nesting = nesting[1..-1] if nesting && nesting[0] == ?/
-
next if nesting.blank?
-
-
paths << nesting.camelize
-
end
-
-
paths.uniq!
-
paths
-
end
-
-
# Search for a file in autoload_paths matching the provided suffix.
-
2
def search_for_file(path_suffix)
-
141
path_suffix = path_suffix.sub(/(\.rb)?$/, ".rb")
-
-
141
autoload_paths.each do |root|
-
864
path = File.join(root, path_suffix)
-
864
return path if File.file? path
-
end
-
nil # Gee, I sure wish we had first_match ;-)
-
end
-
-
# Does the provided path_suffix correspond to an autoloadable module?
-
# Instead of returning a boolean, the autoload base for this module is
-
# returned.
-
2
def autoloadable_module?(path_suffix)
-
19
autoload_paths.each do |load_path|
-
195
return load_path if File.directory? File.join(load_path, path_suffix)
-
end
-
nil
-
end
-
-
2
def load_once_path?(path)
-
# to_s works around a ruby1.9 issue where String#starts_with?(Pathname)
-
# will raise a TypeError: no implicit conversion of Pathname into String
-
autoload_once_paths.any? { |base| path.starts_with? base.to_s }
-
end
-
-
# Attempt to autoload the provided module name by searching for a directory
-
# matching the expected path suffix. If found, the module is created and
-
# assigned to +into+'s constants with the name +const_name+. Provided that
-
# the directory was loaded from a reloadable base path, it is added to the
-
# set of constants that are to be unloaded.
-
2
def autoload_module!(into, const_name, qualified_name, path_suffix)
-
19
return nil unless base_path = autoloadable_module?(path_suffix)
-
mod = Module.new
-
into.const_set const_name, mod
-
autoloaded_constants << qualified_name unless autoload_once_paths.include?(base_path)
-
mod
-
end
-
-
# Load the file at the provided path. +const_paths+ is a set of qualified
-
# constant names. When loading the file, Dependencies will watch for the
-
# addition of these constants. Each that is defined will be marked as
-
# autoloaded, and will be removed when Dependencies.clear is next called.
-
#
-
# If the second parameter is left off, then Dependencies will construct a
-
# set of names that the file at +path+ may define. See
-
# +loadable_constants_for_path+ for more details.
-
2
def load_file(path, const_paths = loadable_constants_for_path(path))
-
log_call path, const_paths
-
const_paths = [const_paths].compact unless const_paths.is_a? Array
-
parent_paths = const_paths.collect { |const_path| const_path[/.*(?=::)/] || ::Object }
-
-
result = nil
-
newly_defined_paths = new_constants_in(*parent_paths) do
-
result = Kernel.load path
-
end
-
-
autoloaded_constants.concat newly_defined_paths unless load_once_path?(path)
-
autoloaded_constants.uniq!
-
log "loading #{path} defined #{newly_defined_paths * ', '}" unless newly_defined_paths.empty?
-
result
-
end
-
-
# Returns the constant path for the provided parent and constant name.
-
2
def qualified_name_for(mod, name)
-
49
mod_name = to_constant_name mod
-
49
mod_name == "Object" ? name.to_s : "#{mod_name}::#{name}"
-
end
-
-
# Load the constant named +const_name+ which is missing from +from_mod+. If
-
# it is not possible to load the constant into from_mod, try its parent
-
# module using +const_missing+.
-
2
def load_missing_constant(from_mod, const_name)
-
44
log_call from_mod, const_name
-
-
44
unless qualified_const_defined?(from_mod.name) && Inflector.constantize(from_mod.name).equal?(from_mod)
-
raise ArgumentError, "A copy of #{from_mod} has been removed from the module tree but is still active!"
-
end
-
-
44
qualified_name = qualified_name_for from_mod, const_name
-
44
path_suffix = qualified_name.underscore
-
-
44
file_path = search_for_file(path_suffix)
-
-
44
if file_path
-
25
expanded = File.expand_path(file_path)
-
25
expanded.sub!(/\.rb\z/, '')
-
-
25
if loaded.include?(expanded)
-
raise "Circular dependency detected while autoloading constant #{qualified_name}"
-
else
-
25
require_or_load(expanded, qualified_name)
-
25
raise LoadError, "Unable to autoload constant #{qualified_name}, expected #{file_path} to define it" unless from_mod.const_defined?(const_name, false)
-
25
return from_mod.const_get(const_name)
-
end
-
elsif mod = autoload_module!(from_mod, const_name, qualified_name, path_suffix)
-
return mod
-
19
elsif (parent = from_mod.parent) && parent != from_mod &&
-
33
! from_mod.parents.any? { |p| p.const_defined?(const_name, false) }
-
# If our parents do not have a constant named +const_name+ then we are free
-
# to attempt to load upwards. If they do have such a constant, then this
-
# const_missing must be due to from_mod::const_name, which should not
-
# return constants from from_mod's parents.
-
17
begin
-
# Since Ruby does not pass the nesting at the point the unknown
-
# constant triggered the callback we cannot fully emulate constant
-
# name lookup and need to make a trade-off: we are going to assume
-
# that the nesting in the body of Foo::Bar is [Foo::Bar, Foo] even
-
# though it might not be. Counterexamples are
-
#
-
# class Foo::Bar
-
# Module.nesting # => [Foo::Bar]
-
# end
-
#
-
# or
-
#
-
# module M::N
-
# module S::T
-
# Module.nesting # => [S::T, M::N]
-
# end
-
# end
-
#
-
# for example.
-
17
return parent.const_missing(const_name)
-
rescue NameError => e
-
5
raise unless e.missing_name? qualified_name_for(parent, const_name)
-
end
-
end
-
-
7
name_error = NameError.new("uninitialized constant #{qualified_name}", const_name)
-
339
name_error.set_backtrace(caller.reject {|l| l.starts_with? __FILE__ })
-
7
raise name_error
-
end
-
-
# Remove the constants that have been autoloaded, and those that have been
-
# marked for unloading. Before each constant is removed a callback is sent
-
# to its class/module if it implements +before_remove_const+.
-
#
-
# The callback implementation should be restricted to cleaning up caches, etc.
-
# as the environment will be in an inconsistent state, e.g. other constants
-
# may have already been unloaded and not accessible.
-
2
def remove_unloadable_constants!
-
autoloaded_constants.each { |const| remove_constant const }
-
autoloaded_constants.clear
-
Reference.clear!
-
explicitly_unloadable_constants.each { |const| remove_constant const }
-
end
-
-
2
class ClassCache
-
2
def initialize
-
2
@store = ThreadSafe::Cache.new
-
end
-
-
2
def empty?
-
@store.empty?
-
end
-
-
2
def key?(key)
-
@store.key?(key)
-
end
-
-
2
def get(key)
-
18
key = key.name if key.respond_to?(:name)
-
18
@store[key] ||= Inflector.constantize(key)
-
end
-
2
alias :[] :get
-
-
2
def safe_get(key)
-
key = key.name if key.respond_to?(:name)
-
@store[key] ||= Inflector.safe_constantize(key)
-
end
-
-
2
def store(klass)
-
2
return self unless klass.respond_to?(:name)
-
raise(ArgumentError, 'anonymous classes cannot be cached') if klass.name.empty?
-
@store[klass.name] = klass
-
self
-
end
-
-
2
def clear!
-
@store.clear
-
end
-
end
-
-
2
Reference = ClassCache.new
-
-
# Store a reference to a class +klass+.
-
2
def reference(klass)
-
2
Reference.store klass
-
end
-
-
# Get the reference for class named +name+.
-
# Raises an exception if referenced class does not exist.
-
2
def constantize(name)
-
14
Reference.get(name)
-
end
-
-
# Get the reference for class named +name+ if one exists.
-
# Otherwise returns +nil+.
-
2
def safe_constantize(name)
-
Reference.safe_get(name)
-
end
-
-
# Determine if the given constant has been automatically loaded.
-
2
def autoloaded?(desc)
-
return false if desc.is_a?(Module) && desc.anonymous?
-
name = to_constant_name desc
-
return false unless qualified_const_defined? name
-
return autoloaded_constants.include?(name)
-
end
-
-
# Will the provided constant descriptor be unloaded?
-
2
def will_unload?(const_desc)
-
autoloaded?(const_desc) ||
-
explicitly_unloadable_constants.include?(to_constant_name(const_desc))
-
end
-
-
# Mark the provided constant name for unloading. This constant will be
-
# unloaded on each request, not just the next one.
-
2
def mark_for_unload(const_desc)
-
name = to_constant_name const_desc
-
if explicitly_unloadable_constants.include? name
-
false
-
else
-
explicitly_unloadable_constants << name
-
true
-
end
-
end
-
-
# Run the provided block and detect the new constants that were loaded during
-
# its execution. Constants may only be regarded as 'new' once -- so if the
-
# block calls +new_constants_in+ again, then the constants defined within the
-
# inner call will not be reported in this one.
-
#
-
# If the provided block does not run to completion, and instead raises an
-
# exception, any new constants are regarded as being only partially defined
-
# and will be removed immediately.
-
2
def new_constants_in(*descs)
-
log_call(*descs)
-
-
constant_watch_stack.watch_namespaces(descs)
-
aborting = true
-
-
begin
-
yield # Now yield to the code that is to define new constants.
-
aborting = false
-
ensure
-
new_constants = constant_watch_stack.new_constants
-
-
log "New constants: #{new_constants * ', '}"
-
return new_constants unless aborting
-
-
log "Error during loading, removing partially loaded constants "
-
new_constants.each { |c| remove_constant(c) }.clear
-
end
-
-
[]
-
end
-
-
# Convert the provided const desc to a qualified constant name (as a string).
-
# A module, class, symbol, or string may be provided.
-
2
def to_constant_name(desc) #:nodoc:
-
49
case desc
-
when String then desc.sub(/^::/, '')
-
when Symbol then desc.to_s
-
when Module
-
desc.name ||
-
49
raise(ArgumentError, "Anonymous modules have no name to be referenced by")
-
else raise TypeError, "Not a valid constant descriptor: #{desc.inspect}"
-
end
-
end
-
-
2
def remove_constant(const) #:nodoc:
-
# Normalize ::Foo, ::Object::Foo, Object::Foo, Object::Object::Foo, etc. as Foo.
-
normalized = const.to_s.sub(/\A::/, '')
-
normalized.sub!(/\A(Object::)+/, '')
-
-
constants = normalized.split('::')
-
to_remove = constants.pop
-
-
# Remove the file path from the loaded list.
-
file_path = search_for_file(const.underscore)
-
if file_path
-
expanded = File.expand_path(file_path)
-
expanded.sub!(/\.rb\z/, '')
-
self.loaded.delete(expanded)
-
end
-
-
if constants.empty?
-
parent = Object
-
else
-
# This method is robust to non-reachable constants.
-
#
-
# Non-reachable constants may be passed if some of the parents were
-
# autoloaded and already removed. It is easier to do a sanity check
-
# here than require the caller to be clever. We check the parent
-
# rather than the very const argument because we do not want to
-
# trigger Kernel#autoloads, see the comment below.
-
parent_name = constants.join('::')
-
return unless qualified_const_defined?(parent_name)
-
parent = constantize(parent_name)
-
end
-
-
log "removing constant #{const}"
-
-
# In an autoloaded user.rb like this
-
#
-
# autoload :Foo, 'foo'
-
#
-
# class User < ActiveRecord::Base
-
# end
-
#
-
# we correctly register "Foo" as being autoloaded. But if the app does
-
# not use the "Foo" constant we need to be careful not to trigger
-
# loading "foo.rb" ourselves. While #const_defined? and #const_get? do
-
# require the file, #autoload? and #remove_const don't.
-
#
-
# We are going to remove the constant nonetheless ---which exists as
-
# far as Ruby is concerned--- because if the user removes the macro
-
# call from a class or module that were not autoloaded, as in the
-
# example above with Object, accessing to that constant must err.
-
unless parent.autoload?(to_remove)
-
begin
-
constantized = parent.const_get(to_remove, false)
-
rescue NameError
-
log "the constant #{const} is not reachable anymore, skipping"
-
return
-
else
-
constantized.before_remove_const if constantized.respond_to?(:before_remove_const)
-
end
-
end
-
-
begin
-
parent.instance_eval { remove_const to_remove }
-
rescue NameError
-
log "the constant #{const} is not reachable anymore, skipping"
-
end
-
end
-
-
2
protected
-
2
def log_call(*args)
-
166
if log_activity?
-
arg_str = args.collect { |arg| arg.inspect } * ', '
-
/in `([a-z_\?\!]+)'/ =~ caller(1).first
-
selector = $1 || '<unknown>'
-
log "called #{selector}(#{arg_str})"
-
end
-
end
-
-
2
def log(msg)
-
80
logger.debug "Dependencies: #{msg}" if log_activity?
-
end
-
-
2
def log_activity?
-
246
logger && log_activity
-
end
-
end
-
end
-
-
2
ActiveSupport::Dependencies.hook!
-
2
require "active_support/inflector/methods"
-
-
2
module ActiveSupport
-
# Autoload and eager load conveniences for your library.
-
#
-
# This module allows you to define autoloads based on
-
# Rails conventions (i.e. no need to define the path
-
# it is automatically guessed based on the filename)
-
# and also define a set of constants that needs to be
-
# eager loaded:
-
#
-
# module MyLib
-
# extend ActiveSupport::Autoload
-
#
-
# autoload :Model
-
#
-
# eager_autoload do
-
# autoload :Cache
-
# end
-
# end
-
#
-
# Then your library can be eager loaded by simply calling:
-
#
-
# MyLib.eager_load!
-
2
module Autoload
-
2
def self.extended(base) # :nodoc:
-
54
base.class_eval do
-
54
@_autoloads = {}
-
54
@_under_path = nil
-
54
@_at_path = nil
-
54
@_eager_autoload = false
-
end
-
end
-
-
2
def autoload(const_name, path = @_at_path)
-
746
unless path
-
561
full = [name, @_under_path, const_name.to_s].compact.join("::")
-
561
path = Inflector.underscore(full)
-
end
-
-
746
if @_eager_autoload
-
294
@_autoloads[const_name] = path
-
end
-
-
746
super const_name, path
-
end
-
-
2
def autoload_under(path)
-
14
@_under_path, old_path = path, @_under_path
-
14
yield
-
ensure
-
14
@_under_path = old_path
-
end
-
-
2
def autoload_at(path)
-
14
@_at_path, old_path = path, @_at_path
-
14
yield
-
ensure
-
14
@_at_path = old_path
-
end
-
-
2
def eager_autoload
-
36
old_eager, @_eager_autoload = @_eager_autoload, true
-
36
yield
-
ensure
-
36
@_eager_autoload = old_eager
-
end
-
-
2
def eager_load!
-
@_autoloads.values.each { |file| require file }
-
end
-
-
2
def autoloads
-
@_autoloads
-
end
-
end
-
end
-
2
require 'singleton'
-
-
2
module ActiveSupport
-
# \Deprecation specifies the API used by Rails to deprecate methods, instance
-
# variables, objects and constants.
-
2
class Deprecation
-
# active_support.rb sets an autoload for ActiveSupport::Deprecation.
-
#
-
# If these requires were at the top of the file the constant would not be
-
# defined by the time their files were loaded. Since some of them reopen
-
# ActiveSupport::Deprecation its autoload would be triggered, resulting in
-
# a circular require warning for active_support/deprecation.rb.
-
#
-
# So, we define the constant first, and load dependencies later.
-
2
require 'active_support/deprecation/instance_delegator'
-
2
require 'active_support/deprecation/behaviors'
-
2
require 'active_support/deprecation/reporting'
-
2
require 'active_support/deprecation/method_wrappers'
-
2
require 'active_support/deprecation/proxy_wrappers'
-
2
require 'active_support/core_ext/module/deprecation'
-
-
2
include Singleton
-
2
include InstanceDelegator
-
2
include Behavior
-
2
include Reporting
-
2
include MethodWrapper
-
-
# The version number in which the deprecated behavior will be removed, by default.
-
2
attr_accessor :deprecation_horizon
-
-
# It accepts two parameters on initialization. The first is a version of library
-
# and the second is a library name
-
#
-
# ActiveSupport::Deprecation.new('2.0', 'MyLibrary')
-
2
def initialize(deprecation_horizon = '4.2', gem_name = 'Rails')
-
2
self.gem_name = gem_name
-
2
self.deprecation_horizon = deprecation_horizon
-
# By default, warnings are not silenced and debugging is off.
-
2
self.silenced = false
-
2
self.debug = false
-
end
-
end
-
end
-
2
require "active_support/notifications"
-
-
2
module ActiveSupport
-
2
class DeprecationException < StandardError
-
end
-
-
2
class Deprecation
-
# Default warning behaviors per Rails.env.
-
2
DEFAULT_BEHAVIORS = {
-
raise: ->(message, callstack) {
-
e = DeprecationException.new(message)
-
e.set_backtrace(callstack)
-
raise e
-
},
-
-
stderr: ->(message, callstack) {
-
$stderr.puts(message)
-
$stderr.puts callstack.join("\n ") if debug
-
},
-
-
log: ->(message, callstack) {
-
logger =
-
if defined?(Rails) && Rails.logger
-
Rails.logger
-
else
-
require 'active_support/logger'
-
ActiveSupport::Logger.new($stderr)
-
end
-
logger.warn message
-
logger.debug callstack.join("\n ") if debug
-
},
-
-
notify: ->(message, callstack) {
-
ActiveSupport::Notifications.instrument("deprecation.rails",
-
:message => message, :callstack => callstack)
-
},
-
-
silence: ->(message, callstack) {},
-
}
-
-
2
module Behavior
-
# Whether to print a backtrace along with the warning.
-
2
attr_accessor :debug
-
-
# Returns the current behavior or if one isn't set, defaults to +:stderr+.
-
2
def behavior
-
@behavior ||= [DEFAULT_BEHAVIORS[:stderr]]
-
end
-
-
# Sets the behavior to the specified value. Can be a single value, array,
-
# or an object that responds to +call+.
-
#
-
# Available behaviors:
-
#
-
# [+raise+] Raise <tt>ActiveSupport::DeprecationException</tt>.
-
# [+stderr+] Log all deprecation warnings to +$stderr+.
-
# [+log+] Log all deprecation warnings to +Rails.logger+.
-
# [+notify+] Use +ActiveSupport::Notifications+ to notify +deprecation.rails+.
-
# [+silence+] Do nothing.
-
#
-
# Setting behaviors only affects deprecations that happen after boot time.
-
# Deprecation warnings raised by gems are not affected by this setting
-
# because they happen before Rails boots up.
-
#
-
# ActiveSupport::Deprecation.behavior = :stderr
-
# ActiveSupport::Deprecation.behavior = [:stderr, :log]
-
# ActiveSupport::Deprecation.behavior = MyCustomHandler
-
# ActiveSupport::Deprecation.behavior = ->(message, callstack) {
-
# # custom stuff
-
# }
-
2
def behavior=(behavior)
-
4
@behavior = Array(behavior).map { |b| DEFAULT_BEHAVIORS[b] || b }
-
end
-
end
-
end
-
end
-
2
require 'active_support/core_ext/kernel/singleton_class'
-
2
require 'active_support/core_ext/module/delegation'
-
-
2
module ActiveSupport
-
2
class Deprecation
-
2
module InstanceDelegator # :nodoc:
-
2
def self.included(base)
-
2
base.extend(ClassMethods)
-
2
base.public_class_method :new
-
end
-
-
2
module ClassMethods # :nodoc:
-
2
def include(included_module)
-
30
included_module.instance_methods.each { |m| method_added(m) }
-
6
super
-
end
-
-
2
def method_added(method_name)
-
30
singleton_class.delegate(method_name, to: :instance)
-
end
-
end
-
end
-
end
-
end
-
2
require 'active_support/core_ext/module/aliasing'
-
2
require 'active_support/core_ext/array/extract_options'
-
-
2
module ActiveSupport
-
2
class Deprecation
-
2
module MethodWrapper
-
# Declare that a method has been deprecated.
-
#
-
# module Fred
-
# extend self
-
#
-
# def foo; end
-
# def bar; end
-
# def baz; end
-
# end
-
#
-
# ActiveSupport::Deprecation.deprecate_methods(Fred, :foo, bar: :qux, baz: 'use Bar#baz instead')
-
# # => [:foo, :bar, :baz]
-
#
-
# Fred.foo
-
# # => "DEPRECATION WARNING: foo is deprecated and will be removed from Rails 4.1."
-
#
-
# Fred.bar
-
# # => "DEPRECATION WARNING: bar is deprecated and will be removed from Rails 4.1 (use qux instead)."
-
#
-
# Fred.baz
-
# # => "DEPRECATION WARNING: baz is deprecated and will be removed from Rails 4.1 (use Bar#baz instead)."
-
2
def deprecate_methods(target_module, *method_names)
-
options = method_names.extract_options!
-
deprecator = options.delete(:deprecator) || ActiveSupport::Deprecation.instance
-
method_names += options.keys
-
-
method_names.each do |method_name|
-
target_module.alias_method_chain(method_name, :deprecation) do |target, punctuation|
-
target_module.send(:define_method, "#{target}_with_deprecation#{punctuation}") do |*args, &block|
-
deprecator.deprecation_warning(method_name, options[method_name])
-
send(:"#{target}_without_deprecation#{punctuation}", *args, &block)
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
2
require 'active_support/inflector/methods'
-
-
2
module ActiveSupport
-
2
class Deprecation
-
2
class DeprecationProxy #:nodoc:
-
2
def self.new(*args, &block)
-
4
object = args.first
-
-
4
return object unless object
-
4
super
-
end
-
-
178
instance_methods.each { |m| undef_method m unless m =~ /^__|^object_id$/ }
-
-
# Don't give a deprecation warning on inspect since test/unit and error
-
# logs rely on it for diagnostics.
-
2
def inspect
-
target.inspect
-
end
-
-
2
private
-
2
def method_missing(called, *args, &block)
-
warn caller, called, args
-
target.__send__(called, *args, &block)
-
end
-
end
-
-
# This DeprecatedObjectProxy transforms object to deprecated object.
-
#
-
# @old_object = DeprecatedObjectProxy.new(Object.new, "Don't use this object anymore!")
-
# @old_object = DeprecatedObjectProxy.new(Object.new, "Don't use this object anymore!", deprecator_instance)
-
#
-
# When someone executes any method except +inspect+ on proxy object this will
-
# trigger +warn+ method on +deprecator_instance+.
-
#
-
# Default deprecator is <tt>ActiveSupport::Deprecation</tt>
-
2
class DeprecatedObjectProxy < DeprecationProxy
-
2
def initialize(object, message, deprecator = ActiveSupport::Deprecation.instance)
-
@object = object
-
@message = message
-
@deprecator = deprecator
-
end
-
-
2
private
-
2
def target
-
@object
-
end
-
-
2
def warn(callstack, called, args)
-
@deprecator.warn(@message, callstack)
-
end
-
end
-
-
# This DeprecatedInstanceVariableProxy transforms instance variable to
-
# deprecated instance variable.
-
#
-
# class Example
-
# def initialize(deprecator)
-
# @request = ActiveSupport::Deprecation::DeprecatedInstanceVariableProxy.new(self, :request, :@request, deprecator)
-
# @_request = :a_request
-
# end
-
#
-
# def request
-
# @_request
-
# end
-
#
-
# def old_request
-
# @request
-
# end
-
# end
-
#
-
# When someone execute any method on @request variable this will trigger
-
# +warn+ method on +deprecator_instance+ and will fetch <tt>@_request</tt>
-
# variable via +request+ method and execute the same method on non-proxy
-
# instance variable.
-
#
-
# Default deprecator is <tt>ActiveSupport::Deprecation</tt>.
-
2
class DeprecatedInstanceVariableProxy < DeprecationProxy
-
2
def initialize(instance, method, var = "@#{method}", deprecator = ActiveSupport::Deprecation.instance)
-
@instance = instance
-
@method = method
-
@var = var
-
@deprecator = deprecator
-
end
-
-
2
private
-
2
def target
-
@instance.__send__(@method)
-
end
-
-
2
def warn(callstack, called, args)
-
@deprecator.warn("#{@var} is deprecated! Call #{@method}.#{called} instead of #{@var}.#{called}. Args: #{args.inspect}", callstack)
-
end
-
end
-
-
# This DeprecatedConstantProxy transforms constant to deprecated constant.
-
#
-
# OLD_CONST = ActiveSupport::Deprecation::DeprecatedConstantProxy.new('OLD_CONST', 'NEW_CONST')
-
# OLD_CONST = ActiveSupport::Deprecation::DeprecatedConstantProxy.new('OLD_CONST', 'NEW_CONST', deprecator_instance)
-
#
-
# When someone use old constant this will trigger +warn+ method on
-
# +deprecator_instance+.
-
#
-
# Default deprecator is <tt>ActiveSupport::Deprecation</tt>.
-
2
class DeprecatedConstantProxy < DeprecationProxy
-
2
def initialize(old_const, new_const, deprecator = ActiveSupport::Deprecation.instance)
-
4
@old_const = old_const
-
4
@new_const = new_const
-
4
@deprecator = deprecator
-
end
-
-
2
def class
-
target.class
-
end
-
-
2
private
-
2
def target
-
ActiveSupport::Inflector.constantize(@new_const.to_s)
-
end
-
-
2
def warn(callstack, called, args)
-
@deprecator.warn("#{@old_const} is deprecated! Use #{@new_const} instead.", callstack)
-
end
-
end
-
end
-
end
-
2
module ActiveSupport
-
2
class Deprecation
-
2
module Reporting
-
# Whether to print a message (silent mode)
-
2
attr_accessor :silenced
-
# Name of gem where method is deprecated
-
2
attr_accessor :gem_name
-
-
# Outputs a deprecation warning to the output configured by
-
# <tt>ActiveSupport::Deprecation.behavior</tt>.
-
#
-
# ActiveSupport::Deprecation.warn('something broke!')
-
# # => "DEPRECATION WARNING: something broke! (called from your_code.rb:1)"
-
2
def warn(message = nil, callstack = nil)
-
return if silenced
-
-
callstack ||= caller(2)
-
deprecation_message(callstack, message).tap do |m|
-
behavior.each { |b| b.call(m, callstack) }
-
end
-
end
-
-
# Silence deprecation warnings within the block.
-
#
-
# ActiveSupport::Deprecation.warn('something broke!')
-
# # => "DEPRECATION WARNING: something broke! (called from your_code.rb:1)"
-
#
-
# ActiveSupport::Deprecation.silence do
-
# ActiveSupport::Deprecation.warn('something broke!')
-
# end
-
# # => nil
-
2
def silence
-
old_silenced, @silenced = @silenced, true
-
yield
-
ensure
-
@silenced = old_silenced
-
end
-
-
2
def deprecation_warning(deprecated_method_name, message = nil, caller_backtrace = nil)
-
caller_backtrace ||= caller(2)
-
deprecated_method_warning(deprecated_method_name, message).tap do |msg|
-
warn(msg, caller_backtrace)
-
end
-
end
-
-
2
private
-
# Outputs a deprecation warning message
-
#
-
# ActiveSupport::Deprecation.deprecated_method_warning(:method_name)
-
# # => "method_name is deprecated and will be removed from Rails #{deprecation_horizon}"
-
# ActiveSupport::Deprecation.deprecated_method_warning(:method_name, :another_method)
-
# # => "method_name is deprecated and will be removed from Rails #{deprecation_horizon} (use another_method instead)"
-
# ActiveSupport::Deprecation.deprecated_method_warning(:method_name, "Optional message")
-
# # => "method_name is deprecated and will be removed from Rails #{deprecation_horizon} (Optional message)"
-
2
def deprecated_method_warning(method_name, message = nil)
-
warning = "#{method_name} is deprecated and will be removed from #{gem_name} #{deprecation_horizon}"
-
case message
-
when Symbol then "#{warning} (use #{message} instead)"
-
when String then "#{warning} (#{message})"
-
else warning
-
end
-
end
-
-
2
def deprecation_message(callstack, message = nil)
-
message ||= "You are using deprecated behavior which will be removed from the next major or minor release."
-
message += '.' unless message =~ /\.$/
-
"DEPRECATION WARNING: #{message} #{deprecation_caller_message(callstack)}"
-
end
-
-
2
def deprecation_caller_message(callstack)
-
file, line, method = extract_callstack(callstack)
-
if file
-
if line && method
-
"(called from #{method} at #{file}:#{line})"
-
else
-
"(called from #{file}:#{line})"
-
end
-
end
-
end
-
-
2
def extract_callstack(callstack)
-
rails_gem_root = File.expand_path("../../../../..", __FILE__) + "/"
-
offending_line = callstack.find { |line| !line.start_with?(rails_gem_root) } || callstack.first
-
if offending_line
-
if md = offending_line.match(/^(.+?):(\d+)(?::in `(.*?)')?/)
-
md.captures
-
else
-
offending_line
-
end
-
end
-
end
-
end
-
end
-
end
-
2
module ActiveSupport
-
# This module provides an internal implementation to track descendants
-
# which is faster than iterating through ObjectSpace.
-
2
module DescendantsTracker
-
2
@@direct_descendants = {}
-
-
2
class << self
-
2
def direct_descendants(klass)
-
@@direct_descendants[klass] || []
-
end
-
-
2
def descendants(klass)
-
284
arr = []
-
284
accumulate_descendants(klass, arr)
-
284
arr
-
end
-
-
2
def clear
-
if defined? ActiveSupport::Dependencies
-
@@direct_descendants.each do |klass, descendants|
-
if ActiveSupport::Dependencies.autoloaded?(klass)
-
@@direct_descendants.delete(klass)
-
else
-
descendants.reject! { |v| ActiveSupport::Dependencies.autoloaded?(v) }
-
end
-
end
-
else
-
@@direct_descendants.clear
-
end
-
end
-
-
# This is the only method that is not thread safe, but is only ever called
-
# during the eager loading phase.
-
2
def store_inherited(klass, descendant)
-
42
(@@direct_descendants[klass] ||= []) << descendant
-
end
-
-
2
private
-
2
def accumulate_descendants(klass, acc)
-
284
if direct_descendants = @@direct_descendants[klass]
-
acc.concat(direct_descendants)
-
direct_descendants.each { |direct_descendant| accumulate_descendants(direct_descendant, acc) }
-
end
-
end
-
end
-
-
2
def inherited(base)
-
42
DescendantsTracker.store_inherited(self, base)
-
42
super
-
end
-
-
2
def direct_descendants
-
DescendantsTracker.direct_descendants(self)
-
end
-
-
2
def descendants
-
DescendantsTracker.descendants(self)
-
end
-
end
-
end
-
2
require 'active_support/proxy_object'
-
2
require 'active_support/core_ext/array/conversions'
-
2
require 'active_support/core_ext/object/acts_like'
-
-
2
module ActiveSupport
-
# Provides accurate date and time measurements using Date#advance and
-
# Time#advance, respectively. It mainly supports the methods on Numeric.
-
#
-
# 1.month.ago # equivalent to Time.now.advance(months: -1)
-
2
class Duration < ProxyObject
-
2
attr_accessor :value, :parts
-
-
2
def initialize(value, parts) #:nodoc:
-
18
@value, @parts = value, parts
-
end
-
-
# Adds another Duration or a Numeric to this Duration. Numeric values
-
# are treated as seconds.
-
2
def +(other)
-
if Duration === other
-
Duration.new(value + other.value, @parts + other.parts)
-
else
-
Duration.new(value + other, @parts + [[:seconds, other]])
-
end
-
end
-
-
# Subtracts another Duration or a Numeric from this Duration. Numeric
-
# values are treated as seconds.
-
2
def -(other)
-
self + (-other)
-
end
-
-
2
def -@ #:nodoc:
-
Duration.new(-value, parts.map { |type,number| [type, -number] })
-
end
-
-
2
def is_a?(klass) #:nodoc:
-
Duration == klass || value.is_a?(klass)
-
end
-
2
alias :kind_of? :is_a?
-
-
# Returns +true+ if +other+ is also a Duration instance with the
-
# same +value+, or if <tt>other == value</tt>.
-
2
def ==(other)
-
if Duration === other
-
other.value == value
-
else
-
other == value
-
end
-
end
-
-
2
def eql?(other)
-
other.is_a?(Duration) && self == other
-
end
-
-
2
def self.===(other) #:nodoc:
-
1054
other.is_a?(Duration)
-
rescue ::NoMethodError
-
false
-
end
-
-
# Calculates a new Time or Date that is as far in the future
-
# as this Duration represents.
-
2
def since(time = ::Time.current)
-
sum(1, time)
-
end
-
2
alias :from_now :since
-
-
# Calculates a new Time or Date that is as far in the past
-
# as this Duration represents.
-
2
def ago(time = ::Time.current)
-
sum(-1, time)
-
end
-
2
alias :until :ago
-
-
2
def inspect #:nodoc:
-
parts.
-
reduce(::Hash.new(0)) { |h,(l,r)| h[l] += r; h }.
-
sort_by {|unit, _ | [:years, :months, :days, :minutes, :seconds].index(unit)}.
-
map {|unit, val| "#{val} #{val == 1 ? unit.to_s.chop : unit.to_s}"}.
-
to_sentence(:locale => :en)
-
end
-
-
2
def as_json(options = nil) #:nodoc:
-
to_i
-
end
-
-
2
protected
-
-
2
def sum(sign, time = ::Time.current) #:nodoc:
-
parts.inject(time) do |t,(type,number)|
-
if t.acts_like?(:time) || t.acts_like?(:date)
-
if type == :seconds
-
t.since(sign * number)
-
else
-
t.advance(type => sign * number)
-
end
-
else
-
raise ::ArgumentError, "expected a time or date, got #{time.inspect}"
-
end
-
end
-
end
-
-
2
private
-
-
# We define it as a workaround to Ruby 2.0.0-p353 bug.
-
# For more information, check rails/rails#13055.
-
# It should be dropped once a new Ruby patch-level
-
# release after 2.0.0-p353 happens.
-
2
def ===(other) #:nodoc:
-
value === other
-
end
-
-
2
def method_missing(method, *args, &block) #:nodoc:
-
6
value.send(method, *args, &block)
-
end
-
end
-
end
-
2
module ActiveSupport
-
# FileUpdateChecker specifies the API used by Rails to watch files
-
# and control reloading. The API depends on four methods:
-
#
-
# * +initialize+ which expects two parameters and one block as
-
# described below.
-
#
-
# * +updated?+ which returns a boolean if there were updates in
-
# the filesystem or not.
-
#
-
# * +execute+ which executes the given block on initialization
-
# and updates the latest watched files and timestamp.
-
#
-
# * +execute_if_updated+ which just executes the block if it was updated.
-
#
-
# After initialization, a call to +execute_if_updated+ must execute
-
# the block only if there was really a change in the filesystem.
-
#
-
# This class is used by Rails to reload the I18n framework whenever
-
# they are changed upon a new request.
-
#
-
# i18n_reloader = ActiveSupport::FileUpdateChecker.new(paths) do
-
# I18n.reload!
-
# end
-
#
-
# ActionDispatch::Reloader.to_prepare do
-
# i18n_reloader.execute_if_updated
-
# end
-
2
class FileUpdateChecker
-
# It accepts two parameters on initialization. The first is an array
-
# of files and the second is an optional hash of directories. The hash must
-
# have directories as keys and the value is an array of extensions to be
-
# watched under that directory.
-
#
-
# This method must also receive a block that will be called once a path
-
# changes. The array of files and list of directories cannot be changed
-
# after FileUpdateChecker has been initialized.
-
2
def initialize(files, dirs={}, &block)
-
6
@files = files.freeze
-
6
@glob = compile_glob(dirs)
-
6
@block = block
-
-
6
@watched = nil
-
6
@updated_at = nil
-
-
6
@last_watched = watched
-
6
@last_update_at = updated_at(@last_watched)
-
end
-
-
# Check if any of the entries were updated. If so, the watched and/or
-
# updated_at values are cached until the block is executed via +execute+
-
# or +execute_if_updated+.
-
2
def updated?
-
2
current_watched = watched
-
2
if @last_watched.size != current_watched.size
-
@watched = current_watched
-
true
-
else
-
2
current_updated_at = updated_at(current_watched)
-
2
if @last_update_at < current_updated_at
-
@watched = current_watched
-
@updated_at = current_updated_at
-
true
-
else
-
2
false
-
end
-
end
-
end
-
-
# Executes the given block and updates the latest watched files and
-
# timestamp.
-
2
def execute
-
4
@last_watched = watched
-
4
@last_update_at = updated_at(@last_watched)
-
4
@block.call
-
ensure
-
4
@watched = nil
-
4
@updated_at = nil
-
end
-
-
# Execute the block given if updated.
-
2
def execute_if_updated
-
2
if updated?
-
execute
-
true
-
else
-
2
false
-
end
-
end
-
-
2
private
-
-
2
def watched
-
@watched || begin
-
98
all = @files.select { |f| File.exist?(f) }
-
12
all.concat(Dir[@glob]) if @glob
-
12
all
-
12
end
-
end
-
-
2
def updated_at(paths)
-
12
@updated_at || max_mtime(paths) || Time.at(0)
-
end
-
-
# This method returns the maximum mtime of the files in +paths+, or +nil+
-
# if the array is empty.
-
#
-
# Files with a mtime in the future are ignored. Such abnormal situation
-
# can happen for example if the user changes the clock by hand. It is
-
# healthy to consider this edge case because with mtimes in the future
-
# reloading is not triggered.
-
2
def max_mtime(paths)
-
12
time_now = Time.now
-
448
paths.map {|path| File.mtime(path)}.reject {|mtime| time_now < mtime}.max
-
end
-
-
2
def compile_glob(hash)
-
6
hash.freeze # Freeze so changes aren't accidentally pushed
-
6
return if hash.empty?
-
-
2
globs = hash.map do |key, value|
-
26
"#{escape(key)}/**/*#{compile_ext(value)}"
-
end
-
2
"{#{globs.join(",")}}"
-
end
-
-
2
def escape(key)
-
26
key.gsub(',','\,')
-
end
-
-
2
def compile_ext(array)
-
26
array = Array(array)
-
26
return if array.empty?
-
26
".{#{array.join(",")}}"
-
end
-
end
-
end
-
2
module ActiveSupport
-
# Returns the version of the currently loaded ActiveSupport as a <tt>Gem::Version</tt>
-
2
def self.gem_version
-
Gem::Version.new VERSION::STRING
-
end
-
-
2
module VERSION
-
2
MAJOR = 4
-
2
MINOR = 1
-
2
TINY = 8
-
2
PRE = nil
-
-
2
STRING = [MAJOR, MINOR, TINY, PRE].compact.join(".")
-
end
-
end
-
2
require 'active_support/core_ext/hash/keys'
-
-
2
module ActiveSupport
-
# Implements a hash where keys <tt>:foo</tt> and <tt>"foo"</tt> are considered
-
# to be the same.
-
#
-
# rgb = ActiveSupport::HashWithIndifferentAccess.new
-
#
-
# rgb[:black] = '#000000'
-
# rgb[:black] # => '#000000'
-
# rgb['black'] # => '#000000'
-
#
-
# rgb['white'] = '#FFFFFF'
-
# rgb[:white] # => '#FFFFFF'
-
# rgb['white'] # => '#FFFFFF'
-
#
-
# Internally symbols are mapped to strings when used as keys in the entire
-
# writing interface (calling <tt>[]=</tt>, <tt>merge</tt>, etc). This
-
# mapping belongs to the public interface. For example, given:
-
#
-
# hash = ActiveSupport::HashWithIndifferentAccess.new(a: 1)
-
#
-
# You are guaranteed that the key is returned as a string:
-
#
-
# hash.keys # => ["a"]
-
#
-
# Technically other types of keys are accepted:
-
#
-
# hash = ActiveSupport::HashWithIndifferentAccess.new(a: 1)
-
# hash[0] = 0
-
# hash # => {"a"=>1, 0=>0}
-
#
-
# but this class is intended for use cases where strings or symbols are the
-
# expected keys and it is convenient to understand both as the same. For
-
# example the +params+ hash in Ruby on Rails.
-
#
-
# Note that core extensions define <tt>Hash#with_indifferent_access</tt>:
-
#
-
# rgb = { black: '#000000', white: '#FFFFFF' }.with_indifferent_access
-
#
-
# which may be handy.
-
2
class HashWithIndifferentAccess < Hash
-
# Returns +true+ so that <tt>Array#extract_options!</tt> finds members of
-
# this class.
-
2
def extractable_options?
-
true
-
end
-
-
2
def with_indifferent_access
-
24
dup
-
end
-
-
2
def nested_under_indifferent_access
-
8
self
-
end
-
-
2
def initialize(constructor = {})
-
1050
if constructor.is_a?(Hash)
-
1048
super()
-
1048
update(constructor)
-
else
-
2
super(constructor)
-
end
-
end
-
-
2
def default(key = nil)
-
174
if key.is_a?(Symbol) && include?(key = key.to_s)
-
41
self[key]
-
else
-
133
super
-
end
-
end
-
-
2
def self.new_from_hash_copying_default(hash)
-
124
hash = hash.to_hash
-
124
new(hash).tap do |new_hash|
-
124
new_hash.default = hash.default
-
end
-
end
-
-
2
def self.[](*args)
-
267
new.merge!(Hash[*args])
-
end
-
-
2
alias_method :regular_writer, :[]= unless method_defined?(:regular_writer)
-
2
alias_method :regular_update, :update unless method_defined?(:regular_update)
-
-
# Assigns a new value to the hash:
-
#
-
# hash = ActiveSupport::HashWithIndifferentAccess.new
-
# hash[:key] = 'value'
-
#
-
# This value can be later fetched using either +:key+ or +'key'+.
-
2
def []=(key, value)
-
1899
regular_writer(convert_key(key), convert_value(value, for: :assignment))
-
end
-
-
2
alias_method :store, :[]=
-
-
# Updates the receiver in-place, merging in the hash passed as argument:
-
#
-
# hash_1 = ActiveSupport::HashWithIndifferentAccess.new
-
# hash_1[:key] = 'value'
-
#
-
# hash_2 = ActiveSupport::HashWithIndifferentAccess.new
-
# hash_2[:key] = 'New Value!'
-
#
-
# hash_1.update(hash_2) # => {"key"=>"New Value!"}
-
#
-
# The argument can be either an
-
# <tt>ActiveSupport::HashWithIndifferentAccess</tt> or a regular +Hash+.
-
# In either case the merge respects the semantics of indifferent access.
-
#
-
# If the argument is a regular hash with keys +:key+ and +"key"+ only one
-
# of the values end up in the receiver, but which one is unspecified.
-
#
-
# When given a block, the value for duplicated keys will be determined
-
# by the result of invoking the block with the duplicated key, the value
-
# in the receiver, and the value in +other_hash+. The rules for duplicated
-
# keys follow the semantics of indifferent access:
-
#
-
# hash_1[:key] = 10
-
# hash_2['key'] = 12
-
# hash_1.update(hash_2) { |key, old, new| old + new } # => {"key"=>22}
-
2
def update(other_hash)
-
1363
if other_hash.is_a? HashWithIndifferentAccess
-
113
super(other_hash)
-
else
-
1250
other_hash.to_hash.each_pair do |key, value|
-
1748
if block_given? && key?(key)
-
value = yield(convert_key(key), self[key], value)
-
end
-
1748
regular_writer(convert_key(key), convert_value(value))
-
end
-
1250
self
-
end
-
end
-
-
2
alias_method :merge!, :update
-
-
# Checks the hash for a key matching the argument passed in:
-
#
-
# hash = ActiveSupport::HashWithIndifferentAccess.new
-
# hash['key'] = 'value'
-
# hash.key?(:key) # => true
-
# hash.key?('key') # => true
-
2
def key?(key)
-
4287
super(convert_key(key))
-
end
-
-
2
alias_method :include?, :key?
-
2
alias_method :has_key?, :key?
-
2
alias_method :member?, :key?
-
-
# Same as <tt>Hash#fetch</tt> where the key passed as argument can be
-
# either a string or a symbol:
-
#
-
# counters = ActiveSupport::HashWithIndifferentAccess.new
-
# counters[:foo] = 1
-
#
-
# counters.fetch('foo') # => 1
-
# counters.fetch(:bar, 0) # => 0
-
# counters.fetch(:bar) { |key| 0 } # => 0
-
# counters.fetch(:zoo) # => KeyError: key not found: "zoo"
-
2
def fetch(key, *extras)
-
super(convert_key(key), *extras)
-
end
-
-
# Returns an array of the values at the specified indices:
-
#
-
# hash = ActiveSupport::HashWithIndifferentAccess.new
-
# hash[:a] = 'x'
-
# hash[:b] = 'y'
-
# hash.values_at('a', 'b') # => ["x", "y"]
-
2
def values_at(*indices)
-
indices.collect { |key| self[convert_key(key)] }
-
end
-
-
# Returns an exact copy of the hash.
-
2
def dup
-
83
self.class.new(self).tap do |new_hash|
-
83
new_hash.default = default
-
end
-
end
-
-
# This method has the same semantics of +update+, except it does not
-
# modify the receiver but rather returns a new hash with indifferent
-
# access with the result of the merge.
-
2
def merge(hash, &block)
-
24
self.dup.update(hash, &block)
-
end
-
-
# Like +merge+ but the other way around: Merges the receiver into the
-
# argument and returns a new hash with indifferent access as result:
-
#
-
# hash = ActiveSupport::HashWithIndifferentAccess.new
-
# hash['a'] = nil
-
# hash.reverse_merge(a: 0, b: 1) # => {"a"=>nil, "b"=>1}
-
2
def reverse_merge(other_hash)
-
super(self.class.new_from_hash_copying_default(other_hash))
-
end
-
-
# Same semantics as +reverse_merge+ but modifies the receiver in-place.
-
2
def reverse_merge!(other_hash)
-
replace(reverse_merge( other_hash ))
-
end
-
-
# Replaces the contents of this hash with other_hash.
-
#
-
# h = { "a" => 100, "b" => 200 }
-
# h.replace({ "c" => 300, "d" => 400 }) # => {"c"=>300, "d"=>400}
-
2
def replace(other_hash)
-
super(self.class.new_from_hash_copying_default(other_hash))
-
end
-
-
# Removes the specified key from the hash.
-
2
def delete(key)
-
66
super(convert_key(key))
-
end
-
-
2
def stringify_keys!; self end
-
2
def deep_stringify_keys!; self end
-
26
def stringify_keys; dup end
-
2
def deep_stringify_keys; dup end
-
2
undef :symbolize_keys!
-
2
undef :deep_symbolize_keys!
-
2
def symbolize_keys; to_hash.symbolize_keys! end
-
2
def deep_symbolize_keys; to_hash.deep_symbolize_keys! end
-
2
def to_options!; self end
-
-
2
def select(*args, &block)
-
dup.tap { |hash| hash.select!(*args, &block) }
-
end
-
-
2
def reject(*args, &block)
-
dup.tap { |hash| hash.reject!(*args, &block) }
-
end
-
-
# Convert to a regular hash with string keys.
-
2
def to_hash
-
_new_hash= {}
-
each do |key, value|
-
_new_hash[convert_key(key)] = convert_value(value, for: :to_hash)
-
end
-
Hash.new(default).merge!(_new_hash)
-
end
-
-
2
protected
-
2
def convert_key(key)
-
8000
key.kind_of?(Symbol) ? key.to_s : key
-
end
-
-
2
def convert_value(value, options = {})
-
6991
if value.is_a? Hash
-
80
if options[:for] == :to_hash
-
value.to_hash
-
else
-
80
value.nested_under_indifferent_access
-
end
-
6911
elsif value.is_a?(Array)
-
1672
unless options[:for] == :assignment
-
1672
value = value.dup
-
end
-
5016
value.map! { |e| convert_value(e, options) }
-
else
-
5239
value
-
end
-
end
-
end
-
end
-
-
2
HashWithIndifferentAccess = ActiveSupport::HashWithIndifferentAccess
-
2
require 'active_support/core_ext/hash/deep_merge'
-
2
require 'active_support/core_ext/hash/except'
-
2
require 'active_support/core_ext/hash/slice'
-
2
begin
-
2
require 'i18n'
-
rescue LoadError => e
-
$stderr.puts "The i18n gem is not available. Please add it to your Gemfile and run bundle install"
-
raise e
-
end
-
2
require 'active_support/lazy_load_hooks'
-
-
2
ActiveSupport.run_load_hooks(:i18n)
-
2
I18n.load_path << "#{File.dirname(__FILE__)}/locale/en.yml"
-
2
require "active_support"
-
2
require "active_support/file_update_checker"
-
2
require "active_support/core_ext/array/wrap"
-
-
2
module I18n
-
2
class Railtie < Rails::Railtie
-
2
config.i18n = ActiveSupport::OrderedOptions.new
-
2
config.i18n.railties_load_path = []
-
2
config.i18n.load_path = []
-
2
config.i18n.fallbacks = ActiveSupport::OrderedOptions.new
-
# Enforce I18n to check the available locales when setting a locale.
-
2
config.i18n.enforce_available_locales = true
-
-
# Set the i18n configuration after initialization since a lot of
-
# configuration is still usually done in application initializers.
-
2
config.after_initialize do |app|
-
2
I18n::Railtie.initialize_i18n(app)
-
end
-
-
# Trigger i18n config before any eager loading has happened
-
# so it's ready if any classes require it when eager loaded.
-
2
config.before_eager_load do |app|
-
I18n::Railtie.initialize_i18n(app)
-
end
-
-
2
protected
-
-
2
@i18n_inited = false
-
-
# Setup i18n configuration.
-
2
def self.initialize_i18n(app)
-
2
return if @i18n_inited
-
-
2
fallbacks = app.config.i18n.delete(:fallbacks)
-
-
# Avoid issues with setting the default_locale by disabling available locales
-
# check while configuring.
-
2
enforce_available_locales = app.config.i18n.delete(:enforce_available_locales)
-
2
enforce_available_locales = I18n.enforce_available_locales unless I18n.enforce_available_locales.nil?
-
2
I18n.enforce_available_locales = false
-
-
2
app.config.i18n.each do |setting, value|
-
4
case setting
-
when :railties_load_path
-
2
app.config.i18n.load_path.unshift(*value)
-
when :load_path
-
2
I18n.load_path += value
-
else
-
I18n.send("#{setting}=", value)
-
end
-
end
-
-
2
init_fallbacks(fallbacks) if fallbacks && validate_fallbacks(fallbacks)
-
-
# Restore available locales check so it will take place from now on.
-
2
I18n.enforce_available_locales = enforce_available_locales
-
-
4
reloader = ActiveSupport::FileUpdateChecker.new(I18n.load_path.dup){ I18n.reload! }
-
2
app.reloaders << reloader
-
2
ActionDispatch::Reloader.to_prepare { reloader.execute_if_updated }
-
2
reloader.execute
-
-
2
@i18n_inited = true
-
end
-
-
2
def self.include_fallbacks_module
-
I18n.backend.class.send(:include, I18n::Backend::Fallbacks)
-
end
-
-
2
def self.init_fallbacks(fallbacks)
-
include_fallbacks_module
-
-
args = case fallbacks
-
when ActiveSupport::OrderedOptions
-
[*(fallbacks[:defaults] || []) << fallbacks[:map]].compact
-
when Hash, Array
-
Array.wrap(fallbacks)
-
else # TrueClass
-
[]
-
end
-
-
I18n.fallbacks = I18n::Locale::Fallbacks.new(*args)
-
end
-
-
2
def self.validate_fallbacks(fallbacks)
-
2
case fallbacks
-
when ActiveSupport::OrderedOptions
-
2
!fallbacks.empty?
-
when TrueClass, Array, Hash
-
true
-
else
-
raise "Unexpected fallback type #{fallbacks.inspect}"
-
end
-
end
-
end
-
end
-
2
require 'active_support/inflector/inflections'
-
-
#--
-
# Defines the standard inflection rules. These are the starting point for
-
# new projects and are not considered complete. The current set of inflection
-
# rules is frozen. This means, we do not change them to become more complete.
-
# This is a safety measure to keep existing applications from breaking.
-
#++
-
2
module ActiveSupport
-
2
Inflector.inflections(:en) do |inflect|
-
2
inflect.plural(/$/, 's')
-
2
inflect.plural(/s$/i, 's')
-
2
inflect.plural(/^(ax|test)is$/i, '\1es')
-
2
inflect.plural(/(octop|vir)us$/i, '\1i')
-
2
inflect.plural(/(octop|vir)i$/i, '\1i')
-
2
inflect.plural(/(alias|status)$/i, '\1es')
-
2
inflect.plural(/(bu)s$/i, '\1ses')
-
2
inflect.plural(/(buffal|tomat)o$/i, '\1oes')
-
2
inflect.plural(/([ti])um$/i, '\1a')
-
2
inflect.plural(/([ti])a$/i, '\1a')
-
2
inflect.plural(/sis$/i, 'ses')
-
2
inflect.plural(/(?:([^f])fe|([lr])f)$/i, '\1\2ves')
-
2
inflect.plural(/(hive)$/i, '\1s')
-
2
inflect.plural(/([^aeiouy]|qu)y$/i, '\1ies')
-
2
inflect.plural(/(x|ch|ss|sh)$/i, '\1es')
-
2
inflect.plural(/(matr|vert|ind)(?:ix|ex)$/i, '\1ices')
-
2
inflect.plural(/^(m|l)ouse$/i, '\1ice')
-
2
inflect.plural(/^(m|l)ice$/i, '\1ice')
-
2
inflect.plural(/^(ox)$/i, '\1en')
-
2
inflect.plural(/^(oxen)$/i, '\1')
-
2
inflect.plural(/(quiz)$/i, '\1zes')
-
-
2
inflect.singular(/s$/i, '')
-
2
inflect.singular(/(ss)$/i, '\1')
-
2
inflect.singular(/(n)ews$/i, '\1ews')
-
2
inflect.singular(/([ti])a$/i, '\1um')
-
2
inflect.singular(/((a)naly|(b)a|(d)iagno|(p)arenthe|(p)rogno|(s)ynop|(t)he)(sis|ses)$/i, '\1sis')
-
2
inflect.singular(/(^analy)(sis|ses)$/i, '\1sis')
-
2
inflect.singular(/([^f])ves$/i, '\1fe')
-
2
inflect.singular(/(hive)s$/i, '\1')
-
2
inflect.singular(/(tive)s$/i, '\1')
-
2
inflect.singular(/([lr])ves$/i, '\1f')
-
2
inflect.singular(/([^aeiouy]|qu)ies$/i, '\1y')
-
2
inflect.singular(/(s)eries$/i, '\1eries')
-
2
inflect.singular(/(m)ovies$/i, '\1ovie')
-
2
inflect.singular(/(x|ch|ss|sh)es$/i, '\1')
-
2
inflect.singular(/^(m|l)ice$/i, '\1ouse')
-
2
inflect.singular(/(bus)(es)?$/i, '\1')
-
2
inflect.singular(/(o)es$/i, '\1')
-
2
inflect.singular(/(shoe)s$/i, '\1')
-
2
inflect.singular(/(cris|test)(is|es)$/i, '\1is')
-
2
inflect.singular(/^(a)x[ie]s$/i, '\1xis')
-
2
inflect.singular(/(octop|vir)(us|i)$/i, '\1us')
-
2
inflect.singular(/(alias|status)(es)?$/i, '\1')
-
2
inflect.singular(/^(ox)en/i, '\1')
-
2
inflect.singular(/(vert|ind)ices$/i, '\1ex')
-
2
inflect.singular(/(matr)ices$/i, '\1ix')
-
2
inflect.singular(/(quiz)zes$/i, '\1')
-
2
inflect.singular(/(database)s$/i, '\1')
-
-
2
inflect.irregular('person', 'people')
-
2
inflect.irregular('man', 'men')
-
2
inflect.irregular('child', 'children')
-
2
inflect.irregular('sex', 'sexes')
-
2
inflect.irregular('move', 'moves')
-
2
inflect.irregular('zombie', 'zombies')
-
-
2
inflect.uncountable(%w(equipment information rice money species series fish sheep jeans police))
-
end
-
end
-
# in case active_support/inflector is required without the rest of active_support
-
2
require 'active_support/inflector/inflections'
-
2
require 'active_support/inflector/transliterate'
-
2
require 'active_support/inflector/methods'
-
-
2
require 'active_support/inflections'
-
2
require 'active_support/core_ext/string/inflections'
-
2
require 'thread_safe'
-
2
require 'active_support/core_ext/array/prepend_and_append'
-
2
require 'active_support/i18n'
-
-
2
module ActiveSupport
-
2
module Inflector
-
2
extend self
-
-
# A singleton instance of this class is yielded by Inflector.inflections,
-
# which can then be used to specify additional inflection rules. If passed
-
# an optional locale, rules for other languages can be specified. The
-
# default locale is <tt>:en</tt>. Only rules for English are provided.
-
#
-
# ActiveSupport::Inflector.inflections(:en) do |inflect|
-
# inflect.plural /^(ox)$/i, '\1\2en'
-
# inflect.singular /^(ox)en/i, '\1'
-
#
-
# inflect.irregular 'octopus', 'octopi'
-
#
-
# inflect.uncountable 'equipment'
-
# end
-
#
-
# New rules are added at the top. So in the example above, the irregular
-
# rule for octopus will now be the first of the pluralization and
-
# singularization rules that is runs. This guarantees that your rules run
-
# before any of the rules that may already have been loaded.
-
2
class Inflections
-
2
@__instance__ = ThreadSafe::Cache.new
-
-
2
def self.instance(locale = :en)
-
1762
@__instance__[locale] ||= new
-
end
-
-
2
attr_reader :plurals, :singulars, :uncountables, :humans, :acronyms, :acronym_regex
-
-
2
def initialize
-
2
@plurals, @singulars, @uncountables, @humans, @acronyms, @acronym_regex = [], [], [], [], {}, /(?=a)b/
-
end
-
-
# Private, for the test suite.
-
2
def initialize_dup(orig) # :nodoc:
-
%w(plurals singulars uncountables humans acronyms acronym_regex).each do |scope|
-
instance_variable_set("@#{scope}", orig.send(scope).dup)
-
end
-
end
-
-
# Specifies a new acronym. An acronym must be specified as it will appear
-
# in a camelized string. An underscore string that contains the acronym
-
# will retain the acronym when passed to +camelize+, +humanize+, or
-
# +titleize+. A camelized string that contains the acronym will maintain
-
# the acronym when titleized or humanized, and will convert the acronym
-
# into a non-delimited single lowercase word when passed to +underscore+.
-
#
-
# acronym 'HTML'
-
# titleize 'html' # => 'HTML'
-
# camelize 'html' # => 'HTML'
-
# underscore 'MyHTML' # => 'my_html'
-
#
-
# The acronym, however, must occur as a delimited unit and not be part of
-
# another word for conversions to recognize it:
-
#
-
# acronym 'HTTP'
-
# camelize 'my_http_delimited' # => 'MyHTTPDelimited'
-
# camelize 'https' # => 'Https', not 'HTTPs'
-
# underscore 'HTTPS' # => 'http_s', not 'https'
-
#
-
# acronym 'HTTPS'
-
# camelize 'https' # => 'HTTPS'
-
# underscore 'HTTPS' # => 'https'
-
#
-
# Note: Acronyms that are passed to +pluralize+ will no longer be
-
# recognized, since the acronym will not occur as a delimited unit in the
-
# pluralized result. To work around this, you must specify the pluralized
-
# form as an acronym as well:
-
#
-
# acronym 'API'
-
# camelize(pluralize('api')) # => 'Apis'
-
#
-
# acronym 'APIs'
-
# camelize(pluralize('api')) # => 'APIs'
-
#
-
# +acronym+ may be used to specify any word that contains an acronym or
-
# otherwise needs to maintain a non-standard capitalization. The only
-
# restriction is that the word must begin with a capital letter.
-
#
-
# acronym 'RESTful'
-
# underscore 'RESTful' # => 'restful'
-
# underscore 'RESTfulController' # => 'restful_controller'
-
# titleize 'RESTfulController' # => 'RESTful Controller'
-
# camelize 'restful' # => 'RESTful'
-
# camelize 'restful_controller' # => 'RESTfulController'
-
#
-
# acronym 'McDonald'
-
# underscore 'McDonald' # => 'mcdonald'
-
# camelize 'mcdonald' # => 'McDonald'
-
2
def acronym(word)
-
@acronyms[word.downcase] = word
-
@acronym_regex = /#{@acronyms.values.join("|")}/
-
end
-
-
# Specifies a new pluralization rule and its replacement. The rule can
-
# either be a string or a regular expression. The replacement should
-
# always be a string that may include references to the matched data from
-
# the rule.
-
2
def plural(rule, replacement)
-
66
@uncountables.delete(rule) if rule.is_a?(String)
-
66
@uncountables.delete(replacement)
-
66
@plurals.prepend([rule, replacement])
-
end
-
-
# Specifies a new singularization rule and its replacement. The rule can
-
# either be a string or a regular expression. The replacement should
-
# always be a string that may include references to the matched data from
-
# the rule.
-
2
def singular(rule, replacement)
-
78
@uncountables.delete(rule) if rule.is_a?(String)
-
78
@uncountables.delete(replacement)
-
78
@singulars.prepend([rule, replacement])
-
end
-
-
# Specifies a new irregular that applies to both pluralization and
-
# singularization at the same time. This can only be used for strings, not
-
# regular expressions. You simply pass the irregular in singular and
-
# plural form.
-
#
-
# irregular 'octopus', 'octopi'
-
# irregular 'person', 'people'
-
2
def irregular(singular, plural)
-
12
@uncountables.delete(singular)
-
12
@uncountables.delete(plural)
-
-
12
s0 = singular[0]
-
12
srest = singular[1..-1]
-
-
12
p0 = plural[0]
-
12
prest = plural[1..-1]
-
-
12
if s0.upcase == p0.upcase
-
12
plural(/(#{s0})#{srest}$/i, '\1' + prest)
-
12
plural(/(#{p0})#{prest}$/i, '\1' + prest)
-
-
12
singular(/(#{s0})#{srest}$/i, '\1' + srest)
-
12
singular(/(#{p0})#{prest}$/i, '\1' + srest)
-
else
-
plural(/#{s0.upcase}(?i)#{srest}$/, p0.upcase + prest)
-
plural(/#{s0.downcase}(?i)#{srest}$/, p0.downcase + prest)
-
plural(/#{p0.upcase}(?i)#{prest}$/, p0.upcase + prest)
-
plural(/#{p0.downcase}(?i)#{prest}$/, p0.downcase + prest)
-
-
singular(/#{s0.upcase}(?i)#{srest}$/, s0.upcase + srest)
-
singular(/#{s0.downcase}(?i)#{srest}$/, s0.downcase + srest)
-
singular(/#{p0.upcase}(?i)#{prest}$/, s0.upcase + srest)
-
singular(/#{p0.downcase}(?i)#{prest}$/, s0.downcase + srest)
-
end
-
end
-
-
# Add uncountable words that shouldn't be attempted inflected.
-
#
-
# uncountable 'money'
-
# uncountable 'money', 'information'
-
# uncountable %w( money information rice )
-
2
def uncountable(*words)
-
2
(@uncountables << words).flatten!
-
end
-
-
# Specifies a humanized form of a string by a regular expression rule or
-
# by a string mapping. When using a regular expression based replacement,
-
# the normal humanize formatting is called after the replacement. When a
-
# string is used, the human form should be specified as desired (example:
-
# 'The name', not 'the_name').
-
#
-
# human /_cnt$/i, '\1_count'
-
# human 'legacy_col_person_name', 'Name'
-
2
def human(rule, replacement)
-
@humans.prepend([rule, replacement])
-
end
-
-
# Clears the loaded inflections within a given scope (default is
-
# <tt>:all</tt>). Give the scope as a symbol of the inflection type, the
-
# options are: <tt>:plurals</tt>, <tt>:singulars</tt>, <tt>:uncountables</tt>,
-
# <tt>:humans</tt>.
-
#
-
# clear :all
-
# clear :plurals
-
2
def clear(scope = :all)
-
case scope
-
when :all
-
@plurals, @singulars, @uncountables, @humans = [], [], [], []
-
else
-
instance_variable_set "@#{scope}", []
-
end
-
end
-
end
-
-
# Yields a singleton instance of Inflector::Inflections so you can specify
-
# additional inflector rules. If passed an optional locale, rules for other
-
# languages can be specified. If not specified, defaults to <tt>:en</tt>.
-
# Only rules for English are provided.
-
#
-
# ActiveSupport::Inflector.inflections(:en) do |inflect|
-
# inflect.uncountable 'rails'
-
# end
-
2
def inflections(locale = :en)
-
1762
if block_given?
-
2
yield Inflections.instance(locale)
-
else
-
1760
Inflections.instance(locale)
-
end
-
end
-
end
-
end
-
# encoding: utf-8
-
-
2
require 'active_support/inflections'
-
-
2
module ActiveSupport
-
# The Inflector transforms words from singular to plural, class names to table
-
# names, modularized class names to ones without, and class names to foreign
-
# keys. The default inflections for pluralization, singularization, and
-
# uncountable words are kept in inflections.rb.
-
#
-
# The Rails core team has stated patches for the inflections library will not
-
# be accepted in order to avoid breaking legacy applications which may be
-
# relying on errant inflections. If you discover an incorrect inflection and
-
# require it for your application or wish to define rules for languages other
-
# than English, please correct or add them yourself (explained below).
-
2
module Inflector
-
2
extend self
-
-
# Returns the plural form of the word in the string.
-
#
-
# If passed an optional +locale+ parameter, the word will be
-
# pluralized using rules defined for that language. By default,
-
# this parameter is set to <tt>:en</tt>.
-
#
-
# 'post'.pluralize # => "posts"
-
# 'octopus'.pluralize # => "octopi"
-
# 'sheep'.pluralize # => "sheep"
-
# 'words'.pluralize # => "words"
-
# 'CamelOctopus'.pluralize # => "CamelOctopi"
-
# 'ley'.pluralize(:es) # => "leyes"
-
2
def pluralize(word, locale = :en)
-
53
apply_inflections(word, inflections(locale).plurals)
-
end
-
-
# The reverse of +pluralize+, returns the singular form of a word in a
-
# string.
-
#
-
# If passed an optional +locale+ parameter, the word will be
-
# singularized using rules defined for that language. By default,
-
# this parameter is set to <tt>:en</tt>.
-
#
-
# 'posts'.singularize # => "post"
-
# 'octopi'.singularize # => "octopus"
-
# 'sheep'.singularize # => "sheep"
-
# 'word'.singularize # => "word"
-
# 'CamelOctopi'.singularize # => "CamelOctopus"
-
# 'leyes'.singularize(:es) # => "ley"
-
2
def singularize(word, locale = :en)
-
90
apply_inflections(word, inflections(locale).singulars)
-
end
-
-
# By default, +camelize+ converts strings to UpperCamelCase. If the argument
-
# to +camelize+ is set to <tt>:lower</tt> then +camelize+ produces
-
# lowerCamelCase.
-
#
-
# +camelize+ will also convert '/' to '::' which is useful for converting
-
# paths to namespaces.
-
#
-
# 'active_model'.camelize # => "ActiveModel"
-
# 'active_model'.camelize(:lower) # => "activeModel"
-
# 'active_model/errors'.camelize # => "ActiveModel::Errors"
-
# 'active_model/errors'.camelize(:lower) # => "activeModel::Errors"
-
#
-
# As a rule of thumb you can think of +camelize+ as the inverse of
-
# +underscore+, though there are cases where that does not hold:
-
#
-
# 'SSLError'.underscore.camelize # => "SslError"
-
2
def camelize(term, uppercase_first_letter = true)
-
219
string = term.to_s
-
219
if uppercase_first_letter
-
438
string = string.sub(/^[a-z\d]*/) { inflections.acronyms[$&] || $&.capitalize }
-
else
-
string = string.sub(/^(?:#{inflections.acronym_regex}(?=\b|[A-Z_])|\w)/) { $&.downcase }
-
end
-
444
string.gsub!(/(?:_|(\/))([a-z\d]*)/i) { "#{$1}#{inflections.acronyms[$2] || $2.capitalize}" }
-
219
string.gsub!('/', '::')
-
219
string
-
end
-
-
# Makes an underscored, lowercase form from the expression in the string.
-
#
-
# Changes '::' to '/' to convert namespaces to paths.
-
#
-
# 'ActiveModel'.underscore # => "active_model"
-
# 'ActiveModel::Errors'.underscore # => "active_model/errors"
-
#
-
# As a rule of thumb you can think of +underscore+ as the inverse of
-
# +camelize+, though there are cases where that does not hold:
-
#
-
# 'SSLError'.underscore.camelize # => "SslError"
-
2
def underscore(camel_cased_word)
-
896
word = camel_cased_word.to_s.gsub('::', '/')
-
896
word.gsub!(/(?:([A-Za-z\d])|^)(#{inflections.acronym_regex})(?=\b|[^a-z])/) { "#{$1}#{$1 && '_'}#{$2.downcase}" }
-
896
word.gsub!(/([A-Z\d]+)([A-Z][a-z])/,'\1_\2')
-
896
word.gsub!(/([a-z\d])([A-Z])/,'\1_\2')
-
896
word.tr!("-", "_")
-
896
word.downcase!
-
896
word
-
end
-
-
# Capitalizes the first word, turns underscores into spaces, and strips a
-
# trailing '_id' if present.
-
# Like +titleize+, this is meant for creating pretty output.
-
#
-
# The capitalization of the first word can be turned off by setting the
-
# optional parameter +capitalize+ to false.
-
# By default, this parameter is true.
-
#
-
# humanize('employee_salary') # => "Employee salary"
-
# humanize('author_id') # => "Author"
-
# humanize('author_id', capitalize: false) # => "author"
-
2
def humanize(lower_case_and_underscored_word, options = {})
-
36
result = lower_case_and_underscored_word.to_s.dup
-
36
inflections.humans.each { |(rule, replacement)| break if result.sub!(rule, replacement) }
-
36
result.gsub!(/_id$/, "")
-
36
result.tr!('_', ' ')
-
36
result.gsub!(/([a-z\d]*)/i) { |match|
-
98
"#{inflections.acronyms[match] || match.downcase}"
-
}
-
72
result.gsub!(/^\w/) { |match| match.upcase } if options.fetch(:capitalize, true)
-
36
result
-
end
-
-
# Capitalizes all the words and replaces some characters in the string to
-
# create a nicer looking title. +titleize+ is meant for creating pretty
-
# output. It is not used in the Rails internals.
-
#
-
# +titleize+ is also aliased as +titlecase+.
-
#
-
# 'man from the boondocks'.titleize # => "Man From The Boondocks"
-
# 'x-men: the last stand'.titleize # => "X Men: The Last Stand"
-
# 'TheManWithoutAPast'.titleize # => "The Man Without A Past"
-
# 'raiders_of_the_lost_ark'.titleize # => "Raiders Of The Lost Ark"
-
2
def titleize(word)
-
humanize(underscore(word)).gsub(/\b(?<!['’`])[a-z]/) { $&.capitalize }
-
end
-
-
# Create the name of a table like Rails does for models to table names. This
-
# method uses the +pluralize+ method on the last word in the string.
-
#
-
# 'RawScaledScorer'.tableize # => "raw_scaled_scorers"
-
# 'egg_and_ham'.tableize # => "egg_and_hams"
-
# 'fancyCategory'.tableize # => "fancy_categories"
-
2
def tableize(class_name)
-
2
pluralize(underscore(class_name))
-
end
-
-
# Create a class name from a plural table name like Rails does for table
-
# names to models. Note that this returns a string and not a Class (To
-
# convert to an actual class follow +classify+ with +constantize+).
-
#
-
# 'egg_and_hams'.classify # => "EggAndHam"
-
# 'posts'.classify # => "Post"
-
#
-
# Singular names are not handled correctly:
-
#
-
# 'calculus'.classify # => "Calculu"
-
2
def classify(table_name)
-
# strip out any leading schema name
-
10
camelize(singularize(table_name.to_s.sub(/.*\./, '')))
-
end
-
-
# Replaces underscores with dashes in the string.
-
#
-
# 'puni_puni'.dasherize # => "puni-puni"
-
2
def dasherize(underscored_word)
-
264
underscored_word.tr('_', '-')
-
end
-
-
# Removes the module part from the expression in the string.
-
#
-
# 'ActiveRecord::CoreExtensions::String::Inflections'.demodulize # => "Inflections"
-
# 'Inflections'.demodulize # => "Inflections"
-
#
-
# See also +deconstantize+.
-
2
def demodulize(path)
-
10
path = path.to_s
-
10
if i = path.rindex('::')
-
path[(i+2)..-1]
-
else
-
10
path
-
end
-
end
-
-
# Removes the rightmost segment from the constant expression in the string.
-
#
-
# 'Net::HTTP'.deconstantize # => "Net"
-
# '::Net::HTTP'.deconstantize # => "::Net"
-
# 'String'.deconstantize # => ""
-
# '::String'.deconstantize # => ""
-
# ''.deconstantize # => ""
-
#
-
# See also +demodulize+.
-
2
def deconstantize(path)
-
path.to_s[0, path.rindex('::') || 0] # implementation based on the one in facets' Module#spacename
-
end
-
-
# Creates a foreign key name from a class name.
-
# +separate_class_name_and_id_with_underscore+ sets whether
-
# the method should put '_' between the name and 'id'.
-
#
-
# 'Message'.foreign_key # => "message_id"
-
# 'Message'.foreign_key(false) # => "messageid"
-
# 'Admin::Post'.foreign_key # => "post_id"
-
2
def foreign_key(class_name, separate_class_name_and_id_with_underscore = true)
-
underscore(demodulize(class_name)) + (separate_class_name_and_id_with_underscore ? "_id" : "id")
-
end
-
-
# Tries to find a constant with the name specified in the argument string.
-
#
-
# 'Module'.constantize # => Module
-
# 'Test::Unit'.constantize # => Test::Unit
-
#
-
# The name is assumed to be the one of a top-level constant, no matter
-
# whether it starts with "::" or not. No lexical context is taken into
-
# account:
-
#
-
# C = 'outside'
-
# module M
-
# C = 'inside'
-
# C # => 'inside'
-
# 'C'.constantize # => 'outside', same as ::C
-
# end
-
#
-
# NameError is raised when the name is not in CamelCase or the constant is
-
# unknown.
-
2
def constantize(camel_cased_word)
-
186
names = camel_cased_word.split('::')
-
-
# Trigger a builtin NameError exception including the ill-formed constant in the message.
-
186
Object.const_get(camel_cased_word) if names.empty?
-
-
# Remove the first blank element in case of '::ClassName' notation.
-
186
names.shift if names.size > 1 && names.first.empty?
-
-
186
names.inject(Object) do |constant, name|
-
251
if constant == Object
-
186
constant.const_get(name)
-
else
-
65
candidate = constant.const_get(name)
-
65
next candidate if constant.const_defined?(name, false)
-
next candidate unless Object.const_defined?(name)
-
-
# Go down the ancestors to check it it's owned
-
# directly before we reach Object or the end of ancestors.
-
constant = constant.ancestors.inject do |const, ancestor|
-
break const if ancestor == Object
-
break ancestor if ancestor.const_defined?(name, false)
-
const
-
end
-
-
# owner is in Object, so raise
-
constant.const_get(name, false)
-
end
-
end
-
end
-
-
# Tries to find a constant with the name specified in the argument string.
-
#
-
# 'Module'.safe_constantize # => Module
-
# 'Test::Unit'.safe_constantize # => Test::Unit
-
#
-
# The name is assumed to be the one of a top-level constant, no matter
-
# whether it starts with "::" or not. No lexical context is taken into
-
# account:
-
#
-
# C = 'outside'
-
# module M
-
# C = 'inside'
-
# C # => 'inside'
-
# 'C'.safe_constantize # => 'outside', same as ::C
-
# end
-
#
-
# +nil+ is returned when the name is not in CamelCase or the constant (or
-
# part of it) is unknown.
-
#
-
# 'blargle'.safe_constantize # => nil
-
# 'UnknownModule'.safe_constantize # => nil
-
# 'UnknownModule::Foo::Bar'.safe_constantize # => nil
-
2
def safe_constantize(camel_cased_word)
-
constantize(camel_cased_word)
-
rescue NameError => e
-
raise unless e.message =~ /(uninitialized constant|wrong constant name) #{const_regexp(camel_cased_word)}$/ ||
-
e.name.to_s == camel_cased_word.to_s
-
rescue ArgumentError => e
-
raise unless e.message =~ /not missing constant #{const_regexp(camel_cased_word)}\!$/
-
end
-
-
# Returns the suffix that should be added to a number to denote the position
-
# in an ordered sequence such as 1st, 2nd, 3rd, 4th.
-
#
-
# ordinal(1) # => "st"
-
# ordinal(2) # => "nd"
-
# ordinal(1002) # => "nd"
-
# ordinal(1003) # => "rd"
-
# ordinal(-11) # => "th"
-
# ordinal(-1021) # => "st"
-
2
def ordinal(number)
-
abs_number = number.to_i.abs
-
-
if (11..13).include?(abs_number % 100)
-
"th"
-
else
-
case abs_number % 10
-
when 1; "st"
-
when 2; "nd"
-
when 3; "rd"
-
else "th"
-
end
-
end
-
end
-
-
# Turns a number into an ordinal string used to denote the position in an
-
# ordered sequence such as 1st, 2nd, 3rd, 4th.
-
#
-
# ordinalize(1) # => "1st"
-
# ordinalize(2) # => "2nd"
-
# ordinalize(1002) # => "1002nd"
-
# ordinalize(1003) # => "1003rd"
-
# ordinalize(-11) # => "-11th"
-
# ordinalize(-1021) # => "-1021st"
-
2
def ordinalize(number)
-
"#{number}#{ordinal(number)}"
-
end
-
-
2
private
-
-
# Mount a regular expression that will match part by part of the constant.
-
#
-
# const_regexp("Foo::Bar::Baz") # => /Foo(::Bar(::Baz)?)?/
-
# const_regexp("::") # => /::/
-
2
def const_regexp(camel_cased_word) #:nodoc:
-
parts = camel_cased_word.split("::")
-
-
return Regexp.escape(camel_cased_word) if parts.blank?
-
-
last = parts.pop
-
-
parts.reverse.inject(last) do |acc, part|
-
part.empty? ? acc : "#{part}(::#{acc})?"
-
end
-
end
-
-
# Applies inflection rules for +singularize+ and +pluralize+.
-
#
-
# apply_inflections('post', inflections.plurals) # => "posts"
-
# apply_inflections('posts', inflections.singulars) # => "post"
-
2
def apply_inflections(word, rules)
-
143
result = word.to_s.dup
-
-
143
if word.empty? || inflections.uncountables.include?(result.downcase[/\b\w+\Z/])
-
result
-
else
-
5203
rules.each { |(rule, replacement)| break if result.sub!(rule, replacement) }
-
143
result
-
end
-
end
-
end
-
end
-
# encoding: utf-8
-
2
require 'active_support/core_ext/string/multibyte'
-
2
require 'active_support/i18n'
-
-
2
module ActiveSupport
-
2
module Inflector
-
-
# Replaces non-ASCII characters with an ASCII approximation, or if none
-
# exists, a replacement character which defaults to "?".
-
#
-
# transliterate('Ærøskøbing')
-
# # => "AEroskobing"
-
#
-
# Default approximations are provided for Western/Latin characters,
-
# e.g, "ø", "ñ", "é", "ß", etc.
-
#
-
# This method is I18n aware, so you can set up custom approximations for a
-
# locale. This can be useful, for example, to transliterate German's "ü"
-
# and "ö" to "ue" and "oe", or to add support for transliterating Russian
-
# to ASCII.
-
#
-
# In order to make your custom transliterations available, you must set
-
# them as the <tt>i18n.transliterate.rule</tt> i18n key:
-
#
-
# # Store the transliterations in locales/de.yml
-
# i18n:
-
# transliterate:
-
# rule:
-
# ü: "ue"
-
# ö: "oe"
-
#
-
# # Or set them using Ruby
-
# I18n.backend.store_translations(:de, i18n: {
-
# transliterate: {
-
# rule: {
-
# 'ü' => 'ue',
-
# 'ö' => 'oe'
-
# }
-
# }
-
# })
-
#
-
# The value for <tt>i18n.transliterate.rule</tt> can be a simple Hash that
-
# maps characters to ASCII approximations as shown above, or, for more
-
# complex requirements, a Proc:
-
#
-
# I18n.backend.store_translations(:de, i18n: {
-
# transliterate: {
-
# rule: ->(string) { MyTransliterator.transliterate(string) }
-
# }
-
# })
-
#
-
# Now you can have different transliterations for each locale:
-
#
-
# I18n.locale = :en
-
# transliterate('Jürgen')
-
# # => "Jurgen"
-
#
-
# I18n.locale = :de
-
# transliterate('Jürgen')
-
# # => "Juergen"
-
2
def transliterate(string, replacement = "?")
-
I18n.transliterate(ActiveSupport::Multibyte::Unicode.normalize(
-
ActiveSupport::Multibyte::Unicode.tidy_bytes(string), :c),
-
:replacement => replacement)
-
end
-
-
# Replaces special characters in a string so that it may be used as part of
-
# a 'pretty' URL.
-
#
-
# class Person
-
# def to_param
-
# "#{id}-#{name.parameterize}"
-
# end
-
# end
-
#
-
# @person = Person.find(1)
-
# # => #<Person id: 1, name: "Donald E. Knuth">
-
#
-
# <%= link_to(@person.name, person_path(@person)) %>
-
# # => <a href="/person/1-donald-e-knuth">Donald E. Knuth</a>
-
2
def parameterize(string, sep = '-')
-
# replace accented chars with their ascii equivalents
-
parameterized_string = transliterate(string)
-
# Turn unwanted chars into the separator
-
parameterized_string.gsub!(/[^a-z0-9\-_]+/i, sep)
-
unless sep.nil? || sep.empty?
-
re_sep = Regexp.escape(sep)
-
# No more than one of the separator in a row.
-
parameterized_string.gsub!(/#{re_sep}{2,}/, sep)
-
# Remove leading/trailing separator.
-
parameterized_string.gsub!(/^#{re_sep}|#{re_sep}$/i, '')
-
end
-
parameterized_string.downcase
-
end
-
-
end
-
end
-
2
require 'active_support/json/decoding'
-
2
require 'active_support/json/encoding'
-
2
require 'active_support/core_ext/module/attribute_accessors'
-
2
require 'active_support/core_ext/module/delegation'
-
2
require 'json'
-
-
2
module ActiveSupport
-
# Look for and parse json strings that look like ISO 8601 times.
-
2
mattr_accessor :parse_json_times
-
-
2
module JSON
-
# matches YAML-formatted dates
-
2
DATE_REGEX = /^(?:\d{4}-\d{2}-\d{2}|\d{4}-\d{1,2}-\d{1,2}[T \t]+\d{1,2}:\d{2}:\d{2}(\.[0-9]*)?(([ \t]*)Z|[-+]\d{2}?(:\d{2})?))$/
-
-
2
class << self
-
# Parses a JSON string (JavaScript Object Notation) into a hash.
-
# See www.json.org for more info.
-
#
-
# ActiveSupport::JSON.decode("{\"team\":\"rails\",\"players\":\"36\"}")
-
# => {"team" => "rails", "players" => "36"}
-
2
def decode(json, options = {})
-
if options.present?
-
raise ArgumentError, "In Rails 4.1, ActiveSupport::JSON.decode no longer " \
-
"accepts an options hash for MultiJSON. MultiJSON reached its end of life " \
-
"and has been removed."
-
end
-
-
data = ::JSON.parse(json, quirks_mode: true)
-
-
if ActiveSupport.parse_json_times
-
convert_dates_from(data)
-
else
-
data
-
end
-
end
-
-
# Returns the class of the error that will be raised when there is an
-
# error in decoding JSON. Using this method means you won't directly
-
# depend on the ActiveSupport's JSON implementation, in case it changes
-
# in the future.
-
#
-
# begin
-
# obj = ActiveSupport::JSON.decode(some_string)
-
# rescue ActiveSupport::JSON.parse_error
-
# Rails.logger.warn("Attempted to decode invalid JSON: #{some_string}")
-
# end
-
2
def parse_error
-
::JSON::ParserError
-
end
-
-
2
private
-
-
2
def convert_dates_from(data)
-
case data
-
when nil
-
nil
-
when DATE_REGEX
-
begin
-
DateTime.parse(data)
-
rescue ArgumentError
-
data
-
end
-
when Array
-
data.map! { |d| convert_dates_from(d) }
-
when Hash
-
data.each do |key, value|
-
data[key] = convert_dates_from(value)
-
end
-
else
-
data
-
end
-
end
-
end
-
end
-
end
-
2
require 'active_support/core_ext/object/json'
-
2
require 'active_support/core_ext/module/delegation'
-
-
2
module ActiveSupport
-
2
class << self
-
2
delegate :use_standard_json_time_format, :use_standard_json_time_format=,
-
:time_precision, :time_precision=,
-
:escape_html_entities_in_json, :escape_html_entities_in_json=,
-
:encode_big_decimal_as_string, :encode_big_decimal_as_string=,
-
:json_encoder, :json_encoder=,
-
:to => :'ActiveSupport::JSON::Encoding'
-
end
-
-
2
module JSON
-
# Dumps objects in JSON (JavaScript Object Notation).
-
# See www.json.org for more info.
-
#
-
# ActiveSupport::JSON.encode({ team: 'rails', players: '36' })
-
# # => "{\"team\":\"rails\",\"players\":\"36\"}"
-
2
def self.encode(value, options = nil)
-
Encoding.json_encoder.new(options).encode(value)
-
end
-
-
2
module Encoding #:nodoc:
-
2
class JSONGemEncoder #:nodoc:
-
2
attr_reader :options
-
-
2
def initialize(options = nil)
-
@options = options || {}
-
end
-
-
# Encode the given object into a JSON string
-
2
def encode(value)
-
stringify jsonify value.as_json(options.dup)
-
end
-
-
2
private
-
# Rails does more escaping than the JSON gem natively does (we
-
# escape \u2028 and \u2029 and optionally >, <, & to work around
-
# certain browser problems).
-
2
ESCAPED_CHARS = {
-
"\u2028" => '\u2028',
-
"\u2029" => '\u2029',
-
'>' => '\u003e',
-
'<' => '\u003c',
-
'&' => '\u0026',
-
}
-
-
2
ESCAPE_REGEX_WITH_HTML_ENTITIES = /[\u2028\u2029><&]/u
-
2
ESCAPE_REGEX_WITHOUT_HTML_ENTITIES = /[\u2028\u2029]/u
-
-
# This class wraps all the strings we see and does the extra escaping
-
2
class EscapedString < String #:nodoc:
-
2
def to_json(*)
-
if Encoding.escape_html_entities_in_json
-
super.gsub ESCAPE_REGEX_WITH_HTML_ENTITIES, ESCAPED_CHARS
-
else
-
super.gsub ESCAPE_REGEX_WITHOUT_HTML_ENTITIES, ESCAPED_CHARS
-
end
-
end
-
end
-
-
# Mark these as private so we don't leak encoding-specific constructs
-
2
private_constant :ESCAPED_CHARS, :ESCAPE_REGEX_WITH_HTML_ENTITIES,
-
:ESCAPE_REGEX_WITHOUT_HTML_ENTITIES, :EscapedString
-
-
# Convert an object into a "JSON-ready" representation composed of
-
# primitives like Hash, Array, String, Numeric, and true/false/nil.
-
# Recursively calls #as_json to the object to recursively build a
-
# fully JSON-ready object.
-
#
-
# This allows developers to implement #as_json without having to
-
# worry about what base types of objects they are allowed to return
-
# or having to remember to call #as_json recursively.
-
#
-
# Note: the +options+ hash passed to +object.to_json+ is only passed
-
# to +object.as_json+, not any of this method's recursive +#as_json+
-
# calls.
-
2
def jsonify(value)
-
case value
-
when String
-
EscapedString.new(value)
-
when Numeric, NilClass, TrueClass, FalseClass
-
value
-
when Hash
-
Hash[value.map { |k, v| [jsonify(k), jsonify(v)] }]
-
when Array
-
value.map { |v| jsonify(v) }
-
else
-
jsonify value.as_json
-
end
-
end
-
-
# Encode a "jsonified" Ruby data structure using the JSON gem
-
2
def stringify(jsonified)
-
::JSON.generate(jsonified, quirks_mode: true, max_nesting: false)
-
end
-
end
-
-
2
class << self
-
# If true, use ISO 8601 format for dates and times. Otherwise, fall back
-
# to the Active Support legacy format.
-
2
attr_accessor :use_standard_json_time_format
-
-
# If true, encode >, <, & as escaped unicode sequences (e.g. > as \u003e)
-
# as a safety measure.
-
2
attr_accessor :escape_html_entities_in_json
-
-
# Sets the precision of encoded time values.
-
# Defaults to 3 (equivalent to millisecond precision)
-
2
attr_accessor :time_precision
-
-
# Sets the encoder used by Rails to encode Ruby objects into JSON strings
-
# in +Object#to_json+ and +ActiveSupport::JSON.encode+.
-
2
attr_accessor :json_encoder
-
-
2
def encode_big_decimal_as_string=(as_string)
-
message = \
-
"The JSON encoder in Rails 4.1 no longer supports encoding BigDecimals as JSON numbers. Instead, " \
-
"the new encoder will always encode them as strings.\n\n" \
-
"You are seeing this error because you have 'active_support.encode_big_decimal_as_string' in " \
-
"your configuration file. If you have been setting this to true, you can safely remove it from " \
-
"your configuration. Otherwise, you should add the 'activesupport-json_encoder' gem to your " \
-
"Gemfile in order to restore this functionality."
-
-
raise NotImplementedError, message
-
end
-
-
2
def encode_big_decimal_as_string
-
message = \
-
"The JSON encoder in Rails 4.1 no longer supports encoding BigDecimals as JSON numbers. Instead, " \
-
"the new encoder will always encode them as strings.\n\n" \
-
"You are seeing this error because you are trying to check the value of the related configuration, " \
-
"'active_support.encode_big_decimal_as_string'. If your application depends on this option, you should " \
-
"add the 'activesupport-json_encoder' gem to your Gemfile. For now, this option will always be true. " \
-
"In the future, it will be removed from Rails, so you should stop checking its value."
-
-
ActiveSupport::Deprecation.warn message
-
-
true
-
end
-
-
# Deprecate CircularReferenceError
-
2
def const_missing(name)
-
if name == :CircularReferenceError
-
message = "The JSON encoder in Rails 4.1 no longer offers protection from circular references. " \
-
"You are seeing this warning because you are rescuing from (or otherwise referencing) " \
-
"ActiveSupport::Encoding::CircularReferenceError. In the future, this error will be " \
-
"removed from Rails. You should remove these rescue blocks from your code and ensure " \
-
"that your data structures are free of circular references so they can be properly " \
-
"serialized into JSON.\n\n" \
-
"For example, the following Hash contains a circular reference to itself:\n" \
-
" h = {}\n" \
-
" h['circular'] = h\n" \
-
"In this case, calling h.to_json would not work properly."
-
-
ActiveSupport::Deprecation.warn message
-
-
SystemStackError
-
else
-
super
-
end
-
end
-
end
-
-
2
self.use_standard_json_time_format = true
-
2
self.escape_html_entities_in_json = true
-
2
self.json_encoder = JSONGemEncoder
-
2
self.time_precision = 3
-
end
-
end
-
end
-
2
require 'thread_safe'
-
2
require 'openssl'
-
-
2
module ActiveSupport
-
# KeyGenerator is a simple wrapper around OpenSSL's implementation of PBKDF2
-
# It can be used to derive a number of keys for various purposes from a given secret.
-
# This lets Rails applications have a single secure secret, but avoid reusing that
-
# key in multiple incompatible contexts.
-
2
class KeyGenerator
-
2
def initialize(secret, options = {})
-
2
@secret = secret
-
# The default iterations are higher than required for our key derivation uses
-
# on the off chance someone uses this for password storage
-
2
@iterations = options[:iterations] || 2**16
-
end
-
-
# Returns a derived key suitable for use. The default key_size is chosen
-
# to be compatible with the default settings of ActiveSupport::MessageVerifier.
-
# i.e. OpenSSL::Digest::SHA1#block_length
-
2
def generate_key(salt, key_size=64)
-
2
OpenSSL::PKCS5.pbkdf2_hmac_sha1(@secret, salt, @iterations, key_size)
-
end
-
end
-
-
# CachingKeyGenerator is a wrapper around KeyGenerator which allows users to avoid
-
# re-executing the key generation process when it's called using the same salt and
-
# key_size
-
2
class CachingKeyGenerator
-
2
def initialize(key_generator)
-
2
@key_generator = key_generator
-
2
@cache_keys = ThreadSafe::Cache.new
-
end
-
-
# Returns a derived key suitable for use. The default key_size is chosen
-
# to be compatible with the default settings of ActiveSupport::MessageVerifier.
-
# i.e. OpenSSL::Digest::SHA1#block_length
-
2
def generate_key(salt, key_size=64)
-
26
@cache_keys["#{salt}#{key_size}"] ||= @key_generator.generate_key(salt, key_size)
-
end
-
end
-
-
2
class LegacyKeyGenerator # :nodoc:
-
2
SECRET_MIN_LENGTH = 30 # Characters
-
-
2
def initialize(secret)
-
ensure_secret_secure(secret)
-
@secret = secret
-
end
-
-
2
def generate_key(salt)
-
@secret
-
end
-
-
2
private
-
-
# To prevent users from using something insecure like "Password" we make sure that the
-
# secret they've provided is at least 30 characters in length.
-
2
def ensure_secret_secure(secret)
-
if secret.blank?
-
raise ArgumentError, "A secret is required to generate an integrity hash " \
-
"for cookie session data. Set a secret_key_base of at least " \
-
"#{SECRET_MIN_LENGTH} characters in config/secrets.yml."
-
end
-
-
if secret.length < SECRET_MIN_LENGTH
-
raise ArgumentError, "Secret should be something secure, " \
-
"like \"#{SecureRandom.hex(16)}\". The value you " \
-
"provided, \"#{secret}\", is shorter than the minimum length " \
-
"of #{SECRET_MIN_LENGTH} characters."
-
end
-
end
-
end
-
end
-
2
module ActiveSupport
-
# lazy_load_hooks allows Rails to lazily load a lot of components and thus
-
# making the app boot faster. Because of this feature now there is no need to
-
# require <tt>ActiveRecord::Base</tt> at boot time purely to apply
-
# configuration. Instead a hook is registered that applies configuration once
-
# <tt>ActiveRecord::Base</tt> is loaded. Here <tt>ActiveRecord::Base</tt> is
-
# used as example but this feature can be applied elsewhere too.
-
#
-
# Here is an example where +on_load+ method is called to register a hook.
-
#
-
# initializer 'active_record.initialize_timezone' do
-
# ActiveSupport.on_load(:active_record) do
-
# self.time_zone_aware_attributes = true
-
# self.default_timezone = :utc
-
# end
-
# end
-
#
-
# When the entirety of +activerecord/lib/active_record/base.rb+ has been
-
# evaluated then +run_load_hooks+ is invoked. The very last line of
-
# +activerecord/lib/active_record/base.rb+ is:
-
#
-
# ActiveSupport.run_load_hooks(:active_record, ActiveRecord::Base)
-
20
@load_hooks = Hash.new { |h,k| h[k] = [] }
-
20
@loaded = Hash.new { |h,k| h[k] = [] }
-
-
2
def self.on_load(name, options = {}, &block)
-
102
@loaded[name].each do |base|
-
46
execute_hook(base, options, block)
-
end
-
-
102
@load_hooks[name] << [block, options]
-
end
-
-
2
def self.execute_hook(base, options, block)
-
98
if options[:yield]
-
16
block.call(base)
-
else
-
82
base.instance_eval(&block)
-
end
-
end
-
-
2
def self.run_load_hooks(name, base = Object)
-
16
@loaded[name] << base
-
16
@load_hooks[name].each do |hook, options|
-
52
execute_hook(base, options, hook)
-
end
-
end
-
end
-
2
require 'active_support/core_ext/module/attribute_accessors'
-
2
require 'active_support/core_ext/class/attribute'
-
2
require 'active_support/subscriber'
-
-
2
module ActiveSupport
-
# ActiveSupport::LogSubscriber is an object set to consume
-
# ActiveSupport::Notifications with the sole purpose of logging them.
-
# The log subscriber dispatches notifications to a registered object based
-
# on its given namespace.
-
#
-
# An example would be Active Record log subscriber responsible for logging
-
# queries:
-
#
-
# module ActiveRecord
-
# class LogSubscriber < ActiveSupport::LogSubscriber
-
# def sql(event)
-
# "#{event.payload[:name]} (#{event.duration}) #{event.payload[:sql]}"
-
# end
-
# end
-
# end
-
#
-
# And it's finally registered as:
-
#
-
# ActiveRecord::LogSubscriber.attach_to :active_record
-
#
-
# Since we need to know all instance methods before attaching the log
-
# subscriber, the line above should be called after your
-
# <tt>ActiveRecord::LogSubscriber</tt> definition.
-
#
-
# After configured, whenever a "sql.active_record" notification is published,
-
# it will properly dispatch the event (ActiveSupport::Notifications::Event) to
-
# the sql method.
-
#
-
# Log subscriber also has some helpers to deal with logging and automatically
-
# flushes all logs when the request finishes (via action_dispatch.callback
-
# notification) in a Rails environment.
-
2
class LogSubscriber < Subscriber
-
# Embed in a String to clear all previous ANSI sequences.
-
2
CLEAR = "\e[0m"
-
2
BOLD = "\e[1m"
-
-
# Colors
-
2
BLACK = "\e[30m"
-
2
RED = "\e[31m"
-
2
GREEN = "\e[32m"
-
2
YELLOW = "\e[33m"
-
2
BLUE = "\e[34m"
-
2
MAGENTA = "\e[35m"
-
2
CYAN = "\e[36m"
-
2
WHITE = "\e[37m"
-
-
2
mattr_accessor :colorize_logging
-
2
self.colorize_logging = true
-
-
2
class << self
-
2
def logger
-
@logger ||= if defined?(Rails) && Rails.respond_to?(:logger)
-
1
Rails.logger
-
26
end
-
end
-
-
2
attr_writer :logger
-
-
2
def log_subscribers
-
subscribers
-
end
-
-
# Flush all log_subscribers' logger.
-
2
def flush_all!
-
13
logger.flush if logger.respond_to?(:flush)
-
end
-
end
-
-
2
def logger
-
LogSubscriber.logger
-
end
-
-
2
def start(name, id, payload)
-
1042
super if logger
-
end
-
-
2
def finish(name, id, payload)
-
1042
super if logger
-
rescue Exception => e
-
logger.error "Could not log #{name.inspect} event. #{e.class}: #{e.message} #{e.backtrace}"
-
end
-
-
2
protected
-
-
2
%w(info debug warn error fatal unknown).each do |level|
-
12
class_eval <<-METHOD, __FILE__, __LINE__ + 1
-
def #{level}(progname = nil, &block)
-
logger.#{level}(progname, &block) if logger
-
end
-
METHOD
-
end
-
-
# Set color by using a string or one of the defined constants. If a third
-
# option is set to +true+, it also adds bold to the string. This is based
-
# on the Highline implementation and will automatically append CLEAR to the
-
# end of the returned String.
-
2
def color(text, color, bold=false)
-
1407
return text unless colorize_logging
-
1407
color = self.class.const_get(color.upcase) if color.is_a?(Symbol)
-
1407
bold = bold ? BOLD : ""
-
1407
"#{bold}#{color}#{text}#{CLEAR}"
-
end
-
end
-
end
-
2
require 'active_support/core_ext/module/attribute_accessors'
-
2
require 'active_support/logger_silence'
-
2
require 'logger'
-
-
2
module ActiveSupport
-
2
class Logger < ::Logger
-
2
include LoggerSilence
-
-
# Broadcasts logs to multiple loggers.
-
2
def self.broadcast(logger) # :nodoc:
-
Module.new do
-
define_method(:add) do |*args, &block|
-
logger.add(*args, &block)
-
super(*args, &block)
-
end
-
-
define_method(:<<) do |x|
-
logger << x
-
super(x)
-
end
-
-
define_method(:close) do
-
logger.close
-
super()
-
end
-
-
define_method(:progname=) do |name|
-
logger.progname = name
-
super(name)
-
end
-
-
define_method(:formatter=) do |formatter|
-
logger.formatter = formatter
-
super(formatter)
-
end
-
-
define_method(:level=) do |level|
-
logger.level = level
-
super(level)
-
end
-
end
-
end
-
-
2
def initialize(*args)
-
2
super
-
2
@formatter = SimpleFormatter.new
-
end
-
-
# Simple formatter which only displays the message.
-
2
class SimpleFormatter < ::Logger::Formatter
-
# This method is invoked when a log event occurs
-
2
def call(severity, timestamp, progname, msg)
-
1223
"#{String === msg ? msg : msg.inspect}\n"
-
end
-
end
-
end
-
end
-
2
require 'active_support/concern'
-
-
2
module LoggerSilence
-
2
extend ActiveSupport::Concern
-
-
2
included do
-
2
cattr_accessor :silencer
-
2
self.silencer = true
-
end
-
-
# Silences the logger for the duration of the block.
-
2
def silence(temporary_level = Logger::ERROR)
-
if silencer
-
begin
-
old_logger_level, self.level = level, temporary_level
-
yield self
-
ensure
-
self.level = old_logger_level
-
end
-
else
-
yield self
-
end
-
end
-
end
-
2
require 'base64'
-
2
require 'active_support/core_ext/object/blank'
-
-
2
module ActiveSupport
-
# +MessageVerifier+ makes it easy to generate and verify messages which are
-
# signed to prevent tampering.
-
#
-
# This is useful for cases like remember-me tokens and auto-unsubscribe links
-
# where the session store isn't suitable or available.
-
#
-
# Remember Me:
-
# cookies[:remember_me] = @verifier.generate([@user.id, 2.weeks.from_now])
-
#
-
# In the authentication filter:
-
#
-
# id, time = @verifier.verify(cookies[:remember_me])
-
# if time < Time.now
-
# self.current_user = User.find(id)
-
# end
-
#
-
# By default it uses Marshal to serialize the message. If you want to use
-
# another serialization method, you can set the serializer in the options
-
# hash upon initialization:
-
#
-
# @verifier = ActiveSupport::MessageVerifier.new('s3Krit', serializer: YAML)
-
2
class MessageVerifier
-
2
class InvalidSignature < StandardError; end
-
-
2
def initialize(secret, options = {})
-
13
@secret = secret
-
13
@digest = options[:digest] || 'SHA1'
-
13
@serializer = options[:serializer] || Marshal
-
end
-
-
2
def verify(signed_message)
-
raise InvalidSignature if signed_message.blank?
-
-
data, digest = signed_message.split("--")
-
if data.present? && digest.present? && secure_compare(digest, generate_digest(data))
-
begin
-
@serializer.load(::Base64.strict_decode64(data))
-
rescue ArgumentError => argument_error
-
raise InvalidSignature if argument_error.message =~ %r{invalid base64}
-
raise
-
end
-
else
-
raise InvalidSignature
-
end
-
end
-
-
2
def generate(value)
-
2
data = ::Base64.strict_encode64(@serializer.dump(value))
-
2
"#{data}--#{generate_digest(data)}"
-
end
-
-
2
private
-
# constant-time comparison algorithm to prevent timing attacks
-
2
def secure_compare(a, b)
-
return false unless a.bytesize == b.bytesize
-
-
l = a.unpack "C#{a.bytesize}"
-
-
res = 0
-
b.each_byte { |byte| res |= byte ^ l.shift }
-
res == 0
-
end
-
-
2
def generate_digest(data)
-
2
require 'openssl' unless defined?(OpenSSL)
-
2
OpenSSL::HMAC.hexdigest(OpenSSL::Digest.const_get(@digest).new, @secret, data)
-
end
-
end
-
end
-
2
module ActiveSupport #:nodoc:
-
2
module Multibyte
-
2
autoload :Chars, 'active_support/multibyte/chars'
-
2
autoload :Unicode, 'active_support/multibyte/unicode'
-
-
# The proxy class returned when calling mb_chars. You can use this accessor
-
# to configure your own proxy class so you can support other encodings. See
-
# the ActiveSupport::Multibyte::Chars implementation for an example how to
-
# do this.
-
#
-
# ActiveSupport::Multibyte.proxy_class = CharsForUTF32
-
2
def self.proxy_class=(klass)
-
@proxy_class = klass
-
end
-
-
# Returns the current proxy class.
-
2
def self.proxy_class
-
@proxy_class ||= ActiveSupport::Multibyte::Chars
-
end
-
end
-
end
-
# encoding: utf-8
-
2
require 'active_support/json'
-
2
require 'active_support/core_ext/string/access'
-
2
require 'active_support/core_ext/string/behavior'
-
2
require 'active_support/core_ext/module/delegation'
-
-
2
module ActiveSupport #:nodoc:
-
2
module Multibyte #:nodoc:
-
# Chars enables you to work transparently with UTF-8 encoding in the Ruby
-
# String class without having extensive knowledge about the encoding. A
-
# Chars object accepts a string upon initialization and proxies String
-
# methods in an encoding safe manner. All the normal String methods are also
-
# implemented on the proxy.
-
#
-
# String methods are proxied through the Chars object, and can be accessed
-
# through the +mb_chars+ method. Methods which would normally return a
-
# String object now return a Chars object so methods can be chained.
-
#
-
# 'The Perfect String '.mb_chars.downcase.strip.normalize # => "the perfect string"
-
#
-
# Chars objects are perfectly interchangeable with String objects as long as
-
# no explicit class checks are made. If certain methods do explicitly check
-
# the class, call +to_s+ before you pass chars objects to them.
-
#
-
# bad.explicit_checking_method 'T'.mb_chars.downcase.to_s
-
#
-
# The default Chars implementation assumes that the encoding of the string
-
# is UTF-8, if you want to handle different encodings you can write your own
-
# multibyte string handler and configure it through
-
# ActiveSupport::Multibyte.proxy_class.
-
#
-
# class CharsForUTF32
-
# def size
-
# @wrapped_string.size / 4
-
# end
-
#
-
# def self.accepts?(string)
-
# string.length % 4 == 0
-
# end
-
# end
-
#
-
# ActiveSupport::Multibyte.proxy_class = CharsForUTF32
-
2
class Chars
-
2
include Comparable
-
2
attr_reader :wrapped_string
-
2
alias to_s wrapped_string
-
2
alias to_str wrapped_string
-
-
2
delegate :<=>, :=~, :acts_like_string?, :to => :wrapped_string
-
-
# Creates a new Chars instance by wrapping _string_.
-
2
def initialize(string)
-
@wrapped_string = string
-
@wrapped_string.force_encoding(Encoding::UTF_8) unless @wrapped_string.frozen?
-
end
-
-
# Forward all undefined methods to the wrapped string.
-
2
def method_missing(method, *args, &block)
-
result = @wrapped_string.__send__(method, *args, &block)
-
if method.to_s =~ /!$/
-
self if result
-
else
-
result.kind_of?(String) ? chars(result) : result
-
end
-
end
-
-
# Returns +true+ if _obj_ responds to the given method. Private methods
-
# are included in the search only if the optional second parameter
-
# evaluates to +true+.
-
2
def respond_to_missing?(method, include_private)
-
@wrapped_string.respond_to?(method, include_private)
-
end
-
-
# Returns +true+ when the proxy class can handle the string. Returns
-
# +false+ otherwise.
-
2
def self.consumes?(string)
-
string.encoding == Encoding::UTF_8
-
end
-
-
# Works just like <tt>String#split</tt>, with the exception that the items
-
# in the resulting list are Chars instances instead of String. This makes
-
# chaining methods easier.
-
#
-
# 'Café périferôl'.mb_chars.split(/é/).map { |part| part.upcase.to_s } # => ["CAF", " P", "RIFERÔL"]
-
2
def split(*args)
-
@wrapped_string.split(*args).map { |i| self.class.new(i) }
-
end
-
-
# Works like like <tt>String#slice!</tt>, but returns an instance of
-
# Chars, or nil if the string was not modified.
-
2
def slice!(*args)
-
chars(@wrapped_string.slice!(*args))
-
end
-
-
# Reverses all characters in the string.
-
#
-
# 'Café'.mb_chars.reverse.to_s # => 'éfaC'
-
2
def reverse
-
chars(Unicode.unpack_graphemes(@wrapped_string).reverse.flatten.pack('U*'))
-
end
-
-
# Limits the byte size of the string to a number of bytes without breaking
-
# characters. Usable when the storage for a string is limited for some
-
# reason.
-
#
-
# 'こんにちは'.mb_chars.limit(7).to_s # => "こん"
-
2
def limit(limit)
-
slice(0...translate_offset(limit))
-
end
-
-
# Converts characters in the string to uppercase.
-
#
-
# 'Laurent, où sont les tests ?'.mb_chars.upcase.to_s # => "LAURENT, OÙ SONT LES TESTS ?"
-
2
def upcase
-
chars Unicode.upcase(@wrapped_string)
-
end
-
-
# Converts characters in the string to lowercase.
-
#
-
# 'VĚDA A VÝZKUM'.mb_chars.downcase.to_s # => "věda a výzkum"
-
2
def downcase
-
chars Unicode.downcase(@wrapped_string)
-
end
-
-
# Converts characters in the string to the opposite case.
-
#
-
# 'El Cañón".mb_chars.swapcase.to_s # => "eL cAÑÓN"
-
2
def swapcase
-
chars Unicode.swapcase(@wrapped_string)
-
end
-
-
# Converts the first character to uppercase and the remainder to lowercase.
-
#
-
# 'über'.mb_chars.capitalize.to_s # => "Über"
-
2
def capitalize
-
(slice(0) || chars('')).upcase + (slice(1..-1) || chars('')).downcase
-
end
-
-
# Capitalizes the first letter of every word, when possible.
-
#
-
# "ÉL QUE SE ENTERÓ".mb_chars.titleize # => "Él Que Se Enteró"
-
# "日本語".mb_chars.titleize # => "日本語"
-
2
def titleize
-
chars(downcase.to_s.gsub(/\b('?\S)/u) { Unicode.upcase($1)})
-
end
-
2
alias_method :titlecase, :titleize
-
-
# Returns the KC normalization of the string by default. NFKC is
-
# considered the best normalization form for passing strings to databases
-
# and validations.
-
#
-
# * <tt>form</tt> - The form you want to normalize in. Should be one of the following:
-
# <tt>:c</tt>, <tt>:kc</tt>, <tt>:d</tt>, or <tt>:kd</tt>. Default is
-
# ActiveSupport::Multibyte::Unicode.default_normalization_form
-
2
def normalize(form = nil)
-
chars(Unicode.normalize(@wrapped_string, form))
-
end
-
-
# Performs canonical decomposition on all the characters.
-
#
-
# 'é'.length # => 2
-
# 'é'.mb_chars.decompose.to_s.length # => 3
-
2
def decompose
-
chars(Unicode.decompose(:canonical, @wrapped_string.codepoints.to_a).pack('U*'))
-
end
-
-
# Performs composition on all the characters.
-
#
-
# 'é'.length # => 3
-
# 'é'.mb_chars.compose.to_s.length # => 2
-
2
def compose
-
chars(Unicode.compose(@wrapped_string.codepoints.to_a).pack('U*'))
-
end
-
-
# Returns the number of grapheme clusters in the string.
-
#
-
# 'क्षि'.mb_chars.length # => 4
-
# 'क्षि'.mb_chars.grapheme_length # => 3
-
2
def grapheme_length
-
Unicode.unpack_graphemes(@wrapped_string).length
-
end
-
-
# Replaces all ISO-8859-1 or CP1252 characters by their UTF-8 equivalent
-
# resulting in a valid UTF-8 string.
-
#
-
# Passing +true+ will forcibly tidy all bytes, assuming that the string's
-
# encoding is entirely CP1252 or ISO-8859-1.
-
2
def tidy_bytes(force = false)
-
chars(Unicode.tidy_bytes(@wrapped_string, force))
-
end
-
-
2
def as_json(options = nil) #:nodoc:
-
to_s.as_json(options)
-
end
-
-
2
%w(capitalize downcase reverse tidy_bytes upcase).each do |method|
-
10
define_method("#{method}!") do |*args|
-
@wrapped_string = send(method, *args).to_s
-
self
-
end
-
end
-
-
2
protected
-
-
2
def translate_offset(byte_offset) #:nodoc:
-
return nil if byte_offset.nil?
-
return 0 if @wrapped_string == ''
-
-
begin
-
@wrapped_string.byteslice(0...byte_offset).unpack('U*').length
-
rescue ArgumentError
-
byte_offset -= 1
-
retry
-
end
-
end
-
-
2
def chars(string) #:nodoc:
-
self.class.new(string)
-
end
-
end
-
end
-
end
-
2
require 'active_support/notifications/instrumenter'
-
2
require 'active_support/notifications/fanout'
-
2
require 'active_support/per_thread_registry'
-
-
2
module ActiveSupport
-
# = Notifications
-
#
-
# <tt>ActiveSupport::Notifications</tt> provides an instrumentation API for
-
# Ruby.
-
#
-
# == Instrumenters
-
#
-
# To instrument an event you just need to do:
-
#
-
# ActiveSupport::Notifications.instrument('render', extra: :information) do
-
# render text: 'Foo'
-
# end
-
#
-
# That executes the block first and notifies all subscribers once done.
-
#
-
# In the example above +render+ is the name of the event, and the rest is called
-
# the _payload_. The payload is a mechanism that allows instrumenters to pass
-
# extra information to subscribers. Payloads consist of a hash whose contents
-
# are arbitrary and generally depend on the event.
-
#
-
# == Subscribers
-
#
-
# You can consume those events and the information they provide by registering
-
# a subscriber.
-
#
-
# ActiveSupport::Notifications.subscribe('render') do |name, start, finish, id, payload|
-
# name # => String, name of the event (such as 'render' from above)
-
# start # => Time, when the instrumented block started execution
-
# finish # => Time, when the instrumented block ended execution
-
# id # => String, unique ID for this notification
-
# payload # => Hash, the payload
-
# end
-
#
-
# For instance, let's store all "render" events in an array:
-
#
-
# events = []
-
#
-
# ActiveSupport::Notifications.subscribe('render') do |*args|
-
# events << ActiveSupport::Notifications::Event.new(*args)
-
# end
-
#
-
# That code returns right away, you are just subscribing to "render" events.
-
# The block is saved and will be called whenever someone instruments "render":
-
#
-
# ActiveSupport::Notifications.instrument('render', extra: :information) do
-
# render text: 'Foo'
-
# end
-
#
-
# event = events.first
-
# event.name # => "render"
-
# event.duration # => 10 (in milliseconds)
-
# event.payload # => { extra: :information }
-
#
-
# The block in the <tt>subscribe</tt> call gets the name of the event, start
-
# timestamp, end timestamp, a string with a unique identifier for that event
-
# (something like "535801666f04d0298cd6"), and a hash with the payload, in
-
# that order.
-
#
-
# If an exception happens during that particular instrumentation the payload will
-
# have a key <tt>:exception</tt> with an array of two elements as value: a string with
-
# the name of the exception class, and the exception message.
-
#
-
# As the previous example depicts, the class <tt>ActiveSupport::Notifications::Event</tt>
-
# is able to take the arguments as they come and provide an object-oriented
-
# interface to that data.
-
#
-
# It is also possible to pass an object as the second parameter passed to the
-
# <tt>subscribe</tt> method instead of a block:
-
#
-
# module ActionController
-
# class PageRequest
-
# def call(name, started, finished, unique_id, payload)
-
# Rails.logger.debug ['notification:', name, started, finished, unique_id, payload].join(' ')
-
# end
-
# end
-
# end
-
#
-
# ActiveSupport::Notifications.subscribe('process_action.action_controller', ActionController::PageRequest.new)
-
#
-
# resulting in the following output within the logs including a hash with the payload:
-
#
-
# notification: process_action.action_controller 2012-04-13 01:08:35 +0300 2012-04-13 01:08:35 +0300 af358ed7fab884532ec7 {
-
# controller: "Devise::SessionsController",
-
# action: "new",
-
# params: {"action"=>"new", "controller"=>"devise/sessions"},
-
# format: :html,
-
# method: "GET",
-
# path: "/login/sign_in",
-
# status: 200,
-
# view_runtime: 279.3080806732178,
-
# db_runtime: 40.053
-
# }
-
#
-
# You can also subscribe to all events whose name matches a certain regexp:
-
#
-
# ActiveSupport::Notifications.subscribe(/render/) do |*args|
-
# ...
-
# end
-
#
-
# and even pass no argument to <tt>subscribe</tt>, in which case you are subscribing
-
# to all events.
-
#
-
# == Temporary Subscriptions
-
#
-
# Sometimes you do not want to subscribe to an event for the entire life of
-
# the application. There are two ways to unsubscribe.
-
#
-
# WARNING: The instrumentation framework is designed for long-running subscribers,
-
# use this feature sparingly because it wipes some internal caches and that has
-
# a negative impact on performance.
-
#
-
# === Subscribe While a Block Runs
-
#
-
# You can subscribe to some event temporarily while some block runs. For
-
# example, in
-
#
-
# callback = lambda {|*args| ... }
-
# ActiveSupport::Notifications.subscribed(callback, "sql.active_record") do
-
# ...
-
# end
-
#
-
# the callback will be called for all "sql.active_record" events instrumented
-
# during the execution of the block. The callback is unsubscribed automatically
-
# after that.
-
#
-
# === Manual Unsubscription
-
#
-
# The +subscribe+ method returns a subscriber object:
-
#
-
# subscriber = ActiveSupport::Notifications.subscribe("render") do |*args|
-
# ...
-
# end
-
#
-
# To prevent that block from being called anymore, just unsubscribe passing
-
# that reference:
-
#
-
# ActiveSupport::Notifications.unsubscribe(subscriber)
-
#
-
# == Default Queue
-
#
-
# Notifications ships with a queue implementation that consumes and publishes events
-
# to all log subscribers. You can use any queue implementation you want.
-
#
-
2
module Notifications
-
2
class << self
-
2
attr_accessor :notifier
-
-
2
def publish(name, *args)
-
notifier.publish(name, *args)
-
end
-
-
2
def instrument(name, payload = {})
-
186
if notifier.listening?(name)
-
214
instrumenter.instrument(name, payload) { yield payload if block_given? }
-
else
-
79
yield payload if block_given?
-
end
-
end
-
-
2
def subscribe(*args, &block)
-
101
notifier.subscribe(*args, &block)
-
end
-
-
2
def subscribed(callback, *args, &block)
-
subscriber = subscribe(*args, &callback)
-
yield
-
ensure
-
unsubscribe(subscriber)
-
end
-
-
2
def unsubscribe(args)
-
30
notifier.unsubscribe(args)
-
end
-
-
2
def instrumenter
-
135
InstrumentationRegistry.instance.instrumenter_for(notifier)
-
end
-
end
-
-
# This class is a registry which holds all of the +Instrumenter+ objects
-
# in a particular thread local. To access the +Instrumenter+ object for a
-
# particular +notifier+, you can call the following method:
-
#
-
# InstrumentationRegistry.instrumenter_for(notifier)
-
#
-
# The instrumenters for multiple notifiers are held in a single instance of
-
# this class.
-
2
class InstrumentationRegistry # :nodoc:
-
2
extend ActiveSupport::PerThreadRegistry
-
-
2
def initialize
-
2
@registry = {}
-
end
-
-
2
def instrumenter_for(notifier)
-
135
@registry[notifier] ||= Instrumenter.new(notifier)
-
end
-
end
-
-
2
self.notifier = Fanout.new
-
end
-
end
-
2
require 'mutex_m'
-
2
require 'thread_safe'
-
-
2
module ActiveSupport
-
2
module Notifications
-
# This is a default queue implementation that ships with Notifications.
-
# It just pushes events to all registered log subscribers.
-
#
-
# This class is thread safe. All methods are reentrant.
-
2
class Fanout
-
2
include Mutex_m
-
-
2
def initialize
-
2
@subscribers = []
-
2
@listeners_for = ThreadSafe::Cache.new
-
2
super
-
end
-
-
2
def subscribe(pattern = nil, block = Proc.new)
-
101
subscriber = Subscribers.new pattern, block
-
101
synchronize do
-
101
@subscribers << subscriber
-
101
@listeners_for.clear
-
end
-
101
subscriber
-
end
-
-
2
def unsubscribe(subscriber)
-
30
synchronize do
-
916
@subscribers.reject! { |s| s.matches?(subscriber) }
-
30
@listeners_for.clear
-
end
-
end
-
-
2
def start(name, id, payload)
-
3151
listeners_for(name).each { |s| s.start(name, id, payload) }
-
end
-
-
2
def finish(name, id, payload)
-
3151
listeners_for(name).each { |s| s.finish(name, id, payload) }
-
end
-
-
2
def publish(name, *args)
-
listeners_for(name).each { |s| s.publish(name, *args) }
-
end
-
-
2
def listeners_for(name)
-
# this is correctly done double-checked locking (ThreadSafe::Cache's lookups have volatile semantics)
-
@listeners_for[name] || synchronize do
-
# use synchronisation when accessing @subscribers
-
2551
@listeners_for[name] ||= @subscribers.select { |s| s.subscribed_to?(name) }
-
2360
end
-
end
-
-
2
def listening?(name)
-
186
listeners_for(name).any?
-
end
-
-
# This is a sync queue, so there is no waiting.
-
2
def wait
-
end
-
-
2
module Subscribers # :nodoc:
-
2
def self.new(pattern, listener)
-
101
if listener.respond_to?(:start) and listener.respond_to?(:finish)
-
56
subscriber = Evented.new pattern, listener
-
else
-
45
subscriber = Timed.new pattern, listener
-
end
-
-
101
unless pattern
-
AllMessages.new(subscriber)
-
else
-
101
subscriber
-
end
-
end
-
-
2
class Evented #:nodoc:
-
2
def initialize(pattern, delegate)
-
101
@pattern = pattern
-
101
@delegate = delegate
-
101
@can_publish = delegate.respond_to?(:publish)
-
end
-
-
2
def publish(name, *args)
-
if @can_publish
-
@delegate.publish name, *args
-
end
-
end
-
-
2
def start(name, id, payload)
-
2009
@delegate.start name, id, payload
-
end
-
-
2
def finish(name, id, payload)
-
2009
@delegate.finish name, id, payload
-
end
-
-
2
def subscribed_to?(name)
-
2466
@pattern === name.to_s
-
end
-
-
2
def matches?(subscriber_or_name)
-
self === subscriber_or_name ||
-
886
@pattern && @pattern === subscriber_or_name
-
end
-
end
-
-
2
class Timed < Evented
-
2
def publish(name, *args)
-
@delegate.call name, *args
-
end
-
-
2
def start(name, id, payload)
-
55
timestack = Thread.current[:_timestack] ||= []
-
55
timestack.push Time.now
-
end
-
-
2
def finish(name, id, payload)
-
55
timestack = Thread.current[:_timestack]
-
55
started = timestack.pop
-
55
@delegate.call(name, started, Time.now, id, payload)
-
end
-
end
-
-
2
class AllMessages # :nodoc:
-
2
def initialize(delegate)
-
@delegate = delegate
-
end
-
-
2
def start(name, id, payload)
-
@delegate.start name, id, payload
-
end
-
-
2
def finish(name, id, payload)
-
@delegate.finish name, id, payload
-
end
-
-
2
def publish(name, *args)
-
@delegate.publish name, *args
-
end
-
-
2
def subscribed_to?(name)
-
true
-
end
-
-
2
alias :matches? :===
-
end
-
end
-
end
-
end
-
end
-
2
require 'securerandom'
-
-
2
module ActiveSupport
-
2
module Notifications
-
# Instrumenters are stored in a thread local.
-
2
class Instrumenter
-
2
attr_reader :id
-
-
2
def initialize(notifier)
-
2
@id = unique_id
-
2
@notifier = notifier
-
end
-
-
# Instrument the given block by measuring the time taken to execute it
-
# and publish it. Notice that events get sent even if an error occurs
-
# in the passed-in block.
-
2
def instrument(name, payload={})
-
1074
start name, payload
-
1074
begin
-
1074
yield payload
-
rescue Exception => e
-
payload[:exception] = [e.class.name, e.message]
-
raise e
-
ensure
-
1074
finish name, payload
-
1074
end
-
end
-
-
# Send a start notification with +name+ and +payload+.
-
2
def start(name, payload)
-
1087
@notifier.start name, @id, payload
-
end
-
-
# Send a finish notification with +name+ and +payload+.
-
2
def finish(name, payload)
-
1087
@notifier.finish name, @id, payload
-
end
-
-
2
private
-
-
2
def unique_id
-
2
SecureRandom.hex(10)
-
end
-
end
-
-
2
class Event
-
2
attr_reader :name, :time, :transaction_id, :payload, :children
-
2
attr_accessor :end
-
-
2
def initialize(name, start, ending, transaction_id, payload)
-
1042
@name = name
-
1042
@payload = payload.dup
-
1042
@time = start
-
1042
@transaction_id = transaction_id
-
1042
@end = ending
-
1042
@children = []
-
1042
@duration = nil
-
end
-
-
2
def duration
-
1956
@duration ||= 1000.0 * (self.end - time)
-
end
-
-
2
def <<(event)
-
@children << event
-
end
-
-
2
def parent_of?(event)
-
@children.include? event
-
end
-
end
-
end
-
end
-
2
module ActiveSupport
-
2
module NumberHelper
-
2
extend ActiveSupport::Autoload
-
-
2
eager_autoload do
-
2
autoload :NumberConverter
-
2
autoload :NumberToRoundedConverter
-
2
autoload :NumberToDelimitedConverter
-
2
autoload :NumberToHumanConverter
-
2
autoload :NumberToHumanSizeConverter
-
2
autoload :NumberToPhoneConverter
-
2
autoload :NumberToCurrencyConverter
-
2
autoload :NumberToPercentageConverter
-
end
-
-
2
extend self
-
-
# Formats a +number+ into a US phone number (e.g., (555)
-
# 123-9876). You can customize the format in the +options+ hash.
-
#
-
# ==== Options
-
#
-
# * <tt>:area_code</tt> - Adds parentheses around the area code.
-
# * <tt>:delimiter</tt> - Specifies the delimiter to use
-
# (defaults to "-").
-
# * <tt>:extension</tt> - Specifies an extension to add to the
-
# end of the generated number.
-
# * <tt>:country_code</tt> - Sets the country code for the phone
-
# number.
-
# ==== Examples
-
#
-
# number_to_phone(5551234) # => 555-1234
-
# number_to_phone('5551234') # => 555-1234
-
# number_to_phone(1235551234) # => 123-555-1234
-
# number_to_phone(1235551234, area_code: true) # => (123) 555-1234
-
# number_to_phone(1235551234, delimiter: ' ') # => 123 555 1234
-
# number_to_phone(1235551234, area_code: true, extension: 555) # => (123) 555-1234 x 555
-
# number_to_phone(1235551234, country_code: 1) # => +1-123-555-1234
-
# number_to_phone('123a456') # => 123a456
-
#
-
# number_to_phone(1235551234, country_code: 1, extension: 1343, delimiter: '.')
-
# # => +1.123.555.1234 x 1343
-
2
def number_to_phone(number, options = {})
-
NumberToPhoneConverter.convert(number, options)
-
end
-
-
# Formats a +number+ into a currency string (e.g., $13.65). You
-
# can customize the format in the +options+ hash.
-
#
-
# ==== Options
-
#
-
# * <tt>:locale</tt> - Sets the locale to be used for formatting
-
# (defaults to current locale).
-
# * <tt>:precision</tt> - Sets the level of precision (defaults
-
# to 2).
-
# * <tt>:unit</tt> - Sets the denomination of the currency
-
# (defaults to "$").
-
# * <tt>:separator</tt> - Sets the separator between the units
-
# (defaults to ".").
-
# * <tt>:delimiter</tt> - Sets the thousands delimiter (defaults
-
# to ",").
-
# * <tt>:format</tt> - Sets the format for non-negative numbers
-
# (defaults to "%u%n"). Fields are <tt>%u</tt> for the
-
# currency, and <tt>%n</tt> for the number.
-
# * <tt>:negative_format</tt> - Sets the format for negative
-
# numbers (defaults to prepending an hyphen to the formatted
-
# number given by <tt>:format</tt>). Accepts the same fields
-
# than <tt>:format</tt>, except <tt>%n</tt> is here the
-
# absolute value of the number.
-
#
-
# ==== Examples
-
#
-
# number_to_currency(1234567890.50) # => $1,234,567,890.50
-
# number_to_currency(1234567890.506) # => $1,234,567,890.51
-
# number_to_currency(1234567890.506, precision: 3) # => $1,234,567,890.506
-
# number_to_currency(1234567890.506, locale: :fr) # => 1 234 567 890,51 €
-
# number_to_currency('123a456') # => $123a456
-
#
-
# number_to_currency(-1234567890.50, negative_format: '(%u%n)')
-
# # => ($1,234,567,890.50)
-
# number_to_currency(1234567890.50, unit: '£', separator: ',', delimiter: '')
-
# # => £1234567890,50
-
# number_to_currency(1234567890.50, unit: '£', separator: ',', delimiter: '', format: '%n %u')
-
# # => 1234567890,50 £
-
2
def number_to_currency(number, options = {})
-
NumberToCurrencyConverter.convert(number, options)
-
end
-
-
# Formats a +number+ as a percentage string (e.g., 65%). You can
-
# customize the format in the +options+ hash.
-
#
-
# ==== Options
-
#
-
# * <tt>:locale</tt> - Sets the locale to be used for formatting
-
# (defaults to current locale).
-
# * <tt>:precision</tt> - Sets the precision of the number
-
# (defaults to 3).
-
# * <tt>:significant</tt> - If +true+, precision will be the #
-
# of significant_digits. If +false+, the # of fractional
-
# digits (defaults to +false+).
-
# * <tt>:separator</tt> - Sets the separator between the
-
# fractional and integer digits (defaults to ".").
-
# * <tt>:delimiter</tt> - Sets the thousands delimiter (defaults
-
# to "").
-
# * <tt>:strip_insignificant_zeros</tt> - If +true+ removes
-
# insignificant zeros after the decimal separator (defaults to
-
# +false+).
-
# * <tt>:format</tt> - Specifies the format of the percentage
-
# string The number field is <tt>%n</tt> (defaults to "%n%").
-
#
-
# ==== Examples
-
#
-
# number_to_percentage(100) # => 100.000%
-
# number_to_percentage('98') # => 98.000%
-
# number_to_percentage(100, precision: 0) # => 100%
-
# number_to_percentage(1000, delimiter: '.', separator: ',') # => 1.000,000%
-
# number_to_percentage(302.24398923423, precision: 5) # => 302.24399%
-
# number_to_percentage(1000, locale: :fr) # => 1 000,000%
-
# number_to_percentage('98a') # => 98a%
-
# number_to_percentage(100, format: '%n %') # => 100 %
-
2
def number_to_percentage(number, options = {})
-
NumberToPercentageConverter.convert(number, options)
-
end
-
-
# Formats a +number+ with grouped thousands using +delimiter+
-
# (e.g., 12,324). You can customize the format in the +options+
-
# hash.
-
#
-
# ==== Options
-
#
-
# * <tt>:locale</tt> - Sets the locale to be used for formatting
-
# (defaults to current locale).
-
# * <tt>:delimiter</tt> - Sets the thousands delimiter (defaults
-
# to ",").
-
# * <tt>:separator</tt> - Sets the separator between the
-
# fractional and integer digits (defaults to ".").
-
#
-
# ==== Examples
-
#
-
# number_to_delimited(12345678) # => 12,345,678
-
# number_to_delimited('123456') # => 123,456
-
# number_to_delimited(12345678.05) # => 12,345,678.05
-
# number_to_delimited(12345678, delimiter: '.') # => 12.345.678
-
# number_to_delimited(12345678, delimiter: ',') # => 12,345,678
-
# number_to_delimited(12345678.05, separator: ' ') # => 12,345,678 05
-
# number_to_delimited(12345678.05, locale: :fr) # => 12 345 678,05
-
# number_to_delimited('112a') # => 112a
-
# number_to_delimited(98765432.98, delimiter: ' ', separator: ',')
-
# # => 98 765 432,98
-
2
def number_to_delimited(number, options = {})
-
NumberToDelimitedConverter.convert(number, options)
-
end
-
-
# Formats a +number+ with the specified level of
-
# <tt>:precision</tt> (e.g., 112.32 has a precision of 2 if
-
# +:significant+ is +false+, and 5 if +:significant+ is +true+).
-
# You can customize the format in the +options+ hash.
-
#
-
# ==== Options
-
#
-
# * <tt>:locale</tt> - Sets the locale to be used for formatting
-
# (defaults to current locale).
-
# * <tt>:precision</tt> - Sets the precision of the number
-
# (defaults to 3).
-
# * <tt>:significant</tt> - If +true+, precision will be the #
-
# of significant_digits. If +false+, the # of fractional
-
# digits (defaults to +false+).
-
# * <tt>:separator</tt> - Sets the separator between the
-
# fractional and integer digits (defaults to ".").
-
# * <tt>:delimiter</tt> - Sets the thousands delimiter (defaults
-
# to "").
-
# * <tt>:strip_insignificant_zeros</tt> - If +true+ removes
-
# insignificant zeros after the decimal separator (defaults to
-
# +false+).
-
#
-
# ==== Examples
-
#
-
# number_to_rounded(111.2345) # => 111.235
-
# number_to_rounded(111.2345, precision: 2) # => 111.23
-
# number_to_rounded(13, precision: 5) # => 13.00000
-
# number_to_rounded(389.32314, precision: 0) # => 389
-
# number_to_rounded(111.2345, significant: true) # => 111
-
# number_to_rounded(111.2345, precision: 1, significant: true) # => 100
-
# number_to_rounded(13, precision: 5, significant: true) # => 13.000
-
# number_to_rounded(111.234, locale: :fr) # => 111,234
-
#
-
# number_to_rounded(13, precision: 5, significant: true, strip_insignificant_zeros: true)
-
# # => 13
-
#
-
# number_to_rounded(389.32314, precision: 4, significant: true) # => 389.3
-
# number_to_rounded(1111.2345, precision: 2, separator: ',', delimiter: '.')
-
# # => 1.111,23
-
2
def number_to_rounded(number, options = {})
-
NumberToRoundedConverter.convert(number, options)
-
end
-
-
# Formats the bytes in +number+ into a more understandable
-
# representation (e.g., giving it 1500 yields 1.5 KB). This
-
# method is useful for reporting file sizes to users. You can
-
# customize the format in the +options+ hash.
-
#
-
# See <tt>number_to_human</tt> if you want to pretty-print a
-
# generic number.
-
#
-
# ==== Options
-
#
-
# * <tt>:locale</tt> - Sets the locale to be used for formatting
-
# (defaults to current locale).
-
# * <tt>:precision</tt> - Sets the precision of the number
-
# (defaults to 3).
-
# * <tt>:significant</tt> - If +true+, precision will be the #
-
# of significant_digits. If +false+, the # of fractional
-
# digits (defaults to +true+)
-
# * <tt>:separator</tt> - Sets the separator between the
-
# fractional and integer digits (defaults to ".").
-
# * <tt>:delimiter</tt> - Sets the thousands delimiter (defaults
-
# to "").
-
# * <tt>:strip_insignificant_zeros</tt> - If +true+ removes
-
# insignificant zeros after the decimal separator (defaults to
-
# +true+)
-
# * <tt>:prefix</tt> - If +:si+ formats the number using the SI
-
# prefix (defaults to :binary)
-
#
-
# ==== Examples
-
#
-
# number_to_human_size(123) # => 123 Bytes
-
# number_to_human_size(1234) # => 1.21 KB
-
# number_to_human_size(12345) # => 12.1 KB
-
# number_to_human_size(1234567) # => 1.18 MB
-
# number_to_human_size(1234567890) # => 1.15 GB
-
# number_to_human_size(1234567890123) # => 1.12 TB
-
# number_to_human_size(1234567, precision: 2) # => 1.2 MB
-
# number_to_human_size(483989, precision: 2) # => 470 KB
-
# number_to_human_size(1234567, precision: 2, separator: ',') # => 1,2 MB
-
#
-
# Non-significant zeros after the fractional separator are stripped out by
-
# default (set <tt>:strip_insignificant_zeros</tt> to +false+ to change that):
-
#
-
# number_to_human_size(1234567890123, precision: 5) # => "1.1229 TB"
-
# number_to_human_size(524288000, precision: 5) # => "500 MB"
-
2
def number_to_human_size(number, options = {})
-
NumberToHumanSizeConverter.convert(number, options)
-
end
-
-
# Pretty prints (formats and approximates) a number in a way it
-
# is more readable by humans (eg.: 1200000000 becomes "1.2
-
# Billion"). This is useful for numbers that can get very large
-
# (and too hard to read).
-
#
-
# See <tt>number_to_human_size</tt> if you want to print a file
-
# size.
-
#
-
# You can also define your own unit-quantifier names if you want
-
# to use other decimal units (eg.: 1500 becomes "1.5
-
# kilometers", 0.150 becomes "150 milliliters", etc). You may
-
# define a wide range of unit quantifiers, even fractional ones
-
# (centi, deci, mili, etc).
-
#
-
# ==== Options
-
#
-
# * <tt>:locale</tt> - Sets the locale to be used for formatting
-
# (defaults to current locale).
-
# * <tt>:precision</tt> - Sets the precision of the number
-
# (defaults to 3).
-
# * <tt>:significant</tt> - If +true+, precision will be the #
-
# of significant_digits. If +false+, the # of fractional
-
# digits (defaults to +true+)
-
# * <tt>:separator</tt> - Sets the separator between the
-
# fractional and integer digits (defaults to ".").
-
# * <tt>:delimiter</tt> - Sets the thousands delimiter (defaults
-
# to "").
-
# * <tt>:strip_insignificant_zeros</tt> - If +true+ removes
-
# insignificant zeros after the decimal separator (defaults to
-
# +true+)
-
# * <tt>:units</tt> - A Hash of unit quantifier names. Or a
-
# string containing an i18n scope where to find this hash. It
-
# might have the following keys:
-
# * *integers*: <tt>:unit</tt>, <tt>:ten</tt>,
-
# *<tt>:hundred</tt>, <tt>:thousand</tt>, <tt>:million</tt>,
-
# *<tt>:billion</tt>, <tt>:trillion</tt>,
-
# *<tt>:quadrillion</tt>
-
# * *fractionals*: <tt>:deci</tt>, <tt>:centi</tt>,
-
# *<tt>:mili</tt>, <tt>:micro</tt>, <tt>:nano</tt>,
-
# *<tt>:pico</tt>, <tt>:femto</tt>
-
# * <tt>:format</tt> - Sets the format of the output string
-
# (defaults to "%n %u"). The field types are:
-
# * %u - The quantifier (ex.: 'thousand')
-
# * %n - The number
-
#
-
# ==== Examples
-
#
-
# number_to_human(123) # => "123"
-
# number_to_human(1234) # => "1.23 Thousand"
-
# number_to_human(12345) # => "12.3 Thousand"
-
# number_to_human(1234567) # => "1.23 Million"
-
# number_to_human(1234567890) # => "1.23 Billion"
-
# number_to_human(1234567890123) # => "1.23 Trillion"
-
# number_to_human(1234567890123456) # => "1.23 Quadrillion"
-
# number_to_human(1234567890123456789) # => "1230 Quadrillion"
-
# number_to_human(489939, precision: 2) # => "490 Thousand"
-
# number_to_human(489939, precision: 4) # => "489.9 Thousand"
-
# number_to_human(1234567, precision: 4,
-
# significant: false) # => "1.2346 Million"
-
# number_to_human(1234567, precision: 1,
-
# separator: ',',
-
# significant: false) # => "1,2 Million"
-
#
-
# Non-significant zeros after the decimal separator are stripped
-
# out by default (set <tt>:strip_insignificant_zeros</tt> to
-
# +false+ to change that):
-
#
-
# number_to_human(12345012345, significant_digits: 6) # => "12.345 Billion"
-
# number_to_human(500000000, precision: 5) # => "500 Million"
-
#
-
# ==== Custom Unit Quantifiers
-
#
-
# You can also use your own custom unit quantifiers:
-
# number_to_human(500000, units: { unit: 'ml', thousand: 'lt' }) # => "500 lt"
-
#
-
# If in your I18n locale you have:
-
#
-
# distance:
-
# centi:
-
# one: "centimeter"
-
# other: "centimeters"
-
# unit:
-
# one: "meter"
-
# other: "meters"
-
# thousand:
-
# one: "kilometer"
-
# other: "kilometers"
-
# billion: "gazillion-distance"
-
#
-
# Then you could do:
-
#
-
# number_to_human(543934, units: :distance) # => "544 kilometers"
-
# number_to_human(54393498, units: :distance) # => "54400 kilometers"
-
# number_to_human(54393498000, units: :distance) # => "54.4 gazillion-distance"
-
# number_to_human(343, units: :distance, precision: 1) # => "300 meters"
-
# number_to_human(1, units: :distance) # => "1 meter"
-
# number_to_human(0.34, units: :distance) # => "34 centimeters"
-
2
def number_to_human(number, options = {})
-
NumberToHumanConverter.convert(number, options)
-
end
-
end
-
end
-
2
require 'active_support/core_ext/hash/deep_merge'
-
-
2
module ActiveSupport
-
2
class OptionMerger #:nodoc:
-
2
instance_methods.each do |method|
-
172
undef_method(method) if method !~ /^(__|instance_eval|class|object_id)/
-
end
-
-
2
def initialize(context, options)
-
6
@context, @options = context, options
-
end
-
-
2
private
-
2
def method_missing(method, *arguments, &block)
-
24
if arguments.first.is_a?(Proc)
-
proc = arguments.pop
-
arguments << lambda { |*args| @options.deep_merge(proc.call(*args)) }
-
else
-
24
arguments << (arguments.last.respond_to?(:to_hash) ? @options.deep_merge(arguments.pop) : @options.dup)
-
end
-
-
24
@context.__send__(method, *arguments, &block)
-
end
-
end
-
end
-
2
require 'yaml'
-
-
2
YAML.add_builtin_type("omap") do |type, val|
-
ActiveSupport::OrderedHash[val.map{ |v| v.to_a.first }]
-
end
-
-
2
module ActiveSupport
-
# <tt>ActiveSupport::OrderedHash</tt> implements a hash that preserves
-
# insertion order.
-
#
-
# oh = ActiveSupport::OrderedHash.new
-
# oh[:a] = 1
-
# oh[:b] = 2
-
# oh.keys # => [:a, :b], this order is guaranteed
-
#
-
# Also, maps the +omap+ feature for YAML files
-
# (See http://yaml.org/type/omap.html) to support ordered items
-
# when loading from yaml.
-
#
-
# <tt>ActiveSupport::OrderedHash</tt> is namespaced to prevent conflicts
-
# with other implementations.
-
2
class OrderedHash < ::Hash
-
2
def to_yaml_type
-
"!tag:yaml.org,2002:omap"
-
end
-
-
2
def encode_with(coder)
-
coder.represent_seq '!omap', map { |k,v| { k => v } }
-
end
-
-
2
def select(*args, &block)
-
dup.tap { |hash| hash.select!(*args, &block) }
-
end
-
-
2
def reject(*args, &block)
-
dup.tap { |hash| hash.reject!(*args, &block) }
-
end
-
-
2
def nested_under_indifferent_access
-
self
-
end
-
-
# Returns true to make sure that this hash is extractable via <tt>Array#extract_options!</tt>
-
2
def extractable_options?
-
true
-
end
-
end
-
end
-
2
module ActiveSupport
-
# Usually key value pairs are handled something like this:
-
#
-
# h = {}
-
# h[:boy] = 'John'
-
# h[:girl] = 'Mary'
-
# h[:boy] # => 'John'
-
# h[:girl] # => 'Mary'
-
#
-
# Using +OrderedOptions+, the above code could be reduced to:
-
#
-
# h = ActiveSupport::OrderedOptions.new
-
# h.boy = 'John'
-
# h.girl = 'Mary'
-
# h.boy # => 'John'
-
# h.girl # => 'Mary'
-
2
class OrderedOptions < Hash
-
2
alias_method :_get, :[] # preserve the original #[] method
-
2
protected :_get # make it protected
-
-
2
def []=(key, value)
-
232
super(key.to_sym, value)
-
end
-
-
2
def [](key)
-
265
super(key.to_sym)
-
end
-
-
2
def method_missing(name, *args)
-
497
name_string = name.to_s
-
497
if name_string.chomp!('=')
-
232
self[name_string] = args.first
-
else
-
265
self[name]
-
end
-
end
-
-
2
def respond_to_missing?(name, include_private)
-
true
-
end
-
end
-
-
# +InheritableOptions+ provides a constructor to build an +OrderedOptions+
-
# hash inherited from another hash.
-
#
-
# Use this if you already have some hash and you want to create a new one based on it.
-
#
-
# h = ActiveSupport::InheritableOptions.new({ girl: 'Mary', boy: 'John' })
-
# h.girl # => 'Mary'
-
# h.boy # => 'John'
-
2
class InheritableOptions < OrderedOptions
-
2
def initialize(parent = nil)
-
90
if parent.kind_of?(OrderedOptions)
-
# use the faster _get when dealing with OrderedOptions
-
606
super() { |h,k| parent._get(k) }
-
26
elsif parent
-
super() { |h,k| parent[k] }
-
else
-
26
super()
-
end
-
end
-
-
2
def inheritable_copy
-
64
self.class.new(self)
-
end
-
end
-
end
-
2
module ActiveSupport
-
# This module is used to encapsulate access to thread local variables.
-
#
-
# Instead of polluting the thread locals namespace:
-
#
-
# Thread.current[:connection_handler]
-
#
-
# you define a class that extends this module:
-
#
-
# module ActiveRecord
-
# class RuntimeRegistry
-
# extend ActiveSupport::PerThreadRegistry
-
#
-
# attr_accessor :connection_handler
-
# end
-
# end
-
#
-
# and invoke the declared instance accessors as class methods. So
-
#
-
# ActiveRecord::RuntimeRegistry.connection_handler = connection_handler
-
#
-
# sets a connection handler local to the current thread, and
-
#
-
# ActiveRecord::RuntimeRegistry.connection_handler
-
#
-
# returns a connection handler local to the current thread.
-
#
-
# This feature is accomplished by instantiating the class and storing the
-
# instance as a thread local keyed by the class name. In the example above
-
# a key "ActiveRecord::RuntimeRegistry" is stored in <tt>Thread.current</tt>.
-
# The class methods proxy to said thread local instance.
-
#
-
# If the class has an initializer, it must accept no arguments.
-
2
module PerThreadRegistry
-
2
def self.extended(object)
-
12
object.instance_variable_set '@per_thread_registry_key', object.name.freeze
-
end
-
-
2
def instance
-
16239
Thread.current[@per_thread_registry_key] ||= new
-
end
-
-
2
protected
-
2
def method_missing(name, *args, &block) # :nodoc:
-
# Caches the method definition as a singleton method of the receiver.
-
6
define_singleton_method(name) do |*a, &b|
-
1991
instance.public_send(name, *a, &b)
-
end
-
-
6
send(name, *args, &block)
-
end
-
end
-
end
-
2
module ActiveSupport
-
# A class with no predefined methods that behaves similarly to Builder's
-
# BlankSlate. Used for proxy classes.
-
2
class ProxyObject < ::BasicObject
-
2
undef_method :==
-
2
undef_method :equal?
-
-
# Let ActiveSupport::ProxyObject at least raise exceptions.
-
2
def raise(*args)
-
::Object.send(:raise, *args)
-
end
-
end
-
end
-
# This is private interface.
-
#
-
# Rails components cherry pick from Active Support as needed, but there are a
-
# few features that are used for sure some way or another and it is not worth
-
# to put individual requires absolutely everywhere. Think blank? for example.
-
#
-
# This file is loaded by every Rails component except Active Support itself,
-
# but it does not belong to the Rails public interface. It is internal to
-
# Rails and can change anytime.
-
-
# Defines Object#blank? and Object#present?.
-
2
require 'active_support/core_ext/object/blank'
-
-
# Rails own autoload, eager_load, etc.
-
2
require 'active_support/dependencies/autoload'
-
-
# Support for ClassMethods and the included macro.
-
2
require 'active_support/concern'
-
-
# Defines Class#class_attribute.
-
2
require 'active_support/core_ext/class/attribute'
-
-
# Defines Module#delegate.
-
2
require 'active_support/core_ext/module/delegation'
-
-
# Defines ActiveSupport::Deprecation.
-
2
require 'active_support/deprecation'
-
2
require "active_support"
-
2
require "active_support/i18n_railtie"
-
-
2
module ActiveSupport
-
2
class Railtie < Rails::Railtie # :nodoc:
-
2
config.active_support = ActiveSupport::OrderedOptions.new
-
-
2
config.eager_load_namespaces << ActiveSupport
-
-
2
initializer "active_support.deprecation_behavior" do |app|
-
2
if deprecation = app.config.active_support.deprecation
-
2
ActiveSupport::Deprecation.behavior = deprecation
-
end
-
end
-
-
# Sets the default value for Time.zone
-
# If assigned value cannot be matched to a TimeZone, an exception will be raised.
-
2
initializer "active_support.initialize_time_zone" do |app|
-
2
require 'active_support/core_ext/time/zones'
-
2
zone_default = Time.find_zone!(app.config.time_zone)
-
-
2
unless zone_default
-
raise 'Value assigned to config.time_zone not recognized. ' \
-
'Run "rake -D time" for a list of tasks for finding appropriate time zone names.'
-
end
-
-
2
Time.zone_default = zone_default
-
end
-
-
# Sets the default week start
-
# If assigned value is not a valid day symbol (e.g. :sunday, :monday, ...), an exception will be raised.
-
2
initializer "active_support.initialize_beginning_of_week" do |app|
-
2
require 'active_support/core_ext/date/calculations'
-
2
beginning_of_week_default = Date.find_beginning_of_week!(app.config.beginning_of_week)
-
-
2
Date.beginning_of_week_default = beginning_of_week_default
-
end
-
-
2
initializer "active_support.set_configs" do |app|
-
2
app.config.active_support.each do |k, v|
-
2
k = "#{k}="
-
2
ActiveSupport.send(k, v) if ActiveSupport.respond_to? k
-
end
-
end
-
end
-
end
-
2
require 'active_support/concern'
-
2
require 'active_support/core_ext/class/attribute'
-
2
require 'active_support/core_ext/string/inflections'
-
2
require 'active_support/core_ext/array/extract_options'
-
-
2
module ActiveSupport
-
# Rescuable module adds support for easier exception handling.
-
2
module Rescuable
-
2
extend Concern
-
-
2
included do
-
2
class_attribute :rescue_handlers
-
2
self.rescue_handlers = []
-
end
-
-
2
module ClassMethods
-
# Rescue exceptions raised in controller actions.
-
#
-
# <tt>rescue_from</tt> receives a series of exception classes or class
-
# names, and a trailing <tt>:with</tt> option with the name of a method
-
# or a Proc object to be called to handle them. Alternatively a block can
-
# be given.
-
#
-
# Handlers that take one argument will be called with the exception, so
-
# that the exception can be inspected when dealing with it.
-
#
-
# Handlers are inherited. They are searched from right to left, from
-
# bottom to top, and up the hierarchy. The handler of the first class for
-
# which <tt>exception.is_a?(klass)</tt> holds true is the one invoked, if
-
# any.
-
#
-
# class ApplicationController < ActionController::Base
-
# rescue_from User::NotAuthorized, with: :deny_access # self defined exception
-
# rescue_from ActiveRecord::RecordInvalid, with: :show_errors
-
#
-
# rescue_from 'MyAppError::Base' do |exception|
-
# render xml: exception, status: 500
-
# end
-
#
-
# protected
-
# def deny_access
-
# ...
-
# end
-
#
-
# def show_errors(exception)
-
# exception.record.new_record? ? ...
-
# end
-
# end
-
#
-
# Exceptions raised inside exception handlers are not propagated up.
-
2
def rescue_from(*klasses, &block)
-
options = klasses.extract_options!
-
-
unless options.has_key?(:with)
-
if block_given?
-
options[:with] = block
-
else
-
raise ArgumentError, "Need a handler. Supply an options hash that has a :with key as the last argument."
-
end
-
end
-
-
klasses.each do |klass|
-
key = if klass.is_a?(Class) && klass <= Exception
-
klass.name
-
elsif klass.is_a?(String)
-
klass
-
else
-
raise ArgumentError, "#{klass} is neither an Exception nor a String"
-
end
-
-
# put the new handler at the end because the list is read in reverse
-
self.rescue_handlers += [[key, options[:with]]]
-
end
-
end
-
end
-
-
# Tries to rescue the exception by looking up and calling a registered handler.
-
2
def rescue_with_handler(exception)
-
if handler = handler_for_rescue(exception)
-
handler.arity != 0 ? handler.call(exception) : handler.call
-
true # don't rely on the return value of the handler
-
end
-
end
-
-
2
def handler_for_rescue(exception)
-
# We go from right to left because pairs are pushed onto rescue_handlers
-
# as rescue_from declarations are found.
-
_, rescuer = self.class.rescue_handlers.reverse.detect do |klass_name, handler|
-
# The purpose of allowing strings in rescue_from is to support the
-
# declaration of handler associations for exception classes whose
-
# definition is yet unknown.
-
#
-
# Since this loop needs the constants it would be inconsistent to
-
# assume they should exist at this point. An early raised exception
-
# could trigger some other handler and the array could include
-
# precisely a string whose corresponding constant has not yet been
-
# seen. This is why we are tolerant to unknown constants.
-
#
-
# Note that this tolerance only matters if the exception was given as
-
# a string, otherwise a NameError will be raised by the interpreter
-
# itself when rescue_from CONSTANT is executed.
-
klass = self.class.const_get(klass_name) rescue nil
-
klass ||= klass_name.constantize rescue nil
-
exception.is_a?(klass) if klass
-
end
-
-
case rescuer
-
when Symbol
-
method(rescuer)
-
when Proc
-
if rescuer.arity == 0
-
Proc.new { instance_exec(&rescuer) }
-
else
-
Proc.new { |_exception| instance_exec(_exception, &rescuer) }
-
end
-
end
-
end
-
end
-
end
-
2
module ActiveSupport
-
# Wrapping a string in this class gives you a prettier way to test
-
# for equality. The value returned by <tt>Rails.env</tt> is wrapped
-
# in a StringInquirer object so instead of calling this:
-
#
-
# Rails.env == 'production'
-
#
-
# you can call this:
-
#
-
# Rails.env.production?
-
2
class StringInquirer < String
-
2
private
-
-
2
def respond_to_missing?(method_name, include_private = false)
-
method_name[-1] == '?'
-
end
-
-
2
def method_missing(method_name, *arguments)
-
36
if method_name[-1] == '?'
-
36
self == method_name[0..-2]
-
else
-
super
-
end
-
end
-
end
-
end
-
2
require 'active_support/per_thread_registry'
-
-
2
module ActiveSupport
-
# ActiveSupport::Subscriber is an object set to consume
-
# ActiveSupport::Notifications. The subscriber dispatches notifications to
-
# a registered object based on its given namespace.
-
#
-
# An example would be Active Record subscriber responsible for collecting
-
# statistics about queries:
-
#
-
# module ActiveRecord
-
# class StatsSubscriber < ActiveSupport::Subscriber
-
# def sql(event)
-
# Statsd.timing("sql.#{event.payload[:name]}", event.duration)
-
# end
-
# end
-
# end
-
#
-
# And it's finally registered as:
-
#
-
# ActiveRecord::StatsSubscriber.attach_to :active_record
-
#
-
# Since we need to know all instance methods before attaching the log
-
# subscriber, the line above should be called after your subscriber definition.
-
#
-
# After configured, whenever a "sql.active_record" notification is published,
-
# it will properly dispatch the event (ActiveSupport::Notifications::Event) to
-
# the +sql+ method.
-
2
class Subscriber
-
2
class << self
-
-
# Attach the subscriber to a namespace.
-
2
def attach_to(namespace, subscriber=new, notifier=ActiveSupport::Notifications)
-
8
@namespace = namespace
-
8
@subscriber = subscriber
-
8
@notifier = notifier
-
-
8
subscribers << subscriber
-
-
# Add event subscribers for all existing methods on the class.
-
8
subscriber.public_methods(false).each do |event|
-
54
add_event_subscriber(event)
-
end
-
end
-
-
# Adds event subscribers for all new methods added to the class.
-
2
def method_added(event)
-
# Only public methods are added as subscribers, and only if a notifier
-
# has been set up. This means that subscribers will only be set up for
-
# classes that call #attach_to.
-
112
if public_method_defined?(event) && notifier
-
add_event_subscriber(event)
-
end
-
end
-
-
2
def subscribers
-
8
@@subscribers ||= []
-
end
-
-
2
protected
-
-
2
attr_reader :subscriber, :notifier, :namespace
-
-
2
def add_event_subscriber(event)
-
54
return if %w{ start finish }.include?(event.to_s)
-
-
54
pattern = "#{event}.#{namespace}"
-
-
# don't add multiple subscribers (eg. if methods are redefined)
-
54
return if subscriber.patterns.include?(pattern)
-
-
54
subscriber.patterns << pattern
-
54
notifier.subscribe(pattern, subscriber)
-
end
-
end
-
-
2
attr_reader :patterns # :nodoc:
-
-
2
def initialize
-
8
@queue_key = [self.class.name, object_id].join "-"
-
8
@patterns = []
-
8
super
-
end
-
-
2
def start(name, id, payload)
-
1042
e = ActiveSupport::Notifications::Event.new(name, Time.now, nil, id, payload)
-
1042
parent = event_stack.last
-
1042
parent << e if parent
-
-
1042
event_stack.push e
-
end
-
-
2
def finish(name, id, payload)
-
1042
finished = Time.now
-
1042
event = event_stack.pop
-
1042
event.end = finished
-
1042
event.payload.merge!(payload)
-
-
1042
method = name.split('.').first
-
1042
send(method, event)
-
end
-
-
2
private
-
-
2
def event_stack
-
3126
SubscriberQueueRegistry.instance.get_queue(@queue_key)
-
end
-
end
-
-
# This is a registry for all the event stacks kept for subscribers.
-
#
-
# See the documentation of <tt>ActiveSupport::PerThreadRegistry</tt>
-
# for further details.
-
2
class SubscriberQueueRegistry # :nodoc:
-
2
extend PerThreadRegistry
-
-
2
def initialize
-
2
@registry = {}
-
end
-
-
2
def get_queue(queue_key)
-
3126
@registry[queue_key] ||= []
-
end
-
end
-
end
-
2
require 'active_support/core_ext/module/delegation'
-
2
require 'active_support/core_ext/object/blank'
-
2
require 'logger'
-
2
require 'active_support/logger'
-
-
2
module ActiveSupport
-
# Wraps any standard Logger object to provide tagging capabilities.
-
#
-
# logger = ActiveSupport::TaggedLogging.new(Logger.new(STDOUT))
-
# logger.tagged('BCX') { logger.info 'Stuff' } # Logs "[BCX] Stuff"
-
# logger.tagged('BCX', "Jason") { logger.info 'Stuff' } # Logs "[BCX] [Jason] Stuff"
-
# logger.tagged('BCX') { logger.tagged('Jason') { logger.info 'Stuff' } } # Logs "[BCX] [Jason] Stuff"
-
#
-
# This is used by the default Rails.logger as configured by Railties to make
-
# it easy to stamp log lines with subdomains, request ids, and anything else
-
# to aid debugging of multi-user production applications.
-
2
module TaggedLogging
-
2
module Formatter # :nodoc:
-
# This method is invoked when a log event occurs.
-
2
def call(severity, timestamp, progname, msg)
-
1223
super(severity, timestamp, progname, "#{tags_text}#{msg}")
-
end
-
-
2
def tagged(*tags)
-
13
new_tags = push_tags(*tags)
-
13
yield self
-
ensure
-
13
pop_tags(new_tags.size)
-
end
-
-
2
def push_tags(*tags)
-
13
tags.flatten.reject(&:blank?).tap do |new_tags|
-
13
current_tags.concat new_tags
-
end
-
end
-
-
2
def pop_tags(size = 1)
-
13
current_tags.pop size
-
end
-
-
2
def clear_tags!
-
13
current_tags.clear
-
end
-
-
2
def current_tags
-
1262
Thread.current[:activesupport_tagged_logging_tags] ||= []
-
end
-
-
2
private
-
2
def tags_text
-
1223
tags = current_tags
-
1223
if tags.any?
-
tags.collect { |tag| "[#{tag}] " }.join
-
end
-
end
-
end
-
-
2
def self.new(logger)
-
# Ensure we set a default formatter so we aren't extending nil!
-
2
logger.formatter ||= ActiveSupport::Logger::SimpleFormatter.new
-
2
logger.formatter.extend Formatter
-
2
logger.extend(self)
-
end
-
-
2
delegate :push_tags, :pop_tags, :clear_tags!, to: :formatter
-
-
2
def tagged(*tags)
-
26
formatter.tagged(*tags) { yield self }
-
end
-
-
2
def flush
-
13
clear_tags!
-
13
super if defined?(super)
-
end
-
end
-
end
-
2
gem 'minitest' # make sure we get the gem, not stdlib
-
2
require 'minitest'
-
2
require 'active_support/testing/tagged_logging'
-
2
require 'active_support/testing/setup_and_teardown'
-
2
require 'active_support/testing/assertions'
-
2
require 'active_support/testing/deprecation'
-
2
require 'active_support/testing/declarative'
-
2
require 'active_support/testing/isolation'
-
2
require 'active_support/testing/constant_lookup'
-
2
require 'active_support/testing/time_helpers'
-
2
require 'active_support/core_ext/kernel/reporting'
-
2
require 'active_support/deprecation'
-
-
2
begin
-
4
silence_warnings { require 'mocha/setup' }
-
rescue LoadError
-
end
-
-
2
module ActiveSupport
-
2
class TestCase < ::Minitest::Test
-
2
Assertion = Minitest::Assertion
-
-
2
alias_method :method_name, :name
-
-
2
$tags = {}
-
2
def self.for_tag(tag)
-
yield if $tags[tag]
-
end
-
-
# FIXME: we have tests that depend on run order, we should fix that and
-
# remove this method call.
-
2
self.i_suck_and_my_tests_are_order_dependent!
-
-
2
include ActiveSupport::Testing::TaggedLogging
-
2
include ActiveSupport::Testing::SetupAndTeardown
-
2
include ActiveSupport::Testing::Assertions
-
2
include ActiveSupport::Testing::Deprecation
-
2
include ActiveSupport::Testing::TimeHelpers
-
2
extend ActiveSupport::Testing::Declarative
-
-
# test/unit backwards compatibility methods
-
2
alias :assert_raise :assert_raises
-
2
alias :assert_not_empty :refute_empty
-
2
alias :assert_not_equal :refute_equal
-
2
alias :assert_not_in_delta :refute_in_delta
-
2
alias :assert_not_in_epsilon :refute_in_epsilon
-
2
alias :assert_not_includes :refute_includes
-
2
alias :assert_not_instance_of :refute_instance_of
-
2
alias :assert_not_kind_of :refute_kind_of
-
2
alias :assert_no_match :refute_match
-
2
alias :assert_not_nil :refute_nil
-
2
alias :assert_not_operator :refute_operator
-
2
alias :assert_not_predicate :refute_predicate
-
2
alias :assert_not_respond_to :refute_respond_to
-
2
alias :assert_not_same :refute_same
-
-
# Fails if the block raises an exception.
-
#
-
# assert_nothing_raised do
-
# ...
-
# end
-
2
def assert_nothing_raised(*args)
-
yield
-
end
-
end
-
end
-
2
require 'active_support/core_ext/object/blank'
-
-
2
module ActiveSupport
-
2
module Testing
-
2
module Assertions
-
# Assert that an expression is not truthy. Passes if <tt>object</tt> is
-
# +nil+ or +false+. "Truthy" means "considered true in a conditional"
-
# like <tt>if foo</tt>.
-
#
-
# assert_not nil # => true
-
# assert_not false # => true
-
# assert_not 'foo' # => 'foo' is not nil or false
-
#
-
# An error message can be specified.
-
#
-
# assert_not foo, 'foo should be false'
-
2
def assert_not(object, message = nil)
-
message ||= "Expected #{mu_pp(object)} to be nil or false"
-
assert !object, message
-
end
-
-
# Test numeric difference between the return value of an expression as a
-
# result of what is evaluated in the yielded block.
-
#
-
# assert_difference 'Article.count' do
-
# post :create, article: {...}
-
# end
-
#
-
# An arbitrary expression is passed in and evaluated.
-
#
-
# assert_difference 'assigns(:article).comments(:reload).size' do
-
# post :create, comment: {...}
-
# end
-
#
-
# An arbitrary positive or negative difference can be specified.
-
# The default is <tt>1</tt>.
-
#
-
# assert_difference 'Article.count', -1 do
-
# post :delete, id: ...
-
# end
-
#
-
# An array of expressions can also be passed in and evaluated.
-
#
-
# assert_difference [ 'Article.count', 'Post.count' ], 2 do
-
# post :create, article: {...}
-
# end
-
#
-
# A lambda or a list of lambdas can be passed in and evaluated:
-
#
-
# assert_difference ->{ Article.count }, 2 do
-
# post :create, article: {...}
-
# end
-
#
-
# assert_difference [->{ Article.count }, ->{ Post.count }], 2 do
-
# post :create, article: {...}
-
# end
-
#
-
# An error message can be specified.
-
#
-
# assert_difference 'Article.count', -1, 'An Article should be destroyed' do
-
# post :delete, id: ...
-
# end
-
2
def assert_difference(expression, difference = 1, message = nil, &block)
-
expressions = Array(expression)
-
-
exps = expressions.map { |e|
-
e.respond_to?(:call) ? e : lambda { eval(e, block.binding) }
-
}
-
before = exps.map { |e| e.call }
-
-
yield
-
-
expressions.zip(exps).each_with_index do |(code, e), i|
-
error = "#{code.inspect} didn't change by #{difference}"
-
error = "#{message}.\n#{error}" if message
-
assert_equal(before[i] + difference, e.call, error)
-
end
-
end
-
-
# Assertion that the numeric result of evaluating an expression is not
-
# changed before and after invoking the passed in block.
-
#
-
# assert_no_difference 'Article.count' do
-
# post :create, article: invalid_attributes
-
# end
-
#
-
# An error message can be specified.
-
#
-
# assert_no_difference 'Article.count', 'An Article should not be created' do
-
# post :create, article: invalid_attributes
-
# end
-
2
def assert_no_difference(expression, message = nil, &block)
-
assert_difference expression, 0, message, &block
-
end
-
end
-
end
-
end
-
1
gem 'minitest'
-
-
1
require 'minitest'
-
-
1
Minitest.autorun
-
2
require "active_support/concern"
-
2
require "active_support/inflector"
-
-
2
module ActiveSupport
-
2
module Testing
-
# Resolves a constant from a minitest spec name.
-
#
-
# Given the following spec-style test:
-
#
-
# describe WidgetsController, :index do
-
# describe "authenticated user" do
-
# describe "returns widgets" do
-
# it "has a controller that exists" do
-
# assert_kind_of WidgetsController, @controller
-
# end
-
# end
-
# end
-
# end
-
#
-
# The test will have the following name:
-
#
-
# "WidgetsController::index::authenticated user::returns widgets"
-
#
-
# The constant WidgetsController can be resolved from the name.
-
# The following code will resolve the constant:
-
#
-
# controller = determine_constant_from_test_name(name) do |constant|
-
# Class === constant && constant < ::ActionController::Metal
-
# end
-
2
module ConstantLookup
-
2
extend ::ActiveSupport::Concern
-
-
2
module ClassMethods # :nodoc:
-
2
def determine_constant_from_test_name(test_name)
-
names = test_name.split "::"
-
while names.size > 0 do
-
names.last.sub!(/Test$/, "")
-
begin
-
constant = names.join("::").constantize
-
break(constant) if yield(constant)
-
rescue NoMethodError # subclass of NameError
-
raise
-
rescue NameError
-
# Constant wasn't found, move on
-
ensure
-
names.pop
-
end
-
end
-
end
-
end
-
-
end
-
end
-
end
-
2
module ActiveSupport
-
2
module Testing
-
2
module Declarative
-
-
2
def self.extended(klass) #:nodoc:
-
2
klass.class_eval do
-
-
2
unless method_defined?(:describe)
-
2
def self.describe(text)
-
if block_given?
-
super
-
else
-
message = "`describe` without a block is deprecated, please switch to: `def self.name; #{text.inspect}; end`\n"
-
ActiveSupport::Deprecation.warn message
-
-
class_eval <<-RUBY_EVAL, __FILE__, __LINE__ + 1
-
def self.name
-
"#{text}"
-
end
-
RUBY_EVAL
-
end
-
end
-
end
-
-
end
-
end
-
-
2
unless defined?(Spec)
-
# Helper to define a test method using a String. Under the hood, it replaces
-
# spaces with underscores and defines the test method.
-
#
-
# test "verify something" do
-
# ...
-
# end
-
1
def test(name, &block)
-
test_name = "test_#{name.gsub(/\s+/,'_')}".to_sym
-
defined = instance_method(test_name) rescue false
-
raise "#{test_name} is already defined in #{self}" if defined
-
if block_given?
-
define_method(test_name, &block)
-
else
-
define_method(test_name) do
-
flunk "No implementation provided for #{name}"
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
2
require 'active_support/deprecation'
-
-
2
module ActiveSupport
-
2
module Testing
-
2
module Deprecation #:nodoc:
-
2
def assert_deprecated(match = nil, &block)
-
result, warnings = collect_deprecations(&block)
-
assert !warnings.empty?, "Expected a deprecation warning within the block but received none"
-
if match
-
match = Regexp.new(Regexp.escape(match)) unless match.is_a?(Regexp)
-
assert warnings.any? { |w| w =~ match }, "No deprecation warning matched #{match}: #{warnings.join(', ')}"
-
end
-
result
-
end
-
-
2
def assert_not_deprecated(&block)
-
result, deprecations = collect_deprecations(&block)
-
assert deprecations.empty?, "Expected no deprecation warning within the block but received #{deprecations.size}: \n #{deprecations * "\n "}"
-
result
-
end
-
-
2
def collect_deprecations
-
old_behavior = ActiveSupport::Deprecation.behavior
-
deprecations = []
-
ActiveSupport::Deprecation.behavior = Proc.new do |message, callstack|
-
deprecations << message
-
end
-
result = yield
-
[result, deprecations]
-
ensure
-
ActiveSupport::Deprecation.behavior = old_behavior
-
end
-
end
-
end
-
end
-
2
require 'rbconfig'
-
-
2
module ActiveSupport
-
2
module Testing
-
2
module Isolation
-
2
require 'thread'
-
-
2
def self.included(klass) #:nodoc:
-
klass.class_eval do
-
parallelize_me!
-
end
-
end
-
-
2
def self.forking_env?
-
2
!ENV["NO_FORK"] && ((RbConfig::CONFIG['host_os'] !~ /mswin|mingw/) && (RUBY_PLATFORM !~ /java/))
-
end
-
-
2
@@class_setup_mutex = Mutex.new
-
-
2
def _run_class_setup # class setup method should only happen in parent
-
@@class_setup_mutex.synchronize do
-
unless defined?(@@ran_class_setup) || ENV['ISOLATION_TEST']
-
self.class.setup if self.class.respond_to?(:setup)
-
@@ran_class_setup = true
-
end
-
end
-
end
-
-
2
def run
-
serialized = run_in_isolation do
-
super
-
end
-
-
Marshal.load(serialized)
-
end
-
-
2
module Forking
-
2
def run_in_isolation(&blk)
-
read, write = IO.pipe
-
read.binmode
-
write.binmode
-
-
pid = fork do
-
read.close
-
yield
-
write.puts [Marshal.dump(self.dup)].pack("m")
-
exit!
-
end
-
-
write.close
-
result = read.read
-
Process.wait2(pid)
-
return result.unpack("m")[0]
-
end
-
end
-
-
2
module Subprocess
-
2
ORIG_ARGV = ARGV.dup unless defined?(ORIG_ARGV)
-
-
# Crazy H4X to get this working in windows / jruby with
-
# no forking.
-
2
def run_in_isolation(&blk)
-
require "tempfile"
-
-
if ENV["ISOLATION_TEST"]
-
yield
-
File.open(ENV["ISOLATION_OUTPUT"], "w") do |file|
-
file.puts [Marshal.dump(self.dup)].pack("m")
-
end
-
exit!
-
else
-
Tempfile.open("isolation") do |tmpfile|
-
ENV["ISOLATION_TEST"] = self.class.name
-
ENV["ISOLATION_OUTPUT"] = tmpfile.path
-
-
load_paths = $-I.map {|p| "-I\"#{File.expand_path(p)}\"" }.join(" ")
-
`#{Gem.ruby} #{load_paths} #{$0} #{ORIG_ARGV.join(" ")}`
-
-
ENV.delete("ISOLATION_TEST")
-
ENV.delete("ISOLATION_OUTPUT")
-
-
return tmpfile.read.unpack("m")[0]
-
end
-
end
-
end
-
end
-
-
2
include forking_env? ? Forking : Subprocess
-
end
-
end
-
end
-
2
require 'active_support/concern'
-
2
require 'active_support/callbacks'
-
-
2
module ActiveSupport
-
2
module Testing
-
# Adds support for +setup+ and +teardown+ callbacks.
-
# These callbacks serve as a replacement to overwriting the
-
# <tt>#setup</tt> and <tt>#teardown</tt> methods of your TestCase.
-
#
-
# class ExampleTest < ActiveSupport::TestCase
-
# setup do
-
# # ...
-
# end
-
#
-
# teardown do
-
# # ...
-
# end
-
# end
-
2
module SetupAndTeardown
-
2
extend ActiveSupport::Concern
-
-
2
included do
-
2
include ActiveSupport::Callbacks
-
2
define_callbacks :setup, :teardown
-
end
-
-
2
module ClassMethods
-
# Add a callback, which runs before <tt>TestCase#setup</tt>.
-
2
def setup(*args, &block)
-
12
set_callback(:setup, :before, *args, &block)
-
end
-
-
# Add a callback, which runs after <tt>TestCase#teardown</tt>.
-
2
def teardown(*args, &block)
-
5
set_callback(:teardown, :after, *args, &block)
-
end
-
end
-
-
2
def before_setup # :nodoc:
-
super
-
run_callbacks :setup
-
end
-
-
2
def after_teardown # :nodoc:
-
run_callbacks :teardown
-
super
-
end
-
end
-
end
-
end
-
2
module ActiveSupport
-
2
module Testing
-
# Logs a "PostsControllerTest: test name" heading before each test to
-
# make test.log easier to search and follow along with.
-
2
module TaggedLogging #:nodoc:
-
2
attr_writer :tagged_logger
-
-
2
def before_setup
-
if tagged_logger
-
heading = "#{self.class}: #{name}"
-
divider = '-' * heading.size
-
tagged_logger.info divider
-
tagged_logger.info heading
-
tagged_logger.info divider
-
end
-
super
-
end
-
-
2
private
-
2
def tagged_logger
-
@tagged_logger ||= (defined?(Rails.logger) && Rails.logger)
-
end
-
end
-
end
-
end
-
2
module ActiveSupport
-
2
module Testing
-
2
class SimpleStubs # :nodoc:
-
2
Stub = Struct.new(:object, :method_name, :original_method)
-
-
2
def initialize
-
@stubs = {}
-
end
-
-
2
def stub_object(object, method_name, return_value)
-
key = [object.object_id, method_name]
-
-
if stub = @stubs[key]
-
unstub_object(stub)
-
end
-
-
new_name = "__simple_stub__#{method_name}"
-
-
@stubs[key] = Stub.new(object, method_name, new_name)
-
-
object.singleton_class.send :alias_method, new_name, method_name
-
object.define_singleton_method(method_name) { return_value }
-
end
-
-
2
def unstub_all!
-
@stubs.each_value do |stub|
-
unstub_object(stub)
-
end
-
@stubs = {}
-
end
-
-
2
private
-
-
2
def unstub_object(stub)
-
singleton_class = stub.object.singleton_class
-
singleton_class.send :undef_method, stub.method_name
-
singleton_class.send :alias_method, stub.method_name, stub.original_method
-
singleton_class.send :undef_method, stub.original_method
-
end
-
end
-
-
# Containing helpers that helps you test passage of time.
-
2
module TimeHelpers
-
# Changes current time to the time in the future or in the past by a given time difference by
-
# stubbing +Time.now+ and +Date.today+.
-
#
-
# Time.current # => Sat, 09 Nov 2013 15:34:49 EST -05:00
-
# travel 1.day
-
# Time.current # => Sun, 10 Nov 2013 15:34:49 EST -05:00
-
# Date.current # => Sun, 10 Nov 2013
-
#
-
# This method also accepts a block, which will return the current time back to its original
-
# state at the end of the block:
-
#
-
# Time.current # => Sat, 09 Nov 2013 15:34:49 EST -05:00
-
# travel 1.day do
-
# User.create.created_at # => Sun, 10 Nov 2013 15:34:49 EST -05:00
-
# end
-
# Time.current # => Sat, 09 Nov 2013 15:34:49 EST -05:00
-
2
def travel(duration, &block)
-
travel_to Time.now + duration, &block
-
end
-
-
# Changes current time to the given time by stubbing +Time.now+ and
-
# +Date.today+ to return the time or date passed into this method.
-
#
-
# Time.current # => Sat, 09 Nov 2013 15:34:49 EST -05:00
-
# travel_to Time.new(2004, 11, 24, 01, 04, 44)
-
# Time.current # => Wed, 24 Nov 2004 01:04:44 EST -05:00
-
# Date.current # => Wed, 24 Nov 2004
-
#
-
# Dates are taken as their timestamp at the beginning of the day in the
-
# application time zone. <tt>Time.current</tt> returns said timestamp,
-
# and <tt>Time.now</tt> its equivalent in the system time zone. Similarly,
-
# <tt>Date.current</tt> returns a date equal to the argument, and
-
# <tt>Date.today</tt> the date according to <tt>Time.now</tt>, which may
-
# be different. (Note that you rarely want to deal with <tt>Time.now</tt>,
-
# or <tt>Date.today</tt>, in order to honor the application time zone
-
# please always use <tt>Time.current</tt> and <tt>Date.current</tt>.)
-
#
-
# This method also accepts a block, which will return the current time back to its original
-
# state at the end of the block:
-
#
-
# Time.current # => Sat, 09 Nov 2013 15:34:49 EST -05:00
-
# travel_to Time.new(2004, 11, 24, 01, 04, 44) do
-
# Time.current # => Wed, 24 Nov 2004 01:04:44 EST -05:00
-
# end
-
# Time.current # => Sat, 09 Nov 2013 15:34:49 EST -05:00
-
2
def travel_to(date_or_time, &block)
-
if date_or_time.is_a?(Date) && !date_or_time.is_a?(DateTime)
-
now = date_or_time.midnight.to_time
-
else
-
now = date_or_time.to_time
-
end
-
-
simple_stubs.stub_object(Time, :now, now)
-
simple_stubs.stub_object(Date, :today, now.to_date)
-
-
if block_given?
-
begin
-
block.call
-
ensure
-
travel_back
-
end
-
end
-
end
-
-
# Returns the current time back to its original state, by removing the stubs added by
-
# `travel` and `travel_to`.
-
#
-
# Time.current # => Sat, 09 Nov 2013 15:34:49 EST -05:00
-
# travel_to Time.new(2004, 11, 24, 01, 04, 44)
-
# Time.current # => Wed, 24 Nov 2004 01:04:44 EST -05:00
-
# travel_back
-
# Time.current # => Sat, 09 Nov 2013 15:34:49 EST -05:00
-
2
def travel_back
-
simple_stubs.unstub_all!
-
end
-
-
2
private
-
-
2
def simple_stubs
-
@simple_stubs ||= SimpleStubs.new
-
end
-
end
-
end
-
end
-
2
require 'active_support'
-
-
2
module ActiveSupport
-
2
autoload :Duration, 'active_support/duration'
-
2
autoload :TimeWithZone, 'active_support/time_with_zone'
-
2
autoload :TimeZone, 'active_support/values/time_zone'
-
end
-
-
2
require 'date'
-
2
require 'time'
-
-
2
require 'active_support/core_ext/time'
-
2
require 'active_support/core_ext/date'
-
2
require 'active_support/core_ext/date_time'
-
-
2
require 'active_support/core_ext/integer/time'
-
2
require 'active_support/core_ext/numeric/time'
-
-
2
require 'active_support/core_ext/string/conversions'
-
2
require 'active_support/core_ext/string/zones'
-
2
require 'active_support/values/time_zone'
-
2
require 'active_support/core_ext/object/acts_like'
-
-
2
module ActiveSupport
-
# A Time-like class that can represent a time in any time zone. Necessary
-
# because standard Ruby Time instances are limited to UTC and the
-
# system's <tt>ENV['TZ']</tt> zone.
-
#
-
# You shouldn't ever need to create a TimeWithZone instance directly via +new+.
-
# Instead use methods +local+, +parse+, +at+ and +now+ on TimeZone instances,
-
# and +in_time_zone+ on Time and DateTime instances.
-
#
-
# Time.zone = 'Eastern Time (US & Canada)' # => 'Eastern Time (US & Canada)'
-
# Time.zone.local(2007, 2, 10, 15, 30, 45) # => Sat, 10 Feb 2007 15:30:45 EST -05:00
-
# Time.zone.parse('2007-02-10 15:30:45') # => Sat, 10 Feb 2007 15:30:45 EST -05:00
-
# Time.zone.at(1170361845) # => Sat, 10 Feb 2007 15:30:45 EST -05:00
-
# Time.zone.now # => Sun, 18 May 2008 13:07:55 EDT -04:00
-
# Time.utc(2007, 2, 10, 20, 30, 45).in_time_zone # => Sat, 10 Feb 2007 15:30:45 EST -05:00
-
#
-
# See Time and TimeZone for further documentation of these methods.
-
#
-
# TimeWithZone instances implement the same API as Ruby Time instances, so
-
# that Time and TimeWithZone instances are interchangeable.
-
#
-
# t = Time.zone.now # => Sun, 18 May 2008 13:27:25 EDT -04:00
-
# t.hour # => 13
-
# t.dst? # => true
-
# t.utc_offset # => -14400
-
# t.zone # => "EDT"
-
# t.to_s(:rfc822) # => "Sun, 18 May 2008 13:27:25 -0400"
-
# t + 1.day # => Mon, 19 May 2008 13:27:25 EDT -04:00
-
# t.beginning_of_year # => Tue, 01 Jan 2008 00:00:00 EST -05:00
-
# t > Time.utc(1999) # => true
-
# t.is_a?(Time) # => true
-
# t.is_a?(ActiveSupport::TimeWithZone) # => true
-
2
class TimeWithZone
-
-
# Report class name as 'Time' to thwart type checking.
-
2
def self.name
-
'Time'
-
end
-
-
2
include Comparable
-
2
attr_reader :time_zone
-
-
2
def initialize(utc_time, time_zone, local_time = nil, period = nil)
-
534
@utc, @time_zone, @time = utc_time, time_zone, local_time
-
534
@period = @utc ? period : get_period_and_ensure_valid_local_time(period)
-
end
-
-
# Returns a Time or DateTime instance that represents the time in +time_zone+.
-
2
def time
-
1068
@time ||= period.to_local(@utc)
-
end
-
-
# Returns a Time or DateTime instance that represents the time in UTC.
-
2
def utc
-
534
@utc ||= period.to_utc(@time)
-
end
-
2
alias_method :comparable_time, :utc
-
2
alias_method :getgm, :utc
-
2
alias_method :getutc, :utc
-
2
alias_method :gmtime, :utc
-
-
# Returns the underlying TZInfo::TimezonePeriod.
-
2
def period
-
534
@period ||= time_zone.period_for_utc(@utc)
-
end
-
-
# Returns the simultaneous time in <tt>Time.zone</tt>, or the specified zone.
-
2
def in_time_zone(new_zone = ::Time.zone)
-
return self if time_zone == new_zone
-
utc.in_time_zone(new_zone)
-
end
-
-
# Returns a <tt>Time.local()</tt> instance of the simultaneous time in your
-
# system's <tt>ENV['TZ']</tt> zone.
-
2
def localtime
-
utc.respond_to?(:getlocal) ? utc.getlocal : utc.to_time.getlocal
-
end
-
2
alias_method :getlocal, :localtime
-
-
# Returns true if the current time is within Daylight Savings Time for the
-
# specified time zone.
-
#
-
# Time.zone = 'Eastern Time (US & Canada)' # => 'Eastern Time (US & Canada)'
-
# Time.zone.parse("2012-5-30").dst? # => true
-
# Time.zone.parse("2012-11-30").dst? # => false
-
2
def dst?
-
period.dst?
-
end
-
2
alias_method :isdst, :dst?
-
-
# Returns true if the current time zone is set to UTC.
-
#
-
# Time.zone = 'UTC' # => 'UTC'
-
# Time.zone.now.utc? # => true
-
# Time.zone = 'Eastern Time (US & Canada)' # => 'Eastern Time (US & Canada)'
-
# Time.zone.now.utc? # => false
-
2
def utc?
-
time_zone.name == 'UTC'
-
end
-
2
alias_method :gmt?, :utc?
-
-
# Returns the offset from current time to UTC time in seconds.
-
2
def utc_offset
-
period.utc_total_offset
-
end
-
2
alias_method :gmt_offset, :utc_offset
-
2
alias_method :gmtoff, :utc_offset
-
-
# Returns a formatted string of the offset from UTC, or an alternative
-
# string if the time zone is already UTC.
-
#
-
# Time.zone = 'Eastern Time (US & Canada)' # => "Eastern Time (US & Canada)"
-
# Time.zone.now.formatted_offset(true) # => "-05:00"
-
# Time.zone.now.formatted_offset(false) # => "-0500"
-
# Time.zone = 'UTC' # => "UTC"
-
# Time.zone.now.formatted_offset(true, "0") # => "0"
-
2
def formatted_offset(colon = true, alternate_utc_string = nil)
-
utc? && alternate_utc_string || TimeZone.seconds_to_utc_offset(utc_offset, colon)
-
end
-
-
# Time uses +zone+ to display the time zone abbreviation, so we're
-
# duck-typing it.
-
2
def zone
-
period.zone_identifier.to_s
-
end
-
-
2
def inspect
-
"#{time.strftime('%a, %d %b %Y %H:%M:%S')} #{zone} #{formatted_offset}"
-
end
-
-
2
def xmlschema(fraction_digits = 0)
-
fraction = if fraction_digits.to_i > 0
-
(".%06i" % time.usec)[0, fraction_digits.to_i + 1]
-
end
-
-
"#{time.strftime("%Y-%m-%dT%H:%M:%S")}#{fraction}#{formatted_offset(true, 'Z')}"
-
end
-
2
alias_method :iso8601, :xmlschema
-
-
# Coerces time to a string for JSON encoding. The default format is ISO 8601.
-
# You can get %Y/%m/%d %H:%M:%S +offset style by setting
-
# <tt>ActiveSupport::JSON::Encoding.use_standard_json_time_format</tt>
-
# to +false+.
-
#
-
# # With ActiveSupport::JSON::Encoding.use_standard_json_time_format = true
-
# Time.utc(2005,2,1,15,15,10).in_time_zone("Hawaii").to_json
-
# # => "2005-02-01T05:15:10.000-10:00"
-
#
-
# # With ActiveSupport::JSON::Encoding.use_standard_json_time_format = false
-
# Time.utc(2005,2,1,15,15,10).in_time_zone("Hawaii").to_json
-
# # => "2005/02/01 05:15:10 -1000"
-
2
def as_json(options = nil)
-
if ActiveSupport::JSON::Encoding.use_standard_json_time_format
-
xmlschema(ActiveSupport::JSON::Encoding.time_precision)
-
else
-
%(#{time.strftime("%Y/%m/%d %H:%M:%S")} #{formatted_offset(false)})
-
end
-
end
-
-
2
def encode_with(coder)
-
if coder.respond_to?(:represent_object)
-
coder.represent_object(nil, utc)
-
else
-
coder.represent_scalar(nil, utc.strftime("%Y-%m-%d %H:%M:%S.%9NZ"))
-
end
-
end
-
-
# Returns a string of the object's date and time in the format used by
-
# HTTP requests.
-
#
-
# Time.zone.now.httpdate # => "Tue, 01 Jan 2013 04:39:43 GMT"
-
2
def httpdate
-
utc.httpdate
-
end
-
-
# Returns a string of the object's date and time in the RFC 2822 standard
-
# format.
-
#
-
# Time.zone.now.rfc2822 # => "Tue, 01 Jan 2013 04:51:39 +0000"
-
2
def rfc2822
-
to_s(:rfc822)
-
end
-
2
alias_method :rfc822, :rfc2822
-
-
# <tt>:db</tt> format outputs time in UTC; all others output time in local.
-
# Uses TimeWithZone's +strftime+, so <tt>%Z</tt> and <tt>%z</tt> work correctly.
-
2
def to_s(format = :default)
-
if format == :db
-
utc.to_s(format)
-
elsif formatter = ::Time::DATE_FORMATS[format]
-
formatter.respond_to?(:call) ? formatter.call(self).to_s : strftime(formatter)
-
else
-
"#{time.strftime("%Y-%m-%d %H:%M:%S")} #{formatted_offset(false, 'UTC')}" # mimicking Ruby 1.9 Time#to_s format
-
end
-
end
-
2
alias_method :to_formatted_s, :to_s
-
-
# Replaces <tt>%Z</tt> and <tt>%z</tt> directives with +zone+ and
-
# +formatted_offset+, respectively, before passing to Time#strftime, so
-
# that zone information is correct
-
2
def strftime(format)
-
format = format.gsub('%Z', zone)
-
.gsub('%z', formatted_offset(false))
-
.gsub('%:z', formatted_offset(true))
-
.gsub('%::z', formatted_offset(true) + ":00")
-
time.strftime(format)
-
end
-
-
# Use the time in UTC for comparisons.
-
2
def <=>(other)
-
utc <=> other
-
end
-
-
# Returns true if the current object's time is within the specified
-
# +min+ and +max+ time.
-
2
def between?(min, max)
-
utc.between?(min, max)
-
end
-
-
# Returns true if the current object's time is in the past.
-
2
def past?
-
utc.past?
-
end
-
-
# Returns true if the current object's time falls within
-
# the current day.
-
2
def today?
-
time.today?
-
end
-
-
# Returns true if the current object's time is in the future.
-
2
def future?
-
utc.future?
-
end
-
-
2
def eql?(other)
-
utc.eql?(other)
-
end
-
-
2
def hash
-
utc.hash
-
end
-
-
2
def +(other)
-
# If we're adding a Duration of variable length (i.e., years, months, days), move forward from #time,
-
# otherwise move forward from #utc, for accuracy when moving across DST boundaries
-
if duration_of_variable_length?(other)
-
method_missing(:+, other)
-
else
-
result = utc.acts_like?(:date) ? utc.since(other) : utc + other rescue utc.since(other)
-
result.in_time_zone(time_zone)
-
end
-
end
-
-
2
def -(other)
-
# If we're subtracting a Duration of variable length (i.e., years, months, days), move backwards from #time,
-
# otherwise move backwards #utc, for accuracy when moving across DST boundaries
-
if other.acts_like?(:time)
-
utc.to_f - other.to_f
-
elsif duration_of_variable_length?(other)
-
method_missing(:-, other)
-
else
-
result = utc.acts_like?(:date) ? utc.ago(other) : utc - other rescue utc.ago(other)
-
result.in_time_zone(time_zone)
-
end
-
end
-
-
2
def since(other)
-
# If we're adding a Duration of variable length (i.e., years, months, days), move forward from #time,
-
# otherwise move forward from #utc, for accuracy when moving across DST boundaries
-
if duration_of_variable_length?(other)
-
method_missing(:since, other)
-
else
-
utc.since(other).in_time_zone(time_zone)
-
end
-
end
-
-
2
def ago(other)
-
since(-other)
-
end
-
-
2
def advance(options)
-
# If we're advancing a value of variable length (i.e., years, weeks, months, days), advance from #time,
-
# otherwise advance from #utc, for accuracy when moving across DST boundaries
-
if options.values_at(:years, :weeks, :months, :days).any?
-
method_missing(:advance, options)
-
else
-
utc.advance(options).in_time_zone(time_zone)
-
end
-
end
-
-
2
%w(year mon month day mday wday yday hour min sec usec nsec to_date).each do |method_name|
-
26
class_eval <<-EOV, __FILE__, __LINE__ + 1
-
def #{method_name} # def month
-
time.#{method_name} # time.month
-
end # end
-
EOV
-
end
-
-
2
def to_a
-
[time.sec, time.min, time.hour, time.day, time.mon, time.year, time.wday, time.yday, dst?, zone]
-
end
-
-
2
def to_f
-
utc.to_f
-
end
-
-
2
def to_i
-
utc.to_i
-
end
-
2
alias_method :tv_sec, :to_i
-
-
2
def to_r
-
utc.to_r
-
end
-
-
# Return an instance of Time in the system timezone.
-
2
def to_time
-
utc.to_time
-
end
-
-
2
def to_datetime
-
utc.to_datetime.new_offset(Rational(utc_offset, 86_400))
-
end
-
-
# So that +self+ <tt>acts_like?(:time)</tt>.
-
2
def acts_like_time?
-
true
-
end
-
-
# Say we're a Time to thwart type checking.
-
2
def is_a?(klass)
-
1602
klass == ::Time || super
-
end
-
2
alias_method :kind_of?, :is_a?
-
-
2
def freeze
-
period; utc; time # preload instance variables before freezing
-
super
-
end
-
-
2
def marshal_dump
-
[utc, time_zone.name, time]
-
end
-
-
2
def marshal_load(variables)
-
initialize(variables[0].utc, ::Time.find_zone(variables[1]), variables[2].utc)
-
end
-
-
# Ensure proxy class responds to all methods that underlying time instance
-
# responds to.
-
2
def respond_to_missing?(sym, include_priv)
-
# consistently respond false to acts_like?(:date), regardless of whether #time is a Time or DateTime
-
534
return false if sym.to_sym == :acts_like_date?
-
534
time.respond_to?(sym, include_priv)
-
end
-
-
# Send the missing method to +time+ instance, and wrap result in a new
-
# TimeWithZone with the existing +time_zone+.
-
2
def method_missing(sym, *args, &block)
-
wrap_with_time_zone time.__send__(sym, *args, &block)
-
rescue NoMethodError => e
-
raise e, e.message.sub(time.inspect, self.inspect), e.backtrace
-
end
-
-
2
private
-
2
def get_period_and_ensure_valid_local_time(period)
-
# we don't want a Time.local instance enforcing its own DST rules as well,
-
# so transfer time values to a utc constructor if necessary
-
@time = transfer_time_values_to_utc_constructor(@time) unless @time.utc?
-
begin
-
period || @time_zone.period_for_local(@time)
-
rescue ::TZInfo::PeriodNotFound
-
# time is in the "spring forward" hour gap, so we're moving the time forward one hour and trying again
-
@time += 1.hour
-
retry
-
end
-
end
-
-
2
def transfer_time_values_to_utc_constructor(time)
-
::Time.utc(time.year, time.month, time.day, time.hour, time.min, time.sec, Rational(time.nsec, 1000))
-
end
-
-
2
def duration_of_variable_length?(obj)
-
ActiveSupport::Duration === obj && obj.parts.any? {|p| [:years, :months, :days].include?(p[0]) }
-
end
-
-
2
def wrap_with_time_zone(time)
-
if time.acts_like?(:time)
-
periods = time_zone.periods_for_local(time)
-
self.class.new(nil, time_zone, time, periods.include?(period) ? period : nil)
-
elsif time.is_a?(Range)
-
wrap_with_time_zone(time.begin)..wrap_with_time_zone(time.end)
-
else
-
time
-
end
-
end
-
end
-
end
-
2
require 'tzinfo'
-
2
require 'thread_safe'
-
2
require 'active_support/core_ext/object/blank'
-
2
require 'active_support/core_ext/object/try'
-
-
2
module ActiveSupport
-
# The TimeZone class serves as a wrapper around TZInfo::Timezone instances.
-
# It allows us to do the following:
-
#
-
# * Limit the set of zones provided by TZInfo to a meaningful subset of 146
-
# zones.
-
# * Retrieve and display zones with a friendlier name
-
# (e.g., "Eastern Time (US & Canada)" instead of "America/New_York").
-
# * Lazily load TZInfo::Timezone instances only when they're needed.
-
# * Create ActiveSupport::TimeWithZone instances via TimeZone's +local+,
-
# +parse+, +at+ and +now+ methods.
-
#
-
# If you set <tt>config.time_zone</tt> in the Rails Application, you can
-
# access this TimeZone object via <tt>Time.zone</tt>:
-
#
-
# # application.rb:
-
# class Application < Rails::Application
-
# config.time_zone = 'Eastern Time (US & Canada)'
-
# end
-
#
-
# Time.zone # => #<TimeZone:0x514834...>
-
# Time.zone.name # => "Eastern Time (US & Canada)"
-
# Time.zone.now # => Sun, 18 May 2008 14:30:44 EDT -04:00
-
#
-
# The version of TZInfo bundled with Active Support only includes the
-
# definitions necessary to support the zones defined by the TimeZone class.
-
# If you need to use zones that aren't defined by TimeZone, you'll need to
-
# install the TZInfo gem (if a recent version of the gem is installed locally,
-
# this will be used instead of the bundled version.)
-
2
class TimeZone
-
# Keys are Rails TimeZone names, values are TZInfo identifiers.
-
2
MAPPING = {
-
"International Date Line West" => "Pacific/Midway",
-
"Midway Island" => "Pacific/Midway",
-
"American Samoa" => "Pacific/Pago_Pago",
-
"Hawaii" => "Pacific/Honolulu",
-
"Alaska" => "America/Juneau",
-
"Pacific Time (US & Canada)" => "America/Los_Angeles",
-
"Tijuana" => "America/Tijuana",
-
"Mountain Time (US & Canada)" => "America/Denver",
-
"Arizona" => "America/Phoenix",
-
"Chihuahua" => "America/Chihuahua",
-
"Mazatlan" => "America/Mazatlan",
-
"Central Time (US & Canada)" => "America/Chicago",
-
"Saskatchewan" => "America/Regina",
-
"Guadalajara" => "America/Mexico_City",
-
"Mexico City" => "America/Mexico_City",
-
"Monterrey" => "America/Monterrey",
-
"Central America" => "America/Guatemala",
-
"Eastern Time (US & Canada)" => "America/New_York",
-
"Indiana (East)" => "America/Indiana/Indianapolis",
-
"Bogota" => "America/Bogota",
-
"Lima" => "America/Lima",
-
"Quito" => "America/Lima",
-
"Atlantic Time (Canada)" => "America/Halifax",
-
"Caracas" => "America/Caracas",
-
"La Paz" => "America/La_Paz",
-
"Santiago" => "America/Santiago",
-
"Newfoundland" => "America/St_Johns",
-
"Brasilia" => "America/Sao_Paulo",
-
"Buenos Aires" => "America/Argentina/Buenos_Aires",
-
"Montevideo" => "America/Montevideo",
-
"Georgetown" => "America/Guyana",
-
"Greenland" => "America/Godthab",
-
"Mid-Atlantic" => "Atlantic/South_Georgia",
-
"Azores" => "Atlantic/Azores",
-
"Cape Verde Is." => "Atlantic/Cape_Verde",
-
"Dublin" => "Europe/Dublin",
-
"Edinburgh" => "Europe/London",
-
"Lisbon" => "Europe/Lisbon",
-
"London" => "Europe/London",
-
"Casablanca" => "Africa/Casablanca",
-
"Monrovia" => "Africa/Monrovia",
-
"UTC" => "Etc/UTC",
-
"Belgrade" => "Europe/Belgrade",
-
"Bratislava" => "Europe/Bratislava",
-
"Budapest" => "Europe/Budapest",
-
"Ljubljana" => "Europe/Ljubljana",
-
"Prague" => "Europe/Prague",
-
"Sarajevo" => "Europe/Sarajevo",
-
"Skopje" => "Europe/Skopje",
-
"Warsaw" => "Europe/Warsaw",
-
"Zagreb" => "Europe/Zagreb",
-
"Brussels" => "Europe/Brussels",
-
"Copenhagen" => "Europe/Copenhagen",
-
"Madrid" => "Europe/Madrid",
-
"Paris" => "Europe/Paris",
-
"Amsterdam" => "Europe/Amsterdam",
-
"Berlin" => "Europe/Berlin",
-
"Bern" => "Europe/Berlin",
-
"Rome" => "Europe/Rome",
-
"Stockholm" => "Europe/Stockholm",
-
"Vienna" => "Europe/Vienna",
-
"West Central Africa" => "Africa/Algiers",
-
"Bucharest" => "Europe/Bucharest",
-
"Cairo" => "Africa/Cairo",
-
"Helsinki" => "Europe/Helsinki",
-
"Kyiv" => "Europe/Kiev",
-
"Riga" => "Europe/Riga",
-
"Sofia" => "Europe/Sofia",
-
"Tallinn" => "Europe/Tallinn",
-
"Vilnius" => "Europe/Vilnius",
-
"Athens" => "Europe/Athens",
-
"Istanbul" => "Europe/Istanbul",
-
"Minsk" => "Europe/Minsk",
-
"Jerusalem" => "Asia/Jerusalem",
-
"Harare" => "Africa/Harare",
-
"Pretoria" => "Africa/Johannesburg",
-
"Moscow" => "Europe/Moscow",
-
"St. Petersburg" => "Europe/Moscow",
-
"Volgograd" => "Europe/Moscow",
-
"Kuwait" => "Asia/Kuwait",
-
"Riyadh" => "Asia/Riyadh",
-
"Nairobi" => "Africa/Nairobi",
-
"Baghdad" => "Asia/Baghdad",
-
"Tehran" => "Asia/Tehran",
-
"Abu Dhabi" => "Asia/Muscat",
-
"Muscat" => "Asia/Muscat",
-
"Baku" => "Asia/Baku",
-
"Tbilisi" => "Asia/Tbilisi",
-
"Yerevan" => "Asia/Yerevan",
-
"Kabul" => "Asia/Kabul",
-
"Ekaterinburg" => "Asia/Yekaterinburg",
-
"Islamabad" => "Asia/Karachi",
-
"Karachi" => "Asia/Karachi",
-
"Tashkent" => "Asia/Tashkent",
-
"Chennai" => "Asia/Kolkata",
-
"Kolkata" => "Asia/Kolkata",
-
"Mumbai" => "Asia/Kolkata",
-
"New Delhi" => "Asia/Kolkata",
-
"Kathmandu" => "Asia/Kathmandu",
-
"Astana" => "Asia/Dhaka",
-
"Dhaka" => "Asia/Dhaka",
-
"Sri Jayawardenepura" => "Asia/Colombo",
-
"Almaty" => "Asia/Almaty",
-
"Novosibirsk" => "Asia/Novosibirsk",
-
"Rangoon" => "Asia/Rangoon",
-
"Bangkok" => "Asia/Bangkok",
-
"Hanoi" => "Asia/Bangkok",
-
"Jakarta" => "Asia/Jakarta",
-
"Krasnoyarsk" => "Asia/Krasnoyarsk",
-
"Beijing" => "Asia/Shanghai",
-
"Chongqing" => "Asia/Chongqing",
-
"Hong Kong" => "Asia/Hong_Kong",
-
"Urumqi" => "Asia/Urumqi",
-
"Kuala Lumpur" => "Asia/Kuala_Lumpur",
-
"Singapore" => "Asia/Singapore",
-
"Taipei" => "Asia/Taipei",
-
"Perth" => "Australia/Perth",
-
"Irkutsk" => "Asia/Irkutsk",
-
"Ulaanbaatar" => "Asia/Ulaanbaatar",
-
"Seoul" => "Asia/Seoul",
-
"Osaka" => "Asia/Tokyo",
-
"Sapporo" => "Asia/Tokyo",
-
"Tokyo" => "Asia/Tokyo",
-
"Yakutsk" => "Asia/Yakutsk",
-
"Darwin" => "Australia/Darwin",
-
"Adelaide" => "Australia/Adelaide",
-
"Canberra" => "Australia/Melbourne",
-
"Melbourne" => "Australia/Melbourne",
-
"Sydney" => "Australia/Sydney",
-
"Brisbane" => "Australia/Brisbane",
-
"Hobart" => "Australia/Hobart",
-
"Vladivostok" => "Asia/Vladivostok",
-
"Guam" => "Pacific/Guam",
-
"Port Moresby" => "Pacific/Port_Moresby",
-
"Magadan" => "Asia/Magadan",
-
"Solomon Is." => "Pacific/Guadalcanal",
-
"New Caledonia" => "Pacific/Noumea",
-
"Fiji" => "Pacific/Fiji",
-
"Kamchatka" => "Asia/Kamchatka",
-
"Marshall Is." => "Pacific/Majuro",
-
"Auckland" => "Pacific/Auckland",
-
"Wellington" => "Pacific/Auckland",
-
"Nuku'alofa" => "Pacific/Tongatapu",
-
"Tokelau Is." => "Pacific/Fakaofo",
-
"Chatham Is." => "Pacific/Chatham",
-
"Samoa" => "Pacific/Apia"
-
}
-
-
2
UTC_OFFSET_WITH_COLON = '%s%02d:%02d'
-
2
UTC_OFFSET_WITHOUT_COLON = UTC_OFFSET_WITH_COLON.sub(':', '')
-
-
2
@lazy_zones_map = ThreadSafe::Cache.new
-
-
# Assumes self represents an offset from UTC in seconds (as returned from
-
# Time#utc_offset) and turns this into an +HH:MM formatted string.
-
#
-
# TimeZone.seconds_to_utc_offset(-21_600) # => "-06:00"
-
2
def self.seconds_to_utc_offset(seconds, colon = true)
-
format = colon ? UTC_OFFSET_WITH_COLON : UTC_OFFSET_WITHOUT_COLON
-
sign = (seconds < 0 ? '-' : '+')
-
hours = seconds.abs / 3600
-
minutes = (seconds.abs % 3600) / 60
-
format % [sign, hours, minutes]
-
end
-
-
2
include Comparable
-
2
attr_reader :name
-
2
attr_reader :tzinfo
-
-
# Create a new TimeZone object with the given name and offset. The
-
# offset is the number of seconds that this time zone is offset from UTC
-
# (GMT). Seconds were chosen as the offset unit because that is the unit
-
# that Ruby uses to represent time zone offsets (see Time#utc_offset).
-
2
def initialize(name, utc_offset = nil, tzinfo = nil)
-
2
@name = name
-
2
@utc_offset = utc_offset
-
2
@tzinfo = tzinfo || TimeZone.find_tzinfo(name)
-
2
@current_period = nil
-
end
-
-
# Returns the offset of this time zone from UTC in seconds.
-
2
def utc_offset
-
2
if @utc_offset
-
@utc_offset
-
else
-
2
@current_period ||= tzinfo.try(:current_period)
-
2
@current_period.try(:utc_offset)
-
end
-
end
-
-
# Returns the offset of this time zone as a formatted string, of the
-
# format "+HH:MM".
-
2
def formatted_offset(colon=true, alternate_utc_string = nil)
-
utc_offset == 0 && alternate_utc_string || self.class.seconds_to_utc_offset(utc_offset, colon)
-
end
-
-
# Compare this time zone to the parameter. The two are compared first on
-
# their offsets, and then by name.
-
2
def <=>(zone)
-
return unless zone.respond_to? :utc_offset
-
result = (utc_offset <=> zone.utc_offset)
-
result = (name <=> zone.name) if result == 0
-
result
-
end
-
-
# Compare #name and TZInfo identifier to a supplied regexp, returning +true+
-
# if a match is found.
-
2
def =~(re)
-
re === name || re === MAPPING[name]
-
end
-
-
# Returns a textual representation of this time zone.
-
2
def to_s
-
"(GMT#{formatted_offset}) #{name}"
-
end
-
-
# Method for creating new ActiveSupport::TimeWithZone instance in time zone
-
# of +self+ from given values.
-
#
-
# Time.zone = 'Hawaii' # => "Hawaii"
-
# Time.zone.local(2007, 2, 1, 15, 30, 45) # => Thu, 01 Feb 2007 15:30:45 HST -10:00
-
2
def local(*args)
-
time = Time.utc(*args)
-
ActiveSupport::TimeWithZone.new(nil, self, time)
-
end
-
-
# Method for creating new ActiveSupport::TimeWithZone instance in time zone
-
# of +self+ from number of seconds since the Unix epoch.
-
#
-
# Time.zone = 'Hawaii' # => "Hawaii"
-
# Time.utc(2000).to_f # => 946684800.0
-
# Time.zone.at(946684800.0) # => Fri, 31 Dec 1999 14:00:00 HST -10:00
-
2
def at(secs)
-
Time.at(secs).utc.in_time_zone(self)
-
end
-
-
# Method for creating new ActiveSupport::TimeWithZone instance in time zone
-
# of +self+ from parsed string.
-
#
-
# Time.zone = 'Hawaii' # => "Hawaii"
-
# Time.zone.parse('1999-12-31 14:00:00') # => Fri, 31 Dec 1999 14:00:00 HST -10:00
-
#
-
# If upper components are missing from the string, they are supplied from
-
# TimeZone#now:
-
#
-
# Time.zone.now # => Fri, 31 Dec 1999 14:00:00 HST -10:00
-
# Time.zone.parse('22:30:00') # => Fri, 31 Dec 1999 22:30:00 HST -10:00
-
2
def parse(str, now=now())
-
parts = Date._parse(str, false)
-
return if parts.empty?
-
-
time = Time.new(
-
parts.fetch(:year, now.year),
-
parts.fetch(:mon, now.month),
-
parts.fetch(:mday, now.day),
-
parts.fetch(:hour, 0),
-
parts.fetch(:min, 0),
-
parts.fetch(:sec, 0) + parts.fetch(:sec_fraction, 0),
-
parts.fetch(:offset, 0)
-
)
-
-
if parts[:offset]
-
TimeWithZone.new(time.utc, self)
-
else
-
TimeWithZone.new(nil, self, time)
-
end
-
end
-
-
# Returns an ActiveSupport::TimeWithZone instance representing the current
-
# time in the time zone represented by +self+.
-
#
-
# Time.zone = 'Hawaii' # => "Hawaii"
-
# Time.zone.now # => Wed, 23 Jan 2008 20:24:27 HST -10:00
-
2
def now
-
time_now.utc.in_time_zone(self)
-
end
-
-
# Return the current date in this time zone.
-
2
def today
-
tzinfo.now.to_date
-
end
-
-
# Returns the next date in this time zone.
-
2
def tomorrow
-
today + 1
-
end
-
-
# Returns the previous date in this time zone.
-
2
def yesterday
-
today - 1
-
end
-
-
# Adjust the given time to the simultaneous time in the time zone
-
# represented by +self+. Returns a Time.utc() instance -- if you want an
-
# ActiveSupport::TimeWithZone instance, use Time#in_time_zone() instead.
-
2
def utc_to_local(time)
-
tzinfo.utc_to_local(time)
-
end
-
-
# Adjust the given time to the simultaneous time in UTC. Returns a
-
# Time.utc() instance.
-
2
def local_to_utc(time, dst=true)
-
tzinfo.local_to_utc(time, dst)
-
end
-
-
# Available so that TimeZone instances respond like TZInfo::Timezone
-
# instances.
-
2
def period_for_utc(time)
-
534
tzinfo.period_for_utc(time)
-
end
-
-
# Available so that TimeZone instances respond like TZInfo::Timezone
-
# instances.
-
2
def period_for_local(time, dst=true)
-
tzinfo.period_for_local(time, dst)
-
end
-
-
2
def periods_for_local(time) #:nodoc:
-
tzinfo.periods_for_local(time)
-
end
-
-
2
def self.find_tzinfo(name)
-
2
TZInfo::TimezoneProxy.new(MAPPING[name] || name)
-
end
-
-
2
class << self
-
2
alias_method :create, :new
-
-
# Returns a TimeZone instance with the given name, or +nil+ if no
-
# such TimeZone instance exists. (This exists to support the use of
-
# this class with the +composed_of+ macro.)
-
2
def new(name)
-
self[name]
-
end
-
-
# Returns an array of all TimeZone objects. There are multiple
-
# TimeZone objects per time zone, in many cases, to make it easier
-
# for users to find their own time zone.
-
2
def all
-
@zones ||= zones_map.values.sort
-
end
-
-
2
def zones_map
-
@zones_map ||= begin
-
MAPPING.each_key {|place| self[place]} # load all the zones
-
@lazy_zones_map
-
end
-
end
-
-
# Locate a specific time zone object. If the argument is a string, it
-
# is interpreted to mean the name of the timezone to locate. If it is a
-
# numeric value it is either the hour offset, or the second offset, of the
-
# timezone to find. (The first one with that offset will be returned.)
-
# Returns +nil+ if no such time zone is known to the system.
-
2
def [](arg)
-
2
case arg
-
when String
-
2
begin
-
4
@lazy_zones_map[arg] ||= create(arg).tap { |tz| tz.utc_offset }
-
rescue TZInfo::InvalidTimezoneIdentifier
-
nil
-
end
-
when Numeric, ActiveSupport::Duration
-
arg *= 3600 if arg.abs <= 13
-
all.find { |z| z.utc_offset == arg.to_i }
-
else
-
raise ArgumentError, "invalid argument to TimeZone[]: #{arg.inspect}"
-
end
-
end
-
-
# A convenience method for returning a collection of TimeZone objects
-
# for time zones in the USA.
-
2
def us_zones
-
@us_zones ||= all.find_all { |z| z.name =~ /US|Arizona|Indiana|Hawaii|Alaska/ }
-
end
-
end
-
-
2
private
-
-
2
def time_now
-
Time.now
-
end
-
end
-
end
-
2
require_relative 'gem_version'
-
-
2
module ActiveSupport
-
# Returns the version of the currently loaded ActiveSupport as a <tt>Gem::Version</tt>
-
2
def self.version
-
gem_version
-
end
-
end
-
2
require 'time'
-
2
require 'base64'
-
2
require 'bigdecimal'
-
2
require 'active_support/core_ext/module/delegation'
-
2
require 'active_support/core_ext/string/inflections'
-
2
require 'active_support/core_ext/date_time/calculations'
-
-
2
module ActiveSupport
-
# = XmlMini
-
#
-
# To use the much faster libxml parser:
-
# gem 'libxml-ruby', '=0.9.7'
-
# XmlMini.backend = 'LibXML'
-
2
module XmlMini
-
2
extend self
-
-
# This module decorates files deserialized using Hash.from_xml with
-
# the <tt>original_filename</tt> and <tt>content_type</tt> methods.
-
2
module FileLike #:nodoc:
-
2
attr_writer :original_filename, :content_type
-
-
2
def original_filename
-
@original_filename || 'untitled'
-
end
-
-
2
def content_type
-
@content_type || 'application/octet-stream'
-
end
-
end
-
-
DEFAULT_ENCODINGS = {
-
"binary" => "base64"
-
2
} unless defined?(DEFAULT_ENCODINGS)
-
-
TYPE_NAMES = {
-
"Symbol" => "symbol",
-
"Fixnum" => "integer",
-
"Bignum" => "integer",
-
"BigDecimal" => "decimal",
-
"Float" => "float",
-
"TrueClass" => "boolean",
-
"FalseClass" => "boolean",
-
"Date" => "date",
-
"DateTime" => "dateTime",
-
"Time" => "dateTime",
-
"Array" => "array",
-
"Hash" => "hash"
-
2
} unless defined?(TYPE_NAMES)
-
-
FORMATTING = {
-
"symbol" => Proc.new { |symbol| symbol.to_s },
-
"date" => Proc.new { |date| date.to_s(:db) },
-
"dateTime" => Proc.new { |time| time.xmlschema },
-
"binary" => Proc.new { |binary| ::Base64.encode64(binary) },
-
"yaml" => Proc.new { |yaml| yaml.to_yaml }
-
2
} unless defined?(FORMATTING)
-
-
# TODO use regexp instead of Date.parse
-
2
unless defined?(PARSING)
-
2
PARSING = {
-
"symbol" => Proc.new { |symbol| symbol.to_s.to_sym },
-
"date" => Proc.new { |date| ::Date.parse(date) },
-
"datetime" => Proc.new { |time| Time.xmlschema(time).utc rescue ::DateTime.parse(time).utc },
-
"integer" => Proc.new { |integer| integer.to_i },
-
"float" => Proc.new { |float| float.to_f },
-
"decimal" => Proc.new { |number| BigDecimal(number) },
-
"boolean" => Proc.new { |boolean| %w(1 true).include?(boolean.to_s.strip) },
-
"string" => Proc.new { |string| string.to_s },
-
"yaml" => Proc.new { |yaml| YAML::load(yaml) rescue yaml },
-
"base64Binary" => Proc.new { |bin| ::Base64.decode64(bin) },
-
"binary" => Proc.new { |bin, entity| _parse_binary(bin, entity) },
-
"file" => Proc.new { |file, entity| _parse_file(file, entity) }
-
}
-
-
2
PARSING.update(
-
"double" => PARSING["float"],
-
"dateTime" => PARSING["datetime"]
-
)
-
end
-
-
2
delegate :parse, :to => :backend
-
-
2
def backend
-
current_thread_backend || @backend
-
end
-
-
2
def backend=(name)
-
2
backend = name && cast_backend_name_to_module(name)
-
2
self.current_thread_backend = backend if current_thread_backend
-
2
@backend = backend
-
end
-
-
2
def with_backend(name)
-
old_backend = current_thread_backend
-
self.current_thread_backend = name && cast_backend_name_to_module(name)
-
yield
-
ensure
-
self.current_thread_backend = old_backend
-
end
-
-
2
def to_tag(key, value, options)
-
type_name = options.delete(:type)
-
merged_options = options.merge(:root => key, :skip_instruct => true)
-
-
if value.is_a?(::Method) || value.is_a?(::Proc)
-
if value.arity == 1
-
value.call(merged_options)
-
else
-
value.call(merged_options, key.to_s.singularize)
-
end
-
elsif value.respond_to?(:to_xml)
-
value.to_xml(merged_options)
-
else
-
type_name ||= TYPE_NAMES[value.class.name]
-
type_name ||= value.class.name if value && !value.respond_to?(:to_str)
-
type_name = type_name.to_s if type_name
-
type_name = "dateTime" if type_name == "datetime"
-
-
key = rename_key(key.to_s, options)
-
-
attributes = options[:skip_types] || type_name.nil? ? { } : { :type => type_name }
-
attributes[:nil] = true if value.nil?
-
-
encoding = options[:encoding] || DEFAULT_ENCODINGS[type_name]
-
attributes[:encoding] = encoding if encoding
-
-
formatted_value = FORMATTING[type_name] && !value.nil? ?
-
FORMATTING[type_name].call(value) : value
-
-
options[:builder].tag!(key, formatted_value, attributes)
-
end
-
end
-
-
2
def rename_key(key, options = {})
-
camelize = options[:camelize]
-
dasherize = !options.has_key?(:dasherize) || options[:dasherize]
-
if camelize
-
key = true == camelize ? key.camelize : key.camelize(camelize)
-
end
-
key = _dasherize(key) if dasherize
-
key
-
end
-
-
2
protected
-
-
2
def _dasherize(key)
-
# $2 must be a non-greedy regex for this to work
-
left, middle, right = /\A(_*)(.*?)(_*)\Z/.match(key.strip)[1,3]
-
"#{left}#{middle.tr('_ ', '--')}#{right}"
-
end
-
-
# TODO: Add support for other encodings
-
2
def _parse_binary(bin, entity) #:nodoc:
-
case entity['encoding']
-
when 'base64'
-
::Base64.decode64(bin)
-
else
-
bin
-
end
-
end
-
-
2
def _parse_file(file, entity)
-
f = StringIO.new(::Base64.decode64(file))
-
f.extend(FileLike)
-
f.original_filename = entity['name']
-
f.content_type = entity['content_type']
-
f
-
end
-
-
2
private
-
-
2
def current_thread_backend
-
2
Thread.current[:xml_mini_backend]
-
end
-
-
2
def current_thread_backend=(name)
-
Thread.current[:xml_mini_backend] = name && cast_backend_name_to_module(name)
-
end
-
-
2
def cast_backend_name_to_module(name)
-
2
if name.is_a?(Module)
-
name
-
else
-
2
require "active_support/xml_mini/#{name.downcase}"
-
2
ActiveSupport.const_get("XmlMini_#{name}")
-
end
-
end
-
end
-
-
2
XmlMini.backend = 'REXML'
-
end
-
2
require 'active_support/core_ext/kernel/reporting'
-
2
require 'active_support/core_ext/object/blank'
-
2
require 'stringio'
-
-
2
module ActiveSupport
-
2
module XmlMini_REXML #:nodoc:
-
2
extend self
-
-
2
CONTENT_KEY = '__content__'.freeze
-
-
# Parse an XML Document string or IO into a simple hash.
-
#
-
# Same as XmlSimple::xml_in but doesn't shoot itself in the foot,
-
# and uses the defaults from Active Support.
-
#
-
# data::
-
# XML Document string or IO to parse
-
2
def parse(data)
-
if !data.respond_to?(:read)
-
data = StringIO.new(data || '')
-
end
-
-
char = data.getc
-
if char.nil?
-
{}
-
else
-
data.ungetc(char)
-
silence_warnings { require 'rexml/document' } unless defined?(REXML::Document)
-
doc = REXML::Document.new(data)
-
-
if doc.root
-
merge_element!({}, doc.root)
-
else
-
raise REXML::ParseException,
-
"The document #{doc.to_s.inspect} does not have a valid root"
-
end
-
end
-
end
-
-
2
private
-
# Convert an XML element and merge into the hash
-
#
-
# hash::
-
# Hash to merge the converted element into.
-
# element::
-
# XML element to merge into hash
-
2
def merge_element!(hash, element)
-
merge!(hash, element.name, collapse(element))
-
end
-
-
# Actually converts an XML document element into a data structure.
-
#
-
# element::
-
# The document element to be collapsed.
-
2
def collapse(element)
-
hash = get_attributes(element)
-
-
if element.has_elements?
-
element.each_element {|child| merge_element!(hash, child) }
-
merge_texts!(hash, element) unless empty_content?(element)
-
hash
-
else
-
merge_texts!(hash, element)
-
end
-
end
-
-
# Merge all the texts of an element into the hash
-
#
-
# hash::
-
# Hash to add the converted element to.
-
# element::
-
# XML element whose texts are to me merged into the hash
-
2
def merge_texts!(hash, element)
-
unless element.has_text?
-
hash
-
else
-
# must use value to prevent double-escaping
-
texts = ''
-
element.texts.each { |t| texts << t.value }
-
merge!(hash, CONTENT_KEY, texts)
-
end
-
end
-
-
# Adds a new key/value pair to an existing Hash. If the key to be added
-
# already exists and the existing value associated with key is not
-
# an Array, it will be wrapped in an Array. Then the new value is
-
# appended to that Array.
-
#
-
# hash::
-
# Hash to add key/value pair to.
-
# key::
-
# Key to be added.
-
# value::
-
# Value to be associated with key.
-
2
def merge!(hash, key, value)
-
if hash.has_key?(key)
-
if hash[key].instance_of?(Array)
-
hash[key] << value
-
else
-
hash[key] = [hash[key], value]
-
end
-
elsif value.instance_of?(Array)
-
hash[key] = [value]
-
else
-
hash[key] = value
-
end
-
hash
-
end
-
-
# Converts the attributes array of an XML element into a hash.
-
# Returns an empty Hash if node has no attributes.
-
#
-
# element::
-
# XML element to extract attributes from.
-
2
def get_attributes(element)
-
attributes = {}
-
element.attributes.each { |n,v| attributes[n] = v }
-
attributes
-
end
-
-
# Determines if a document element has text content
-
#
-
# element::
-
# XML element to be checked.
-
2
def empty_content?(element)
-
element.texts.join.blank?
-
end
-
end
-
end
-
# encoding:utf-8
-
#--
-
# Copyright (C) 2006-2015 Bob Aman
-
#
-
# Licensed under the Apache License, Version 2.0 (the "License");
-
# you may not use this file except in compliance with the License.
-
# You may obtain a copy of the License at
-
#
-
# http://www.apache.org/licenses/LICENSE-2.0
-
#
-
# Unless required by applicable law or agreed to in writing, software
-
# distributed under the License is distributed on an "AS IS" BASIS,
-
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-
# See the License for the specific language governing permissions and
-
# limitations under the License.
-
#++
-
-
-
2
begin
-
2
require "addressable/idna/native"
-
rescue LoadError
-
# libidn or the idn gem was not available, fall back on a pure-Ruby
-
# implementation...
-
2
require "addressable/idna/pure"
-
end
-
# encoding:utf-8
-
#--
-
# Copyright (C) 2006-2015 Bob Aman
-
#
-
# Licensed under the Apache License, Version 2.0 (the "License");
-
# you may not use this file except in compliance with the License.
-
# You may obtain a copy of the License at
-
#
-
# http://www.apache.org/licenses/LICENSE-2.0
-
#
-
# Unless required by applicable law or agreed to in writing, software
-
# distributed under the License is distributed on an "AS IS" BASIS,
-
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-
# See the License for the specific language governing permissions and
-
# limitations under the License.
-
#++
-
-
-
2
require "idn"
-
-
module Addressable
-
module IDNA
-
def self.punycode_encode(value)
-
IDN::Punycode.encode(value.to_s)
-
end
-
-
def self.punycode_decode(value)
-
IDN::Punycode.decode(value.to_s)
-
end
-
-
def self.unicode_normalize_kc(value)
-
IDN::Stringprep.nfkc_normalize(value.to_s)
-
end
-
-
def self.to_ascii(value)
-
value.to_s.split('.', -1).map do |segment|
-
if segment.size > 0
-
IDN::Idna.toASCII(segment)
-
else
-
''
-
end
-
end.join('.')
-
end
-
-
def self.to_unicode(value)
-
value.to_s.split('.', -1).map do |segment|
-
if segment.size > 0
-
IDN::Idna.toUnicode(segment)
-
else
-
''
-
end
-
end.join('.')
-
end
-
end
-
end
-
# encoding:utf-8
-
#--
-
# Copyright (C) 2006-2015 Bob Aman
-
#
-
# Licensed under the Apache License, Version 2.0 (the "License");
-
# you may not use this file except in compliance with the License.
-
# You may obtain a copy of the License at
-
#
-
# http://www.apache.org/licenses/LICENSE-2.0
-
#
-
# Unless required by applicable law or agreed to in writing, software
-
# distributed under the License is distributed on an "AS IS" BASIS,
-
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-
# See the License for the specific language governing permissions and
-
# limitations under the License.
-
#++
-
-
-
2
module Addressable
-
2
module IDNA
-
# This module is loosely based on idn_actionmailer by Mick Staugaard,
-
# the unicode library by Yoshida Masato, and the punycode implementation
-
# by Kazuhiro Nishiyama. Most of the code was copied verbatim, but
-
# some reformatting was done, and some translation from C was done.
-
#
-
# Without their code to work from as a base, we'd all still be relying
-
# on the presence of libidn. Which nobody ever seems to have installed.
-
#
-
# Original sources:
-
# http://github.com/staugaard/idn_actionmailer
-
# http://www.yoshidam.net/Ruby.html#unicode
-
# http://rubyforge.org/frs/?group_id=2550
-
-
-
2
UNICODE_TABLE = File.expand_path(
-
File.join(File.dirname(__FILE__), '../../..', 'data/unicode.data')
-
)
-
-
2
ACE_PREFIX = "xn--"
-
-
2
UTF8_REGEX = /\A(?:
-
[\x09\x0A\x0D\x20-\x7E] # ASCII
-
| [\xC2-\xDF][\x80-\xBF] # non-overlong 2-byte
-
| \xE0[\xA0-\xBF][\x80-\xBF] # excluding overlongs
-
| [\xE1-\xEC\xEE\xEF][\x80-\xBF]{2} # straight 3-byte
-
| \xED[\x80-\x9F][\x80-\xBF] # excluding surrogates
-
| \xF0[\x90-\xBF][\x80-\xBF]{2} # planes 1-3
-
| [\xF1-\xF3][\x80-\xBF]{3} # planes 4nil5
-
| \xF4[\x80-\x8F][\x80-\xBF]{2} # plane 16
-
)*\z/mnx
-
-
2
UTF8_REGEX_MULTIBYTE = /(?:
-
[\xC2-\xDF][\x80-\xBF] # non-overlong 2-byte
-
| \xE0[\xA0-\xBF][\x80-\xBF] # excluding overlongs
-
| [\xE1-\xEC\xEE\xEF][\x80-\xBF]{2} # straight 3-byte
-
| \xED[\x80-\x9F][\x80-\xBF] # excluding surrogates
-
| \xF0[\x90-\xBF][\x80-\xBF]{2} # planes 1-3
-
| [\xF1-\xF3][\x80-\xBF]{3} # planes 4nil5
-
| \xF4[\x80-\x8F][\x80-\xBF]{2} # plane 16
-
)/mnx
-
-
# :startdoc:
-
-
# Converts from a Unicode internationalized domain name to an ASCII
-
# domain name as described in RFC 3490.
-
2
def self.to_ascii(input)
-
input = input.to_s unless input.is_a?(String)
-
input = input.dup
-
if input.respond_to?(:force_encoding)
-
input.force_encoding(Encoding::ASCII_8BIT)
-
end
-
if input =~ UTF8_REGEX && input =~ UTF8_REGEX_MULTIBYTE
-
parts = unicode_downcase(input).split('.')
-
parts.map! do |part|
-
if part.respond_to?(:force_encoding)
-
part.force_encoding(Encoding::ASCII_8BIT)
-
end
-
if part =~ UTF8_REGEX && part =~ UTF8_REGEX_MULTIBYTE
-
ACE_PREFIX + punycode_encode(unicode_normalize_kc(part))
-
else
-
part
-
end
-
end
-
parts.join('.')
-
else
-
input
-
end
-
end
-
-
# Converts from an ASCII domain name to a Unicode internationalized
-
# domain name as described in RFC 3490.
-
2
def self.to_unicode(input)
-
input = input.to_s unless input.is_a?(String)
-
parts = input.split('.')
-
parts.map! do |part|
-
if part =~ /^#{ACE_PREFIX}(.+)/
-
punycode_decode(part[/^#{ACE_PREFIX}(.+)/, 1])
-
else
-
part
-
end
-
end
-
output = parts.join('.')
-
if output.respond_to?(:force_encoding)
-
output.force_encoding(Encoding::UTF_8)
-
end
-
output
-
end
-
-
# Unicode normalization form KC.
-
2
def self.unicode_normalize_kc(input)
-
input = input.to_s unless input.is_a?(String)
-
unpacked = input.unpack("U*")
-
unpacked =
-
unicode_compose(unicode_sort_canonical(unicode_decompose(unpacked)))
-
return unpacked.pack("U*")
-
end
-
-
##
-
# Unicode aware downcase method.
-
#
-
# @api private
-
# @param [String] input
-
# The input string.
-
# @return [String] The downcased result.
-
2
def self.unicode_downcase(input)
-
input = input.to_s unless input.is_a?(String)
-
unpacked = input.unpack("U*")
-
unpacked.map! { |codepoint| lookup_unicode_lowercase(codepoint) }
-
return unpacked.pack("U*")
-
end
-
4
(class <<self; private :unicode_downcase; end)
-
-
2
def self.unicode_compose(unpacked)
-
unpacked_result = []
-
length = unpacked.length
-
-
return unpacked if length == 0
-
-
starter = unpacked[0]
-
starter_cc = lookup_unicode_combining_class(starter)
-
starter_cc = 256 if starter_cc != 0
-
for i in 1...length
-
ch = unpacked[i]
-
cc = lookup_unicode_combining_class(ch)
-
-
if (starter_cc == 0 &&
-
(composite = unicode_compose_pair(starter, ch)) != nil)
-
starter = composite
-
startercc = lookup_unicode_combining_class(composite)
-
else
-
unpacked_result << starter
-
starter = ch
-
startercc = cc
-
end
-
end
-
unpacked_result << starter
-
return unpacked_result
-
end
-
4
(class <<self; private :unicode_compose; end)
-
-
2
def self.unicode_compose_pair(ch_one, ch_two)
-
if ch_one >= HANGUL_LBASE && ch_one < HANGUL_LBASE + HANGUL_LCOUNT &&
-
ch_two >= HANGUL_VBASE && ch_two < HANGUL_VBASE + HANGUL_VCOUNT
-
# Hangul L + V
-
return HANGUL_SBASE + (
-
(ch_one - HANGUL_LBASE) * HANGUL_VCOUNT + (ch_two - HANGUL_VBASE)
-
) * HANGUL_TCOUNT
-
elsif ch_one >= HANGUL_SBASE &&
-
ch_one < HANGUL_SBASE + HANGUL_SCOUNT &&
-
(ch_one - HANGUL_SBASE) % HANGUL_TCOUNT == 0 &&
-
ch_two >= HANGUL_TBASE && ch_two < HANGUL_TBASE + HANGUL_TCOUNT
-
# Hangul LV + T
-
return ch_one + (ch_two - HANGUL_TBASE)
-
end
-
-
p = []
-
ucs4_to_utf8 = lambda do |ch|
-
if ch < 128
-
p << ch
-
elsif ch < 2048
-
p << (ch >> 6 | 192)
-
p << (ch & 63 | 128)
-
elsif ch < 0x10000
-
p << (ch >> 12 | 224)
-
p << (ch >> 6 & 63 | 128)
-
p << (ch & 63 | 128)
-
elsif ch < 0x200000
-
p << (ch >> 18 | 240)
-
p << (ch >> 12 & 63 | 128)
-
p << (ch >> 6 & 63 | 128)
-
p << (ch & 63 | 128)
-
elsif ch < 0x4000000
-
p << (ch >> 24 | 248)
-
p << (ch >> 18 & 63 | 128)
-
p << (ch >> 12 & 63 | 128)
-
p << (ch >> 6 & 63 | 128)
-
p << (ch & 63 | 128)
-
elsif ch < 0x80000000
-
p << (ch >> 30 | 252)
-
p << (ch >> 24 & 63 | 128)
-
p << (ch >> 18 & 63 | 128)
-
p << (ch >> 12 & 63 | 128)
-
p << (ch >> 6 & 63 | 128)
-
p << (ch & 63 | 128)
-
end
-
end
-
-
ucs4_to_utf8.call(ch_one)
-
ucs4_to_utf8.call(ch_two)
-
-
return lookup_unicode_composition(p)
-
end
-
4
(class <<self; private :unicode_compose_pair; end)
-
-
2
def self.unicode_sort_canonical(unpacked)
-
unpacked = unpacked.dup
-
i = 1
-
length = unpacked.length
-
-
return unpacked if length < 2
-
-
while i < length
-
last = unpacked[i-1]
-
ch = unpacked[i]
-
last_cc = lookup_unicode_combining_class(last)
-
cc = lookup_unicode_combining_class(ch)
-
if cc != 0 && last_cc != 0 && last_cc > cc
-
unpacked[i] = last
-
unpacked[i-1] = ch
-
i -= 1 if i > 1
-
else
-
i += 1
-
end
-
end
-
return unpacked
-
end
-
4
(class <<self; private :unicode_sort_canonical; end)
-
-
2
def self.unicode_decompose(unpacked)
-
unpacked_result = []
-
for cp in unpacked
-
if cp >= HANGUL_SBASE && cp < HANGUL_SBASE + HANGUL_SCOUNT
-
l, v, t = unicode_decompose_hangul(cp)
-
unpacked_result << l
-
unpacked_result << v if v
-
unpacked_result << t if t
-
else
-
dc = lookup_unicode_compatibility(cp)
-
unless dc
-
unpacked_result << cp
-
else
-
unpacked_result.concat(unicode_decompose(dc.unpack("U*")))
-
end
-
end
-
end
-
return unpacked_result
-
end
-
4
(class <<self; private :unicode_decompose; end)
-
-
2
def self.unicode_decompose_hangul(codepoint)
-
sindex = codepoint - HANGUL_SBASE;
-
if sindex < 0 || sindex >= HANGUL_SCOUNT
-
l = codepoint
-
v = t = nil
-
return l, v, t
-
end
-
l = HANGUL_LBASE + sindex / HANGUL_NCOUNT
-
v = HANGUL_VBASE + (sindex % HANGUL_NCOUNT) / HANGUL_TCOUNT
-
t = HANGUL_TBASE + sindex % HANGUL_TCOUNT
-
if t == HANGUL_TBASE
-
t = nil
-
end
-
return l, v, t
-
end
-
4
(class <<self; private :unicode_decompose_hangul; end)
-
-
2
def self.lookup_unicode_combining_class(codepoint)
-
codepoint_data = UNICODE_DATA[codepoint]
-
(codepoint_data ?
-
(codepoint_data[UNICODE_DATA_COMBINING_CLASS] || 0) :
-
0)
-
end
-
4
(class <<self; private :lookup_unicode_combining_class; end)
-
-
2
def self.lookup_unicode_compatibility(codepoint)
-
codepoint_data = UNICODE_DATA[codepoint]
-
(codepoint_data ?
-
codepoint_data[UNICODE_DATA_COMPATIBILITY] : nil)
-
end
-
4
(class <<self; private :lookup_unicode_compatibility; end)
-
-
2
def self.lookup_unicode_lowercase(codepoint)
-
codepoint_data = UNICODE_DATA[codepoint]
-
(codepoint_data ?
-
(codepoint_data[UNICODE_DATA_LOWERCASE] || codepoint) :
-
codepoint)
-
end
-
4
(class <<self; private :lookup_unicode_lowercase; end)
-
-
2
def self.lookup_unicode_composition(unpacked)
-
return COMPOSITION_TABLE[unpacked]
-
end
-
4
(class <<self; private :lookup_unicode_composition; end)
-
-
2
HANGUL_SBASE = 0xac00
-
2
HANGUL_LBASE = 0x1100
-
2
HANGUL_LCOUNT = 19
-
2
HANGUL_VBASE = 0x1161
-
2
HANGUL_VCOUNT = 21
-
2
HANGUL_TBASE = 0x11a7
-
2
HANGUL_TCOUNT = 28
-
2
HANGUL_NCOUNT = HANGUL_VCOUNT * HANGUL_TCOUNT # 588
-
2
HANGUL_SCOUNT = HANGUL_LCOUNT * HANGUL_NCOUNT # 11172
-
-
2
UNICODE_DATA_COMBINING_CLASS = 0
-
2
UNICODE_DATA_EXCLUSION = 1
-
2
UNICODE_DATA_CANONICAL = 2
-
2
UNICODE_DATA_COMPATIBILITY = 3
-
2
UNICODE_DATA_UPPERCASE = 4
-
2
UNICODE_DATA_LOWERCASE = 5
-
2
UNICODE_DATA_TITLECASE = 6
-
-
2
begin
-
2
if defined?(FakeFS)
-
fakefs_state = FakeFS.activated?
-
FakeFS.deactivate!
-
end
-
# This is a sparse Unicode table. Codepoints without entries are
-
# assumed to have the value: [0, 0, nil, nil, nil, nil, nil]
-
2
UNICODE_DATA = File.open(UNICODE_TABLE, "rb") do |file|
-
2
Marshal.load(file.read)
-
end
-
ensure
-
2
if defined?(FakeFS)
-
FakeFS.activate! if fakefs_state
-
end
-
end
-
-
2
COMPOSITION_TABLE = {}
-
2
for codepoint, data in UNICODE_DATA
-
8466
canonical = data[UNICODE_DATA_CANONICAL]
-
8466
exclusion = data[UNICODE_DATA_EXCLUSION]
-
-
8466
if canonical && exclusion == 0
-
1836
COMPOSITION_TABLE[canonical.unpack("C*")] = codepoint
-
end
-
end
-
-
2
UNICODE_MAX_LENGTH = 256
-
2
ACE_MAX_LENGTH = 256
-
-
2
PUNYCODE_BASE = 36
-
2
PUNYCODE_TMIN = 1
-
2
PUNYCODE_TMAX = 26
-
2
PUNYCODE_SKEW = 38
-
2
PUNYCODE_DAMP = 700
-
2
PUNYCODE_INITIAL_BIAS = 72
-
2
PUNYCODE_INITIAL_N = 0x80
-
2
PUNYCODE_DELIMITER = 0x2D
-
-
2
PUNYCODE_MAXINT = 1 << 64
-
-
2
PUNYCODE_PRINT_ASCII =
-
"\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n" +
-
"\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n" +
-
" !\"\#$%&'()*+,-./" +
-
"0123456789:;<=>?" +
-
"@ABCDEFGHIJKLMNO" +
-
"PQRSTUVWXYZ[\\]^_" +
-
"`abcdefghijklmno" +
-
"pqrstuvwxyz{|}~\n"
-
-
# Input is invalid.
-
2
class PunycodeBadInput < StandardError; end
-
# Output would exceed the space provided.
-
2
class PunycodeBigOutput < StandardError; end
-
# Input needs wider integers to process.
-
2
class PunycodeOverflow < StandardError; end
-
-
2
def self.punycode_encode(unicode)
-
unicode = unicode.to_s unless unicode.is_a?(String)
-
input = unicode.unpack("U*")
-
output = [0] * (ACE_MAX_LENGTH + 1)
-
input_length = input.size
-
output_length = [ACE_MAX_LENGTH]
-
-
# Initialize the state
-
n = PUNYCODE_INITIAL_N
-
delta = out = 0
-
max_out = output_length[0]
-
bias = PUNYCODE_INITIAL_BIAS
-
-
# Handle the basic code points:
-
input_length.times do |j|
-
if punycode_basic?(input[j])
-
if max_out - out < 2
-
raise PunycodeBigOutput,
-
"Output would exceed the space provided."
-
end
-
output[out] = input[j]
-
out += 1
-
end
-
end
-
-
h = b = out
-
-
# h is the number of code points that have been handled, b is the
-
# number of basic code points, and out is the number of characters
-
# that have been output.
-
-
if b > 0
-
output[out] = PUNYCODE_DELIMITER
-
out += 1
-
end
-
-
# Main encoding loop:
-
-
while h < input_length
-
# All non-basic code points < n have been
-
# handled already. Find the next larger one:
-
-
m = PUNYCODE_MAXINT
-
input_length.times do |j|
-
m = input[j] if (n...m) === input[j]
-
end
-
-
# Increase delta enough to advance the decoder's
-
# <n,i> state to <m,0>, but guard against overflow:
-
-
if m - n > (PUNYCODE_MAXINT - delta) / (h + 1)
-
raise PunycodeOverflow, "Input needs wider integers to process."
-
end
-
delta += (m - n) * (h + 1)
-
n = m
-
-
input_length.times do |j|
-
# Punycode does not need to check whether input[j] is basic:
-
if input[j] < n
-
delta += 1
-
if delta == 0
-
raise PunycodeOverflow,
-
"Input needs wider integers to process."
-
end
-
end
-
-
if input[j] == n
-
# Represent delta as a generalized variable-length integer:
-
-
q = delta; k = PUNYCODE_BASE
-
while true
-
if out >= max_out
-
raise PunycodeBigOutput,
-
"Output would exceed the space provided."
-
end
-
t = (
-
if k <= bias
-
PUNYCODE_TMIN
-
elsif k >= bias + PUNYCODE_TMAX
-
PUNYCODE_TMAX
-
else
-
k - bias
-
end
-
)
-
break if q < t
-
output[out] =
-
punycode_encode_digit(t + (q - t) % (PUNYCODE_BASE - t))
-
out += 1
-
q = (q - t) / (PUNYCODE_BASE - t)
-
k += PUNYCODE_BASE
-
end
-
-
output[out] = punycode_encode_digit(q)
-
out += 1
-
bias = punycode_adapt(delta, h + 1, h == b)
-
delta = 0
-
h += 1
-
end
-
end
-
-
delta += 1
-
n += 1
-
end
-
-
output_length[0] = out
-
-
outlen = out
-
outlen.times do |j|
-
c = output[j]
-
unless c >= 0 && c <= 127
-
raise StandardError, "Invalid output char."
-
end
-
unless PUNYCODE_PRINT_ASCII[c]
-
raise PunycodeBadInput, "Input is invalid."
-
end
-
end
-
-
output[0..outlen].map { |x| x.chr }.join("").sub(/\0+\z/, "")
-
end
-
4
(class <<self; private :punycode_encode; end)
-
-
2
def self.punycode_decode(punycode)
-
input = []
-
output = []
-
-
if ACE_MAX_LENGTH * 2 < punycode.size
-
raise PunycodeBigOutput, "Output would exceed the space provided."
-
end
-
punycode.each_byte do |c|
-
unless c >= 0 && c <= 127
-
raise PunycodeBadInput, "Input is invalid."
-
end
-
input.push(c)
-
end
-
-
input_length = input.length
-
output_length = [UNICODE_MAX_LENGTH]
-
-
# Initialize the state
-
n = PUNYCODE_INITIAL_N
-
-
out = i = 0
-
max_out = output_length[0]
-
bias = PUNYCODE_INITIAL_BIAS
-
-
# Handle the basic code points: Let b be the number of input code
-
# points before the last delimiter, or 0 if there is none, then
-
# copy the first b code points to the output.
-
-
b = 0
-
input_length.times do |j|
-
b = j if punycode_delimiter?(input[j])
-
end
-
if b > max_out
-
raise PunycodeBigOutput, "Output would exceed the space provided."
-
end
-
-
b.times do |j|
-
unless punycode_basic?(input[j])
-
raise PunycodeBadInput, "Input is invalid."
-
end
-
output[out] = input[j]
-
out+=1
-
end
-
-
# Main decoding loop: Start just after the last delimiter if any
-
# basic code points were copied; start at the beginning otherwise.
-
-
in_ = b > 0 ? b + 1 : 0
-
while in_ < input_length
-
-
# in_ is the index of the next character to be consumed, and
-
# out is the number of code points in the output array.
-
-
# Decode a generalized variable-length integer into delta,
-
# which gets added to i. The overflow checking is easier
-
# if we increase i as we go, then subtract off its starting
-
# value at the end to obtain delta.
-
-
oldi = i; w = 1; k = PUNYCODE_BASE
-
while true
-
if in_ >= input_length
-
raise PunycodeBadInput, "Input is invalid."
-
end
-
digit = punycode_decode_digit(input[in_])
-
in_+=1
-
if digit >= PUNYCODE_BASE
-
raise PunycodeBadInput, "Input is invalid."
-
end
-
if digit > (PUNYCODE_MAXINT - i) / w
-
raise PunycodeOverflow, "Input needs wider integers to process."
-
end
-
i += digit * w
-
t = (
-
if k <= bias
-
PUNYCODE_TMIN
-
elsif k >= bias + PUNYCODE_TMAX
-
PUNYCODE_TMAX
-
else
-
k - bias
-
end
-
)
-
break if digit < t
-
if w > PUNYCODE_MAXINT / (PUNYCODE_BASE - t)
-
raise PunycodeOverflow, "Input needs wider integers to process."
-
end
-
w *= PUNYCODE_BASE - t
-
k += PUNYCODE_BASE
-
end
-
-
bias = punycode_adapt(i - oldi, out + 1, oldi == 0)
-
-
# I was supposed to wrap around from out + 1 to 0,
-
# incrementing n each time, so we'll fix that now:
-
-
if i / (out + 1) > PUNYCODE_MAXINT - n
-
raise PunycodeOverflow, "Input needs wider integers to process."
-
end
-
n += i / (out + 1)
-
i %= out + 1
-
-
# Insert n at position i of the output:
-
-
# not needed for Punycode:
-
# raise PUNYCODE_INVALID_INPUT if decode_digit(n) <= base
-
if out >= max_out
-
raise PunycodeBigOutput, "Output would exceed the space provided."
-
end
-
-
#memmove(output + i + 1, output + i, (out - i) * sizeof *output)
-
output[i + 1, out - i] = output[i, out - i]
-
output[i] = n
-
i += 1
-
-
out += 1
-
end
-
-
output_length[0] = out
-
-
output.pack("U*")
-
end
-
4
(class <<self; private :punycode_decode; end)
-
-
2
def self.punycode_basic?(codepoint)
-
codepoint < 0x80
-
end
-
4
(class <<self; private :punycode_basic?; end)
-
-
2
def self.punycode_delimiter?(codepoint)
-
codepoint == PUNYCODE_DELIMITER
-
end
-
4
(class <<self; private :punycode_delimiter?; end)
-
-
2
def self.punycode_encode_digit(d)
-
d + 22 + 75 * ((d < 26) ? 1 : 0)
-
end
-
4
(class <<self; private :punycode_encode_digit; end)
-
-
# Returns the numeric value of a basic codepoint
-
# (for use in representing integers) in the range 0 to
-
# base - 1, or PUNYCODE_BASE if codepoint does not represent a value.
-
2
def self.punycode_decode_digit(codepoint)
-
if codepoint - 48 < 10
-
codepoint - 22
-
elsif codepoint - 65 < 26
-
codepoint - 65
-
elsif codepoint - 97 < 26
-
codepoint - 97
-
else
-
PUNYCODE_BASE
-
end
-
end
-
4
(class <<self; private :punycode_decode_digit; end)
-
-
# Bias adaptation method
-
2
def self.punycode_adapt(delta, numpoints, firsttime)
-
delta = firsttime ? delta / PUNYCODE_DAMP : delta >> 1
-
# delta >> 1 is a faster way of doing delta / 2
-
delta += delta / numpoints
-
difference = PUNYCODE_BASE - PUNYCODE_TMIN
-
-
k = 0
-
while delta > (difference * PUNYCODE_TMAX) / 2
-
delta /= difference
-
k += PUNYCODE_BASE
-
end
-
-
k + (difference + 1) * delta / (delta + PUNYCODE_SKEW)
-
end
-
4
(class <<self; private :punycode_adapt; end)
-
end
-
# :startdoc:
-
end
-
# encoding:utf-8
-
#--
-
# Copyright (C) 2006-2015 Bob Aman
-
#
-
# Licensed under the Apache License, Version 2.0 (the "License");
-
# you may not use this file except in compliance with the License.
-
# You may obtain a copy of the License at
-
#
-
# http://www.apache.org/licenses/LICENSE-2.0
-
#
-
# Unless required by applicable law or agreed to in writing, software
-
# distributed under the License is distributed on an "AS IS" BASIS,
-
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-
# See the License for the specific language governing permissions and
-
# limitations under the License.
-
#++
-
-
-
2
require "addressable/version"
-
2
require "addressable/idna"
-
-
##
-
# Addressable is a library for processing links and URIs.
-
2
module Addressable
-
##
-
# This is an implementation of a URI parser based on
-
# <a href="http://www.ietf.org/rfc/rfc3986.txt">RFC 3986</a>,
-
# <a href="http://www.ietf.org/rfc/rfc3987.txt">RFC 3987</a>.
-
2
class URI
-
##
-
# Raised if something other than a uri is supplied.
-
2
class InvalidURIError < StandardError
-
end
-
-
##
-
# Container for the character classes specified in
-
# <a href="http://www.ietf.org/rfc/rfc3986.txt">RFC 3986</a>.
-
2
module CharacterClasses
-
2
ALPHA = "a-zA-Z"
-
2
DIGIT = "0-9"
-
2
GEN_DELIMS = "\\:\\/\\?\\#\\[\\]\\@"
-
2
SUB_DELIMS = "\\!\\$\\&\\'\\(\\)\\*\\+\\,\\;\\="
-
2
RESERVED = GEN_DELIMS + SUB_DELIMS
-
2
UNRESERVED = ALPHA + DIGIT + "\\-\\.\\_\\~"
-
2
PCHAR = UNRESERVED + SUB_DELIMS + "\\:\\@"
-
2
SCHEME = ALPHA + DIGIT + "\\-\\+\\."
-
2
HOST = ALPHA + DIGIT + "\\-\\.\\[\\:\\]"
-
2
AUTHORITY = PCHAR
-
2
PATH = PCHAR + "\\/"
-
2
QUERY = PCHAR + "\\/\\?"
-
2
FRAGMENT = PCHAR + "\\/\\?"
-
end
-
-
2
SLASH = '/'
-
2
EMPTY_STR = ''
-
-
2
URIREGEX = /^(([^:\/?#]+):)?(\/\/([^\/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?$/
-
-
2
PORT_MAPPING = {
-
"http" => 80,
-
"https" => 443,
-
"ftp" => 21,
-
"tftp" => 69,
-
"sftp" => 22,
-
"ssh" => 22,
-
"svn+ssh" => 22,
-
"telnet" => 23,
-
"nntp" => 119,
-
"gopher" => 70,
-
"wais" => 210,
-
"ldap" => 389,
-
"prospero" => 1525
-
}
-
-
##
-
# Returns a URI object based on the parsed string.
-
#
-
# @param [String, Addressable::URI, #to_str] uri
-
# The URI string to parse.
-
# No parsing is performed if the object is already an
-
# <code>Addressable::URI</code>.
-
#
-
# @return [Addressable::URI] The parsed URI.
-
2
def self.parse(uri)
-
# If we were given nil, return nil.
-
return nil unless uri
-
# If a URI object is passed, just return itself.
-
return uri.dup if uri.kind_of?(self)
-
-
# If a URI object of the Ruby standard library variety is passed,
-
# convert it to a string, then parse the string.
-
# We do the check this way because we don't want to accidentally
-
# cause a missing constant exception to be thrown.
-
if uri.class.name =~ /^URI\b/
-
uri = uri.to_s
-
end
-
-
# Otherwise, convert to a String
-
begin
-
uri = uri.to_str
-
rescue TypeError, NoMethodError
-
raise TypeError, "Can't convert #{uri.class} into String."
-
end if not uri.is_a? String
-
-
# This Regexp supplied as an example in RFC 3986, and it works great.
-
scan = uri.scan(URIREGEX)
-
fragments = scan[0]
-
scheme = fragments[1]
-
authority = fragments[3]
-
path = fragments[4]
-
query = fragments[6]
-
fragment = fragments[8]
-
user = nil
-
password = nil
-
host = nil
-
port = nil
-
if authority != nil
-
# The Regexp above doesn't split apart the authority.
-
userinfo = authority[/^([^\[\]]*)@/, 1]
-
if userinfo != nil
-
user = userinfo.strip[/^([^:]*):?/, 1]
-
password = userinfo.strip[/:(.*)$/, 1]
-
end
-
host = authority.gsub(
-
/^([^\[\]]*)@/, EMPTY_STR
-
).gsub(
-
/:([^:@\[\]]*?)$/, EMPTY_STR
-
)
-
port = authority[/:([^:@\[\]]*?)$/, 1]
-
end
-
if port == EMPTY_STR
-
port = nil
-
end
-
-
return new(
-
:scheme => scheme,
-
:user => user,
-
:password => password,
-
:host => host,
-
:port => port,
-
:path => path,
-
:query => query,
-
:fragment => fragment
-
)
-
end
-
-
##
-
# Converts an input to a URI. The input does not have to be a valid
-
# URI — the method will use heuristics to guess what URI was intended.
-
# This is not standards-compliant, merely user-friendly.
-
#
-
# @param [String, Addressable::URI, #to_str] uri
-
# The URI string to parse.
-
# No parsing is performed if the object is already an
-
# <code>Addressable::URI</code>.
-
# @param [Hash] hints
-
# A <code>Hash</code> of hints to the heuristic parser.
-
# Defaults to <code>{:scheme => "http"}</code>.
-
#
-
# @return [Addressable::URI] The parsed URI.
-
2
def self.heuristic_parse(uri, hints={})
-
# If we were given nil, return nil.
-
return nil unless uri
-
# If a URI object is passed, just return itself.
-
return uri.dup if uri.kind_of?(self)
-
-
# If a URI object of the Ruby standard library variety is passed,
-
# convert it to a string, then parse the string.
-
# We do the check this way because we don't want to accidentally
-
# cause a missing constant exception to be thrown.
-
if uri.class.name =~ /^URI\b/
-
uri = uri.to_s
-
end
-
-
if !uri.respond_to?(:to_str)
-
raise TypeError, "Can't convert #{uri.class} into String."
-
end
-
# Otherwise, convert to a String
-
uri = uri.to_str.dup
-
hints = {
-
:scheme => "http"
-
}.merge(hints)
-
case uri
-
when /^http:\/+/
-
uri.gsub!(/^http:\/+/, "http://")
-
when /^https:\/+/
-
uri.gsub!(/^https:\/+/, "https://")
-
when /^feed:\/+http:\/+/
-
uri.gsub!(/^feed:\/+http:\/+/, "feed:http://")
-
when /^feed:\/+/
-
uri.gsub!(/^feed:\/+/, "feed://")
-
when /^file:\/+/
-
uri.gsub!(/^file:\/+/, "file:///")
-
when /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}/
-
uri.gsub!(/^/, hints[:scheme] + "://")
-
end
-
parsed = self.parse(uri)
-
if parsed.scheme =~ /^[^\/?#\.]+\.[^\/?#]+$/
-
parsed = self.parse(hints[:scheme] + "://" + uri)
-
end
-
if parsed.path.include?(".")
-
new_host = parsed.path[/^([^\/]+\.[^\/]*)/, 1]
-
if new_host
-
parsed.defer_validation do
-
new_path = parsed.path.gsub(
-
Regexp.new("^" + Regexp.escape(new_host)), EMPTY_STR)
-
parsed.host = new_host
-
parsed.path = new_path
-
parsed.scheme = hints[:scheme] unless parsed.scheme
-
end
-
end
-
end
-
return parsed
-
end
-
-
##
-
# Converts a path to a file scheme URI. If the path supplied is
-
# relative, it will be returned as a relative URI. If the path supplied
-
# is actually a non-file URI, it will parse the URI as if it had been
-
# parsed with <code>Addressable::URI.parse</code>. Handles all of the
-
# various Microsoft-specific formats for specifying paths.
-
#
-
# @param [String, Addressable::URI, #to_str] path
-
# Typically a <code>String</code> path to a file or directory, but
-
# will return a sensible return value if an absolute URI is supplied
-
# instead.
-
#
-
# @return [Addressable::URI]
-
# The parsed file scheme URI or the original URI if some other URI
-
# scheme was provided.
-
#
-
# @example
-
# base = Addressable::URI.convert_path("/absolute/path/")
-
# uri = Addressable::URI.convert_path("relative/path")
-
# (base + uri).to_s
-
# #=> "file:///absolute/path/relative/path"
-
#
-
# Addressable::URI.convert_path(
-
# "c:\\windows\\My Documents 100%20\\foo.txt"
-
# ).to_s
-
# #=> "file:///c:/windows/My%20Documents%20100%20/foo.txt"
-
#
-
# Addressable::URI.convert_path("http://example.com/").to_s
-
# #=> "http://example.com/"
-
2
def self.convert_path(path)
-
# If we were given nil, return nil.
-
return nil unless path
-
# If a URI object is passed, just return itself.
-
return path if path.kind_of?(self)
-
if !path.respond_to?(:to_str)
-
raise TypeError, "Can't convert #{path.class} into String."
-
end
-
# Otherwise, convert to a String
-
path = path.to_str.strip
-
-
path.gsub!(/^file:\/?\/?/, EMPTY_STR) if path =~ /^file:\/?\/?/
-
path = SLASH + path if path =~ /^([a-zA-Z])[\|:]/
-
uri = self.parse(path)
-
-
if uri.scheme == nil
-
# Adjust windows-style uris
-
uri.path.gsub!(/^\/?([a-zA-Z])[\|:][\\\/]/) do
-
"/#{$1.downcase}:/"
-
end
-
uri.path.gsub!(/\\/, SLASH)
-
if File.exist?(uri.path) &&
-
File.stat(uri.path).directory?
-
uri.path.gsub!(/\/$/, EMPTY_STR)
-
uri.path = uri.path + '/'
-
end
-
-
# If the path is absolute, set the scheme and host.
-
if uri.path =~ /^\//
-
uri.scheme = "file"
-
uri.host = EMPTY_STR
-
end
-
uri.normalize!
-
end
-
-
return uri
-
end
-
-
##
-
# Joins several URIs together.
-
#
-
# @param [String, Addressable::URI, #to_str] *uris
-
# The URIs to join.
-
#
-
# @return [Addressable::URI] The joined URI.
-
#
-
# @example
-
# base = "http://example.com/"
-
# uri = Addressable::URI.parse("relative/path")
-
# Addressable::URI.join(base, uri)
-
# #=> #<Addressable::URI:0xcab390 URI:http://example.com/relative/path>
-
2
def self.join(*uris)
-
uri_objects = uris.collect do |uri|
-
if !uri.respond_to?(:to_str)
-
raise TypeError, "Can't convert #{uri.class} into String."
-
end
-
uri.kind_of?(self) ? uri : self.parse(uri.to_str)
-
end
-
result = uri_objects.shift.dup
-
for uri in uri_objects
-
result.join!(uri)
-
end
-
return result
-
end
-
-
##
-
# Percent encodes a URI component.
-
#
-
# @param [String, #to_str] component The URI component to encode.
-
#
-
# @param [String, Regexp] character_class
-
# The characters which are not percent encoded. If a <code>String</code>
-
# is passed, the <code>String</code> must be formatted as a regular
-
# expression character class. (Do not include the surrounding square
-
# brackets.) For example, <code>"b-zB-Z0-9"</code> would cause
-
# everything but the letters 'b' through 'z' and the numbers '0' through
-
# '9' to be percent encoded. If a <code>Regexp</code> is passed, the
-
# value <code>/[^b-zB-Z0-9]/</code> would have the same effect. A set of
-
# useful <code>String</code> values may be found in the
-
# <code>Addressable::URI::CharacterClasses</code> module. The default
-
# value is the reserved plus unreserved character classes specified in
-
# <a href="http://www.ietf.org/rfc/rfc3986.txt">RFC 3986</a>.
-
#
-
# @param [Regexp] upcase_encoded
-
# A string of characters that may already be percent encoded, and whose
-
# encodings should be upcased. This allows normalization of percent
-
# encodings for characters not included in the
-
# <code>character_class</code>.
-
#
-
# @return [String] The encoded component.
-
#
-
# @example
-
# Addressable::URI.encode_component("simple/example", "b-zB-Z0-9")
-
# => "simple%2Fex%61mple"
-
# Addressable::URI.encode_component("simple/example", /[^b-zB-Z0-9]/)
-
# => "simple%2Fex%61mple"
-
# Addressable::URI.encode_component(
-
# "simple/example", Addressable::URI::CharacterClasses::UNRESERVED
-
# )
-
# => "simple%2Fexample"
-
2
def self.encode_component(component, character_class=
-
CharacterClasses::RESERVED + CharacterClasses::UNRESERVED,
-
upcase_encoded='')
-
return nil if component.nil?
-
-
begin
-
if component.kind_of?(Symbol) ||
-
component.kind_of?(Numeric) ||
-
component.kind_of?(TrueClass) ||
-
component.kind_of?(FalseClass)
-
component = component.to_s
-
else
-
component = component.to_str
-
end
-
rescue TypeError, NoMethodError
-
raise TypeError, "Can't convert #{component.class} into String."
-
end if !component.is_a? String
-
-
if ![String, Regexp].include?(character_class.class)
-
raise TypeError,
-
"Expected String or Regexp, got #{character_class.inspect}"
-
end
-
if character_class.kind_of?(String)
-
character_class = /[^#{character_class}]/
-
end
-
if component.respond_to?(:force_encoding)
-
# We can't perform regexps on invalid UTF sequences, but
-
# here we need to, so switch to ASCII.
-
component = component.dup
-
component.force_encoding(Encoding::ASCII_8BIT)
-
end
-
# Avoiding gsub! because there are edge cases with frozen strings
-
component = component.gsub(character_class) do |sequence|
-
(sequence.unpack('C*').map { |c| "%" + ("%02x" % c).upcase }).join
-
end
-
if upcase_encoded.length > 0
-
component = component.gsub(/%(#{upcase_encoded.chars.map do |char|
-
char.unpack('C*').map { |c| '%02x' % c }.join
-
end.join('|')})/i) { |s| s.upcase }
-
end
-
return component
-
end
-
-
2
class << self
-
2
alias_method :encode_component, :encode_component
-
end
-
-
##
-
# Unencodes any percent encoded characters within a URI component.
-
# This method may be used for unencoding either components or full URIs,
-
# however, it is recommended to use the <code>unencode_component</code>
-
# alias when unencoding components.
-
#
-
# @param [String, Addressable::URI, #to_str] uri
-
# The URI or component to unencode.
-
#
-
# @param [Class] return_type
-
# The type of object to return.
-
# This value may only be set to <code>String</code> or
-
# <code>Addressable::URI</code>. All other values are invalid. Defaults
-
# to <code>String</code>.
-
#
-
# @param [String] leave_encoded
-
# A string of characters to leave encoded. If a percent encoded character
-
# in this list is encountered then it will remain percent encoded.
-
#
-
# @return [String, Addressable::URI]
-
# The unencoded component or URI.
-
# The return type is determined by the <code>return_type</code>
-
# parameter.
-
2
def self.unencode(uri, return_type=String, leave_encoded='')
-
return nil if uri.nil?
-
-
begin
-
uri = uri.to_str
-
rescue NoMethodError, TypeError
-
raise TypeError, "Can't convert #{uri.class} into String."
-
end if !uri.is_a? String
-
if ![String, ::Addressable::URI].include?(return_type)
-
raise TypeError,
-
"Expected Class (String or Addressable::URI), " +
-
"got #{return_type.inspect}"
-
end
-
uri = uri.dup
-
# Seriously, only use UTF-8. I'm really not kidding!
-
uri.force_encoding("utf-8") if uri.respond_to?(:force_encoding)
-
leave_encoded.force_encoding("utf-8") if leave_encoded.respond_to?(:force_encoding)
-
result = uri.gsub(/%[0-9a-f]{2}/iu) do |sequence|
-
c = sequence[1..3].to_i(16).chr
-
c.force_encoding("utf-8") if c.respond_to?(:force_encoding)
-
leave_encoded.include?(c) ? sequence : c
-
end
-
result.force_encoding("utf-8") if result.respond_to?(:force_encoding)
-
if return_type == String
-
return result
-
elsif return_type == ::Addressable::URI
-
return ::Addressable::URI.parse(result)
-
end
-
end
-
-
2
class << self
-
2
alias_method :unescape, :unencode
-
2
alias_method :unencode_component, :unencode
-
2
alias_method :unescape_component, :unencode
-
end
-
-
-
##
-
# Normalizes the encoding of a URI component.
-
#
-
# @param [String, #to_str] component The URI component to encode.
-
#
-
# @param [String, Regexp] character_class
-
# The characters which are not percent encoded. If a <code>String</code>
-
# is passed, the <code>String</code> must be formatted as a regular
-
# expression character class. (Do not include the surrounding square
-
# brackets.) For example, <code>"b-zB-Z0-9"</code> would cause
-
# everything but the letters 'b' through 'z' and the numbers '0'
-
# through '9' to be percent encoded. If a <code>Regexp</code> is passed,
-
# the value <code>/[^b-zB-Z0-9]/</code> would have the same effect. A
-
# set of useful <code>String</code> values may be found in the
-
# <code>Addressable::URI::CharacterClasses</code> module. The default
-
# value is the reserved plus unreserved character classes specified in
-
# <a href="http://www.ietf.org/rfc/rfc3986.txt">RFC 3986</a>.
-
#
-
# @param [String] leave_encoded
-
# When <code>character_class</code> is a <code>String</code> then
-
# <code>leave_encoded</code> is a string of characters that should remain
-
# percent encoded while normalizing the component; if they appear percent
-
# encoded in the original component, then they will be upcased ("%2f"
-
# normalized to "%2F") but otherwise left alone.
-
#
-
# @return [String] The normalized component.
-
#
-
# @example
-
# Addressable::URI.normalize_component("simpl%65/%65xampl%65", "b-zB-Z")
-
# => "simple%2Fex%61mple"
-
# Addressable::URI.normalize_component(
-
# "simpl%65/%65xampl%65", /[^b-zB-Z]/
-
# )
-
# => "simple%2Fex%61mple"
-
# Addressable::URI.normalize_component(
-
# "simpl%65/%65xampl%65",
-
# Addressable::URI::CharacterClasses::UNRESERVED
-
# )
-
# => "simple%2Fexample"
-
# Addressable::URI.normalize_component(
-
# "one%20two%2fthree%26four",
-
# "0-9a-zA-Z &/",
-
# "/"
-
# )
-
# => "one two%2Fthree&four"
-
2
def self.normalize_component(component, character_class=
-
CharacterClasses::RESERVED + CharacterClasses::UNRESERVED,
-
leave_encoded='')
-
return nil if component.nil?
-
-
begin
-
component = component.to_str
-
rescue NoMethodError, TypeError
-
raise TypeError, "Can't convert #{component.class} into String."
-
end if !component.is_a? String
-
-
if ![String, Regexp].include?(character_class.class)
-
raise TypeError,
-
"Expected String or Regexp, got #{character_class.inspect}"
-
end
-
if character_class.kind_of?(String)
-
leave_re = if leave_encoded.length > 0
-
character_class = "#{character_class}%" unless character_class.include?('%')
-
-
"|%(?!#{leave_encoded.chars.map do |char|
-
seq = char.unpack('C*').map { |c| '%02x' % c }.join
-
[seq.upcase, seq.downcase]
-
end.flatten.join('|')})"
-
end
-
-
character_class = /[^#{character_class}]#{leave_re}/
-
end
-
if component.respond_to?(:force_encoding)
-
# We can't perform regexps on invalid UTF sequences, but
-
# here we need to, so switch to ASCII.
-
component = component.dup
-
component.force_encoding(Encoding::ASCII_8BIT)
-
end
-
unencoded = self.unencode_component(component, String, leave_encoded)
-
begin
-
encoded = self.encode_component(
-
Addressable::IDNA.unicode_normalize_kc(unencoded),
-
character_class,
-
leave_encoded
-
)
-
rescue ArgumentError
-
encoded = self.encode_component(unencoded)
-
end
-
if encoded.respond_to?(:force_encoding)
-
encoded.force_encoding(Encoding::UTF_8)
-
end
-
return encoded
-
end
-
-
##
-
# Percent encodes any special characters in the URI.
-
#
-
# @param [String, Addressable::URI, #to_str] uri
-
# The URI to encode.
-
#
-
# @param [Class] return_type
-
# The type of object to return.
-
# This value may only be set to <code>String</code> or
-
# <code>Addressable::URI</code>. All other values are invalid. Defaults
-
# to <code>String</code>.
-
#
-
# @return [String, Addressable::URI]
-
# The encoded URI.
-
# The return type is determined by the <code>return_type</code>
-
# parameter.
-
2
def self.encode(uri, return_type=String)
-
return nil if uri.nil?
-
-
begin
-
uri = uri.to_str
-
rescue NoMethodError, TypeError
-
raise TypeError, "Can't convert #{uri.class} into String."
-
end if !uri.is_a? String
-
-
if ![String, ::Addressable::URI].include?(return_type)
-
raise TypeError,
-
"Expected Class (String or Addressable::URI), " +
-
"got #{return_type.inspect}"
-
end
-
uri_object = uri.kind_of?(self) ? uri : self.parse(uri)
-
encoded_uri = Addressable::URI.new(
-
:scheme => self.encode_component(uri_object.scheme,
-
Addressable::URI::CharacterClasses::SCHEME),
-
:authority => self.encode_component(uri_object.authority,
-
Addressable::URI::CharacterClasses::AUTHORITY),
-
:path => self.encode_component(uri_object.path,
-
Addressable::URI::CharacterClasses::PATH),
-
:query => self.encode_component(uri_object.query,
-
Addressable::URI::CharacterClasses::QUERY),
-
:fragment => self.encode_component(uri_object.fragment,
-
Addressable::URI::CharacterClasses::FRAGMENT)
-
)
-
if return_type == String
-
return encoded_uri.to_s
-
elsif return_type == ::Addressable::URI
-
return encoded_uri
-
end
-
end
-
-
2
class << self
-
2
alias_method :escape, :encode
-
end
-
-
##
-
# Normalizes the encoding of a URI. Characters within a hostname are
-
# not percent encoded to allow for internationalized domain names.
-
#
-
# @param [String, Addressable::URI, #to_str] uri
-
# The URI to encode.
-
#
-
# @param [Class] return_type
-
# The type of object to return.
-
# This value may only be set to <code>String</code> or
-
# <code>Addressable::URI</code>. All other values are invalid. Defaults
-
# to <code>String</code>.
-
#
-
# @return [String, Addressable::URI]
-
# The encoded URI.
-
# The return type is determined by the <code>return_type</code>
-
# parameter.
-
2
def self.normalized_encode(uri, return_type=String)
-
begin
-
uri = uri.to_str
-
rescue NoMethodError, TypeError
-
raise TypeError, "Can't convert #{uri.class} into String."
-
end if !uri.is_a? String
-
-
if ![String, ::Addressable::URI].include?(return_type)
-
raise TypeError,
-
"Expected Class (String or Addressable::URI), " +
-
"got #{return_type.inspect}"
-
end
-
uri_object = uri.kind_of?(self) ? uri : self.parse(uri)
-
components = {
-
:scheme => self.unencode_component(uri_object.scheme),
-
:user => self.unencode_component(uri_object.user),
-
:password => self.unencode_component(uri_object.password),
-
:host => self.unencode_component(uri_object.host),
-
:port => (uri_object.port.nil? ? nil : uri_object.port.to_s),
-
:path => self.unencode_component(uri_object.path),
-
:query => self.unencode_component(uri_object.query),
-
:fragment => self.unencode_component(uri_object.fragment)
-
}
-
components.each do |key, value|
-
if value != nil
-
begin
-
components[key] =
-
Addressable::IDNA.unicode_normalize_kc(value.to_str)
-
rescue ArgumentError
-
# Likely a malformed UTF-8 character, skip unicode normalization
-
components[key] = value.to_str
-
end
-
end
-
end
-
encoded_uri = Addressable::URI.new(
-
:scheme => self.encode_component(components[:scheme],
-
Addressable::URI::CharacterClasses::SCHEME),
-
:user => self.encode_component(components[:user],
-
Addressable::URI::CharacterClasses::UNRESERVED),
-
:password => self.encode_component(components[:password],
-
Addressable::URI::CharacterClasses::UNRESERVED),
-
:host => components[:host],
-
:port => components[:port],
-
:path => self.encode_component(components[:path],
-
Addressable::URI::CharacterClasses::PATH),
-
:query => self.encode_component(components[:query],
-
Addressable::URI::CharacterClasses::QUERY),
-
:fragment => self.encode_component(components[:fragment],
-
Addressable::URI::CharacterClasses::FRAGMENT)
-
)
-
if return_type == String
-
return encoded_uri.to_s
-
elsif return_type == ::Addressable::URI
-
return encoded_uri
-
end
-
end
-
-
##
-
# Encodes a set of key/value pairs according to the rules for the
-
# <code>application/x-www-form-urlencoded</code> MIME type.
-
#
-
# @param [#to_hash, #to_ary] form_values
-
# The form values to encode.
-
#
-
# @param [TrueClass, FalseClass] sort
-
# Sort the key/value pairs prior to encoding.
-
# Defaults to <code>false</code>.
-
#
-
# @return [String]
-
# The encoded value.
-
2
def self.form_encode(form_values, sort=false)
-
if form_values.respond_to?(:to_hash)
-
form_values = form_values.to_hash.to_a
-
elsif form_values.respond_to?(:to_ary)
-
form_values = form_values.to_ary
-
else
-
raise TypeError, "Can't convert #{form_values.class} into Array."
-
end
-
-
form_values = form_values.inject([]) do |accu, (key, value)|
-
if value.kind_of?(Array)
-
value.each do |v|
-
accu << [key.to_s, v.to_s]
-
end
-
else
-
accu << [key.to_s, value.to_s]
-
end
-
accu
-
end
-
-
if sort
-
# Useful for OAuth and optimizing caching systems
-
form_values = form_values.sort
-
end
-
escaped_form_values = form_values.map do |(key, value)|
-
# Line breaks are CRLF pairs
-
[
-
self.encode_component(
-
key.gsub(/(\r\n|\n|\r)/, "\r\n"),
-
CharacterClasses::UNRESERVED
-
).gsub("%20", "+"),
-
self.encode_component(
-
value.gsub(/(\r\n|\n|\r)/, "\r\n"),
-
CharacterClasses::UNRESERVED
-
).gsub("%20", "+")
-
]
-
end
-
return escaped_form_values.map do |(key, value)|
-
"#{key}=#{value}"
-
end.join("&")
-
end
-
-
##
-
# Decodes a <code>String</code> according to the rules for the
-
# <code>application/x-www-form-urlencoded</code> MIME type.
-
#
-
# @param [String, #to_str] encoded_value
-
# The form values to decode.
-
#
-
# @return [Array]
-
# The decoded values.
-
# This is not a <code>Hash</code> because of the possibility for
-
# duplicate keys.
-
2
def self.form_unencode(encoded_value)
-
if !encoded_value.respond_to?(:to_str)
-
raise TypeError, "Can't convert #{encoded_value.class} into String."
-
end
-
encoded_value = encoded_value.to_str
-
split_values = encoded_value.split("&").map do |pair|
-
pair.split("=", 2)
-
end
-
return split_values.map do |(key, value)|
-
[
-
key ? self.unencode_component(
-
key.gsub("+", "%20")).gsub(/(\r\n|\n|\r)/, "\n") : nil,
-
value ? (self.unencode_component(
-
value.gsub("+", "%20")).gsub(/(\r\n|\n|\r)/, "\n")) : nil
-
]
-
end
-
end
-
-
##
-
# Creates a new uri object from component parts.
-
#
-
# @option [String, #to_str] scheme The scheme component.
-
# @option [String, #to_str] user The user component.
-
# @option [String, #to_str] password The password component.
-
# @option [String, #to_str] userinfo
-
# The userinfo component. If this is supplied, the user and password
-
# components must be omitted.
-
# @option [String, #to_str] host The host component.
-
# @option [String, #to_str] port The port component.
-
# @option [String, #to_str] authority
-
# The authority component. If this is supplied, the user, password,
-
# userinfo, host, and port components must be omitted.
-
# @option [String, #to_str] path The path component.
-
# @option [String, #to_str] query The query component.
-
# @option [String, #to_str] fragment The fragment component.
-
#
-
# @return [Addressable::URI] The constructed URI object.
-
2
def initialize(options={})
-
if options.has_key?(:authority)
-
if (options.keys & [:userinfo, :user, :password, :host, :port]).any?
-
raise ArgumentError,
-
"Cannot specify both an authority and any of the components " +
-
"within the authority."
-
end
-
end
-
if options.has_key?(:userinfo)
-
if (options.keys & [:user, :password]).any?
-
raise ArgumentError,
-
"Cannot specify both a userinfo and either the user or password."
-
end
-
end
-
-
self.defer_validation do
-
# Bunch of crazy logic required because of the composite components
-
# like userinfo and authority.
-
self.scheme = options[:scheme] if options[:scheme]
-
self.user = options[:user] if options[:user]
-
self.password = options[:password] if options[:password]
-
self.userinfo = options[:userinfo] if options[:userinfo]
-
self.host = options[:host] if options[:host]
-
self.port = options[:port] if options[:port]
-
self.authority = options[:authority] if options[:authority]
-
self.path = options[:path] if options[:path]
-
self.query = options[:query] if options[:query]
-
self.query_values = options[:query_values] if options[:query_values]
-
self.fragment = options[:fragment] if options[:fragment]
-
end
-
self.to_s
-
end
-
-
##
-
# Freeze URI, initializing instance variables.
-
#
-
# @return [Addressable::URI] The frozen URI object.
-
2
def freeze
-
self.normalized_scheme
-
self.normalized_user
-
self.normalized_password
-
self.normalized_userinfo
-
self.normalized_host
-
self.normalized_port
-
self.normalized_authority
-
self.normalized_site
-
self.normalized_path
-
self.normalized_query
-
self.normalized_fragment
-
self.hash
-
super
-
end
-
-
##
-
# The scheme component for this URI.
-
#
-
# @return [String] The scheme component.
-
2
def scheme
-
return defined?(@scheme) ? @scheme : nil
-
end
-
-
##
-
# The scheme component for this URI, normalized.
-
#
-
# @return [String] The scheme component, normalized.
-
2
def normalized_scheme
-
return nil unless self.scheme
-
@normalized_scheme ||= begin
-
if self.scheme =~ /^\s*ssh\+svn\s*$/i
-
"svn+ssh"
-
else
-
Addressable::URI.normalize_component(
-
self.scheme.strip.downcase,
-
Addressable::URI::CharacterClasses::SCHEME
-
)
-
end
-
end
-
end
-
-
##
-
# Sets the scheme component for this URI.
-
#
-
# @param [String, #to_str] new_scheme The new scheme component.
-
2
def scheme=(new_scheme)
-
if new_scheme && !new_scheme.respond_to?(:to_str)
-
raise TypeError, "Can't convert #{new_scheme.class} into String."
-
elsif new_scheme
-
new_scheme = new_scheme.to_str
-
end
-
if new_scheme && new_scheme !~ /\A[a-z][a-z0-9\.\+\-]*\z/i
-
raise InvalidURIError, "Invalid scheme format: #{new_scheme}"
-
end
-
@scheme = new_scheme
-
@scheme = nil if @scheme.to_s.strip.empty?
-
-
# Reset dependent values
-
remove_instance_variable(:@normalized_scheme) if defined?(@normalized_scheme)
-
remove_composite_values
-
-
# Ensure we haven't created an invalid URI
-
validate()
-
end
-
-
##
-
# The user component for this URI.
-
#
-
# @return [String] The user component.
-
2
def user
-
return defined?(@user) ? @user : nil
-
end
-
-
##
-
# The user component for this URI, normalized.
-
#
-
# @return [String] The user component, normalized.
-
2
def normalized_user
-
return nil unless self.user
-
return @normalized_user if defined?(@normalized_user)
-
@normalized_user ||= begin
-
if normalized_scheme =~ /https?/ && self.user.strip.empty? &&
-
(!self.password || self.password.strip.empty?)
-
nil
-
else
-
Addressable::URI.normalize_component(
-
self.user.strip,
-
Addressable::URI::CharacterClasses::UNRESERVED
-
)
-
end
-
end
-
end
-
-
##
-
# Sets the user component for this URI.
-
#
-
# @param [String, #to_str] new_user The new user component.
-
2
def user=(new_user)
-
if new_user && !new_user.respond_to?(:to_str)
-
raise TypeError, "Can't convert #{new_user.class} into String."
-
end
-
@user = new_user ? new_user.to_str : nil
-
-
# You can't have a nil user with a non-nil password
-
if password != nil
-
@user = EMPTY_STR if @user.nil?
-
end
-
-
# Reset dependent values
-
remove_instance_variable(:@userinfo) if defined?(@userinfo)
-
remove_instance_variable(:@normalized_userinfo) if defined?(@normalized_userinfo)
-
remove_instance_variable(:@authority) if defined?(@authority)
-
remove_instance_variable(:@normalized_user) if defined?(@normalized_user)
-
remove_composite_values
-
-
# Ensure we haven't created an invalid URI
-
validate()
-
end
-
-
##
-
# The password component for this URI.
-
#
-
# @return [String] The password component.
-
2
def password
-
return defined?(@password) ? @password : nil
-
end
-
-
##
-
# The password component for this URI, normalized.
-
#
-
# @return [String] The password component, normalized.
-
2
def normalized_password
-
return nil unless self.password
-
return @normalized_password if defined?(@normalized_password)
-
@normalized_password ||= begin
-
if self.normalized_scheme =~ /https?/ && self.password.strip.empty? &&
-
(!self.user || self.user.strip.empty?)
-
nil
-
else
-
Addressable::URI.normalize_component(
-
self.password.strip,
-
Addressable::URI::CharacterClasses::UNRESERVED
-
)
-
end
-
end
-
end
-
-
##
-
# Sets the password component for this URI.
-
#
-
# @param [String, #to_str] new_password The new password component.
-
2
def password=(new_password)
-
if new_password && !new_password.respond_to?(:to_str)
-
raise TypeError, "Can't convert #{new_password.class} into String."
-
end
-
@password = new_password ? new_password.to_str : nil
-
-
# You can't have a nil user with a non-nil password
-
@password ||= nil
-
@user ||= nil
-
if @password != nil
-
@user = EMPTY_STR if @user.nil?
-
end
-
-
# Reset dependent values
-
remove_instance_variable(:@userinfo) if defined?(@userinfo)
-
remove_instance_variable(:@normalized_userinfo) if defined?(@normalized_userinfo)
-
remove_instance_variable(:@authority) if defined?(@authority)
-
remove_instance_variable(:@normalized_password) if defined?(@normalized_password)
-
remove_composite_values
-
-
# Ensure we haven't created an invalid URI
-
validate()
-
end
-
-
##
-
# The userinfo component for this URI.
-
# Combines the user and password components.
-
#
-
# @return [String] The userinfo component.
-
2
def userinfo
-
current_user = self.user
-
current_password = self.password
-
(current_user || current_password) && @userinfo ||= begin
-
if current_user && current_password
-
"#{current_user}:#{current_password}"
-
elsif current_user && !current_password
-
"#{current_user}"
-
end
-
end
-
end
-
-
##
-
# The userinfo component for this URI, normalized.
-
#
-
# @return [String] The userinfo component, normalized.
-
2
def normalized_userinfo
-
return nil unless self.userinfo
-
return @normalized_userinfo if defined?(@normalized_userinfo)
-
@normalized_userinfo ||= begin
-
current_user = self.normalized_user
-
current_password = self.normalized_password
-
if !current_user && !current_password
-
nil
-
elsif current_user && current_password
-
"#{current_user}:#{current_password}"
-
elsif current_user && !current_password
-
"#{current_user}"
-
end
-
end
-
end
-
-
##
-
# Sets the userinfo component for this URI.
-
#
-
# @param [String, #to_str] new_userinfo The new userinfo component.
-
2
def userinfo=(new_userinfo)
-
if new_userinfo && !new_userinfo.respond_to?(:to_str)
-
raise TypeError, "Can't convert #{new_userinfo.class} into String."
-
end
-
new_user, new_password = if new_userinfo
-
[
-
new_userinfo.to_str.strip[/^(.*):/, 1],
-
new_userinfo.to_str.strip[/:(.*)$/, 1]
-
]
-
else
-
[nil, nil]
-
end
-
-
# Password assigned first to ensure validity in case of nil
-
self.password = new_password
-
self.user = new_user
-
-
# Reset dependent values
-
remove_instance_variable(:@authority) if defined?(@authority)
-
remove_composite_values
-
-
# Ensure we haven't created an invalid URI
-
validate()
-
end
-
-
##
-
# The host component for this URI.
-
#
-
# @return [String] The host component.
-
2
def host
-
return defined?(@host) ? @host : nil
-
end
-
-
##
-
# The host component for this URI, normalized.
-
#
-
# @return [String] The host component, normalized.
-
2
def normalized_host
-
return nil unless self.host
-
@normalized_host ||= begin
-
if !self.host.strip.empty?
-
result = ::Addressable::IDNA.to_ascii(
-
URI.unencode_component(self.host.strip.downcase)
-
)
-
if result =~ /[^\.]\.$/
-
# Single trailing dots are unnecessary.
-
result = result[0...-1]
-
end
-
result = Addressable::URI.normalize_component(
-
result,
-
CharacterClasses::HOST)
-
result
-
else
-
EMPTY_STR
-
end
-
end
-
end
-
-
##
-
# Sets the host component for this URI.
-
#
-
# @param [String, #to_str] new_host The new host component.
-
2
def host=(new_host)
-
if new_host && !new_host.respond_to?(:to_str)
-
raise TypeError, "Can't convert #{new_host.class} into String."
-
end
-
@host = new_host ? new_host.to_str : nil
-
-
unreserved = CharacterClasses::UNRESERVED
-
sub_delims = CharacterClasses::SUB_DELIMS
-
if !@host.nil? && (@host =~ /[<>{}\/\?\#\@"[[:space:]]]/ ||
-
(@host[/^\[(.*)\]$/, 1] != nil && @host[/^\[(.*)\]$/, 1] !~
-
Regexp.new("^[#{unreserved}#{sub_delims}:]*$")))
-
raise InvalidURIError, "Invalid character in host: '#{@host.to_s}'"
-
end
-
-
# Reset dependent values
-
remove_instance_variable(:@authority) if defined?(@authority)
-
remove_instance_variable(:@normalized_host) if defined?(@normalized_host)
-
remove_composite_values
-
-
# Ensure we haven't created an invalid URI
-
validate()
-
end
-
-
##
-
# This method is same as URI::Generic#host except
-
# brackets for IPv6 (and 'IPvFuture') addresses are removed.
-
#
-
# @see Addressable::URI#host
-
#
-
# @return [String] The hostname for this URI.
-
2
def hostname
-
v = self.host
-
/\A\[(.*)\]\z/ =~ v ? $1 : v
-
end
-
-
##
-
# This method is same as URI::Generic#host= except
-
# the argument can be a bare IPv6 address (or 'IPvFuture').
-
#
-
# @see Addressable::URI#host=
-
#
-
# @param [String, #to_str] new_hostname The new hostname for this URI.
-
2
def hostname=(new_hostname)
-
if new_hostname &&
-
(new_hostname.respond_to?(:ipv4?) || new_hostname.respond_to?(:ipv6?))
-
new_hostname = new_hostname.to_s
-
elsif new_hostname && !new_hostname.respond_to?(:to_str)
-
raise TypeError, "Can't convert #{new_hostname.class} into String."
-
end
-
v = new_hostname ? new_hostname.to_str : nil
-
v = "[#{v}]" if /\A\[.*\]\z/ !~ v && /:/ =~ v
-
self.host = v
-
end
-
-
##
-
# The authority component for this URI.
-
# Combines the user, password, host, and port components.
-
#
-
# @return [String] The authority component.
-
2
def authority
-
self.host && @authority ||= begin
-
authority = ""
-
if self.userinfo != nil
-
authority << "#{self.userinfo}@"
-
end
-
authority << self.host
-
if self.port != nil
-
authority << ":#{self.port}"
-
end
-
authority
-
end
-
end
-
-
##
-
# The authority component for this URI, normalized.
-
#
-
# @return [String] The authority component, normalized.
-
2
def normalized_authority
-
return nil unless self.authority
-
@normalized_authority ||= begin
-
authority = ""
-
if self.normalized_userinfo != nil
-
authority << "#{self.normalized_userinfo}@"
-
end
-
authority << self.normalized_host
-
if self.normalized_port != nil
-
authority << ":#{self.normalized_port}"
-
end
-
authority
-
end
-
end
-
-
##
-
# Sets the authority component for this URI.
-
#
-
# @param [String, #to_str] new_authority The new authority component.
-
2
def authority=(new_authority)
-
if new_authority
-
if !new_authority.respond_to?(:to_str)
-
raise TypeError, "Can't convert #{new_authority.class} into String."
-
end
-
new_authority = new_authority.to_str
-
new_userinfo = new_authority[/^([^\[\]]*)@/, 1]
-
if new_userinfo
-
new_user = new_userinfo.strip[/^([^:]*):?/, 1]
-
new_password = new_userinfo.strip[/:(.*)$/, 1]
-
end
-
new_host = new_authority.gsub(
-
/^([^\[\]]*)@/, EMPTY_STR
-
).gsub(
-
/:([^:@\[\]]*?)$/, EMPTY_STR
-
)
-
new_port =
-
new_authority[/:([^:@\[\]]*?)$/, 1]
-
end
-
-
# Password assigned first to ensure validity in case of nil
-
self.password = defined?(new_password) ? new_password : nil
-
self.user = defined?(new_user) ? new_user : nil
-
self.host = defined?(new_host) ? new_host : nil
-
self.port = defined?(new_port) ? new_port : nil
-
-
# Reset dependent values
-
remove_instance_variable(:@userinfo) if defined?(@userinfo)
-
remove_instance_variable(:@normalized_userinfo) if defined?(@normalized_userinfo)
-
remove_composite_values
-
-
# Ensure we haven't created an invalid URI
-
validate()
-
end
-
-
##
-
# The origin for this URI, serialized to ASCII, as per
-
# RFC 6454, section 6.2.
-
#
-
# @return [String] The serialized origin.
-
2
def origin
-
if self.scheme && self.authority
-
if self.normalized_port
-
"#{self.normalized_scheme}://#{self.normalized_host}" +
-
":#{self.normalized_port}"
-
else
-
"#{self.normalized_scheme}://#{self.normalized_host}"
-
end
-
else
-
"null"
-
end
-
end
-
-
##
-
# Sets the origin for this URI, serialized to ASCII, as per
-
# RFC 6454, section 6.2. This assignment will reset the `userinfo`
-
# component.
-
#
-
# @param [String, #to_str] new_origin The new origin component.
-
2
def origin=(new_origin)
-
if new_origin
-
if !new_origin.respond_to?(:to_str)
-
raise TypeError, "Can't convert #{new_origin.class} into String."
-
end
-
new_origin = new_origin.to_str
-
new_scheme = new_origin[/^([^:\/?#]+):\/\//, 1]
-
unless new_scheme
-
raise InvalidURIError, 'An origin cannot omit the scheme.'
-
end
-
new_host = new_origin[/:\/\/([^\/?#:]+)/, 1]
-
unless new_host
-
raise InvalidURIError, 'An origin cannot omit the host.'
-
end
-
new_port = new_origin[/:([^:@\[\]\/]*?)$/, 1]
-
end
-
-
self.scheme = defined?(new_scheme) ? new_scheme : nil
-
self.host = defined?(new_host) ? new_host : nil
-
self.port = defined?(new_port) ? new_port : nil
-
self.userinfo = nil
-
-
# Reset dependent values
-
remove_instance_variable(:@userinfo) if defined?(@userinfo)
-
remove_instance_variable(:@normalized_userinfo) if defined?(@normalized_userinfo)
-
remove_instance_variable(:@authority) if defined?(@authority)
-
remove_instance_variable(:@normalized_authority) if defined?(@normalized_authority)
-
remove_composite_values
-
-
# Ensure we haven't created an invalid URI
-
validate()
-
end
-
-
# Returns an array of known ip-based schemes. These schemes typically
-
# use a similar URI form:
-
# <code>//<user>:<password>@<host>:<port>/<url-path></code>
-
2
def self.ip_based_schemes
-
return self.port_mapping.keys
-
end
-
-
# Returns a hash of common IP-based schemes and their default port
-
# numbers. Adding new schemes to this hash, as necessary, will allow
-
# for better URI normalization.
-
2
def self.port_mapping
-
PORT_MAPPING
-
end
-
-
##
-
# The port component for this URI.
-
# This is the port number actually given in the URI. This does not
-
# infer port numbers from default values.
-
#
-
# @return [Integer] The port component.
-
2
def port
-
return defined?(@port) ? @port : nil
-
end
-
-
##
-
# The port component for this URI, normalized.
-
#
-
# @return [Integer] The port component, normalized.
-
2
def normalized_port
-
return nil unless self.port
-
return @normalized_port if defined?(@normalized_port)
-
@normalized_port ||= begin
-
if URI.port_mapping[self.normalized_scheme] == self.port
-
nil
-
else
-
self.port
-
end
-
end
-
end
-
-
##
-
# Sets the port component for this URI.
-
#
-
# @param [String, Integer, #to_s] new_port The new port component.
-
2
def port=(new_port)
-
if new_port != nil && new_port.respond_to?(:to_str)
-
new_port = Addressable::URI.unencode_component(new_port.to_str)
-
end
-
-
if new_port.respond_to?(:valid_encoding?) && !new_port.valid_encoding?
-
raise InvalidURIError, "Invalid encoding in port"
-
end
-
-
if new_port != nil && !(new_port.to_s =~ /^\d+$/)
-
raise InvalidURIError,
-
"Invalid port number: #{new_port.inspect}"
-
end
-
-
@port = new_port.to_s.to_i
-
@port = nil if @port == 0
-
-
# Reset dependent values
-
remove_instance_variable(:@authority) if defined?(@authority)
-
remove_instance_variable(:@normalized_port) if defined?(@normalized_port)
-
remove_composite_values
-
-
# Ensure we haven't created an invalid URI
-
validate()
-
end
-
-
##
-
# The inferred port component for this URI.
-
# This method will normalize to the default port for the URI's scheme if
-
# the port isn't explicitly specified in the URI.
-
#
-
# @return [Integer] The inferred port component.
-
2
def inferred_port
-
if self.port.to_i == 0
-
self.default_port
-
else
-
self.port.to_i
-
end
-
end
-
-
##
-
# The default port for this URI's scheme.
-
# This method will always returns the default port for the URI's scheme
-
# regardless of the presence of an explicit port in the URI.
-
#
-
# @return [Integer] The default port.
-
2
def default_port
-
URI.port_mapping[self.scheme.strip.downcase] if self.scheme
-
end
-
-
##
-
# The combination of components that represent a site.
-
# Combines the scheme, user, password, host, and port components.
-
# Primarily useful for HTTP and HTTPS.
-
#
-
# For example, <code>"http://example.com/path?query"</code> would have a
-
# <code>site</code> value of <code>"http://example.com"</code>.
-
#
-
# @return [String] The components that identify a site.
-
2
def site
-
(self.scheme || self.authority) && @site ||= begin
-
site_string = ""
-
site_string << "#{self.scheme}:" if self.scheme != nil
-
site_string << "//#{self.authority}" if self.authority != nil
-
site_string
-
end
-
end
-
-
##
-
# The normalized combination of components that represent a site.
-
# Combines the scheme, user, password, host, and port components.
-
# Primarily useful for HTTP and HTTPS.
-
#
-
# For example, <code>"http://example.com/path?query"</code> would have a
-
# <code>site</code> value of <code>"http://example.com"</code>.
-
#
-
# @return [String] The normalized components that identify a site.
-
2
def normalized_site
-
return nil unless self.site
-
@normalized_site ||= begin
-
site_string = ""
-
if self.normalized_scheme != nil
-
site_string << "#{self.normalized_scheme}:"
-
end
-
if self.normalized_authority != nil
-
site_string << "//#{self.normalized_authority}"
-
end
-
site_string
-
end
-
end
-
-
##
-
# Sets the site value for this URI.
-
#
-
# @param [String, #to_str] new_site The new site value.
-
2
def site=(new_site)
-
if new_site
-
if !new_site.respond_to?(:to_str)
-
raise TypeError, "Can't convert #{new_site.class} into String."
-
end
-
new_site = new_site.to_str
-
# These two regular expressions derived from the primary parsing
-
# expression
-
self.scheme = new_site[/^(?:([^:\/?#]+):)?(?:\/\/(?:[^\/?#]*))?$/, 1]
-
self.authority = new_site[
-
/^(?:(?:[^:\/?#]+):)?(?:\/\/([^\/?#]*))?$/, 1
-
]
-
else
-
self.scheme = nil
-
self.authority = nil
-
end
-
end
-
-
##
-
# The path component for this URI.
-
#
-
# @return [String] The path component.
-
2
def path
-
return defined?(@path) ? @path : EMPTY_STR
-
end
-
-
2
NORMPATH = /^(?!\/)[^\/:]*:.*$/
-
##
-
# The path component for this URI, normalized.
-
#
-
# @return [String] The path component, normalized.
-
2
def normalized_path
-
@normalized_path ||= begin
-
path = self.path.to_s
-
if self.scheme == nil && path =~ NORMPATH
-
# Relative paths with colons in the first segment are ambiguous.
-
path = path.sub(":", "%2F")
-
end
-
# String#split(delimeter, -1) uses the more strict splitting behavior
-
# found by default in Python.
-
result = path.strip.split(SLASH, -1).map do |segment|
-
Addressable::URI.normalize_component(
-
segment,
-
Addressable::URI::CharacterClasses::PCHAR
-
)
-
end.join(SLASH)
-
-
result = URI.normalize_path(result)
-
if result.empty? &&
-
["http", "https", "ftp", "tftp"].include?(self.normalized_scheme)
-
result = SLASH
-
end
-
result
-
end
-
end
-
-
##
-
# Sets the path component for this URI.
-
#
-
# @param [String, #to_str] new_path The new path component.
-
2
def path=(new_path)
-
if new_path && !new_path.respond_to?(:to_str)
-
raise TypeError, "Can't convert #{new_path.class} into String."
-
end
-
@path = (new_path || EMPTY_STR).to_str
-
if !@path.empty? && @path[0..0] != SLASH && host != nil
-
@path = "/#{@path}"
-
end
-
-
# Reset dependent values
-
remove_instance_variable(:@normalized_path) if defined?(@normalized_path)
-
remove_composite_values
-
end
-
-
##
-
# The basename, if any, of the file in the path component.
-
#
-
# @return [String] The path's basename.
-
2
def basename
-
# Path cannot be nil
-
return File.basename(self.path).gsub(/;[^\/]*$/, EMPTY_STR)
-
end
-
-
##
-
# The extname, if any, of the file in the path component.
-
# Empty string if there is no extension.
-
#
-
# @return [String] The path's extname.
-
2
def extname
-
return nil unless self.path
-
return File.extname(self.basename)
-
end
-
-
##
-
# The query component for this URI.
-
#
-
# @return [String] The query component.
-
2
def query
-
return defined?(@query) ? @query : nil
-
end
-
-
##
-
# The query component for this URI, normalized.
-
#
-
# @return [String] The query component, normalized.
-
2
def normalized_query(*flags)
-
return nil unless self.query
-
return @normalized_query if defined?(@normalized_query)
-
@normalized_query ||= begin
-
modified_query_class = Addressable::URI::CharacterClasses::QUERY.dup
-
# Make sure possible key-value pair delimiters are escaped.
-
modified_query_class.sub!("\\&", "").sub!("\\;", "")
-
pairs = (self.query || "").split("&", -1)
-
pairs.sort! if flags.include?(:sorted)
-
component = pairs.map do |pair|
-
Addressable::URI.normalize_component(pair, modified_query_class, "+")
-
end.join("&")
-
component == "" ? nil : component
-
end
-
end
-
-
##
-
# Sets the query component for this URI.
-
#
-
# @param [String, #to_str] new_query The new query component.
-
2
def query=(new_query)
-
if new_query && !new_query.respond_to?(:to_str)
-
raise TypeError, "Can't convert #{new_query.class} into String."
-
end
-
@query = new_query ? new_query.to_str : nil
-
-
# Reset dependent values
-
remove_instance_variable(:@normalized_query) if defined?(@normalized_query)
-
remove_composite_values
-
end
-
-
##
-
# Converts the query component to a Hash value.
-
#
-
# @param [Class] return_type The return type desired. Value must be either
-
# `Hash` or `Array`.
-
#
-
# @return [Hash, Array, nil] The query string parsed as a Hash or Array
-
# or nil if the query string is blank.
-
#
-
# @example
-
# Addressable::URI.parse("?one=1&two=2&three=3").query_values
-
# #=> {"one" => "1", "two" => "2", "three" => "3"}
-
# Addressable::URI.parse("?one=two&one=three").query_values(Array)
-
# #=> [["one", "two"], ["one", "three"]]
-
# Addressable::URI.parse("?one=two&one=three").query_values(Hash)
-
# #=> {"one" => "three"}
-
# Addressable::URI.parse("?").query_values
-
# #=> {}
-
# Addressable::URI.parse("").query_values
-
# #=> nil
-
2
def query_values(return_type=Hash)
-
empty_accumulator = Array == return_type ? [] : {}
-
if return_type != Hash && return_type != Array
-
raise ArgumentError, "Invalid return type. Must be Hash or Array."
-
end
-
return nil if self.query == nil
-
split_query = self.query.split("&").map do |pair|
-
pair.split("=", 2) if pair && !pair.empty?
-
end.compact
-
return split_query.inject(empty_accumulator.dup) do |accu, pair|
-
# I'd rather use key/value identifiers instead of array lookups,
-
# but in this case I really want to maintain the exact pair structure,
-
# so it's best to make all changes in-place.
-
pair[0] = URI.unencode_component(pair[0])
-
if pair[1].respond_to?(:to_str)
-
# I loathe the fact that I have to do this. Stupid HTML 4.01.
-
# Treating '+' as a space was just an unbelievably bad idea.
-
# There was nothing wrong with '%20'!
-
# If it ain't broke, don't fix it!
-
pair[1] = URI.unencode_component(pair[1].to_str.gsub(/\+/, " "))
-
end
-
if return_type == Hash
-
accu[pair[0]] = pair[1]
-
else
-
accu << pair
-
end
-
accu
-
end
-
end
-
-
##
-
# Sets the query component for this URI from a Hash object.
-
# An empty Hash or Array will result in an empty query string.
-
#
-
# @param [Hash, #to_hash, Array] new_query_values The new query values.
-
#
-
# @example
-
# uri.query_values = {:a => "a", :b => ["c", "d", "e"]}
-
# uri.query
-
# # => "a=a&b=c&b=d&b=e"
-
# uri.query_values = [['a', 'a'], ['b', 'c'], ['b', 'd'], ['b', 'e']]
-
# uri.query
-
# # => "a=a&b=c&b=d&b=e"
-
# uri.query_values = [['a', 'a'], ['b', ['c', 'd', 'e']]]
-
# uri.query
-
# # => "a=a&b=c&b=d&b=e"
-
# uri.query_values = [['flag'], ['key', 'value']]
-
# uri.query
-
# # => "flag&key=value"
-
2
def query_values=(new_query_values)
-
if new_query_values == nil
-
self.query = nil
-
return nil
-
end
-
-
if !new_query_values.is_a?(Array)
-
if !new_query_values.respond_to?(:to_hash)
-
raise TypeError,
-
"Can't convert #{new_query_values.class} into Hash."
-
end
-
new_query_values = new_query_values.to_hash
-
new_query_values = new_query_values.map do |key, value|
-
key = key.to_s if key.kind_of?(Symbol)
-
[key, value]
-
end
-
# Useful default for OAuth and caching.
-
# Only to be used for non-Array inputs. Arrays should preserve order.
-
new_query_values.sort!
-
end
-
-
# new_query_values have form [['key1', 'value1'], ['key2', 'value2']]
-
buffer = ""
-
new_query_values.each do |key, value|
-
encoded_key = URI.encode_component(
-
key, CharacterClasses::UNRESERVED
-
)
-
if value == nil
-
buffer << "#{encoded_key}&"
-
elsif value.kind_of?(Array)
-
value.each do |sub_value|
-
encoded_value = URI.encode_component(
-
sub_value, CharacterClasses::UNRESERVED
-
)
-
buffer << "#{encoded_key}=#{encoded_value}&"
-
end
-
else
-
encoded_value = URI.encode_component(
-
value, CharacterClasses::UNRESERVED
-
)
-
buffer << "#{encoded_key}=#{encoded_value}&"
-
end
-
end
-
self.query = buffer.chop
-
end
-
-
##
-
# The HTTP request URI for this URI. This is the path and the
-
# query string.
-
#
-
# @return [String] The request URI required for an HTTP request.
-
2
def request_uri
-
return nil if self.absolute? && self.scheme !~ /^https?$/
-
return (
-
(!self.path.empty? ? self.path : SLASH) +
-
(self.query ? "?#{self.query}" : EMPTY_STR)
-
)
-
end
-
-
##
-
# Sets the HTTP request URI for this URI.
-
#
-
# @param [String, #to_str] new_request_uri The new HTTP request URI.
-
2
def request_uri=(new_request_uri)
-
if !new_request_uri.respond_to?(:to_str)
-
raise TypeError, "Can't convert #{new_request_uri.class} into String."
-
end
-
if self.absolute? && self.scheme !~ /^https?$/
-
raise InvalidURIError,
-
"Cannot set an HTTP request URI for a non-HTTP URI."
-
end
-
new_request_uri = new_request_uri.to_str
-
path_component = new_request_uri[/^([^\?]*)\?(?:.*)$/, 1]
-
query_component = new_request_uri[/^(?:[^\?]*)\?(.*)$/, 1]
-
path_component = path_component.to_s
-
path_component = (!path_component.empty? ? path_component : SLASH)
-
self.path = path_component
-
self.query = query_component
-
-
# Reset dependent values
-
remove_composite_values
-
end
-
-
##
-
# The fragment component for this URI.
-
#
-
# @return [String] The fragment component.
-
2
def fragment
-
return defined?(@fragment) ? @fragment : nil
-
end
-
-
##
-
# The fragment component for this URI, normalized.
-
#
-
# @return [String] The fragment component, normalized.
-
2
def normalized_fragment
-
return nil unless self.fragment
-
return @normalized_fragment if defined?(@normalized_fragment)
-
@normalized_fragment ||= begin
-
component = Addressable::URI.normalize_component(
-
self.fragment,
-
Addressable::URI::CharacterClasses::FRAGMENT
-
)
-
component == "" ? nil : component
-
end
-
end
-
-
##
-
# Sets the fragment component for this URI.
-
#
-
# @param [String, #to_str] new_fragment The new fragment component.
-
2
def fragment=(new_fragment)
-
if new_fragment && !new_fragment.respond_to?(:to_str)
-
raise TypeError, "Can't convert #{new_fragment.class} into String."
-
end
-
@fragment = new_fragment ? new_fragment.to_str : nil
-
-
# Reset dependent values
-
remove_instance_variable(:@normalized_fragment) if defined?(@normalized_fragment)
-
remove_composite_values
-
-
# Ensure we haven't created an invalid URI
-
validate()
-
end
-
-
##
-
# Determines if the scheme indicates an IP-based protocol.
-
#
-
# @return [TrueClass, FalseClass]
-
# <code>true</code> if the scheme indicates an IP-based protocol.
-
# <code>false</code> otherwise.
-
2
def ip_based?
-
if self.scheme
-
return URI.ip_based_schemes.include?(
-
self.scheme.strip.downcase)
-
end
-
return false
-
end
-
-
##
-
# Determines if the URI is relative.
-
#
-
# @return [TrueClass, FalseClass]
-
# <code>true</code> if the URI is relative. <code>false</code>
-
# otherwise.
-
2
def relative?
-
return self.scheme.nil?
-
end
-
-
##
-
# Determines if the URI is absolute.
-
#
-
# @return [TrueClass, FalseClass]
-
# <code>true</code> if the URI is absolute. <code>false</code>
-
# otherwise.
-
2
def absolute?
-
return !relative?
-
end
-
-
##
-
# Joins two URIs together.
-
#
-
# @param [String, Addressable::URI, #to_str] The URI to join with.
-
#
-
# @return [Addressable::URI] The joined URI.
-
2
def join(uri)
-
if !uri.respond_to?(:to_str)
-
raise TypeError, "Can't convert #{uri.class} into String."
-
end
-
if !uri.kind_of?(URI)
-
# Otherwise, convert to a String, then parse.
-
uri = URI.parse(uri.to_str)
-
end
-
if uri.to_s.empty?
-
return self.dup
-
end
-
-
joined_scheme = nil
-
joined_user = nil
-
joined_password = nil
-
joined_host = nil
-
joined_port = nil
-
joined_path = nil
-
joined_query = nil
-
joined_fragment = nil
-
-
# Section 5.2.2 of RFC 3986
-
if uri.scheme != nil
-
joined_scheme = uri.scheme
-
joined_user = uri.user
-
joined_password = uri.password
-
joined_host = uri.host
-
joined_port = uri.port
-
joined_path = URI.normalize_path(uri.path)
-
joined_query = uri.query
-
else
-
if uri.authority != nil
-
joined_user = uri.user
-
joined_password = uri.password
-
joined_host = uri.host
-
joined_port = uri.port
-
joined_path = URI.normalize_path(uri.path)
-
joined_query = uri.query
-
else
-
if uri.path == nil || uri.path.empty?
-
joined_path = self.path
-
if uri.query != nil
-
joined_query = uri.query
-
else
-
joined_query = self.query
-
end
-
else
-
if uri.path[0..0] == SLASH
-
joined_path = URI.normalize_path(uri.path)
-
else
-
base_path = self.path.dup
-
base_path = EMPTY_STR if base_path == nil
-
base_path = URI.normalize_path(base_path)
-
-
# Section 5.2.3 of RFC 3986
-
#
-
# Removes the right-most path segment from the base path.
-
if base_path =~ /\//
-
base_path.gsub!(/\/[^\/]+$/, SLASH)
-
else
-
base_path = EMPTY_STR
-
end
-
-
# If the base path is empty and an authority segment has been
-
# defined, use a base path of SLASH
-
if base_path.empty? && self.authority != nil
-
base_path = SLASH
-
end
-
-
joined_path = URI.normalize_path(base_path + uri.path)
-
end
-
joined_query = uri.query
-
end
-
joined_user = self.user
-
joined_password = self.password
-
joined_host = self.host
-
joined_port = self.port
-
end
-
joined_scheme = self.scheme
-
end
-
joined_fragment = uri.fragment
-
-
return self.class.new(
-
:scheme => joined_scheme,
-
:user => joined_user,
-
:password => joined_password,
-
:host => joined_host,
-
:port => joined_port,
-
:path => joined_path,
-
:query => joined_query,
-
:fragment => joined_fragment
-
)
-
end
-
2
alias_method :+, :join
-
-
##
-
# Destructive form of <code>join</code>.
-
#
-
# @param [String, Addressable::URI, #to_str] The URI to join with.
-
#
-
# @return [Addressable::URI] The joined URI.
-
#
-
# @see Addressable::URI#join
-
2
def join!(uri)
-
replace_self(self.join(uri))
-
end
-
-
##
-
# Merges a URI with a <code>Hash</code> of components.
-
# This method has different behavior from <code>join</code>. Any
-
# components present in the <code>hash</code> parameter will override the
-
# original components. The path component is not treated specially.
-
#
-
# @param [Hash, Addressable::URI, #to_hash] The components to merge with.
-
#
-
# @return [Addressable::URI] The merged URI.
-
#
-
# @see Hash#merge
-
2
def merge(hash)
-
if !hash.respond_to?(:to_hash)
-
raise TypeError, "Can't convert #{hash.class} into Hash."
-
end
-
hash = hash.to_hash
-
-
if hash.has_key?(:authority)
-
if (hash.keys & [:userinfo, :user, :password, :host, :port]).any?
-
raise ArgumentError,
-
"Cannot specify both an authority and any of the components " +
-
"within the authority."
-
end
-
end
-
if hash.has_key?(:userinfo)
-
if (hash.keys & [:user, :password]).any?
-
raise ArgumentError,
-
"Cannot specify both a userinfo and either the user or password."
-
end
-
end
-
-
uri = self.class.new
-
uri.defer_validation do
-
# Bunch of crazy logic required because of the composite components
-
# like userinfo and authority.
-
uri.scheme =
-
hash.has_key?(:scheme) ? hash[:scheme] : self.scheme
-
if hash.has_key?(:authority)
-
uri.authority =
-
hash.has_key?(:authority) ? hash[:authority] : self.authority
-
end
-
if hash.has_key?(:userinfo)
-
uri.userinfo =
-
hash.has_key?(:userinfo) ? hash[:userinfo] : self.userinfo
-
end
-
if !hash.has_key?(:userinfo) && !hash.has_key?(:authority)
-
uri.user =
-
hash.has_key?(:user) ? hash[:user] : self.user
-
uri.password =
-
hash.has_key?(:password) ? hash[:password] : self.password
-
end
-
if !hash.has_key?(:authority)
-
uri.host =
-
hash.has_key?(:host) ? hash[:host] : self.host
-
uri.port =
-
hash.has_key?(:port) ? hash[:port] : self.port
-
end
-
uri.path =
-
hash.has_key?(:path) ? hash[:path] : self.path
-
uri.query =
-
hash.has_key?(:query) ? hash[:query] : self.query
-
uri.fragment =
-
hash.has_key?(:fragment) ? hash[:fragment] : self.fragment
-
end
-
-
return uri
-
end
-
-
##
-
# Destructive form of <code>merge</code>.
-
#
-
# @param [Hash, Addressable::URI, #to_hash] The components to merge with.
-
#
-
# @return [Addressable::URI] The merged URI.
-
#
-
# @see Addressable::URI#merge
-
2
def merge!(uri)
-
replace_self(self.merge(uri))
-
end
-
-
##
-
# Returns the shortest normalized relative form of this URI that uses the
-
# supplied URI as a base for resolution. Returns an absolute URI if
-
# necessary. This is effectively the opposite of <code>route_to</code>.
-
#
-
# @param [String, Addressable::URI, #to_str] uri The URI to route from.
-
#
-
# @return [Addressable::URI]
-
# The normalized relative URI that is equivalent to the original URI.
-
2
def route_from(uri)
-
uri = URI.parse(uri).normalize
-
normalized_self = self.normalize
-
if normalized_self.relative?
-
raise ArgumentError, "Expected absolute URI, got: #{self.to_s}"
-
end
-
if uri.relative?
-
raise ArgumentError, "Expected absolute URI, got: #{uri.to_s}"
-
end
-
if normalized_self == uri
-
return Addressable::URI.parse("##{normalized_self.fragment}")
-
end
-
components = normalized_self.to_hash
-
if normalized_self.scheme == uri.scheme
-
components[:scheme] = nil
-
if normalized_self.authority == uri.authority
-
components[:user] = nil
-
components[:password] = nil
-
components[:host] = nil
-
components[:port] = nil
-
if normalized_self.path == uri.path
-
components[:path] = nil
-
if normalized_self.query == uri.query
-
components[:query] = nil
-
end
-
else
-
if uri.path != SLASH and components[:path]
-
self_splitted_path = split_path(components[:path])
-
uri_splitted_path = split_path(uri.path)
-
self_dir = self_splitted_path.shift
-
uri_dir = uri_splitted_path.shift
-
while !self_splitted_path.empty? && !uri_splitted_path.empty? and self_dir == uri_dir
-
self_dir = self_splitted_path.shift
-
uri_dir = uri_splitted_path.shift
-
end
-
components[:path] = (uri_splitted_path.fill('..') + [self_dir] + self_splitted_path).join(SLASH)
-
end
-
end
-
end
-
end
-
# Avoid network-path references.
-
if components[:host] != nil
-
components[:scheme] = normalized_self.scheme
-
end
-
return Addressable::URI.new(
-
:scheme => components[:scheme],
-
:user => components[:user],
-
:password => components[:password],
-
:host => components[:host],
-
:port => components[:port],
-
:path => components[:path],
-
:query => components[:query],
-
:fragment => components[:fragment]
-
)
-
end
-
-
##
-
# Returns the shortest normalized relative form of the supplied URI that
-
# uses this URI as a base for resolution. Returns an absolute URI if
-
# necessary. This is effectively the opposite of <code>route_from</code>.
-
#
-
# @param [String, Addressable::URI, #to_str] uri The URI to route to.
-
#
-
# @return [Addressable::URI]
-
# The normalized relative URI that is equivalent to the supplied URI.
-
2
def route_to(uri)
-
return URI.parse(uri).route_from(self)
-
end
-
-
##
-
# Returns a normalized URI object.
-
#
-
# NOTE: This method does not attempt to fully conform to specifications.
-
# It exists largely to correct other people's failures to read the
-
# specifications, and also to deal with caching issues since several
-
# different URIs may represent the same resource and should not be
-
# cached multiple times.
-
#
-
# @return [Addressable::URI] The normalized URI.
-
2
def normalize
-
# This is a special exception for the frequently misused feed
-
# URI scheme.
-
if normalized_scheme == "feed"
-
if self.to_s =~ /^feed:\/*http:\/*/
-
return URI.parse(
-
self.to_s[/^feed:\/*(http:\/*.*)/, 1]
-
).normalize
-
end
-
end
-
-
return self.class.new(
-
:scheme => normalized_scheme,
-
:authority => normalized_authority,
-
:path => normalized_path,
-
:query => normalized_query,
-
:fragment => normalized_fragment
-
)
-
end
-
-
##
-
# Destructively normalizes this URI object.
-
#
-
# @return [Addressable::URI] The normalized URI.
-
#
-
# @see Addressable::URI#normalize
-
2
def normalize!
-
replace_self(self.normalize)
-
end
-
-
##
-
# Creates a URI suitable for display to users. If semantic attacks are
-
# likely, the application should try to detect these and warn the user.
-
# See <a href="http://www.ietf.org/rfc/rfc3986.txt">RFC 3986</a>,
-
# section 7.6 for more information.
-
#
-
# @return [Addressable::URI] A URI suitable for display purposes.
-
2
def display_uri
-
display_uri = self.normalize
-
display_uri.host = ::Addressable::IDNA.to_unicode(display_uri.host)
-
return display_uri
-
end
-
-
##
-
# Returns <code>true</code> if the URI objects are equal. This method
-
# normalizes both URIs before doing the comparison, and allows comparison
-
# against <code>Strings</code>.
-
#
-
# @param [Object] uri The URI to compare.
-
#
-
# @return [TrueClass, FalseClass]
-
# <code>true</code> if the URIs are equivalent, <code>false</code>
-
# otherwise.
-
2
def ===(uri)
-
if uri.respond_to?(:normalize)
-
uri_string = uri.normalize.to_s
-
else
-
begin
-
uri_string = ::Addressable::URI.parse(uri).normalize.to_s
-
rescue InvalidURIError, TypeError
-
return false
-
end
-
end
-
return self.normalize.to_s == uri_string
-
end
-
-
##
-
# Returns <code>true</code> if the URI objects are equal. This method
-
# normalizes both URIs before doing the comparison.
-
#
-
# @param [Object] uri The URI to compare.
-
#
-
# @return [TrueClass, FalseClass]
-
# <code>true</code> if the URIs are equivalent, <code>false</code>
-
# otherwise.
-
2
def ==(uri)
-
return false unless uri.kind_of?(URI)
-
return self.normalize.to_s == uri.normalize.to_s
-
end
-
-
##
-
# Returns <code>true</code> if the URI objects are equal. This method
-
# does NOT normalize either URI before doing the comparison.
-
#
-
# @param [Object] uri The URI to compare.
-
#
-
# @return [TrueClass, FalseClass]
-
# <code>true</code> if the URIs are equivalent, <code>false</code>
-
# otherwise.
-
2
def eql?(uri)
-
return false unless uri.kind_of?(URI)
-
return self.to_s == uri.to_s
-
end
-
-
##
-
# A hash value that will make a URI equivalent to its normalized
-
# form.
-
#
-
# @return [Integer] A hash of the URI.
-
2
def hash
-
@hash ||= self.to_s.hash * -1
-
end
-
-
##
-
# Clones the URI object.
-
#
-
# @return [Addressable::URI] The cloned URI.
-
2
def dup
-
duplicated_uri = self.class.new(
-
:scheme => self.scheme ? self.scheme.dup : nil,
-
:user => self.user ? self.user.dup : nil,
-
:password => self.password ? self.password.dup : nil,
-
:host => self.host ? self.host.dup : nil,
-
:port => self.port,
-
:path => self.path ? self.path.dup : nil,
-
:query => self.query ? self.query.dup : nil,
-
:fragment => self.fragment ? self.fragment.dup : nil
-
)
-
return duplicated_uri
-
end
-
-
##
-
# Omits components from a URI.
-
#
-
# @param [Symbol] *components The components to be omitted.
-
#
-
# @return [Addressable::URI] The URI with components omitted.
-
#
-
# @example
-
# uri = Addressable::URI.parse("http://example.com/path?query")
-
# #=> #<Addressable::URI:0xcc5e7a URI:http://example.com/path?query>
-
# uri.omit(:scheme, :authority)
-
# #=> #<Addressable::URI:0xcc4d86 URI:/path?query>
-
2
def omit(*components)
-
invalid_components = components - [
-
:scheme, :user, :password, :userinfo, :host, :port, :authority,
-
:path, :query, :fragment
-
]
-
unless invalid_components.empty?
-
raise ArgumentError,
-
"Invalid component names: #{invalid_components.inspect}."
-
end
-
duplicated_uri = self.dup
-
duplicated_uri.defer_validation do
-
components.each do |component|
-
duplicated_uri.send((component.to_s + "=").to_sym, nil)
-
end
-
duplicated_uri.user = duplicated_uri.normalized_user
-
end
-
duplicated_uri
-
end
-
-
##
-
# Destructive form of omit.
-
#
-
# @param [Symbol] *components The components to be omitted.
-
#
-
# @return [Addressable::URI] The URI with components omitted.
-
#
-
# @see Addressable::URI#omit
-
2
def omit!(*components)
-
replace_self(self.omit(*components))
-
end
-
-
##
-
# Determines if the URI is an empty string.
-
#
-
# @return [TrueClass, FalseClass]
-
# Returns <code>true</code> if empty, <code>false</code> otherwise.
-
2
def empty?
-
return self.to_s.empty?
-
end
-
-
##
-
# Converts the URI to a <code>String</code>.
-
#
-
# @return [String] The URI's <code>String</code> representation.
-
2
def to_s
-
if self.scheme == nil && self.path != nil && !self.path.empty? &&
-
self.path =~ NORMPATH
-
raise InvalidURIError,
-
"Cannot assemble URI string with ambiguous path: '#{self.path}'"
-
end
-
@uri_string ||= begin
-
uri_string = ""
-
uri_string << "#{self.scheme}:" if self.scheme != nil
-
uri_string << "//#{self.authority}" if self.authority != nil
-
uri_string << self.path.to_s
-
uri_string << "?#{self.query}" if self.query != nil
-
uri_string << "##{self.fragment}" if self.fragment != nil
-
if uri_string.respond_to?(:force_encoding)
-
uri_string.force_encoding(Encoding::UTF_8)
-
end
-
uri_string
-
end
-
end
-
-
##
-
# URI's are glorified <code>Strings</code>. Allow implicit conversion.
-
2
alias_method :to_str, :to_s
-
-
##
-
# Returns a Hash of the URI components.
-
#
-
# @return [Hash] The URI as a <code>Hash</code> of components.
-
2
def to_hash
-
return {
-
:scheme => self.scheme,
-
:user => self.user,
-
:password => self.password,
-
:host => self.host,
-
:port => self.port,
-
:path => self.path,
-
:query => self.query,
-
:fragment => self.fragment
-
}
-
end
-
-
##
-
# Returns a <code>String</code> representation of the URI object's state.
-
#
-
# @return [String] The URI object's state, as a <code>String</code>.
-
2
def inspect
-
sprintf("#<%s:%#0x URI:%s>", URI.to_s, self.object_id, self.to_s)
-
end
-
-
##
-
# This method allows you to make several changes to a URI simultaneously,
-
# which separately would cause validation errors, but in conjunction,
-
# are valid. The URI will be revalidated as soon as the entire block has
-
# been executed.
-
#
-
# @param [Proc] block
-
# A set of operations to perform on a given URI.
-
2
def defer_validation(&block)
-
raise LocalJumpError, "No block given." unless block
-
@validation_deferred = true
-
block.call()
-
@validation_deferred = false
-
validate
-
return nil
-
end
-
-
2
protected
-
2
SELF_REF = '.'
-
2
PARENT = '..'
-
-
2
RULE_2A = /\/\.\/|\/\.$/
-
2
RULE_2B_2C = /\/([^\/]*)\/\.\.\/|\/([^\/]*)\/\.\.$/
-
2
RULE_2D = /^\.\.?\/?/
-
2
RULE_PREFIXED_PARENT = /^\/\.\.?\/|^(\/\.\.?)+\/?$/
-
-
##
-
# Resolves paths to their simplest form.
-
#
-
# @param [String] path The path to normalize.
-
#
-
# @return [String] The normalized path.
-
2
def self.normalize_path(path)
-
# Section 5.2.4 of RFC 3986
-
-
return nil if path.nil?
-
normalized_path = path.dup
-
begin
-
mod = nil
-
mod ||= normalized_path.gsub!(RULE_2A, SLASH)
-
-
pair = normalized_path.match(RULE_2B_2C)
-
parent, current = pair[1], pair[2] if pair
-
if pair && ((parent != SELF_REF && parent != PARENT) ||
-
(current != SELF_REF && current != PARENT))
-
mod ||= normalized_path.gsub!(
-
Regexp.new(
-
"/#{Regexp.escape(parent.to_s)}/\\.\\./|" +
-
"(/#{Regexp.escape(current.to_s)}/\\.\\.$)"
-
), SLASH
-
)
-
end
-
-
mod ||= normalized_path.gsub!(RULE_2D, EMPTY_STR)
-
# Non-standard, removes prefixed dotted segments from path.
-
mod ||= normalized_path.gsub!(RULE_PREFIXED_PARENT, SLASH)
-
end until mod.nil?
-
-
return normalized_path
-
end
-
-
##
-
# Ensures that the URI is valid.
-
2
def validate
-
return if !!@validation_deferred
-
if self.scheme != nil && self.ip_based? &&
-
(self.host == nil || self.host.empty?) &&
-
(self.path == nil || self.path.empty?)
-
raise InvalidURIError,
-
"Absolute URI missing hierarchical segment: '#{self.to_s}'"
-
end
-
if self.host == nil
-
if self.port != nil ||
-
self.user != nil ||
-
self.password != nil
-
raise InvalidURIError, "Hostname not supplied: '#{self.to_s}'"
-
end
-
end
-
if self.path != nil && !self.path.empty? && self.path[0..0] != SLASH &&
-
self.authority != nil
-
raise InvalidURIError,
-
"Cannot have a relative path with an authority set: '#{self.to_s}'"
-
end
-
return nil
-
end
-
-
##
-
# Replaces the internal state of self with the specified URI's state.
-
# Used in destructive operations to avoid massive code repetition.
-
#
-
# @param [Addressable::URI] uri The URI to replace <code>self</code> with.
-
#
-
# @return [Addressable::URI] <code>self</code>.
-
2
def replace_self(uri)
-
# Reset dependent values
-
instance_variables.each do |var|
-
remove_instance_variable(var) if instance_variable_defined?(var)
-
end
-
-
@scheme = uri.scheme
-
@user = uri.user
-
@password = uri.password
-
@host = uri.host
-
@port = uri.port
-
@path = uri.path
-
@query = uri.query
-
@fragment = uri.fragment
-
return self
-
end
-
-
##
-
# Splits path string with "/" (slash).
-
# It is considered that there is empty string after last slash when
-
# path ends with slash.
-
#
-
# @param [String] path The path to split.
-
#
-
# @return [Array<String>] An array of parts of path.
-
2
def split_path(path)
-
splitted = path.split(SLASH)
-
splitted << EMPTY_STR if path.end_with? SLASH
-
splitted
-
end
-
-
##
-
# Resets composite values for the entire URI
-
#
-
# @api private
-
2
def remove_composite_values
-
remove_instance_variable(:@uri_string) if defined?(@uri_string)
-
remove_instance_variable(:@hash) if defined?(@hash)
-
end
-
end
-
end
-
# encoding:utf-8
-
#--
-
# Copyright (C) 2006-2015 Bob Aman
-
#
-
# Licensed under the Apache License, Version 2.0 (the "License");
-
# you may not use this file except in compliance with the License.
-
# You may obtain a copy of the License at
-
#
-
# http://www.apache.org/licenses/LICENSE-2.0
-
#
-
# Unless required by applicable law or agreed to in writing, software
-
# distributed under the License is distributed on an "AS IS" BASIS,
-
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-
# See the License for the specific language governing permissions and
-
# limitations under the License.
-
#++
-
-
-
# Used to prevent the class/module from being loaded more than once
-
2
if !defined?(Addressable::VERSION)
-
2
module Addressable
-
2
module VERSION
-
2
MAJOR = 2
-
2
MINOR = 4
-
2
TINY = 0
-
-
2
STRING = [MAJOR, MINOR, TINY].join('.')
-
end
-
end
-
end
-
2
require 'arel/crud'
-
2
require 'arel/factory_methods'
-
-
2
require 'arel/expressions'
-
2
require 'arel/predications'
-
2
require 'arel/window_predications'
-
2
require 'arel/math'
-
2
require 'arel/alias_predication'
-
2
require 'arel/order_predications'
-
2
require 'arel/table'
-
2
require 'arel/attributes'
-
2
require 'arel/compatibility/wheres'
-
-
#### these are deprecated
-
2
require 'arel/expression'
-
####
-
-
2
require 'arel/visitors'
-
-
2
require 'arel/tree_manager'
-
2
require 'arel/insert_manager'
-
2
require 'arel/select_manager'
-
2
require 'arel/update_manager'
-
2
require 'arel/delete_manager'
-
2
require 'arel/nodes'
-
-
-
#### these are deprecated
-
2
require 'arel/deprecated'
-
2
require 'arel/sql/engine'
-
2
require 'arel/sql_literal'
-
####
-
-
2
module Arel
-
2
VERSION = '5.0.1'
-
-
2
def self.sql raw_sql
-
283
Arel::Nodes::SqlLiteral.new raw_sql
-
end
-
-
2
def self.star
-
283
sql '*'
-
end
-
## Convenience Alias
-
2
Node = Arel::Nodes::Node
-
end
-
2
module Arel
-
2
module AliasPredication
-
2
def as other
-
Nodes::As.new self, Nodes::SqlLiteral.new(other)
-
end
-
end
-
end
-
2
require 'arel/attributes/attribute'
-
-
2
module Arel
-
2
module Attributes
-
###
-
# Factory method to wrap a raw database +column+ to an Arel Attribute.
-
2
def self.for column
-
case column.type
-
when :string, :text, :binary then String
-
when :integer then Integer
-
when :float then Float
-
when :decimal then Decimal
-
when :date, :datetime, :timestamp, :time then Time
-
when :boolean then Boolean
-
else
-
Undefined
-
end
-
end
-
end
-
end
-
2
module Arel
-
2
module Attributes
-
2
class Attribute < Struct.new :relation, :name
-
2
include Arel::Expressions
-
2
include Arel::Predications
-
2
include Arel::AliasPredication
-
2
include Arel::OrderPredications
-
2
include Arel::Math
-
-
###
-
# Create a node for lowering this attribute
-
2
def lower
-
relation.lower self
-
end
-
end
-
-
2
class String < Attribute; end
-
2
class Time < Attribute; end
-
2
class Boolean < Attribute; end
-
2
class Decimal < Attribute; end
-
2
class Float < Attribute; end
-
2
class Integer < Attribute; end
-
2
class Undefined < Attribute; end
-
end
-
-
2
Attribute = Attributes::Attribute
-
end
-
2
module Arel
-
2
module Compatibility # :nodoc:
-
2
class Wheres # :nodoc:
-
2
include Enumerable
-
-
2
module Value # :nodoc:
-
2
attr_accessor :visitor
-
2
def value
-
visitor.accept self
-
end
-
-
2
def name
-
super.to_sym
-
end
-
end
-
-
2
def initialize engine, collection
-
@engine = engine
-
@collection = collection
-
end
-
-
2
def each
-
to_sql = Visitors::ToSql.new @engine
-
-
@collection.each { |c|
-
c.extend(Value)
-
c.visitor = to_sql
-
yield c
-
}
-
end
-
end
-
end
-
end
-
2
module Arel
-
###
-
# FIXME hopefully we can remove this
-
2
module Crud
-
2
def compile_update values, pk
-
um = UpdateManager.new @engine
-
-
if Nodes::SqlLiteral === values
-
relation = @ctx.from
-
else
-
relation = values.first.first.relation
-
end
-
um.key = pk
-
um.table relation
-
um.set values
-
um.take @ast.limit.expr if @ast.limit
-
um.order(*@ast.orders)
-
um.wheres = @ctx.wheres
-
um
-
end
-
-
2
def compile_insert values
-
im = create_insert
-
im.insert values
-
im
-
end
-
-
2
def create_insert
-
267
InsertManager.new @engine
-
end
-
-
2
def compile_delete
-
dm = DeleteManager.new @engine
-
dm.wheres = @ctx.wheres
-
dm.from @ctx.froms
-
dm
-
end
-
-
end
-
end
-
2
module Arel
-
2
class DeleteManager < Arel::TreeManager
-
2
def initialize engine
-
super
-
@ast = Nodes::DeleteStatement.new
-
@ctx = @ast
-
end
-
-
2
def from relation
-
@ast.relation = relation
-
self
-
end
-
-
2
def wheres= list
-
@ast.wheres = list
-
end
-
end
-
end
-
2
module Arel
-
2
InnerJoin = Nodes::InnerJoin
-
2
OuterJoin = Nodes::OuterJoin
-
end
-
2
module Arel
-
2
module Expression
-
2
include Arel::OrderPredications
-
end
-
end
-
2
module Arel
-
2
module Expressions
-
2
def count distinct = false
-
Nodes::Count.new [self], distinct
-
end
-
-
2
def sum
-
Nodes::Sum.new [self], Nodes::SqlLiteral.new('sum_id')
-
end
-
-
2
def maximum
-
Nodes::Max.new [self], Nodes::SqlLiteral.new('max_id')
-
end
-
-
2
def minimum
-
Nodes::Min.new [self], Nodes::SqlLiteral.new('min_id')
-
end
-
-
2
def average
-
Nodes::Avg.new [self], Nodes::SqlLiteral.new('avg_id')
-
end
-
-
2
def extract field
-
Nodes::Extract.new [self], field
-
end
-
end
-
end
-
2
module Arel
-
###
-
# Methods for creating various nodes
-
2
module FactoryMethods
-
2
def create_true
-
Arel::Nodes::True.new
-
end
-
-
2
def create_false
-
Arel::Nodes::False.new
-
end
-
-
2
def create_table_alias relation, name
-
Nodes::TableAlias.new(relation, name)
-
end
-
-
2
def create_join to, constraint = nil, klass = Nodes::InnerJoin
-
klass.new(to, constraint)
-
end
-
-
2
def create_string_join to
-
create_join to, nil, Nodes::StringJoin
-
end
-
-
2
def create_and clauses
-
Nodes::And.new clauses
-
end
-
-
2
def create_on expr
-
Nodes::On.new expr
-
end
-
-
2
def grouping expr
-
Nodes::Grouping.new expr
-
end
-
-
###
-
# Create a LOWER() function
-
2
def lower column
-
Nodes::NamedFunction.new 'LOWER', [column]
-
end
-
end
-
end
-
2
module Arel
-
2
class InsertManager < Arel::TreeManager
-
2
def initialize engine
-
267
super
-
267
@ast = Nodes::InsertStatement.new
-
end
-
-
2
def into table
-
267
@ast.relation = table
-
267
self
-
end
-
-
2
def columns; @ast.columns end
-
2
def values= val; @ast.values = val; end
-
-
2
def insert fields
-
267
return if fields.empty?
-
-
267
if String === fields
-
@ast.values = SqlLiteral.new(fields)
-
else
-
267
@ast.relation ||= fields.first.first.relation
-
-
267
values = []
-
-
267
fields.each do |column, value|
-
1405
@ast.columns << column
-
1405
values << value
-
end
-
267
@ast.values = create_values values, @ast.columns
-
end
-
end
-
-
2
def create_values values, columns
-
267
Nodes::Values.new values, columns
-
end
-
end
-
end
-
2
module Arel
-
2
module Math
-
2
def *(other)
-
Arel::Nodes::Multiplication.new(self, other)
-
end
-
-
2
def +(other)
-
Arel::Nodes::Grouping.new(Arel::Nodes::Addition.new(self, other))
-
end
-
-
2
def -(other)
-
Arel::Nodes::Grouping.new(Arel::Nodes::Subtraction.new(self, other))
-
end
-
-
2
def /(other)
-
Arel::Nodes::Division.new(self, other)
-
end
-
end
-
end
-
# node
-
2
require 'arel/nodes/node'
-
2
require 'arel/nodes/select_statement'
-
2
require 'arel/nodes/select_core'
-
2
require 'arel/nodes/insert_statement'
-
2
require 'arel/nodes/update_statement'
-
-
# terminal
-
-
2
require 'arel/nodes/terminal'
-
2
require 'arel/nodes/true'
-
2
require 'arel/nodes/false'
-
-
# unary
-
2
require 'arel/nodes/unary'
-
2
require 'arel/nodes/grouping'
-
2
require 'arel/nodes/ascending'
-
2
require 'arel/nodes/descending'
-
2
require 'arel/nodes/unqualified_column'
-
2
require 'arel/nodes/with'
-
-
# binary
-
2
require 'arel/nodes/binary'
-
2
require 'arel/nodes/equality'
-
2
require 'arel/nodes/in' # Why is this subclassed from equality?
-
2
require 'arel/nodes/join_source'
-
2
require 'arel/nodes/delete_statement'
-
2
require 'arel/nodes/table_alias'
-
2
require 'arel/nodes/infix_operation'
-
2
require 'arel/nodes/over'
-
-
# nary
-
2
require 'arel/nodes/and'
-
-
# function
-
# FIXME: Function + Alias can be rewritten as a Function and Alias node.
-
# We should make Function a Unary node and deprecate the use of "aliaz"
-
2
require 'arel/nodes/function'
-
2
require 'arel/nodes/count'
-
2
require 'arel/nodes/extract'
-
2
require 'arel/nodes/values'
-
2
require 'arel/nodes/named_function'
-
-
# windows
-
2
require 'arel/nodes/window'
-
-
# joins
-
2
require 'arel/nodes/inner_join'
-
2
require 'arel/nodes/outer_join'
-
2
require 'arel/nodes/string_join'
-
-
2
require 'arel/nodes/sql_literal'
-
2
module Arel
-
2
module Nodes
-
2
class And < Arel::Nodes::Node
-
2
attr_reader :children
-
-
2
def initialize children, right = nil
-
210
super()
-
210
unless Array === children
-
warn "(#{caller.first}) AND nodes should be created with a list"
-
children = [children, right]
-
end
-
210
@children = children
-
end
-
-
2
def left
-
children.first
-
end
-
-
2
def right
-
children[1]
-
end
-
-
2
def hash
-
children.hash
-
end
-
-
2
def eql? other
-
self.class == other.class &&
-
self.children == other.children
-
end
-
2
alias :== :eql?
-
end
-
end
-
end
-
2
module Arel
-
2
module Nodes
-
2
class Ascending < Ordering
-
-
2
def reverse
-
Descending.new(expr)
-
end
-
-
2
def direction
-
:asc
-
end
-
-
2
def ascending?
-
true
-
end
-
-
2
def descending?
-
false
-
end
-
-
end
-
end
-
end
-
2
module Arel
-
2
module Nodes
-
2
class Binary < Arel::Nodes::Node
-
2
attr_accessor :left, :right
-
-
2
def initialize left, right
-
1531
super()
-
1531
@left = left
-
1531
@right = right
-
end
-
-
2
def initialize_copy other
-
super
-
@left = @left.clone if @left
-
@right = @right.clone if @right
-
end
-
-
2
def hash
-
210
[@left, @right].hash
-
end
-
-
2
def eql? other
-
self.class == other.class &&
-
678
self.left == other.left &&
-
self.right == other.right
-
end
-
2
alias :== :eql?
-
end
-
-
%w{
-
As
-
Assignment
-
Between
-
DoesNotMatch
-
GreaterThan
-
GreaterThanOrEqual
-
Join
-
LessThan
-
LessThanOrEqual
-
Matches
-
NotEqual
-
NotIn
-
Or
-
Union
-
UnionAll
-
Intersect
-
Except
-
2
}.each do |name|
-
34
const_set name, Class.new(Binary)
-
end
-
end
-
end
-
2
module Arel
-
2
module Nodes
-
2
class Count < Arel::Nodes::Function
-
2
def initialize expr, distinct = false, aliaz = nil
-
super(expr, aliaz)
-
@distinct = distinct
-
end
-
end
-
end
-
end
-
2
module Arel
-
2
module Nodes
-
2
class DeleteStatement < Arel::Nodes::Binary
-
2
alias :relation :left
-
2
alias :relation= :left=
-
2
alias :wheres :right
-
2
alias :wheres= :right=
-
-
2
def initialize relation = nil, wheres = []
-
super
-
end
-
-
2
def initialize_copy other
-
super
-
@right = @right.clone
-
end
-
end
-
end
-
end
-
2
module Arel
-
2
module Nodes
-
2
class Descending < Ordering
-
-
2
def reverse
-
Ascending.new(expr)
-
end
-
-
2
def direction
-
:desc
-
end
-
-
2
def ascending?
-
false
-
end
-
-
2
def descending?
-
true
-
end
-
-
end
-
end
-
end
-
2
module Arel
-
2
module Nodes
-
2
class Equality < Arel::Nodes::Binary
-
2
def operator; :== end
-
2
alias :operand1 :left
-
2
alias :operand2 :right
-
end
-
end
-
end
-
2
module Arel
-
2
module Nodes
-
-
2
class Extract < Arel::Nodes::Unary
-
2
include Arel::Expression
-
2
include Arel::Predications
-
-
2
attr_accessor :field
-
2
attr_accessor :alias
-
-
2
def initialize expr, field, aliaz = nil
-
super(expr)
-
@field = field
-
@alias = aliaz && SqlLiteral.new(aliaz)
-
end
-
-
2
def as aliaz
-
self.alias = SqlLiteral.new(aliaz)
-
self
-
end
-
-
2
def hash
-
super ^ [@field, @alias].hash
-
end
-
-
2
def eql? other
-
super &&
-
self.field == other.field &&
-
self.alias == other.alias
-
end
-
2
alias :== :eql?
-
end
-
end
-
end
-
2
module Arel
-
2
module Nodes
-
2
class False < Arel::Nodes::Node
-
2
def hash
-
self.class.hash
-
end
-
-
2
def eql? other
-
self.class == other.class
-
end
-
end
-
end
-
end
-
2
module Arel
-
2
module Nodes
-
2
class Function < Arel::Nodes::Node
-
2
include Arel::Expression
-
2
include Arel::Predications
-
2
include Arel::WindowPredications
-
2
attr_accessor :expressions, :alias, :distinct
-
-
2
def initialize expr, aliaz = nil
-
super()
-
@expressions = expr
-
@alias = aliaz && SqlLiteral.new(aliaz)
-
@distinct = false
-
end
-
-
2
def as aliaz
-
self.alias = SqlLiteral.new(aliaz)
-
self
-
end
-
-
2
def hash
-
[@expressions, @alias, @distinct].hash
-
end
-
-
2
def eql? other
-
self.class == other.class &&
-
self.expressions == other.expressions &&
-
self.alias == other.alias &&
-
self.distinct == other.distinct
-
end
-
end
-
-
%w{
-
Sum
-
Exists
-
Max
-
Min
-
Avg
-
2
}.each do |name|
-
10
const_set(name, Class.new(Function))
-
end
-
end
-
end
-
2
module Arel
-
2
module Nodes
-
2
class Grouping < Unary
-
2
include Arel::Predications
-
end
-
end
-
end
-
2
module Arel
-
2
module Nodes
-
2
class In < Equality
-
end
-
end
-
end
-
2
module Arel
-
2
module Nodes
-
-
2
class InfixOperation < Binary
-
2
include Arel::Expressions
-
2
include Arel::Predications
-
2
include Arel::OrderPredications
-
2
include Arel::AliasPredication
-
2
include Arel::Math
-
-
2
attr_reader :operator
-
-
2
def initialize operator, left, right
-
super(left, right)
-
@operator = operator
-
end
-
end
-
-
2
class Multiplication < InfixOperation
-
2
def initialize left, right
-
super(:*, left, right)
-
end
-
end
-
-
2
class Division < InfixOperation
-
2
def initialize left, right
-
super(:/, left, right)
-
end
-
end
-
-
2
class Addition < InfixOperation
-
2
def initialize left, right
-
super(:+, left, right)
-
end
-
end
-
-
2
class Subtraction < InfixOperation
-
2
def initialize left, right
-
super(:-, left, right)
-
end
-
end
-
-
end
-
end
-
2
module Arel
-
2
module Nodes
-
2
class InnerJoin < Arel::Nodes::Join
-
end
-
end
-
end
-
2
module Arel
-
2
module Nodes
-
2
class InsertStatement < Arel::Nodes::Node
-
2
attr_accessor :relation, :columns, :values
-
-
2
def initialize
-
267
super()
-
267
@relation = nil
-
267
@columns = []
-
267
@values = nil
-
end
-
-
2
def initialize_copy other
-
super
-
@columns = @columns.clone
-
@values = @values.clone if @values
-
end
-
-
2
def hash
-
[@relation, @columns, @values].hash
-
end
-
-
2
def eql? other
-
self.class == other.class &&
-
self.relation == other.relation &&
-
self.columns == other.columns &&
-
self.values == other.values
-
end
-
2
alias :== :eql?
-
end
-
end
-
end
-
2
module Arel
-
2
module Nodes
-
###
-
# Class that represents a join source
-
#
-
# http://www.sqlite.org/syntaxdiagrams.html#join-source
-
-
2
class JoinSource < Arel::Nodes::Binary
-
2
def initialize single_source, joinop = []
-
478
super
-
end
-
-
2
def empty?
-
211
!left && right.empty?
-
end
-
end
-
end
-
end
-
2
module Arel
-
2
module Nodes
-
2
class NamedFunction < Arel::Nodes::Function
-
2
attr_accessor :name
-
-
2
def initialize name, expr, aliaz = nil
-
super(expr, aliaz)
-
@name = name
-
end
-
-
2
def hash
-
super ^ @name.hash
-
end
-
-
2
def eql? other
-
super && self.name == other.name
-
end
-
2
alias :== :eql?
-
end
-
end
-
end
-
2
module Arel
-
2
module Nodes
-
###
-
# Abstract base class for all AST nodes
-
2
class Node
-
2
include Arel::FactoryMethods
-
2
include Enumerable
-
-
2
if $DEBUG
-
def _caller
-
@caller
-
end
-
-
def initialize
-
@caller = caller.dup
-
end
-
end
-
-
###
-
# Factory method to create a Nodes::Not node that has the recipient of
-
# the caller as a child.
-
2
def not
-
Nodes::Not.new self
-
end
-
-
###
-
# Factory method to create a Nodes::Grouping node that has an Nodes::Or
-
# node as a child.
-
2
def or right
-
Nodes::Grouping.new Nodes::Or.new(self, right)
-
end
-
-
###
-
# Factory method to create an Nodes::And node.
-
2
def and right
-
Nodes::And.new [self, right]
-
end
-
-
# FIXME: this method should go away. I don't like people calling
-
# to_sql on non-head nodes. This forces us to walk the AST until we
-
# can find a node that has a "relation" member.
-
#
-
# Maybe we should just use `Table.engine`? :'(
-
2
def to_sql engine = Table.engine
-
engine.connection.visitor.accept self
-
end
-
-
# Iterate through AST, nodes will be yielded depth-first
-
2
def each &block
-
478
return enum_for(:each) unless block_given?
-
-
478
::Arel::Visitors::DepthFirst.new(block).accept self
-
end
-
end
-
end
-
end
-
2
module Arel
-
2
module Nodes
-
2
class OuterJoin < Arel::Nodes::Join
-
end
-
end
-
end
-
2
module Arel
-
2
module Nodes
-
-
2
class Over < Binary
-
2
include Arel::AliasPredication
-
-
2
def initialize(left, right = nil)
-
super(left, right)
-
end
-
-
2
def operator; 'OVER' end
-
end
-
-
end
-
end
-
2
module Arel
-
2
module Nodes
-
2
class SelectCore < Arel::Nodes::Node
-
2
attr_accessor :top, :projections, :wheres, :groups, :windows
-
2
attr_accessor :having, :source, :set_quantifier
-
-
2
def initialize
-
478
super()
-
478
@source = JoinSource.new nil
-
478
@top = nil
-
-
# http://savage.net.au/SQL/sql-92.bnf.html#set%20quantifier
-
478
@set_quantifier = nil
-
478
@projections = []
-
478
@wheres = []
-
478
@groups = []
-
478
@having = nil
-
478
@windows = []
-
end
-
-
2
def from
-
@source.left
-
end
-
-
2
def from= value
-
@source.left = value
-
end
-
-
2
alias :froms= :from=
-
2
alias :froms :from
-
-
2
def initialize_copy other
-
super
-
@source = @source.clone if @source
-
@projections = @projections.clone
-
@wheres = @wheres.clone
-
@groups = @groups.clone
-
@having = @having.clone if @having
-
@windows = @windows.clone
-
end
-
-
2
def hash
-
[
-
@source, @top, @set_quantifier, @projections,
-
@wheres, @groups, @having, @windows
-
].hash
-
end
-
-
2
def eql? other
-
self.class == other.class &&
-
self.source == other.source &&
-
self.top == other.top &&
-
self.set_quantifier == other.set_quantifier &&
-
self.projections == other.projections &&
-
self.wheres == other.wheres &&
-
self.groups == other.groups &&
-
self.having == other.having &&
-
self.windows == other.windows
-
end
-
2
alias :== :eql?
-
end
-
end
-
end
-
2
module Arel
-
2
module Nodes
-
2
class SelectStatement < Arel::Nodes::Node
-
2
attr_reader :cores
-
2
attr_accessor :limit, :orders, :lock, :offset, :with
-
-
2
def initialize cores = [SelectCore.new]
-
478
super()
-
478
@cores = cores
-
478
@orders = []
-
478
@limit = nil
-
478
@lock = nil
-
478
@offset = nil
-
478
@with = nil
-
end
-
-
2
def initialize_copy other
-
super
-
@cores = @cores.map { |x| x.clone }
-
@orders = @orders.map { |x| x.clone }
-
end
-
-
2
def hash
-
[@cores, @orders, @limit, @lock, @offset, @with].hash
-
end
-
-
2
def eql? other
-
self.class == other.class &&
-
self.cores == other.cores &&
-
self.orders == other.orders &&
-
self.limit == other.limit &&
-
self.lock == other.lock &&
-
self.offset == other.offset &&
-
self.with == other.with
-
end
-
2
alias :== :eql?
-
end
-
end
-
end
-
2
module Arel
-
2
module Nodes
-
2
class SqlLiteral < String
-
2
include Arel::Expressions
-
2
include Arel::Predications
-
2
include Arel::AliasPredication
-
2
include Arel::OrderPredications
-
-
2
def encode_with(coder)
-
coder.scalar = self.to_s
-
end
-
end
-
-
2
class BindParam < SqlLiteral
-
end
-
end
-
end
-
2
module Arel
-
2
module Nodes
-
2
class StringJoin < Arel::Nodes::Join
-
2
def initialize left, right = nil
-
super
-
end
-
end
-
end
-
end
-
2
module Arel
-
2
module Nodes
-
2
class TableAlias < Arel::Nodes::Binary
-
2
alias :name :right
-
2
alias :relation :left
-
2
alias :table_alias :name
-
-
2
def [] name
-
Attribute.new(self, name)
-
end
-
-
2
def table_name
-
relation.respond_to?(:name) ? relation.name : name
-
end
-
-
2
def engine
-
relation.engine
-
end
-
end
-
end
-
end
-
2
module Arel
-
2
module Nodes
-
2
class Distinct < Arel::Nodes::Node
-
2
def hash
-
self.class.hash
-
end
-
-
2
def eql? other
-
self.class == other.class
-
end
-
end
-
end
-
end
-
2
module Arel
-
2
module Nodes
-
2
class True < Arel::Nodes::Node
-
2
def hash
-
self.class.hash
-
end
-
-
2
def eql? other
-
self.class == other.class
-
end
-
end
-
end
-
end
-
2
module Arel
-
2
module Nodes
-
2
class Unary < Arel::Nodes::Node
-
2
attr_accessor :expr
-
2
alias :value :expr
-
-
2
def initialize expr
-
420
super()
-
420
@expr = expr
-
end
-
-
2
def hash
-
@expr.hash
-
end
-
-
2
def eql? other
-
self.class == other.class &&
-
self.expr == other.expr
-
end
-
2
alias :== :eql?
-
end
-
-
%w{
-
Bin
-
Group
-
Having
-
Limit
-
Not
-
Offset
-
On
-
Ordering
-
Top
-
Lock
-
DistinctOn
-
2
}.each do |name|
-
22
const_set(name, Class.new(Unary))
-
end
-
end
-
end
-
2
module Arel
-
2
module Nodes
-
2
class UnqualifiedColumn < Arel::Nodes::Unary
-
2
alias :attribute :expr
-
2
alias :attribute= :expr=
-
-
2
def relation
-
@expr.relation
-
end
-
-
2
def column
-
@expr.column
-
end
-
-
2
def name
-
@expr.name
-
end
-
end
-
end
-
end
-
2
module Arel
-
2
module Nodes
-
2
class UpdateStatement < Arel::Nodes::Node
-
2
attr_accessor :relation, :wheres, :values, :orders, :limit
-
2
attr_accessor :key
-
-
2
def initialize
-
@relation = nil
-
@wheres = []
-
@values = []
-
@orders = []
-
@limit = nil
-
@key = nil
-
end
-
-
2
def initialize_copy other
-
super
-
@wheres = @wheres.clone
-
@values = @values.clone
-
end
-
-
2
def hash
-
[@relation, @wheres, @values, @orders, @limit, @key].hash
-
end
-
-
2
def eql? other
-
self.class == other.class &&
-
self.relation == other.relation &&
-
self.wheres == other.wheres &&
-
self.values == other.values &&
-
self.orders == other.orders &&
-
self.limit == other.limit &&
-
self.key == other.key
-
end
-
2
alias :== :eql?
-
end
-
end
-
end
-
2
module Arel
-
2
module Nodes
-
2
class Values < Arel::Nodes::Binary
-
2
alias :expressions :left
-
2
alias :expressions= :left=
-
2
alias :columns :right
-
2
alias :columns= :right=
-
-
2
def initialize exprs, columns = []
-
267
super
-
end
-
end
-
end
-
end
-
2
module Arel
-
2
module Nodes
-
2
class With < Arel::Nodes::Unary
-
2
alias children expr
-
end
-
-
2
class WithRecursive < With; end
-
end
-
end
-
-
2
module Arel
-
2
module OrderPredications
-
-
2
def asc
-
Nodes::Ascending.new self
-
end
-
-
2
def desc
-
Nodes::Descending.new self
-
end
-
-
end
-
end
-
2
module Arel
-
2
module Predications
-
2
def not_eq other
-
Nodes::NotEqual.new self, other
-
end
-
-
2
def not_eq_any others
-
grouping_any :not_eq, others
-
end
-
-
2
def not_eq_all others
-
grouping_all :not_eq, others
-
end
-
-
2
def eq other
-
354
Nodes::Equality.new self, other
-
end
-
-
2
def eq_any others
-
grouping_any :eq, others
-
end
-
-
2
def eq_all others
-
grouping_all :eq, others
-
end
-
-
2
def in other
-
case other
-
when Arel::SelectManager
-
Arel::Nodes::In.new(self, other.ast)
-
when Range
-
if other.begin == -Float::INFINITY && other.end == Float::INFINITY
-
Nodes::NotIn.new self, []
-
elsif other.end == Float::INFINITY
-
Nodes::GreaterThanOrEqual.new(self, other.begin)
-
elsif other.begin == -Float::INFINITY && other.exclude_end?
-
Nodes::LessThan.new(self, other.end)
-
elsif other.begin == -Float::INFINITY
-
Nodes::LessThanOrEqual.new(self, other.end)
-
elsif other.exclude_end?
-
left = Nodes::GreaterThanOrEqual.new(self, other.begin)
-
right = Nodes::LessThan.new(self, other.end)
-
Nodes::And.new [left, right]
-
else
-
Nodes::Between.new(self, Nodes::And.new([other.begin, other.end]))
-
end
-
else
-
Nodes::In.new self, other
-
end
-
end
-
-
2
def in_any others
-
grouping_any :in, others
-
end
-
-
2
def in_all others
-
grouping_all :in, others
-
end
-
-
2
def not_in other
-
case other
-
when Arel::SelectManager
-
Arel::Nodes::NotIn.new(self, other.ast)
-
when Range
-
if other.begin == -Float::INFINITY && other.end == Float::INFINITY
-
Nodes::In.new self, []
-
elsif other.end == Float::INFINITY
-
Nodes::LessThan.new(self, other.begin)
-
elsif other.begin == -Float::INFINITY && other.exclude_end?
-
Nodes::GreaterThanOrEqual.new(self, other.end)
-
elsif other.begin == -Float::INFINITY
-
Nodes::GreaterThan.new(self, other.end)
-
elsif other.exclude_end?
-
left = Nodes::LessThan.new(self, other.begin)
-
right = Nodes::GreaterThanOrEqual.new(self, other.end)
-
Nodes::Or.new left, right
-
else
-
left = Nodes::LessThan.new(self, other.begin)
-
right = Nodes::GreaterThan.new(self, other.end)
-
Nodes::Or.new left, right
-
end
-
else
-
Nodes::NotIn.new self, other
-
end
-
end
-
-
2
def not_in_any others
-
grouping_any :not_in, others
-
end
-
-
2
def not_in_all others
-
grouping_all :not_in, others
-
end
-
-
2
def matches other
-
Nodes::Matches.new self, other
-
end
-
-
2
def matches_any others
-
grouping_any :matches, others
-
end
-
-
2
def matches_all others
-
grouping_all :matches, others
-
end
-
-
2
def does_not_match other
-
Nodes::DoesNotMatch.new self, other
-
end
-
-
2
def does_not_match_any others
-
grouping_any :does_not_match, others
-
end
-
-
2
def does_not_match_all others
-
grouping_all :does_not_match, others
-
end
-
-
2
def gteq right
-
Nodes::GreaterThanOrEqual.new self, right
-
end
-
-
2
def gteq_any others
-
grouping_any :gteq, others
-
end
-
-
2
def gteq_all others
-
grouping_all :gteq, others
-
end
-
-
2
def gt right
-
Nodes::GreaterThan.new self, right
-
end
-
-
2
def gt_any others
-
grouping_any :gt, others
-
end
-
-
2
def gt_all others
-
grouping_all :gt, others
-
end
-
-
2
def lt right
-
Nodes::LessThan.new self, right
-
end
-
-
2
def lt_any others
-
grouping_any :lt, others
-
end
-
-
2
def lt_all others
-
grouping_all :lt, others
-
end
-
-
2
def lteq right
-
Nodes::LessThanOrEqual.new self, right
-
end
-
-
2
def lteq_any others
-
grouping_any :lteq, others
-
end
-
-
2
def lteq_all others
-
grouping_all :lteq, others
-
end
-
-
2
private
-
-
2
def grouping_any method_id, others
-
nodes = others.map {|expr| send(method_id, expr)}
-
Nodes::Grouping.new nodes.inject { |memo,node|
-
Nodes::Or.new(memo, node)
-
}
-
end
-
-
2
def grouping_all method_id, others
-
Nodes::Grouping.new Nodes::And.new(others.map {|expr| send(method_id, expr)})
-
end
-
end
-
end
-
2
module Arel
-
2
class SelectManager < Arel::TreeManager
-
2
include Arel::Crud
-
-
2
STRING_OR_SYMBOL_CLASS = [Symbol, String]
-
-
2
def initialize engine, table = nil
-
478
super(engine)
-
478
@ast = Nodes::SelectStatement.new
-
478
@ctx = @ast.cores.last
-
478
from table
-
end
-
-
2
def initialize_copy other
-
super
-
@ctx = @ast.cores.last
-
end
-
-
2
def limit
-
@ast.limit && @ast.limit.expr
-
end
-
2
alias :taken :limit
-
-
2
def constraints
-
@ctx.wheres
-
end
-
-
2
def offset
-
@ast.offset && @ast.offset.expr
-
end
-
-
2
def skip amount
-
if amount
-
@ast.offset = Nodes::Offset.new(amount)
-
else
-
@ast.offset = nil
-
end
-
self
-
end
-
2
alias :offset= :skip
-
-
###
-
# Produces an Arel::Nodes::Exists node
-
2
def exists
-
Arel::Nodes::Exists.new @ast
-
end
-
-
2
def as other
-
create_table_alias grouping(@ast), Nodes::SqlLiteral.new(other)
-
end
-
-
2
def lock locking = Arel.sql('FOR UPDATE')
-
case locking
-
when true
-
locking = Arel.sql('FOR UPDATE')
-
when Arel::Nodes::SqlLiteral
-
when String
-
locking = Arel.sql locking
-
end
-
-
@ast.lock = Nodes::Lock.new(locking)
-
self
-
end
-
-
2
def locked
-
17
@ast.lock
-
end
-
-
2
def on *exprs
-
@ctx.source.right.last.right = Nodes::On.new(collapse(exprs))
-
self
-
end
-
-
2
def group *columns
-
columns.each do |column|
-
# FIXME: backwards compat
-
column = Nodes::SqlLiteral.new(column) if String === column
-
column = Nodes::SqlLiteral.new(column.to_s) if Symbol === column
-
-
@ctx.groups.push Nodes::Group.new column
-
end
-
self
-
end
-
-
2
def from table
-
478
table = Nodes::SqlLiteral.new(table) if String === table
-
# FIXME: this is a hack to support
-
# test_with_two_tables_in_from_without_getting_double_quoted
-
# from the AR tests.
-
-
478
case table
-
when Nodes::Join
-
@ctx.source.right << table
-
else
-
478
@ctx.source.left = table
-
end
-
-
478
self
-
end
-
-
2
def froms
-
@ast.cores.map { |x| x.from }.compact
-
end
-
-
2
def join relation, klass = Nodes::InnerJoin
-
return self unless relation
-
-
case relation
-
when String, Nodes::SqlLiteral
-
raise if relation.blank?
-
klass = Nodes::StringJoin
-
end
-
-
@ctx.source.right << create_join(relation, nil, klass)
-
self
-
end
-
-
2
def having *exprs
-
@ctx.having = Nodes::Having.new(collapse(exprs, @ctx.having))
-
self
-
end
-
-
2
def window name
-
window = Nodes::NamedWindow.new(name)
-
@ctx.windows.push window
-
window
-
end
-
-
2
def project *projections
-
# FIXME: converting these to SQLLiterals is probably not good, but
-
# rails tests require it.
-
478
@ctx.projections.concat projections.map { |x|
-
478
STRING_OR_SYMBOL_CLASS.include?(x.class) ? SqlLiteral.new(x.to_s) : x
-
}
-
478
self
-
end
-
-
2
def projections
-
@ctx.projections
-
end
-
-
2
def projections= projections
-
@ctx.projections = projections
-
end
-
-
2
def distinct(value = true)
-
478
if value
-
@ctx.set_quantifier = Arel::Nodes::Distinct.new
-
else
-
478
@ctx.set_quantifier = nil
-
end
-
end
-
-
2
def order *expr
-
# FIXME: We SHOULD NOT be converting these to SqlLiteral automatically
-
@ast.orders.concat expr.map { |x|
-
STRING_OR_SYMBOL_CLASS.include?(x.class) ? Nodes::SqlLiteral.new(x.to_s) : x
-
}
-
self
-
end
-
-
2
def orders
-
@ast.orders
-
end
-
-
2
def where_sql
-
return if @ctx.wheres.empty?
-
-
viz = Visitors::WhereSql.new @engine.connection
-
Nodes::SqlLiteral.new viz.accept @ctx
-
end
-
-
2
def union operation, other = nil
-
if other
-
node_class = Nodes.const_get("Union#{operation.to_s.capitalize}")
-
else
-
other = operation
-
node_class = Nodes::Union
-
end
-
-
node_class.new self.ast, other.ast
-
end
-
-
2
def intersect other
-
Nodes::Intersect.new ast, other.ast
-
end
-
-
2
def except other
-
Nodes::Except.new ast, other.ast
-
end
-
2
alias :minus :except
-
-
2
def with *subqueries
-
if subqueries.first.is_a? Symbol
-
node_class = Nodes.const_get("With#{subqueries.shift.to_s.capitalize}")
-
else
-
node_class = Nodes::With
-
end
-
@ast.with = node_class.new(subqueries.flatten)
-
-
self
-
end
-
-
2
def take limit
-
210
if limit
-
210
@ast.limit = Nodes::Limit.new(limit)
-
210
@ctx.top = Nodes::Top.new(limit)
-
else
-
@ast.limit = nil
-
@ctx.top = nil
-
end
-
210
self
-
end
-
2
alias limit= take
-
-
2
def join_sql
-
return nil if @ctx.source.right.empty?
-
-
sql = visitor.dup.extend(Visitors::JoinSql).accept @ctx
-
Nodes::SqlLiteral.new sql
-
end
-
-
2
def order_clauses
-
visitor = Visitors::OrderClauses.new(@engine.connection)
-
visitor.accept(@ast).map { |x|
-
Nodes::SqlLiteral.new x
-
}
-
end
-
-
2
def join_sources
-
195
@ctx.source.right
-
end
-
-
2
def source
-
@ctx.source
-
end
-
-
2
def joins manager
-
if $VERBOSE
-
warn "joins is deprecated and will be removed in 4.0.0"
-
warn "please remove your call to joins from #{caller.first}"
-
end
-
manager.join_sql
-
end
-
-
2
class Row < Struct.new(:data) # :nodoc:
-
2
def id
-
data['id']
-
end
-
-
2
def method_missing(name, *args)
-
name = name.to_s
-
return data[name] if data.key?(name)
-
super
-
end
-
end
-
-
2
def to_a # :nodoc:
-
warn "to_a is deprecated. Please remove it from #{caller[0]}"
-
# FIXME: I think `select` should be made public...
-
@engine.connection.send(:select, to_sql, 'AREL').map { |x| Row.new(x) }
-
end
-
-
2
private
-
2
def collapse exprs, existing = nil
-
exprs = exprs.unshift(existing.expr) if existing
-
exprs = exprs.compact.map { |expr|
-
if String === expr
-
# FIXME: Don't do this automatically
-
Arel.sql(expr)
-
else
-
expr
-
end
-
}
-
-
if exprs.length == 1
-
exprs.first
-
else
-
create_and exprs
-
end
-
end
-
end
-
end
-
2
module Arel
-
2
module Sql
-
2
class Engine
-
2
def self.new thing
-
#warn "#{caller.first} -- Engine will be removed"
-
thing
-
end
-
end
-
end
-
end
-
2
module Arel
-
2
class SqlLiteral < Nodes::SqlLiteral
-
end
-
end
-
2
module Arel
-
2
class Table
-
2
include Arel::Crud
-
2
include Arel::FactoryMethods
-
-
2
@engine = nil
-
4
class << self; attr_accessor :engine; end
-
-
2
attr_accessor :name, :engine, :aliases, :table_alias
-
-
# TableAlias and Table both have a #table_name which is the name of the underlying table
-
2
alias :table_name :name
-
-
2
def initialize name, engine = Table.engine
-
85
@name = name.to_s
-
85
@engine = engine
-
85
@columns = nil
-
85
@aliases = []
-
85
@table_alias = nil
-
85
@primary_key = nil
-
-
85
if Hash === engine
-
@engine = engine[:engine] || Table.engine
-
-
# Sometime AR sends an :as parameter to table, to let the table know
-
# that it is an Alias. We may want to override new, and return a
-
# TableAlias node?
-
@table_alias = engine[:as] unless engine[:as].to_s == @name
-
end
-
end
-
-
2
def primary_key
-
if $VERBOSE
-
warn <<-eowarn
-
primary_key (#{caller.first}) is deprecated and will be removed in Arel 4.0.0
-
eowarn
-
end
-
@primary_key ||= begin
-
primary_key_name = @engine.connection.primary_key(name)
-
# some tables might be without primary key
-
primary_key_name && self[primary_key_name]
-
end
-
end
-
-
2
def alias name = "#{self.name}_2"
-
Nodes::TableAlias.new(self, name).tap do |node|
-
@aliases << node
-
end
-
end
-
-
2
def from table
-
SelectManager.new(@engine, table)
-
end
-
-
2
def joins manager
-
if $VERBOSE
-
warn "joins is deprecated and will be removed in 4.0.0"
-
warn "please remove your call to joins from #{caller.first}"
-
end
-
nil
-
end
-
-
2
def join relation, klass = Nodes::InnerJoin
-
return from(self) unless relation
-
-
case relation
-
when String, Nodes::SqlLiteral
-
raise if relation.blank?
-
klass = Nodes::StringJoin
-
end
-
-
from(self).join(relation, klass)
-
end
-
-
2
def group *columns
-
from(self).group(*columns)
-
end
-
-
2
def order *expr
-
from(self).order(*expr)
-
end
-
-
2
def where condition
-
from(self).where condition
-
end
-
-
2
def project *things
-
from(self).project(*things)
-
end
-
-
2
def take amount
-
from(self).take amount
-
end
-
-
2
def skip amount
-
from(self).skip amount
-
end
-
-
2
def having expr
-
from(self).having expr
-
end
-
-
2
def [] name
-
2042
::Arel::Attribute.new self, name
-
end
-
-
2
def select_manager
-
SelectManager.new(@engine)
-
end
-
-
2
def insert_manager
-
InsertManager.new(@engine)
-
end
-
-
2
def hash
-
# Perf note: aliases, table alias and engine is excluded from the hash
-
# aliases can have a loop back to this table breaking hashes in parent
-
# relations, for the vast majority of cases @name is unique to a query
-
1615
@name.hash
-
end
-
-
2
def eql? other
-
self.class == other.class &&
-
self.name == other.name &&
-
self.engine == other.engine &&
-
self.aliases == other.aliases &&
-
self.table_alias == other.table_alias
-
end
-
2
alias :== :eql?
-
-
2
private
-
-
2
def attributes_for columns
-
return nil unless columns
-
-
columns.map do |column|
-
Attributes.for(column).new self, column.name.to_sym
-
end
-
end
-
-
end
-
end
-
2
module Arel
-
2
class TreeManager
-
2
include Arel::FactoryMethods
-
-
2
attr_reader :ast, :engine
-
-
2
attr_accessor :bind_values
-
-
2
def initialize engine
-
745
@engine = engine
-
745
@ctx = nil
-
745
@bind_values = []
-
end
-
-
2
def to_dot
-
Visitors::Dot.new.accept @ast
-
end
-
-
2
def visitor
-
engine.connection.visitor
-
end
-
-
2
def to_sql
-
visitor.accept @ast
-
end
-
-
2
def initialize_copy other
-
super
-
@ast = @ast.clone
-
end
-
-
2
def where expr
-
210
if Arel::TreeManager === expr
-
expr = expr.ast
-
end
-
210
@ctx.wheres << expr
-
210
self
-
end
-
end
-
end
-
2
module Arel
-
2
class UpdateManager < Arel::TreeManager
-
2
def initialize engine
-
super
-
@ast = Nodes::UpdateStatement.new
-
@ctx = @ast
-
end
-
-
2
def take limit
-
@ast.limit = Nodes::Limit.new(limit) if limit
-
self
-
end
-
-
2
def key= key
-
@ast.key = key
-
end
-
-
2
def key
-
@ast.key
-
end
-
-
2
def order *expr
-
@ast.orders = expr
-
self
-
end
-
-
###
-
# UPDATE +table+
-
2
def table table
-
@ast.relation = table
-
self
-
end
-
-
2
def wheres= exprs
-
@ast.wheres = exprs
-
end
-
-
2
def where expr
-
@ast.wheres << expr
-
self
-
end
-
-
2
def set values
-
if String === values
-
@ast.values = [values]
-
else
-
@ast.values = values.map { |column,value|
-
Nodes::Assignment.new(
-
Nodes::UnqualifiedColumn.new(column),
-
value
-
)
-
}
-
end
-
self
-
end
-
end
-
end
-
2
require 'arel/visitors/visitor'
-
2
require 'arel/visitors/depth_first'
-
2
require 'arel/visitors/to_sql'
-
2
require 'arel/visitors/sqlite'
-
2
require 'arel/visitors/postgresql'
-
2
require 'arel/visitors/mysql'
-
2
require 'arel/visitors/mssql'
-
2
require 'arel/visitors/oracle'
-
2
require 'arel/visitors/join_sql'
-
2
require 'arel/visitors/where_sql'
-
2
require 'arel/visitors/order_clauses'
-
2
require 'arel/visitors/dot'
-
2
require 'arel/visitors/ibm_db'
-
2
require 'arel/visitors/informix'
-
-
2
module Arel
-
2
module Visitors
-
2
VISITORS = {
-
'postgresql' => Arel::Visitors::PostgreSQL,
-
'mysql' => Arel::Visitors::MySQL,
-
'mysql2' => Arel::Visitors::MySQL,
-
'mssql' => Arel::Visitors::MSSQL,
-
'sqlserver' => Arel::Visitors::MSSQL,
-
'oracle_enhanced' => Arel::Visitors::Oracle,
-
'sqlite' => Arel::Visitors::SQLite,
-
'sqlite3' => Arel::Visitors::SQLite,
-
'ibm_db' => Arel::Visitors::IBM_DB,
-
'informix' => Arel::Visitors::Informix,
-
}
-
-
2
ENGINE_VISITORS = Hash.new do |hash, engine|
-
pool = engine.connection_pool
-
adapter = pool.spec.config[:adapter]
-
hash[engine] = (VISITORS[adapter] || Visitors::ToSql).new(engine)
-
end
-
-
2
def self.visitor_for engine
-
ENGINE_VISITORS[engine]
-
end
-
4
class << self; alias :for :visitor_for; end
-
end
-
end
-
2
module Arel
-
2
module Visitors
-
2
module BindVisitor
-
2
def initialize target
-
@block = nil
-
super
-
end
-
-
2
def accept node, &block
-
@block = block if block_given?
-
super
-
end
-
-
2
private
-
-
2
def visit_Arel_Nodes_Assignment o, a
-
if o.right.is_a? Arel::Nodes::BindParam
-
"#{visit o.left, a} = #{visit o.right, a}"
-
else
-
super
-
end
-
end
-
-
2
def visit_Arel_Nodes_BindParam o, a
-
if @block
-
@block.call
-
else
-
super
-
end
-
end
-
-
end
-
end
-
end
-
2
module Arel
-
2
module Visitors
-
2
class DepthFirst < Arel::Visitors::Visitor
-
2
def initialize block = nil
-
478
@block = block || Proc.new
-
end
-
-
2
private
-
-
2
def visit o, a = nil
-
10655
super
-
10655
@block.call o
-
end
-
-
2
def unary o, a
-
210
visit o.expr, a
-
end
-
2
alias :visit_Arel_Nodes_Group :unary
-
2
alias :visit_Arel_Nodes_Grouping :unary
-
2
alias :visit_Arel_Nodes_Having :unary
-
2
alias :visit_Arel_Nodes_Limit :unary
-
2
alias :visit_Arel_Nodes_Not :unary
-
2
alias :visit_Arel_Nodes_Offset :unary
-
2
alias :visit_Arel_Nodes_On :unary
-
2
alias :visit_Arel_Nodes_Ordering :unary
-
2
alias :visit_Arel_Nodes_Ascending :unary
-
2
alias :visit_Arel_Nodes_Descending :unary
-
2
alias :visit_Arel_Nodes_Top :unary
-
2
alias :visit_Arel_Nodes_UnqualifiedColumn :unary
-
-
2
def function o, a
-
visit o.expressions, a
-
visit o.alias, a
-
visit o.distinct, a
-
end
-
2
alias :visit_Arel_Nodes_Avg :function
-
2
alias :visit_Arel_Nodes_Exists :function
-
2
alias :visit_Arel_Nodes_Max :function
-
2
alias :visit_Arel_Nodes_Min :function
-
2
alias :visit_Arel_Nodes_Sum :function
-
-
2
def visit_Arel_Nodes_NamedFunction o, a
-
visit o.name, a
-
visit o.expressions, a
-
visit o.distinct, a
-
visit o.alias, a
-
end
-
-
2
def visit_Arel_Nodes_Count o, a
-
visit o.expressions, a
-
visit o.alias, a
-
visit o.distinct, a
-
end
-
-
2
def nary o, a
-
420
o.children.each { |child| visit child, a }
-
end
-
2
alias :visit_Arel_Nodes_And :nary
-
-
2
def binary o, a
-
688
visit o.left, a
-
688
visit o.right, a
-
end
-
2
alias :visit_Arel_Nodes_As :binary
-
2
alias :visit_Arel_Nodes_Assignment :binary
-
2
alias :visit_Arel_Nodes_Between :binary
-
2
alias :visit_Arel_Nodes_DeleteStatement :binary
-
2
alias :visit_Arel_Nodes_DoesNotMatch :binary
-
2
alias :visit_Arel_Nodes_Equality :binary
-
2
alias :visit_Arel_Nodes_GreaterThan :binary
-
2
alias :visit_Arel_Nodes_GreaterThanOrEqual :binary
-
2
alias :visit_Arel_Nodes_In :binary
-
2
alias :visit_Arel_Nodes_InfixOperation :binary
-
2
alias :visit_Arel_Nodes_JoinSource :binary
-
2
alias :visit_Arel_Nodes_InnerJoin :binary
-
2
alias :visit_Arel_Nodes_LessThan :binary
-
2
alias :visit_Arel_Nodes_LessThanOrEqual :binary
-
2
alias :visit_Arel_Nodes_Matches :binary
-
2
alias :visit_Arel_Nodes_NotEqual :binary
-
2
alias :visit_Arel_Nodes_NotIn :binary
-
2
alias :visit_Arel_Nodes_Or :binary
-
2
alias :visit_Arel_Nodes_OuterJoin :binary
-
2
alias :visit_Arel_Nodes_TableAlias :binary
-
2
alias :visit_Arel_Nodes_Values :binary
-
-
2
def visit_Arel_Nodes_StringJoin o, a
-
visit o.left, a
-
end
-
-
2
def visit_Arel_Attribute o, a
-
493
visit o.relation, a
-
493
visit o.name, a
-
end
-
2
alias :visit_Arel_Attributes_Integer :visit_Arel_Attribute
-
2
alias :visit_Arel_Attributes_Float :visit_Arel_Attribute
-
2
alias :visit_Arel_Attributes_String :visit_Arel_Attribute
-
2
alias :visit_Arel_Attributes_Time :visit_Arel_Attribute
-
2
alias :visit_Arel_Attributes_Boolean :visit_Arel_Attribute
-
2
alias :visit_Arel_Attributes_Attribute :visit_Arel_Attribute
-
2
alias :visit_Arel_Attributes_Decimal :visit_Arel_Attribute
-
-
2
def visit_Arel_Table o, a
-
971
visit o.name, a
-
end
-
-
2
def terminal o, a
-
end
-
2
alias :visit_ActiveSupport_Multibyte_Chars :terminal
-
2
alias :visit_ActiveSupport_StringInquirer :terminal
-
2
alias :visit_Arel_Nodes_Lock :terminal
-
2
alias :visit_Arel_Nodes_Node :terminal
-
2
alias :visit_Arel_Nodes_SqlLiteral :terminal
-
2
alias :visit_Arel_Nodes_BindParam :terminal
-
2
alias :visit_Arel_Nodes_Window :terminal
-
2
alias :visit_Arel_SqlLiteral :terminal
-
2
alias :visit_BigDecimal :terminal
-
2
alias :visit_Bignum :terminal
-
2
alias :visit_Class :terminal
-
2
alias :visit_Date :terminal
-
2
alias :visit_DateTime :terminal
-
2
alias :visit_FalseClass :terminal
-
2
alias :visit_Fixnum :terminal
-
2
alias :visit_Float :terminal
-
2
alias :visit_NilClass :terminal
-
2
alias :visit_String :terminal
-
2
alias :visit_Symbol :terminal
-
2
alias :visit_Time :terminal
-
2
alias :visit_TrueClass :terminal
-
-
2
def visit_Arel_Nodes_InsertStatement o, a
-
visit o.relation, a
-
visit o.columns, a
-
visit o.values, a
-
end
-
-
2
def visit_Arel_Nodes_SelectCore o, a
-
478
visit o.projections, a
-
478
visit o.source, a
-
478
visit o.wheres, a
-
478
visit o.groups, a
-
478
visit o.windows, a
-
478
visit o.having, a
-
end
-
-
2
def visit_Arel_Nodes_SelectStatement o, a
-
478
visit o.cores, a
-
478
visit o.orders, a
-
478
visit o.limit, a
-
478
visit o.lock, a
-
478
visit o.offset, a
-
end
-
-
2
def visit_Arel_Nodes_UpdateStatement o, a
-
visit o.relation, a
-
visit o.values, a
-
visit o.wheres, a
-
visit o.orders, a
-
visit o.limit, a
-
end
-
-
2
def visit_Array o, a
-
4512
o.each { |i| visit i, a }
-
end
-
-
2
def visit_Hash o, a
-
o.each { |k,v| visit(k, a); visit(v, a) }
-
end
-
end
-
end
-
end
-
2
module Arel
-
2
module Visitors
-
2
class Dot < Arel::Visitors::Visitor
-
2
class Node # :nodoc:
-
2
attr_accessor :name, :id, :fields
-
-
2
def initialize name, id, fields = []
-
@name = name
-
@id = id
-
@fields = fields
-
end
-
end
-
-
2
class Edge < Struct.new :name, :from, :to # :nodoc:
-
end
-
-
2
def initialize
-
@nodes = []
-
@edges = []
-
@node_stack = []
-
@edge_stack = []
-
@seen = {}
-
end
-
-
2
def accept object
-
super
-
to_dot
-
end
-
-
2
private
-
2
def visit_Arel_Nodes_Ordering o, a
-
visit_edge o, a, "expr"
-
end
-
-
2
def visit_Arel_Nodes_TableAlias o, a
-
visit_edge o, a, "name"
-
visit_edge o, a, "relation"
-
end
-
-
2
def visit_Arel_Nodes_Count o, a
-
visit_edge o, a, "expressions"
-
visit_edge o, a, "distinct"
-
end
-
-
2
def visit_Arel_Nodes_Values o, a
-
visit_edge o, a, "expressions"
-
end
-
-
2
def visit_Arel_Nodes_StringJoin o, a
-
visit_edge o, a, "left"
-
end
-
-
2
def visit_Arel_Nodes_InnerJoin o, a
-
visit_edge o, a, "left"
-
visit_edge o, a, "right"
-
end
-
2
alias :visit_Arel_Nodes_OuterJoin :visit_Arel_Nodes_InnerJoin
-
-
2
def visit_Arel_Nodes_DeleteStatement o, a
-
visit_edge o, a, "relation"
-
visit_edge o, a, "wheres"
-
end
-
-
2
def unary o, a
-
visit_edge o, a, "expr"
-
end
-
2
alias :visit_Arel_Nodes_Group :unary
-
2
alias :visit_Arel_Nodes_Grouping :unary
-
2
alias :visit_Arel_Nodes_Having :unary
-
2
alias :visit_Arel_Nodes_Limit :unary
-
2
alias :visit_Arel_Nodes_Not :unary
-
2
alias :visit_Arel_Nodes_Offset :unary
-
2
alias :visit_Arel_Nodes_On :unary
-
2
alias :visit_Arel_Nodes_Top :unary
-
2
alias :visit_Arel_Nodes_UnqualifiedColumn :unary
-
2
alias :visit_Arel_Nodes_Preceding :unary
-
2
alias :visit_Arel_Nodes_Following :unary
-
2
alias :visit_Arel_Nodes_Rows :unary
-
2
alias :visit_Arel_Nodes_Range :unary
-
-
2
def window o, a
-
visit_edge o, a, "orders"
-
visit_edge o, a, "framing"
-
end
-
2
alias :visit_Arel_Nodes_Window :window
-
-
2
def named_window o, a
-
visit_edge o, a, "orders"
-
visit_edge o, a, "framing"
-
visit_edge o, a, "name"
-
end
-
2
alias :visit_Arel_Nodes_NamedWindow :named_window
-
-
2
def function o, a
-
visit_edge o, a, "expressions"
-
visit_edge o, a, "distinct"
-
visit_edge o, a, "alias"
-
end
-
2
alias :visit_Arel_Nodes_Exists :function
-
2
alias :visit_Arel_Nodes_Min :function
-
2
alias :visit_Arel_Nodes_Max :function
-
2
alias :visit_Arel_Nodes_Avg :function
-
2
alias :visit_Arel_Nodes_Sum :function
-
-
2
def extract o, a
-
visit_edge o, a, "expressions"
-
visit_edge o, a, "alias"
-
end
-
2
alias :visit_Arel_Nodes_Extract :extract
-
-
2
def visit_Arel_Nodes_NamedFunction o, a
-
visit_edge o, a, "name"
-
visit_edge o, a, "expressions"
-
visit_edge o, a, "distinct"
-
visit_edge o, a, "alias"
-
end
-
-
2
def visit_Arel_Nodes_InsertStatement o, a
-
visit_edge o, a, "relation"
-
visit_edge o, a, "columns"
-
visit_edge o, a, "values"
-
end
-
-
2
def visit_Arel_Nodes_SelectCore o, a
-
visit_edge o, a, "source"
-
visit_edge o, a, "projections"
-
visit_edge o, a, "wheres"
-
visit_edge o, a, "windows"
-
end
-
-
2
def visit_Arel_Nodes_SelectStatement o, a
-
visit_edge o, a, "cores"
-
visit_edge o, a, "limit"
-
visit_edge o, a, "orders"
-
visit_edge o, a, "offset"
-
end
-
-
2
def visit_Arel_Nodes_UpdateStatement o, a
-
visit_edge o, a, "relation"
-
visit_edge o, a, "wheres"
-
visit_edge o, a, "values"
-
end
-
-
2
def visit_Arel_Table o, a
-
visit_edge o, a, "name"
-
end
-
-
2
def visit_Arel_Attribute o, a
-
visit_edge o, a, "relation"
-
visit_edge o, a, "name"
-
end
-
2
alias :visit_Arel_Attributes_Integer :visit_Arel_Attribute
-
2
alias :visit_Arel_Attributes_Float :visit_Arel_Attribute
-
2
alias :visit_Arel_Attributes_String :visit_Arel_Attribute
-
2
alias :visit_Arel_Attributes_Time :visit_Arel_Attribute
-
2
alias :visit_Arel_Attributes_Boolean :visit_Arel_Attribute
-
2
alias :visit_Arel_Attributes_Attribute :visit_Arel_Attribute
-
-
2
def nary o, a
-
o.children.each_with_index do |x,i|
-
edge(i) { visit x, a }
-
end
-
end
-
2
alias :visit_Arel_Nodes_And :nary
-
-
2
def binary o, a
-
visit_edge o, a, "left"
-
visit_edge o, a, "right"
-
end
-
2
alias :visit_Arel_Nodes_As :binary
-
2
alias :visit_Arel_Nodes_Assignment :binary
-
2
alias :visit_Arel_Nodes_Between :binary
-
2
alias :visit_Arel_Nodes_DoesNotMatch :binary
-
2
alias :visit_Arel_Nodes_Equality :binary
-
2
alias :visit_Arel_Nodes_GreaterThan :binary
-
2
alias :visit_Arel_Nodes_GreaterThanOrEqual :binary
-
2
alias :visit_Arel_Nodes_In :binary
-
2
alias :visit_Arel_Nodes_JoinSource :binary
-
2
alias :visit_Arel_Nodes_LessThan :binary
-
2
alias :visit_Arel_Nodes_LessThanOrEqual :binary
-
2
alias :visit_Arel_Nodes_Matches :binary
-
2
alias :visit_Arel_Nodes_NotEqual :binary
-
2
alias :visit_Arel_Nodes_NotIn :binary
-
2
alias :visit_Arel_Nodes_Or :binary
-
2
alias :visit_Arel_Nodes_Over :binary
-
-
2
def visit_String o, a
-
@node_stack.last.fields << o
-
end
-
2
alias :visit_Time :visit_String
-
2
alias :visit_Date :visit_String
-
2
alias :visit_DateTime :visit_String
-
2
alias :visit_NilClass :visit_String
-
2
alias :visit_TrueClass :visit_String
-
2
alias :visit_FalseClass :visit_String
-
2
alias :visit_Arel_SqlLiteral :visit_String
-
2
alias :visit_Arel_Nodes_BindParam :visit_String
-
2
alias :visit_Fixnum :visit_String
-
2
alias :visit_BigDecimal :visit_String
-
2
alias :visit_Float :visit_String
-
2
alias :visit_Symbol :visit_String
-
2
alias :visit_Arel_Nodes_SqlLiteral :visit_String
-
-
2
def visit_Hash o, a
-
o.each_with_index do |pair, i|
-
edge("pair_#{i}") { visit pair, a }
-
end
-
end
-
-
2
def visit_Array o, a
-
o.each_with_index do |x,i|
-
edge(i) { visit x, a }
-
end
-
end
-
-
2
def visit_edge o, a, method
-
edge(method) { visit o.send(method), a }
-
end
-
-
2
def visit o, a = nil
-
if node = @seen[o.object_id]
-
@edge_stack.last.to = node
-
return
-
end
-
-
node = Node.new(o.class.name, o.object_id)
-
@seen[node.id] = node
-
@nodes << node
-
with_node node do
-
super
-
end
-
end
-
-
2
def edge name
-
edge = Edge.new(name, @node_stack.last)
-
@edge_stack.push edge
-
@edges << edge
-
yield
-
@edge_stack.pop
-
end
-
-
2
def with_node node
-
if edge = @edge_stack.last
-
edge.to = node
-
end
-
-
@node_stack.push node
-
yield
-
@node_stack.pop
-
end
-
-
2
def quote string
-
string.to_s.gsub('"', '\"')
-
end
-
-
2
def to_dot
-
"digraph \"Arel\" {\nnode [width=0.375,height=0.25,shape=record];\n" +
-
@nodes.map { |node|
-
label = "<f0>#{node.name}"
-
-
node.fields.each_with_index do |field, i|
-
label << "|<f#{i + 1}>#{quote field}"
-
end
-
-
"#{node.id} [label=\"#{label}\"];"
-
}.join("\n") + "\n" + @edges.map { |edge|
-
"#{edge.from.id} -> #{edge.to.id} [label=\"#{edge.name}\"];"
-
}.join("\n") + "\n}"
-
end
-
end
-
end
-
end
-
2
module Arel
-
2
module Visitors
-
2
class IBM_DB < Arel::Visitors::ToSql
-
2
private
-
-
2
def visit_Arel_Nodes_Limit o, a
-
"FETCH FIRST #{visit o.expr, a} ROWS ONLY"
-
end
-
-
end
-
end
-
end
-
2
module Arel
-
2
module Visitors
-
2
class Informix < Arel::Visitors::ToSql
-
2
private
-
2
def visit_Arel_Nodes_SelectStatement o, a
-
[
-
"SELECT",
-
(visit(o.offset, a) if o.offset),
-
(visit(o.limit, a) if o.limit),
-
o.cores.map { |x| visit_Arel_Nodes_SelectCore x, a }.join,
-
("ORDER BY #{o.orders.map { |x| visit x, a }.join(', ')}" unless o.orders.empty?),
-
(visit(o.lock, a) if o.lock),
-
].compact.join ' '
-
end
-
2
def visit_Arel_Nodes_SelectCore o, a
-
[
-
"#{o.projections.map { |x| visit x, a }.join ', '}",
-
("FROM #{visit(o.source, a)}" if o.source && !o.source.empty?),
-
("WHERE #{o.wheres.map { |x| visit x, a }.join ' AND ' }" unless o.wheres.empty?),
-
("GROUP BY #{o.groups.map { |x| visit x, a }.join ', ' }" unless o.groups.empty?),
-
(visit(o.having, a) if o.having),
-
].compact.join ' '
-
end
-
2
def visit_Arel_Nodes_Offset o, a
-
"SKIP #{visit o.expr, a}"
-
end
-
2
def visit_Arel_Nodes_Limit o, a
-
"LIMIT #{visit o.expr, a}"
-
end
-
end
-
end
-
end
-
-
2
module Arel
-
2
module Visitors
-
###
-
# This class produces SQL for JOIN clauses but omits the "single-source"
-
# part of the Join grammar:
-
#
-
# http://www.sqlite.org/syntaxdiagrams.html#join-source
-
#
-
# This visitor is used in SelectManager#join_sql and is for backwards
-
# compatibility with Arel V1.0
-
2
module JoinSql
-
2
private
-
-
2
def visit_Arel_Nodes_SelectCore o, a
-
o.source.right.map { |j| visit j, a }.join ' '
-
end
-
end
-
end
-
end
-
2
module Arel
-
2
module Visitors
-
2
class MSSQL < Arel::Visitors::ToSql
-
2
private
-
-
# `top` wouldn't really work here. I.e. User.select("distinct first_name").limit(10) would generate
-
# "select top 10 distinct first_name from users", which is invalid query! it should be
-
# "select distinct top 10 first_name from users"
-
2
def visit_Arel_Nodes_Top o, a
-
""
-
end
-
-
2
def visit_Arel_Nodes_SelectStatement o, a
-
if !o.limit && !o.offset
-
return super o, a
-
end
-
-
select_order_by = "ORDER BY #{o.orders.map { |x| visit x, a }.join(', ')}" unless o.orders.empty?
-
-
is_select_count = false
-
sql = o.cores.map { |x|
-
core_order_by = select_order_by || determine_order_by(x, a)
-
if select_count? x
-
x.projections = [row_num_literal(core_order_by)]
-
is_select_count = true
-
else
-
x.projections << row_num_literal(core_order_by)
-
end
-
-
visit_Arel_Nodes_SelectCore x, a
-
}.join
-
-
sql = "SELECT _t.* FROM (#{sql}) as _t WHERE #{get_offset_limit_clause(o)}"
-
# fixme count distinct wouldn't work with limit or offset
-
sql = "SELECT COUNT(1) as count_id FROM (#{sql}) AS subquery" if is_select_count
-
sql
-
end
-
-
2
def get_offset_limit_clause o
-
first_row = o.offset ? o.offset.expr.to_i + 1 : 1
-
last_row = o.limit ? o.limit.expr.to_i - 1 + first_row : nil
-
if last_row
-
" _row_num BETWEEN #{first_row} AND #{last_row}"
-
else
-
" _row_num >= #{first_row}"
-
end
-
end
-
-
2
def determine_order_by x, a
-
unless x.groups.empty?
-
"ORDER BY #{x.groups.map { |g| visit g, a }.join ', ' }"
-
else
-
"ORDER BY #{find_left_table_pk(x.froms, a)}"
-
end
-
end
-
-
2
def row_num_literal order_by
-
Nodes::SqlLiteral.new("ROW_NUMBER() OVER (#{order_by}) as _row_num")
-
end
-
-
2
def select_count? x
-
x.projections.length == 1 && Arel::Nodes::Count === x.projections.first
-
end
-
-
# FIXME raise exception of there is no pk?
-
# FIXME!! Table.primary_key will be deprecated. What is the replacement??
-
2
def find_left_table_pk o, a
-
return visit o.primary_key, a if o.instance_of? Arel::Table
-
find_left_table_pk o.left, a if o.kind_of? Arel::Nodes::Join
-
end
-
end
-
end
-
end
-
2
module Arel
-
2
module Visitors
-
2
class MySQL < Arel::Visitors::ToSql
-
2
private
-
2
def visit_Arel_Nodes_Union o, a, suppress_parens = false
-
left_result = case o.left
-
when Arel::Nodes::Union
-
visit_Arel_Nodes_Union o.left, a, true
-
else
-
visit o.left, a
-
end
-
-
right_result = case o.right
-
when Arel::Nodes::Union
-
visit_Arel_Nodes_Union o.right, a, true
-
else
-
visit o.right, a
-
end
-
-
if suppress_parens
-
"#{left_result} UNION #{right_result}"
-
else
-
"( #{left_result} UNION #{right_result} )"
-
end
-
end
-
-
2
def visit_Arel_Nodes_Bin o, a
-
"BINARY #{visit o.expr, a}"
-
end
-
-
###
-
# :'(
-
# http://dev.mysql.com/doc/refman/5.0/en/select.html#id3482214
-
2
def visit_Arel_Nodes_SelectStatement o, a
-
o.limit = Arel::Nodes::Limit.new(18446744073709551615) if o.offset && !o.limit
-
super
-
end
-
-
2
def visit_Arel_Nodes_SelectCore o, a
-
o.froms ||= Arel.sql('DUAL')
-
super
-
end
-
-
2
def visit_Arel_Nodes_UpdateStatement o, a
-
[
-
"UPDATE #{visit o.relation, a}",
-
("SET #{o.values.map { |value| visit value, a }.join ', '}" unless o.values.empty?),
-
("WHERE #{o.wheres.map { |x| visit x, a }.join ' AND '}" unless o.wheres.empty?),
-
("ORDER BY #{o.orders.map { |x| visit x, a }.join(', ')}" unless o.orders.empty?),
-
(visit(o.limit, a) if o.limit),
-
].compact.join ' '
-
end
-
-
end
-
end
-
end
-
2
module Arel
-
2
module Visitors
-
2
class Oracle < Arel::Visitors::ToSql
-
2
private
-
-
2
def visit_Arel_Nodes_SelectStatement o, a
-
o = order_hacks(o, a)
-
-
# if need to select first records without ORDER BY and GROUP BY and without DISTINCT
-
# then can use simple ROWNUM in WHERE clause
-
if o.limit && o.orders.empty? && !o.offset && o.cores.first.set_quantifier.class.to_s !~ /Distinct/
-
o.cores.last.wheres.push Nodes::LessThanOrEqual.new(
-
Nodes::SqlLiteral.new('ROWNUM'), o.limit.expr
-
)
-
return super
-
end
-
-
if o.limit && o.offset
-
o = o.dup
-
limit = o.limit.expr.to_i
-
offset = o.offset
-
o.offset = nil
-
sql = super(o, a)
-
return <<-eosql
-
SELECT * FROM (
-
SELECT raw_sql_.*, rownum raw_rnum_
-
FROM (#{sql}) raw_sql_
-
WHERE rownum <= #{offset.expr.to_i + limit}
-
)
-
WHERE #{visit offset, a}
-
eosql
-
end
-
-
if o.limit
-
o = o.dup
-
limit = o.limit.expr
-
return "SELECT * FROM (#{super(o, a)}) WHERE ROWNUM <= #{visit limit, a}"
-
end
-
-
if o.offset
-
o = o.dup
-
offset = o.offset
-
o.offset = nil
-
sql = super(o, a)
-
return <<-eosql
-
SELECT * FROM (
-
SELECT raw_sql_.*, rownum raw_rnum_
-
FROM (#{sql}) raw_sql_
-
)
-
WHERE #{visit offset, a}
-
eosql
-
end
-
-
super
-
end
-
-
2
def visit_Arel_Nodes_Limit o, a
-
end
-
-
2
def visit_Arel_Nodes_Offset o, a
-
"raw_rnum_ > #{visit o.expr, a}"
-
end
-
-
2
def visit_Arel_Nodes_Except o, a
-
"( #{visit o.left, a} MINUS #{visit o.right, a} )"
-
end
-
-
2
def visit_Arel_Nodes_UpdateStatement o, a
-
# Oracle does not allow ORDER BY/LIMIT in UPDATEs.
-
if o.orders.any? && o.limit.nil?
-
# However, there is no harm in silently eating the ORDER BY clause if no LIMIT has been provided,
-
# otherwise let the user deal with the error
-
o = o.dup
-
o.orders = []
-
end
-
-
super
-
end
-
-
###
-
# Hacks for the order clauses specific to Oracle
-
2
def order_hacks o, a
-
return o if o.orders.empty?
-
return o unless o.cores.any? do |core|
-
core.projections.any? do |projection|
-
/FIRST_VALUE/ === projection
-
end
-
end
-
# Previous version with join and split broke ORDER BY clause
-
# if it contained functions with several arguments (separated by ',').
-
#
-
# orders = o.orders.map { |x| visit x, a }.join(', ').split(',')
-
orders = o.orders.map do |x|
-
string = visit x, a
-
if string.include?(',')
-
split_order_string(string)
-
else
-
string
-
end
-
end.flatten
-
o.orders = []
-
orders.each_with_index do |order, i|
-
o.orders <<
-
Nodes::SqlLiteral.new("alias_#{i}__#{' DESC' if /\bdesc$/i === order}")
-
end
-
o
-
end
-
-
# Split string by commas but count opening and closing brackets
-
# and ignore commas inside brackets.
-
2
def split_order_string(string)
-
array = []
-
i = 0
-
string.split(',').each do |part|
-
if array[i]
-
array[i] << ',' << part
-
else
-
# to ensure that array[i] will be String and not Arel::Nodes::SqlLiteral
-
array[i] = '' << part
-
end
-
i += 1 if array[i].count('(') == array[i].count(')')
-
end
-
array
-
end
-
-
end
-
end
-
end
-
2
module Arel
-
2
module Visitors
-
2
class OrderClauses < Arel::Visitors::ToSql
-
2
private
-
-
2
def visit_Arel_Nodes_SelectStatement o, a
-
o.orders.map { |x| visit x, a }
-
end
-
end
-
end
-
end
-
2
module Arel
-
2
module Visitors
-
2
class PostgreSQL < Arel::Visitors::ToSql
-
2
private
-
-
2
def visit_Arel_Nodes_Matches o, a
-
a = o.left if Arel::Attributes::Attribute === o.left
-
"#{visit o.left, a} ILIKE #{visit o.right, a}"
-
end
-
-
2
def visit_Arel_Nodes_DoesNotMatch o, a
-
a = o.left if Arel::Attributes::Attribute === o.left
-
"#{visit o.left, a} NOT ILIKE #{visit o.right, a}"
-
end
-
-
2
def visit_Arel_Nodes_DistinctOn o, a
-
"DISTINCT ON ( #{visit o.expr, a} )"
-
end
-
end
-
end
-
end
-
2
module Arel
-
2
module Visitors
-
2
class SQLite < Arel::Visitors::ToSql
-
2
private
-
-
# Locks are not supported in SQLite
-
2
def visit_Arel_Nodes_Lock o, a
-
end
-
-
2
def visit_Arel_Nodes_SelectStatement o, a
-
211
o.limit = Arel::Nodes::Limit.new(-1) if o.offset && !o.limit
-
211
super
-
end
-
end
-
end
-
end
-
2
require 'bigdecimal'
-
2
require 'date'
-
-
2
module Arel
-
2
module Visitors
-
2
class ToSql < Arel::Visitors::Visitor
-
##
-
# This is some roflscale crazy stuff. I'm roflscaling this because
-
# building SQL queries is a hotspot. I will explain the roflscale so that
-
# others will not rm this code.
-
#
-
# In YARV, string literals in a method body will get duped when the byte
-
# code is executed. Let's take a look:
-
#
-
# > puts RubyVM::InstructionSequence.new('def foo; "bar"; end').disasm
-
#
-
# == disasm: <RubyVM::InstructionSequence:foo@<compiled>>=====
-
# 0000 trace 8
-
# 0002 trace 1
-
# 0004 putstring "bar"
-
# 0006 trace 16
-
# 0008 leave
-
#
-
# The `putstring` bytecode will dup the string and push it on the stack.
-
# In many cases in our SQL visitor, that string is never mutated, so there
-
# is no need to dup the literal.
-
#
-
# If we change to a constant lookup, the string will not be duped, and we
-
# can reduce the objects in our system:
-
#
-
# > puts RubyVM::InstructionSequence.new('BAR = "bar"; def foo; BAR; end').disasm
-
#
-
# == disasm: <RubyVM::InstructionSequence:foo@<compiled>>========
-
# 0000 trace 8
-
# 0002 trace 1
-
# 0004 getinlinecache 11, <ic:0>
-
# 0007 getconstant :BAR
-
# 0009 setinlinecache <ic:0>
-
# 0011 trace 16
-
# 0013 leave
-
#
-
# `getconstant` should be a hash lookup, and no object is duped when the
-
# value of the constant is pushed on the stack. Hence the crazy
-
# constants below.
-
#
-
# `matches` and `doesNotMatch` operate case-insensitively via Visitor subclasses
-
# specialized for specific databases when necessary.
-
#
-
-
2
WHERE = ' WHERE ' # :nodoc:
-
2
SPACE = ' ' # :nodoc:
-
2
COMMA = ', ' # :nodoc:
-
2
GROUP_BY = ' GROUP BY ' # :nodoc:
-
2
ORDER_BY = ' ORDER BY ' # :nodoc:
-
2
WINDOW = ' WINDOW ' # :nodoc:
-
2
AND = ' AND ' # :nodoc:
-
-
2
DISTINCT = 'DISTINCT' # :nodoc:
-
-
2
def initialize connection
-
2
@connection = connection
-
2
@schema_cache = connection.schema_cache
-
2
@quoted_tables = {}
-
2
@quoted_columns = {}
-
end
-
-
2
private
-
-
2
def visit_Arel_Nodes_DeleteStatement o, a
-
[
-
"DELETE FROM #{visit o.relation}",
-
("WHERE #{o.wheres.map { |x| visit x }.join AND}" unless o.wheres.empty?)
-
].compact.join ' '
-
end
-
-
# FIXME: we should probably have a 2-pass visitor for this
-
2
def build_subselect key, o
-
stmt = Nodes::SelectStatement.new
-
core = stmt.cores.first
-
core.froms = o.relation
-
core.wheres = o.wheres
-
core.projections = [key]
-
stmt.limit = o.limit
-
stmt.orders = o.orders
-
stmt
-
end
-
-
2
def visit_Arel_Nodes_UpdateStatement o, a
-
if o.orders.empty? && o.limit.nil?
-
wheres = o.wheres
-
else
-
wheres = [Nodes::In.new(o.key, [build_subselect(o.key, o)])]
-
end
-
-
[
-
"UPDATE #{visit o.relation, a}",
-
("SET #{o.values.map { |value| visit value, a }.join ', '}" unless o.values.empty?),
-
("WHERE #{wheres.map { |x| visit x, a }.join ' AND '}" unless wheres.empty?),
-
].compact.join ' '
-
end
-
-
2
def visit_Arel_Nodes_InsertStatement o, a
-
[
-
"INSERT INTO #{visit o.relation, a}",
-
-
("(#{o.columns.map { |x|
-
1405
quote_column_name x.name
-
267
}.join ', '})" unless o.columns.empty?),
-
-
267
(visit o.values, a if o.values),
-
267
].compact.join ' '
-
end
-
-
2
def visit_Arel_Nodes_Exists o, a
-
"EXISTS (#{visit o.expressions, a})#{
-
o.alias ? " AS #{visit o.alias, a}" : ''}"
-
end
-
-
2
def visit_Arel_Nodes_True o, a
-
"TRUE"
-
end
-
-
2
def visit_Arel_Nodes_False o, a
-
"FALSE"
-
end
-
-
2
def table_exists? name
-
197
@schema_cache.table_exists? name
-
end
-
-
2
def column_for attr
-
197
return unless attr
-
197
name = attr.name.to_s
-
197
table = attr.relation.table_name
-
-
197
return nil unless table_exists? table
-
-
197
column_cache(table)[name]
-
end
-
-
2
def column_cache(table)
-
197
@schema_cache.columns_hash(table)
-
end
-
-
2
def visit_Arel_Nodes_Values o, a
-
267
"VALUES (#{o.expressions.zip(o.columns).map { |value, attr|
-
1405
if Nodes::SqlLiteral === value
-
1405
visit value, a
-
else
-
quote(value, attr && column_for(attr))
-
end
-
}.join ', '})"
-
end
-
-
2
def visit_Arel_Nodes_SelectStatement o, a
-
211
str = ''
-
-
211
if o.with
-
str << visit(o.with, a)
-
str << SPACE
-
end
-
-
422
o.cores.each { |x| str << visit_Arel_Nodes_SelectCore(x, a) }
-
-
211
unless o.orders.empty?
-
str << SPACE
-
str << ORDER_BY
-
len = o.orders.length - 1
-
o.orders.each_with_index { |x, i|
-
str << visit(x, a)
-
str << COMMA unless len == i
-
}
-
end
-
-
211
str << " #{visit(o.limit, a)}" if o.limit
-
211
str << " #{visit(o.offset, a)}" if o.offset
-
211
str << " #{visit(o.lock, a)}" if o.lock
-
-
211
str.strip!
-
211
str
-
end
-
-
2
def visit_Arel_Nodes_SelectCore o, a
-
211
str = "SELECT"
-
-
211
str << " #{visit(o.top, a)}" if o.top
-
211
str << " #{visit(o.set_quantifier, a)}" if o.set_quantifier
-
-
211
unless o.projections.empty?
-
211
str << SPACE
-
211
len = o.projections.length - 1
-
211
o.projections.each_with_index do |x, i|
-
211
str << visit(x, a)
-
211
str << COMMA unless len == i
-
end
-
end
-
-
211
str << " FROM #{visit(o.source, a)}" if o.source && !o.source.empty?
-
-
211
unless o.wheres.empty?
-
210
str << WHERE
-
210
len = o.wheres.length - 1
-
210
o.wheres.each_with_index do |x, i|
-
210
str << visit(x, a)
-
210
str << AND unless len == i
-
end
-
end
-
-
211
unless o.groups.empty?
-
str << GROUP_BY
-
len = o.groups.length - 1
-
o.groups.each_with_index do |x, i|
-
str << visit(x, a)
-
str << COMMA unless len == i
-
end
-
end
-
-
211
str << " #{visit(o.having, a)}" if o.having
-
-
211
unless o.windows.empty?
-
str << WINDOW
-
len = o.windows.length - 1
-
o.windows.each_with_index do |x, i|
-
str << visit(x, a)
-
str << COMMA unless len == i
-
end
-
end
-
-
211
str
-
end
-
-
2
def visit_Arel_Nodes_Bin o, a
-
visit o.expr, a
-
end
-
-
2
def visit_Arel_Nodes_Distinct o, a
-
DISTINCT
-
end
-
-
2
def visit_Arel_Nodes_DistinctOn o, a
-
raise NotImplementedError, 'DISTINCT ON not implemented for this db'
-
end
-
-
2
def visit_Arel_Nodes_With o, a
-
"WITH #{o.children.map { |x| visit x, a }.join(', ')}"
-
end
-
-
2
def visit_Arel_Nodes_WithRecursive o, a
-
"WITH RECURSIVE #{o.children.map { |x| visit x, a }.join(', ')}"
-
end
-
-
2
def visit_Arel_Nodes_Union o, a
-
"( #{visit o.left, a} UNION #{visit o.right, a} )"
-
end
-
-
2
def visit_Arel_Nodes_UnionAll o, a
-
"( #{visit o.left, a} UNION ALL #{visit o.right, a} )"
-
end
-
-
2
def visit_Arel_Nodes_Intersect o, a
-
"( #{visit o.left, a} INTERSECT #{visit o.right, a} )"
-
end
-
-
2
def visit_Arel_Nodes_Except o, a
-
"( #{visit o.left, a} EXCEPT #{visit o.right, a} )"
-
end
-
-
2
def visit_Arel_Nodes_NamedWindow o, a
-
"#{quote_column_name o.name} AS #{visit_Arel_Nodes_Window o, a}"
-
end
-
-
2
def visit_Arel_Nodes_Window o, a
-
s = [
-
("ORDER BY #{o.orders.map { |x| visit(x, a) }.join(', ')}" unless o.orders.empty?),
-
(visit o.framing, a if o.framing)
-
].compact.join ' '
-
"(#{s})"
-
end
-
-
2
def visit_Arel_Nodes_Rows o, a
-
if o.expr
-
"ROWS #{visit o.expr, a}"
-
else
-
"ROWS"
-
end
-
end
-
-
2
def visit_Arel_Nodes_Range o, a
-
if o.expr
-
"RANGE #{visit o.expr, a}"
-
else
-
"RANGE"
-
end
-
end
-
-
2
def visit_Arel_Nodes_Preceding o, a
-
"#{o.expr ? visit(o.expr, a) : 'UNBOUNDED'} PRECEDING"
-
end
-
-
2
def visit_Arel_Nodes_Following o, a
-
"#{o.expr ? visit(o.expr, a) : 'UNBOUNDED'} FOLLOWING"
-
end
-
-
2
def visit_Arel_Nodes_CurrentRow o, a
-
"CURRENT ROW"
-
end
-
-
2
def visit_Arel_Nodes_Over o, a
-
case o.right
-
when nil
-
"#{visit o.left, a} OVER ()"
-
when Arel::Nodes::SqlLiteral
-
"#{visit o.left, a} OVER #{visit o.right, a}"
-
when String, Symbol
-
"#{visit o.left, a} OVER #{quote_column_name o.right.to_s}"
-
else
-
"#{visit o.left, a} OVER #{visit o.right, a}"
-
end
-
end
-
-
2
def visit_Arel_Nodes_Having o, a
-
"HAVING #{visit o.expr, a}"
-
end
-
-
2
def visit_Arel_Nodes_Offset o, a
-
"OFFSET #{visit o.expr, a}"
-
end
-
-
2
def visit_Arel_Nodes_Limit o, a
-
210
"LIMIT #{visit o.expr, a}"
-
end
-
-
# FIXME: this does nothing on most databases, but does on MSSQL
-
2
def visit_Arel_Nodes_Top o, a
-
210
""
-
end
-
-
2
def visit_Arel_Nodes_Lock o, a
-
visit o.expr, a
-
end
-
-
2
def visit_Arel_Nodes_Grouping o, a
-
"(#{visit o.expr, a})"
-
end
-
-
2
def visit_Arel_SelectManager o, a
-
"(#{o.to_sql.rstrip})"
-
end
-
-
2
def visit_Arel_Nodes_Ascending o, a
-
"#{visit o.expr, a} ASC"
-
end
-
-
2
def visit_Arel_Nodes_Descending o, a
-
"#{visit o.expr, a} DESC"
-
end
-
-
2
def visit_Arel_Nodes_Group o, a
-
visit o.expr, a
-
end
-
-
2
def visit_Arel_Nodes_NamedFunction o, a
-
"#{o.name}(#{o.distinct ? 'DISTINCT ' : ''}#{o.expressions.map { |x|
-
visit x, a
-
}.join(', ')})#{o.alias ? " AS #{visit o.alias, a}" : ''}"
-
end
-
-
2
def visit_Arel_Nodes_Extract o, a
-
"EXTRACT(#{o.field.to_s.upcase} FROM #{visit o.expr, a})#{o.alias ? " AS #{visit o.alias, a}" : ''}"
-
end
-
-
2
def visit_Arel_Nodes_Count o, a
-
"COUNT(#{o.distinct ? 'DISTINCT ' : ''}#{o.expressions.map { |x|
-
visit x, a
-
}.join(', ')})#{o.alias ? " AS #{visit o.alias, a}" : ''}"
-
end
-
-
2
def visit_Arel_Nodes_Sum o, a
-
"SUM(#{o.distinct ? 'DISTINCT ' : ''}#{o.expressions.map { |x|
-
visit x, a }.join(', ')})#{o.alias ? " AS #{visit o.alias, a}" : ''}"
-
end
-
-
2
def visit_Arel_Nodes_Max o, a
-
"MAX(#{o.distinct ? 'DISTINCT ' : ''}#{o.expressions.map { |x|
-
visit x, a }.join(', ')})#{o.alias ? " AS #{visit o.alias, a}" : ''}"
-
end
-
-
2
def visit_Arel_Nodes_Min o, a
-
"MIN(#{o.distinct ? 'DISTINCT ' : ''}#{o.expressions.map { |x|
-
visit x, a }.join(', ')})#{o.alias ? " AS #{visit o.alias, a}" : ''}"
-
end
-
-
2
def visit_Arel_Nodes_Avg o, a
-
"AVG(#{o.distinct ? 'DISTINCT ' : ''}#{o.expressions.map { |x|
-
visit x, a }.join(', ')})#{o.alias ? " AS #{visit o.alias, a}" : ''}"
-
end
-
-
2
def visit_Arel_Nodes_TableAlias o, a
-
"#{visit o.relation, a} #{quote_table_name o.name}"
-
end
-
-
2
def visit_Arel_Nodes_Between o, a
-
a = o.left if Arel::Attributes::Attribute === o.left
-
"#{visit o.left, a} BETWEEN #{visit o.right, a}"
-
end
-
-
2
def visit_Arel_Nodes_GreaterThanOrEqual o, a
-
a = o.left if Arel::Attributes::Attribute === o.left
-
"#{visit o.left, a} >= #{visit o.right, a}"
-
end
-
-
2
def visit_Arel_Nodes_GreaterThan o, a
-
a = o.left if Arel::Attributes::Attribute === o.left
-
"#{visit o.left, a} > #{visit o.right, a}"
-
end
-
-
2
def visit_Arel_Nodes_LessThanOrEqual o, a
-
a = o.left if Arel::Attributes::Attribute === o.left
-
"#{visit o.left, a} <= #{visit o.right, a}"
-
end
-
-
2
def visit_Arel_Nodes_LessThan o, a
-
a = o.left if Arel::Attributes::Attribute === o.left
-
"#{visit o.left, a} < #{visit o.right, a}"
-
end
-
-
2
def visit_Arel_Nodes_Matches o, a
-
a = o.left if Arel::Attributes::Attribute === o.left
-
"#{visit o.left, a} LIKE #{visit o.right, a}"
-
end
-
-
2
def visit_Arel_Nodes_DoesNotMatch o, a
-
a = o.left if Arel::Attributes::Attribute === o.left
-
"#{visit o.left, a} NOT LIKE #{visit o.right, a}"
-
end
-
-
2
def visit_Arel_Nodes_JoinSource o, a
-
[
-
211
(visit(o.left, a) if o.left),
-
o.right.map { |j| visit j, a }.join(' ')
-
211
].compact.join ' '
-
end
-
-
2
def visit_Arel_Nodes_StringJoin o, a
-
visit o.left, a
-
end
-
-
2
def visit_Arel_Nodes_OuterJoin o, a
-
"LEFT OUTER JOIN #{visit o.left, a} #{visit o.right, a}"
-
end
-
-
2
def visit_Arel_Nodes_InnerJoin o, a
-
s = "INNER JOIN #{visit o.left, a}"
-
if o.right
-
s << SPACE
-
s << visit(o.right, a)
-
end
-
s
-
end
-
-
2
def visit_Arel_Nodes_On o, a
-
"ON #{visit o.expr, a}"
-
end
-
-
2
def visit_Arel_Nodes_Not o, a
-
"NOT (#{visit o.expr, a})"
-
end
-
-
2
def visit_Arel_Table o, a
-
478
if o.table_alias
-
"#{quote_table_name o.name} #{quote_table_name o.table_alias}"
-
else
-
478
quote_table_name o.name
-
end
-
end
-
-
2
def visit_Arel_Nodes_In o, a
-
if Array === o.right && o.right.empty?
-
'1=0'
-
else
-
a = o.left if Arel::Attributes::Attribute === o.left
-
"#{visit o.left, a} IN (#{visit o.right, a})"
-
end
-
end
-
-
2
def visit_Arel_Nodes_NotIn o, a
-
if Array === o.right && o.right.empty?
-
'1=1'
-
else
-
a = o.left if Arel::Attributes::Attribute === o.left
-
"#{visit o.left, a} NOT IN (#{visit o.right, a})"
-
end
-
end
-
-
2
def visit_Arel_Nodes_And o, a
-
420
o.children.map { |x| visit x, a }.join ' AND '
-
end
-
-
2
def visit_Arel_Nodes_Or o, a
-
"#{visit o.left, a} OR #{visit o.right, a}"
-
end
-
-
2
def visit_Arel_Nodes_Assignment o, a
-
right = quote(o.right, column_for(o.left))
-
"#{visit o.left, a} = #{right}"
-
end
-
-
2
def visit_Arel_Nodes_Equality o, a
-
210
right = o.right
-
-
210
a = o.left if Arel::Attributes::Attribute === o.left
-
210
if right.nil?
-
13
"#{visit o.left, a} IS NULL"
-
else
-
197
"#{visit o.left, a} = #{visit right, a}"
-
end
-
end
-
-
2
def visit_Arel_Nodes_NotEqual o, a
-
right = o.right
-
-
a = o.left if Arel::Attributes::Attribute === o.left
-
if right.nil?
-
"#{visit o.left, a} IS NOT NULL"
-
else
-
"#{visit o.left, a} != #{visit right, a}"
-
end
-
end
-
-
2
def visit_Arel_Nodes_As o, a
-
"#{visit o.left, a} AS #{visit o.right, a}"
-
end
-
-
2
def visit_Arel_Nodes_UnqualifiedColumn o, a
-
"#{quote_column_name o.name}"
-
end
-
-
2
def visit_Arel_Attributes_Attribute o, a
-
226
join_name = o.relation.table_alias || o.relation.name
-
226
"#{quote_table_name join_name}.#{quote_column_name o.name}"
-
end
-
2
alias :visit_Arel_Attributes_Integer :visit_Arel_Attributes_Attribute
-
2
alias :visit_Arel_Attributes_Float :visit_Arel_Attributes_Attribute
-
2
alias :visit_Arel_Attributes_Decimal :visit_Arel_Attributes_Attribute
-
2
alias :visit_Arel_Attributes_String :visit_Arel_Attributes_Attribute
-
2
alias :visit_Arel_Attributes_Time :visit_Arel_Attributes_Attribute
-
2
alias :visit_Arel_Attributes_Boolean :visit_Arel_Attributes_Attribute
-
-
1812
def literal o, a; o end
-
-
2
alias :visit_Arel_Nodes_BindParam :literal
-
2
alias :visit_Arel_Nodes_SqlLiteral :literal
-
2
alias :visit_Arel_SqlLiteral :literal # This is deprecated
-
2
alias :visit_Bignum :literal
-
2
alias :visit_Fixnum :literal
-
-
2
def quoted o, a
-
197
quote(o, column_for(a))
-
end
-
-
2
alias :visit_ActiveSupport_Multibyte_Chars :quoted
-
2
alias :visit_ActiveSupport_StringInquirer :quoted
-
2
alias :visit_BigDecimal :quoted
-
2
alias :visit_Class :quoted
-
2
alias :visit_Date :quoted
-
2
alias :visit_DateTime :quoted
-
2
alias :visit_FalseClass :quoted
-
2
alias :visit_Float :quoted
-
2
alias :visit_Hash :quoted
-
2
alias :visit_NilClass :quoted
-
2
alias :visit_String :quoted
-
2
alias :visit_Symbol :quoted
-
2
alias :visit_Time :quoted
-
2
alias :visit_TrueClass :quoted
-
-
2
def visit_Arel_Nodes_InfixOperation o, a
-
"#{visit o.left, a} #{o.operator} #{visit o.right, a}"
-
end
-
-
2
alias :visit_Arel_Nodes_Addition :visit_Arel_Nodes_InfixOperation
-
2
alias :visit_Arel_Nodes_Subtraction :visit_Arel_Nodes_InfixOperation
-
2
alias :visit_Arel_Nodes_Multiplication :visit_Arel_Nodes_InfixOperation
-
2
alias :visit_Arel_Nodes_Division :visit_Arel_Nodes_InfixOperation
-
-
2
def visit_Array o, a
-
o.map { |x| visit x, a }.join(', ')
-
end
-
-
2
def quote value, column = nil
-
197
return value if Arel::Nodes::SqlLiteral === value
-
197
@connection.quote value, column
-
end
-
-
2
def quote_table_name name
-
704
return name if Arel::Nodes::SqlLiteral === name
-
704
@quoted_tables[name] ||= @connection.quote_table_name(name)
-
end
-
-
2
def quote_column_name name
-
1631
@quoted_columns[name] ||= Arel::Nodes::SqlLiteral === name ? name : @connection.quote_column_name(name)
-
end
-
end
-
end
-
end
-
2
module Arel
-
2
module Visitors
-
2
class Visitor
-
2
def accept object
-
956
visit object
-
end
-
-
2
private
-
-
2
DISPATCH = Hash.new do |hash, visitor_class|
-
4
hash[visitor_class] =
-
Hash.new do |method_hash, node_class|
-
58
method_hash[node_class] = "visit_#{(node_class.name || '').gsub('::', '_')}"
-
end
-
end
-
-
2
def dispatch
-
15162
DISPATCH[self.class]
-
end
-
-
2
def visit object, attribute = nil
-
15162
send dispatch[object.class], object, attribute
-
rescue NoMethodError => e
-
raise e if respond_to?(dispatch[object.class], true)
-
superklass = object.class.ancestors.find { |klass|
-
respond_to?(dispatch[klass], true)
-
}
-
raise(TypeError, "Cannot visit #{object.class}") unless superklass
-
dispatch[object.class] = dispatch[superklass]
-
retry
-
end
-
end
-
end
-
end
-
2
module Arel
-
2
module Visitors
-
2
class WhereSql < Arel::Visitors::ToSql
-
2
def visit_Arel_Nodes_SelectCore o, a
-
"WHERE #{o.wheres.map { |x| visit x, a }.join ' AND ' }"
-
end
-
end
-
end
-
end
-
2
module Arel
-
2
module WindowPredications
-
-
2
def over(expr = nil)
-
Nodes::Over.new(self, expr)
-
end
-
-
end
-
end
-
# A Ruby library implementing OpenBSD's bcrypt()/crypt_blowfish algorithm for
-
# hashing passwords.
-
2
module BCrypt
-
end
-
-
2
if RUBY_PLATFORM == "java"
-
require 'java'
-
else
-
2
require "openssl"
-
end
-
-
2
begin
-
2
RUBY_VERSION =~ /(\d+.\d+)/
-
2
require "#{$1}/bcrypt_ext"
-
rescue LoadError
-
2
require "bcrypt_ext"
-
end
-
-
2
require 'bcrypt/error'
-
2
require 'bcrypt/engine'
-
2
require 'bcrypt/password'
-
2
module BCrypt
-
# A Ruby wrapper for the bcrypt() C extension calls and the Java calls.
-
2
class Engine
-
# The default computational expense parameter.
-
2
DEFAULT_COST = 10
-
# The minimum cost supported by the algorithm.
-
2
MIN_COST = 4
-
# Maximum possible size of bcrypt() salts.
-
2
MAX_SALT_LENGTH = 16
-
-
2
if RUBY_PLATFORM != "java"
-
# C-level routines which, if they don't get the right input, will crash the
-
# hell out of the Ruby process.
-
2
private_class_method :__bc_salt
-
2
private_class_method :__bc_crypt
-
end
-
-
2
@cost = nil
-
-
# Returns the cost factor that will be used if one is not specified when
-
# creating a password hash. Defaults to DEFAULT_COST if not set.
-
2
def self.cost
-
@cost || DEFAULT_COST
-
end
-
-
# Set a default cost factor that will be used if one is not specified when
-
# creating a password hash.
-
#
-
# Example:
-
#
-
# BCrypt::Engine::DEFAULT_COST #=> 10
-
# BCrypt::Password.create('secret').cost #=> 10
-
#
-
# BCrypt::Engine.cost = 8
-
# BCrypt::Password.create('secret').cost #=> 8
-
#
-
# # cost can still be overridden as needed
-
# BCrypt::Password.create('secret', :cost => 6).cost #=> 6
-
2
def self.cost=(cost)
-
@cost = cost
-
end
-
-
# Given a secret and a valid salt (see BCrypt::Engine.generate_salt) calculates
-
# a bcrypt() password hash.
-
2
def self.hash_secret(secret, salt, _ = nil)
-
196
if valid_secret?(secret)
-
196
if valid_salt?(salt)
-
196
if RUBY_PLATFORM == "java"
-
Java.bcrypt_jruby.BCrypt.hashpw(secret.to_s, salt.to_s)
-
else
-
196
__bc_crypt(secret.to_s, salt)
-
end
-
else
-
raise Errors::InvalidSalt.new("invalid salt")
-
end
-
else
-
raise Errors::InvalidSecret.new("invalid secret")
-
end
-
end
-
-
# Generates a random salt with a given computational cost.
-
2
def self.generate_salt(cost = self.cost)
-
196
cost = cost.to_i
-
196
if cost > 0
-
196
if cost < MIN_COST
-
cost = MIN_COST
-
end
-
196
if RUBY_PLATFORM == "java"
-
Java.bcrypt_jruby.BCrypt.gensalt(cost)
-
else
-
196
prefix = "$2a$05$CCCCCCCCCCCCCCCCCCCCC.E5YPO9kmyuRGyh0XouQYb4YMJKvyOeW"
-
196
__bc_salt(prefix, cost, OpenSSL::Random.random_bytes(MAX_SALT_LENGTH))
-
end
-
else
-
raise Errors::InvalidCost.new("cost must be numeric and > 0")
-
end
-
end
-
-
# Returns true if +salt+ is a valid bcrypt() salt, false if not.
-
2
def self.valid_salt?(salt)
-
196
!!(salt =~ /^\$[0-9a-z]{2,}\$[0-9]{2,}\$[A-Za-z0-9\.\/]{22,}$/)
-
end
-
-
# Returns true if +secret+ is a valid bcrypt() secret, false if not.
-
2
def self.valid_secret?(secret)
-
196
secret.respond_to?(:to_s)
-
end
-
-
# Returns the cost factor which will result in computation times less than +upper_time_limit_in_ms+.
-
#
-
# Example:
-
#
-
# BCrypt::Engine.calibrate(200) #=> 10
-
# BCrypt::Engine.calibrate(1000) #=> 12
-
#
-
# # should take less than 200ms
-
# BCrypt::Password.create("woo", :cost => 10)
-
#
-
# # should take less than 1000ms
-
# BCrypt::Password.create("woo", :cost => 12)
-
2
def self.calibrate(upper_time_limit_in_ms)
-
40.times do |i|
-
start_time = Time.now
-
Password.create("testing testing", :cost => i+1)
-
end_time = Time.now - start_time
-
return i if end_time * 1_000 > upper_time_limit_in_ms
-
end
-
end
-
-
# Autodetects the cost from the salt string.
-
2
def self.autodetect_cost(salt)
-
salt[4..5].to_i
-
end
-
end
-
-
end
-
2
module BCrypt
-
-
2
class Error < StandardError # :nodoc:
-
end
-
-
2
module Errors # :nodoc:
-
-
# The salt parameter provided to bcrypt() is invalid.
-
2
class InvalidSalt < BCrypt::Error; end
-
-
# The hash parameter provided to bcrypt() is invalid.
-
2
class InvalidHash < BCrypt::Error; end
-
-
# The cost parameter provided to bcrypt() is invalid.
-
2
class InvalidCost < BCrypt::Error; end
-
-
# The secret parameter provided to bcrypt() is invalid.
-
2
class InvalidSecret < BCrypt::Error; end
-
-
end
-
-
end
-
2
module BCrypt
-
# A password management class which allows you to safely store users' passwords and compare them.
-
#
-
# Example usage:
-
#
-
# include BCrypt
-
#
-
# # hash a user's password
-
# @password = Password.create("my grand secret")
-
# @password #=> "$2a$10$GtKs1Kbsig8ULHZzO1h2TetZfhO4Fmlxphp8bVKnUlZCBYYClPohG"
-
#
-
# # store it safely
-
# @user.update_attribute(:password, @password)
-
#
-
# # read it back
-
# @user.reload!
-
# @db_password = Password.new(@user.password)
-
#
-
# # compare it after retrieval
-
# @db_password == "my grand secret" #=> true
-
# @db_password == "a paltry guess" #=> false
-
#
-
2
class Password < String
-
# The hash portion of the stored password hash.
-
2
attr_reader :checksum
-
# The salt of the store password hash (including version and cost).
-
2
attr_reader :salt
-
# The version of the bcrypt() algorithm used to create the hash.
-
2
attr_reader :version
-
# The cost factor used to create the hash.
-
2
attr_reader :cost
-
-
2
class << self
-
# Hashes a secret, returning a BCrypt::Password instance. Takes an optional <tt>:cost</tt> option, which is a
-
# logarithmic variable which determines how computational expensive the hash is to calculate (a <tt>:cost</tt> of
-
# 4 is twice as much work as a <tt>:cost</tt> of 3). The higher the <tt>:cost</tt> the harder it becomes for
-
# attackers to try to guess passwords (even if a copy of your database is stolen), but the slower it is to check
-
# users' passwords.
-
#
-
# Example:
-
#
-
# @password = BCrypt::Password.create("my secret", :cost => 13)
-
2
def create(secret, options = {})
-
196
cost = options[:cost] || BCrypt::Engine.cost
-
196
raise ArgumentError if cost > 31
-
196
Password.new(BCrypt::Engine.hash_secret(secret, BCrypt::Engine.generate_salt(cost)))
-
end
-
-
2
def valid_hash?(h)
-
196
h =~ /^\$[0-9a-z]{2}\$[0-9]{2}\$[A-Za-z0-9\.\/]{53}$/
-
end
-
end
-
-
# Initializes a BCrypt::Password instance with the data from a stored hash.
-
2
def initialize(raw_hash)
-
196
if valid_hash?(raw_hash)
-
196
self.replace(raw_hash)
-
196
@version, @cost, @salt, @checksum = split_hash(self)
-
else
-
raise Errors::InvalidHash.new("invalid hash")
-
end
-
end
-
-
# Compares a potential secret against the hash. Returns true if the secret is the original secret, false otherwise.
-
2
def ==(secret)
-
super(BCrypt::Engine.hash_secret(secret, @salt))
-
end
-
2
alias_method :is_password?, :==
-
-
2
private
-
-
# Returns true if +h+ is a valid hash.
-
2
def valid_hash?(h)
-
196
self.class.valid_hash?(h)
-
end
-
-
# call-seq:
-
# split_hash(raw_hash) -> version, cost, salt, hash
-
#
-
# Splits +h+ into version, cost, salt, and hash and returns them in that order.
-
2
def split_hash(h)
-
196
_, v, c, mash = h.split('$')
-
196
return v.to_str, c.to_i, h[0, 29].to_str, mash[-31, 31].to_str
-
end
-
end
-
-
end
-
2
require 'rails'
-
-
2
module Bootstrap
-
2
module Generators
-
2
class Engine < ::Rails::Engine
-
2
config.app_generators.stylesheets false
-
-
2
initializer 'bootstrap-generators.setup', group: :all do |app|
-
2
app.config.less.paths << ::File.expand_path('../../vendor/twitter/bootstrap/less', __FILE__) if app.config.respond_to?(:less)
-
2
app.config.assets.paths << ::File.expand_path('../../vendor/twitter/bootstrap/sass', __FILE__) if app.config.respond_to?(:sass)
-
-
2
app.config.assets.paths << ::Rails.root.join('app', 'assets', 'fonts')
-
-
2
app.config.assets.precompile << /\.(?:svg|eot|woff|woff2|ttf)$/
-
end
-
end
-
end
-
end
-
2
module Bootstrap
-
2
class << self
-
# Inspired by Kaminari
-
2
def load!
-
2
register_compass_extension if compass?
-
-
2
if rails?
-
2
register_rails_engine
-
end
-
-
2
configure_sass
-
end
-
-
# Paths
-
2
def gem_path
-
2
@gem_path ||= File.expand_path '..', File.dirname(__FILE__)
-
end
-
-
2
def stylesheets_path
-
2
File.join assets_path, 'stylesheets'
-
end
-
-
2
def fonts_path
-
File.join assets_path, 'fonts'
-
end
-
-
2
def javascripts_path
-
File.join assets_path, 'javascripts'
-
end
-
-
2
def assets_path
-
2
@assets_path ||= File.join gem_path, 'assets'
-
end
-
-
# Environment detection helpers
-
2
def asset_pipeline?
-
defined?(::Sprockets)
-
end
-
-
2
def compass?
-
2
defined?(::Compass)
-
end
-
-
2
def rails?
-
2
defined?(::Rails)
-
end
-
-
2
private
-
-
2
def configure_sass
-
2
require 'sass' unless defined?(::Sass)
-
-
2
::Sass.load_paths << stylesheets_path
-
-
# bootstrap requires minimum precision of 10, see https://github.com/twbs/bootstrap-sass/issues/409
-
2
::Sass::Script::Number.precision = [10, ::Sass::Script::Number.precision].max
-
end
-
-
2
def register_compass_extension
-
::Compass::Frameworks.register(
-
'bootstrap',
-
:path => gem_path,
-
:stylesheets_directory => stylesheets_path,
-
:templates_directory => File.join(gem_path, 'templates')
-
)
-
end
-
-
2
def register_rails_engine
-
2
require 'bootstrap-sass/engine'
-
end
-
end
-
end
-
-
2
Bootstrap.load!
-
2
module Bootstrap
-
2
module Rails
-
2
class Engine < ::Rails::Engine
-
2
initializer 'bootstrap-sass.assets.precompile' do |app|
-
2
%w(stylesheets javascripts fonts images).each do |sub|
-
8
app.config.assets.paths << root.join('assets', sub)
-
end
-
2
app.config.assets.precompile << %r(bootstrap/glyphicons-halflings-regular\.(?:eot|svg|ttf|woff)$)
-
end
-
end
-
end
-
end
-
2
require 'byebug/attacher'
-
#
-
# Main Container for all of Byebug's code
-
#
-
2
module Byebug
-
#
-
# Enters byebug right before (or right after if _before_ is false) return
-
# events occur. Before entering byebug the init script is read.
-
#
-
2
def self.attach
-
require 'byebug/core'
-
-
unless started?
-
self.mode = :attached
-
-
start
-
run_init_script
-
end
-
-
current_context.step_out(3, true)
-
end
-
end
-
-
#
-
# Adds a `byebug` method to the Kernel module.
-
#
-
# Dropping a `byebug` call anywhere in your code, you get a debug prompt.
-
#
-
2
module Kernel
-
2
def byebug
-
Byebug.attach
-
end
-
-
2
alias debugger byebug
-
end
-
# frozen_string_literal: true
-
2
require 'timeout'
-
2
require 'nokogiri'
-
2
require 'xpath'
-
-
2
module Capybara
-
2
class CapybaraError < StandardError; end
-
2
class DriverNotFoundError < CapybaraError; end
-
2
class FrozenInTime < CapybaraError; end
-
2
class ElementNotFound < CapybaraError; end
-
2
class ModalNotFound < CapybaraError; end
-
2
class Ambiguous < ElementNotFound; end
-
2
class ExpectationNotMet < ElementNotFound; end
-
2
class FileNotFound < CapybaraError; end
-
2
class UnselectNotAllowed < CapybaraError; end
-
2
class NotSupportedByDriverError < CapybaraError; end
-
2
class InfiniteRedirectError < CapybaraError; end
-
2
class ScopeError < CapybaraError; end
-
2
class WindowError < CapybaraError; end
-
2
class ReadOnlyElementError < CapybaraError; end
-
-
2
class << self
-
2
attr_accessor :asset_host, :app_host, :run_server, :default_host, :always_include_port
-
2
attr_accessor :server_port, :exact, :match, :exact_options, :visible_text_only
-
2
attr_accessor :default_selector, :default_max_wait_time, :ignore_hidden_elements
-
2
attr_accessor :save_path, :wait_on_first_by_default, :automatic_reload
-
2
attr_accessor :reuse_server, :raise_server_errors, :server_errors
-
2
attr_writer :default_driver, :current_driver, :javascript_driver, :session_name, :server_host
-
2
attr_reader :save_and_open_page_path
-
2
attr_accessor :app
-
-
##
-
#
-
# Configure Capybara to suit your needs.
-
#
-
# Capybara.configure do |config|
-
# config.run_server = false
-
# config.app_host = 'http://www.google.com'
-
# end
-
#
-
# === Configurable options
-
#
-
# [app_host = String] The default host to use when giving a relative URL to visit
-
# [always_include_port = Boolean] Whether the Rack server's port should automatically be inserted into every visited URL (Default: false)
-
# [asset_host = String] Where dynamic assets are hosted - will be prepended to relative asset locations if present (Default: nil)
-
# [run_server = Boolean] Whether to start a Rack server for the given Rack app (Default: true)
-
# [raise_server_errors = Boolean] Should errors raised in the server be raised in the tests? (Default: true)
-
# [server_errors = Array\<Class\>] Error classes that should be raised in the tests if they are raised in the server and Capybara.raise_server_errors is true (Default: [StandardError])
-
# [default_selector = :css/:xpath] Methods which take a selector use the given type by default (Default: :css)
-
# [default_max_wait_time = Numeric] The maximum number of seconds to wait for asynchronous processes to finish (Default: 2)
-
# [ignore_hidden_elements = Boolean] Whether to ignore hidden elements on the page (Default: true)
-
# [automatic_reload = Boolean] Whether to automatically reload elements as Capybara is waiting (Default: true)
-
# [save_path = String] Where to put pages saved through save_(page|screenshot), save_and_open_(page|screenshot) (Default: Dir.pwd)
-
# [wait_on_first_by_default = Boolean] Whether Node#first defaults to Capybara waiting behavior for at least 1 element to match (Default: false)
-
# [reuse_server = Boolean] Reuse the server thread between multiple sessions using the same app object (Default: true)
-
# === DSL Options
-
#
-
# when using capybara/dsl, the following options are also available:
-
#
-
# [default_driver = Symbol] The name of the driver to use by default. (Default: :rack_test)
-
# [javascript_driver = Symbol] The name of a driver to use for JavaScript enabled tests. (Default: :selenium)
-
#
-
2
def configure
-
2
yield self
-
end
-
-
##
-
#
-
# Register a new driver for Capybara.
-
#
-
# Capybara.register_driver :rack_test do |app|
-
# Capybara::RackTest::Driver.new(app)
-
# end
-
#
-
# @param [Symbol] name The name of the new driver
-
# @yield [app] This block takes a rack app and returns a Capybara driver
-
# @yieldparam [<Rack>] app The rack application that this driver runs against. May be nil.
-
# @yieldreturn [Capybara::Driver::Base] A Capybara driver instance
-
#
-
2
def register_driver(name, &block)
-
6
drivers[name] = block
-
end
-
-
##
-
#
-
# Register a new server for Capybara.
-
#
-
# Capybara.register_server :webrick do |app, port, host|
-
# require 'rack/handler/webrick'
-
# Rack::Handler::WEBrick.run(app, ...)
-
# end
-
#
-
# @param [Symbol] name The name of the new driver
-
# @yield [app, port, host] This block takes a rack app and a port and returns a rack server listening on that port
-
# @yieldparam [<Rack>] app The rack application that this server will contain.
-
# @yieldparam port The port number the server should listen on
-
# @yieldparam host The host/ip to bind to
-
# @yieldreturn [Capybara::Driver::Base] A Capybara driver instance
-
#
-
2
def register_server(name, &block)
-
6
servers[name.to_sym] = block
-
end
-
-
##
-
#
-
# Add a new selector to Capybara. Selectors can be used by various methods in Capybara
-
# to find certain elements on the page in a more convenient way. For example adding a
-
# selector to find certain table rows might look like this:
-
#
-
# Capybara.add_selector(:row) do
-
# xpath { |num| ".//tbody/tr[#{num}]" }
-
# end
-
#
-
# This makes it possible to use this selector in a variety of ways:
-
#
-
# find(:row, 3)
-
# page.find('table#myTable').find(:row, 3).text
-
# page.find('table#myTable').has_selector?(:row, 3)
-
# within(:row, 3) { expect(page).to have_content('$100.000') }
-
#
-
# Here is another example:
-
#
-
# Capybara.add_selector(:id) do
-
# xpath { |id| XPath.descendant[XPath.attr(:id) == id.to_s] }
-
# end
-
#
-
# Note that this particular selector already ships with Capybara.
-
#
-
# @param [Symbol] name The name of the selector to add
-
# @yield A block executed in the context of the new {Capybara::Selector}
-
#
-
2
def add_selector(name, &block)
-
32
Capybara::Selector.add(name, &block)
-
end
-
-
##
-
#
-
# Modify a selector previously created by {Capybara.add_selector}.
-
# For example modifying the :button selector to also find divs styled
-
# to look like buttons might look like this
-
#
-
# Capybara.modify_selector(:button) do
-
# xpath { |locator| XPath::HTML.button(locator).or(XPath::css('div.btn')[XPath::string.n.is(locator)]) }
-
# end
-
#
-
# @param [Symbol] name The name of the selector to modify
-
# @yield A block executed in the context of the existing {Capybara::Selector}
-
#
-
2
def modify_selector(name, &block)
-
Capybara::Selector.update(name, &block)
-
end
-
-
2
def drivers
-
8
@drivers ||= {}
-
end
-
-
2
def servers
-
8
@servers ||= {}
-
end
-
-
##
-
#
-
# Register a proc that Capybara will call to run the Rack application.
-
#
-
# Capybara.server do |app, port, host|
-
# require 'rack/handler/mongrel'
-
# Rack::Handler::Mongrel.run(app, :Port => port)
-
# end
-
#
-
# By default, Capybara will try to run webrick.
-
#
-
# @yield [app, port, host] This block receives a rack app, port, and host/ip and should run a Rack handler
-
#
-
2
def server(&block)
-
if block_given?
-
warn "DEPRECATED: Passing a block to Capybara::server is deprecated, please use Capybara::register_server instead"
-
@server = block
-
else
-
@server
-
end
-
end
-
-
##
-
#
-
# Set the server to use.
-
#
-
# Capybara.server = :webrick
-
#
-
# @param [Symbol] name Name of the server type to use
-
# @see register_server
-
#
-
2
def server=(name)
-
2
@server = if name.respond_to? :call
-
name
-
else
-
2
servers[name.to_sym]
-
end
-
end
-
-
##
-
#
-
# Wraps the given string, which should contain an HTML document or fragment
-
# in a {Capybara::Node::Simple} which exposes all {Capybara::Node::Matchers},
-
# {Capybara::Node::Finders} and {Capybara::Node::DocumentMatchers}. This allows you to query
-
# any string containing HTML in the exact same way you would query the current document in a Capybara
-
# session.
-
#
-
# Example: A single element
-
#
-
# node = Capybara.string('<a href="foo">bar</a>')
-
# anchor = node.first('a')
-
# anchor[:href] #=> 'foo'
-
# anchor.text #=> 'bar'
-
#
-
# Example: Multiple elements
-
#
-
# node = Capybara.string <<-HTML
-
# <ul>
-
# <li id="home">Home</li>
-
# <li id="projects">Projects</li>
-
# </ul>
-
# HTML
-
#
-
# node.find('#projects').text # => 'Projects'
-
# node.has_selector?('li#home', :text => 'Home')
-
# node.has_selector?('#projects')
-
# node.find('ul').find('li:first-child').text # => 'Home'
-
#
-
# @param [String] html An html fragment or document
-
# @return [Capybara::Node::Simple] A node which has Capybara's finders and matchers
-
#
-
2
def string(html)
-
Capybara::Node::Simple.new(html)
-
end
-
-
##
-
#
-
# Runs Capybara's default server for the given application and port
-
# under most circumstances you should not have to call this method
-
# manually.
-
#
-
# @param [Rack Application] app The rack application to run
-
# @param [Fixnum] port The port to run the application on
-
#
-
2
def run_default_server(app, port)
-
servers[:webrick].call(app, port, server_host)
-
end
-
-
##
-
#
-
# @return [Symbol] The name of the driver to use by default
-
#
-
2
def default_driver
-
14
@default_driver || :rack_test
-
end
-
-
##
-
#
-
# @return [Symbol] The name of the driver currently in use
-
#
-
2
def current_driver
-
14
@current_driver || default_driver
-
end
-
2
alias_method :mode, :current_driver
-
-
##
-
#
-
# @return [Symbol] The name of the driver used when JavaScript is needed
-
#
-
2
def javascript_driver
-
@javascript_driver || :selenium
-
end
-
-
##
-
#
-
# Use the default driver as the current driver
-
#
-
2
def use_default_driver
-
6
@current_driver = nil
-
end
-
-
##
-
#
-
# Yield a block using a specific driver
-
#
-
2
def using_driver(driver)
-
previous_driver = Capybara.current_driver
-
Capybara.current_driver = driver
-
yield
-
ensure
-
@current_driver = previous_driver
-
end
-
-
##
-
#
-
# @return [String] The IP address bound by default server
-
#
-
2
def server_host
-
@server_host || '127.0.0.1'
-
end
-
-
##
-
#
-
# Yield a block using a specific wait time
-
#
-
2
def using_wait_time(seconds)
-
previous_wait_time = Capybara.default_max_wait_time
-
Capybara.default_max_wait_time = seconds
-
yield
-
ensure
-
Capybara.default_max_wait_time = previous_wait_time
-
end
-
-
##
-
#
-
# The current Capybara::Session based on what is set as Capybara.app and Capybara.current_driver
-
#
-
# @return [Capybara::Session] The currently used session
-
#
-
2
def current_session
-
13
session_pool["#{current_driver}:#{session_name}:#{app.object_id}"] ||= Capybara::Session.new(current_driver, app)
-
end
-
-
##
-
#
-
# Reset sessions, cleaning out the pool of sessions. This will remove any session information such
-
# as cookies.
-
#
-
2
def reset_sessions!
-
#reset in reverse so sessions that started servers are reset last
-
12
session_pool.reverse_each { |mode, session| session.reset! }
-
end
-
2
alias_method :reset!, :reset_sessions!
-
-
##
-
#
-
# The current session name.
-
#
-
# @return [Symbol] The name of the currently used session.
-
#
-
2
def session_name
-
13
@session_name ||= :default
-
end
-
-
##
-
#
-
# Yield a block using a specific session name.
-
#
-
2
def using_session(name)
-
previous_session_name = self.session_name
-
self.session_name = name
-
yield
-
ensure
-
self.session_name = previous_session_name
-
end
-
-
##
-
#
-
# Parse raw html into a document using Nokogiri, and adjust textarea contents as defined by the spec.
-
#
-
# @param [String] html The raw html
-
# @return [Nokogiri::HTML::Document] HTML document
-
#
-
2
def HTML(html)
-
7
Nokogiri::HTML(html).tap do |document|
-
7
document.xpath('//textarea').each do |textarea|
-
textarea.content=textarea.content.sub(/\A\n/,'')
-
end
-
end
-
end
-
-
# @deprecated Use default_max_wait_time instead
-
2
def default_wait_time
-
deprecate('default_wait_time', 'default_max_wait_time', true)
-
default_max_wait_time
-
end
-
-
# @deprecated Use default_max_wait_time= instead
-
2
def default_wait_time=(t)
-
deprecate('default_wait_time=', 'default_max_wait_time=')
-
self.default_max_wait_time = t
-
end
-
-
2
def save_and_open_page_path=(path)
-
warn "DEPRECATED: #save_and_open_page_path is deprecated, please use #save_path instead. \n"\
-
"Note: Behavior is slightly different with relative paths - see documentation" unless path.nil?
-
@save_and_open_page_path = path
-
end
-
-
2
def included(base)
-
base.send(:include, Capybara::DSL)
-
warn "`include Capybara` is deprecated. Please use `include Capybara::DSL` instead."
-
end
-
-
2
def reuse_server=(bool)
-
2
warn "Capybara.reuse_server == false is a BETA feature and may change in a future version" unless bool
-
2
@reuse_server = bool
-
end
-
-
2
def deprecate(method, alternate_method, once=false)
-
@deprecation_notified ||= {}
-
warn "DEPRECATED: ##{method} is deprecated, please use ##{alternate_method} instead" unless once and @deprecation_notified[method]
-
@deprecation_notified[method]=true
-
end
-
-
2
private
-
-
2
def session_pool
-
19
@session_pool ||= {}
-
end
-
end
-
-
2
self.default_driver = nil
-
2
self.current_driver = nil
-
2
self.server_host = nil
-
-
2
module Driver; end
-
2
module RackTest; end
-
2
module Selenium; end
-
-
2
require 'capybara/helpers'
-
2
require 'capybara/session'
-
2
require 'capybara/window'
-
2
require 'capybara/server'
-
2
require 'capybara/selector'
-
2
require 'capybara/result'
-
2
require 'capybara/version'
-
-
2
require 'capybara/queries/base_query'
-
2
require 'capybara/queries/selector_query'
-
2
require 'capybara/queries/text_query'
-
2
require 'capybara/queries/title_query'
-
2
require 'capybara/queries/current_path_query'
-
2
require 'capybara/queries/match_query'
-
2
require 'capybara/query'
-
-
2
require 'capybara/node/finders'
-
2
require 'capybara/node/matchers'
-
2
require 'capybara/node/actions'
-
2
require 'capybara/node/document_matchers'
-
2
require 'capybara/node/simple'
-
2
require 'capybara/node/base'
-
2
require 'capybara/node/element'
-
2
require 'capybara/node/document'
-
-
2
require 'capybara/driver/base'
-
2
require 'capybara/driver/node'
-
-
2
require 'capybara/rack_test/driver'
-
2
require 'capybara/rack_test/node'
-
2
require 'capybara/rack_test/form'
-
2
require 'capybara/rack_test/browser'
-
2
require 'capybara/rack_test/css_handlers.rb'
-
-
2
require 'capybara/selenium/node'
-
2
require 'capybara/selenium/driver'
-
end
-
-
2
Capybara.register_server :default do |app, port, host|
-
Capybara.run_default_server(app, port)
-
end
-
-
2
Capybara.register_server :webrick do |app, port, host|
-
require 'rack/handler/webrick'
-
Rack::Handler::WEBrick.run(app, :Host => host, :Port => port, :AccessLog => [], :Logger => WEBrick::Log::new(nil, 0))
-
end
-
-
2
Capybara.register_server :puma do |app, port, host|
-
require 'puma'
-
Puma::Server.new(app).tap do |s|
-
s.add_tcp_listener host, port
-
end.run.join
-
end
-
-
2
Capybara.configure do |config|
-
2
config.always_include_port = false
-
2
config.run_server = true
-
2
config.server = :default
-
2
config.default_selector = :css
-
2
config.default_max_wait_time = 2
-
2
config.ignore_hidden_elements = true
-
2
config.default_host = "http://www.example.com"
-
2
config.automatic_reload = true
-
2
config.match = :smart
-
2
config.exact = false
-
2
config.raise_server_errors = true
-
2
config.server_errors = [StandardError]
-
2
config.visible_text_only = false
-
2
config.wait_on_first_by_default = false
-
2
config.reuse_server = true
-
end
-
-
2
Capybara.register_driver :rack_test do |app|
-
Capybara::RackTest::Driver.new(app)
-
end
-
-
2
Capybara.register_driver :selenium do |app|
-
Capybara::Selenium::Driver.new(app)
-
end
-
-
# frozen_string_literal: true
-
1
require 'capybara/dsl'
-
1
require 'capybara/rspec/matchers'
-
-
1
World(Capybara::DSL)
-
1
World(Capybara::RSpecMatchers)
-
-
1
After do
-
6
Capybara.reset_sessions!
-
end
-
-
1
Before do
-
6
Capybara.use_default_driver
-
end
-
-
1
Before '@javascript' do
-
Capybara.current_driver = Capybara.javascript_driver
-
end
-
-
1
Before do |scenario|
-
6
scenario.source_tag_names.each do |tag|
-
driver_name = tag.sub(/^@/, '').to_sym
-
if Capybara.drivers.has_key?(driver_name)
-
Capybara.current_driver = driver_name
-
end
-
end
-
end
-
# frozen_string_literal: true
-
2
class Capybara::Driver::Base
-
2
def current_url
-
raise NotImplementedError
-
end
-
-
2
def visit(path)
-
raise NotImplementedError
-
end
-
-
2
def find_xpath(query)
-
raise NotImplementedError
-
end
-
-
2
def find_css(query)
-
raise NotImplementedError
-
end
-
-
2
def html
-
raise NotImplementedError
-
end
-
-
2
def go_back
-
raise Capybara::NotSupportedByDriverError, 'Capybara::Driver::Base#go_back'
-
end
-
-
2
def go_forward
-
raise Capybara::NotSupportedByDriverError, 'Capybara::Driver::Base#go_forward'
-
end
-
-
2
def execute_script(script)
-
raise Capybara::NotSupportedByDriverError, 'Capybara::Driver::Base#execute_script'
-
end
-
-
2
def evaluate_script(script)
-
raise Capybara::NotSupportedByDriverError, 'Capybara::Driver::Base#evaluate_script'
-
end
-
-
2
def save_screenshot(path, options={})
-
raise Capybara::NotSupportedByDriverError, 'Capybara::Driver::Base#save_screenshot'
-
end
-
-
2
def response_headers
-
raise Capybara::NotSupportedByDriverError, 'Capybara::Driver::Base#response_headers'
-
end
-
-
2
def status_code
-
raise Capybara::NotSupportedByDriverError, 'Capybara::Driver::Base#status_code'
-
end
-
-
2
def within_frame(frame_handle)
-
raise Capybara::NotSupportedByDriverError, 'Capybara::Driver::Base#within_frame'
-
end
-
-
2
def current_window_handle
-
raise Capybara::NotSupportedByDriverError, 'Capybara::Driver::Base#current_window_handle'
-
end
-
-
2
def window_size(handle)
-
raise Capybara::NotSupportedByDriverError, 'Capybara::Driver::Base#window_size'
-
end
-
-
2
def resize_window_to(handle, width, height)
-
raise Capybara::NotSupportedByDriverError, 'Capybara::Driver::Base#resize_window_to'
-
end
-
-
2
def maximize_window(handle)
-
raise Capybara::NotSupportedByDriverError, 'Capybara::Driver::Base#maximize_current_window'
-
end
-
-
2
def close_window(handle)
-
raise Capybara::NotSupportedByDriverError, 'Capybara::Driver::Base#close_window'
-
end
-
-
2
def window_handles
-
raise Capybara::NotSupportedByDriverError, 'Capybara::Driver::Base#window_handles'
-
end
-
-
2
def open_new_window
-
raise Capybara::NotSupportedByDriverError, 'Capybara::Driver::Base#open_new_window'
-
end
-
-
2
def switch_to_window(handle)
-
raise Capybara::NotSupportedByDriverError, 'Capybara::Driver::Base#switch_to_window'
-
end
-
-
2
def within_window(locator)
-
raise Capybara::NotSupportedByDriverError, 'Capybara::Driver::Base#within_window'
-
end
-
-
2
def no_such_window_error
-
raise Capybara::NotSupportedByDriverError, 'Capybara::Driver::Base#no_such_window_error'
-
end
-
-
-
##
-
#
-
# Execute the block, and then accept the modal opened.
-
# @param type [:alert, :confirm, :prompt]
-
# @option options [Numeric] :wait How long to wait for the modal to appear after executing the block.
-
# @option options [String, Regexp] :text Text to verify is in the message shown in the modal
-
# @option options [String] :with Text to fill in in the case of a prompt
-
# @return [String] the message shown in the modal
-
# @raise [Capybara::ModalNotFound] if modal dialog hasn't been found
-
#
-
2
def accept_modal(type, options={}, &blk)
-
raise Capybara::NotSupportedByDriverError, 'Capybara::Driver::Base#accept_modal'
-
end
-
-
##
-
#
-
# Execute the block, and then dismiss the modal opened.
-
# @param type [:alert, :confirm, :prompt]
-
# @option options [Numeric] :wait How long to wait for the modal to appear after executing the block.
-
# @option options [String, Regexp] :text Text to verify is in the message shown in the modal
-
# @return [String] the message shown in the modal
-
# @raise [Capybara::ModalNotFound] if modal dialog hasn't been found
-
#
-
2
def dismiss_modal(type, options={}, &blk)
-
raise Capybara::NotSupportedByDriverError, 'Capybara::Driver::Base#dismiss_modal'
-
end
-
-
2
def invalid_element_errors
-
[]
-
end
-
-
2
def wait?
-
false
-
end
-
-
2
def reset!
-
end
-
-
2
def needs_server?
-
1
false
-
end
-
-
# @deprecated This method is being removed
-
2
def browser_initialized?
-
warn "DEPRECATED: #browser_initialized? is deprecated and will be removed in the next version of Capybara"
-
true
-
end
-
end
-
# frozen_string_literal: true
-
2
require 'capybara'
-
-
2
module Capybara
-
2
module DSL
-
2
def self.included(base)
-
warn "including Capybara::DSL in the global scope is not recommended!" if base == Object
-
super
-
end
-
-
2
def self.extended(base)
-
8
warn "extending the main object with Capybara::DSL is not recommended!" if base == TOPLEVEL_BINDING.eval("self")
-
8
super
-
end
-
-
##
-
#
-
# Shortcut to working in a different session.
-
#
-
2
def using_session(name, &block)
-
Capybara.using_session(name, &block)
-
end
-
-
##
-
#
-
# Shortcut to using a different wait time.
-
#
-
2
def using_wait_time(seconds, &block)
-
Capybara.using_wait_time(seconds, &block)
-
end
-
-
##
-
#
-
# Shortcut to accessing the current session.
-
#
-
# class MyClass
-
# include Capybara::DSL
-
#
-
# def has_header?
-
# page.has_css?('h1')
-
# end
-
# end
-
#
-
# @return [Capybara::Session] The current session object
-
#
-
2
def page
-
13
Capybara.current_session
-
end
-
-
2
Session::DSL_METHODS.each do |method|
-
190
define_method method do |*args, &block|
-
13
page.send method, *args, &block
-
end
-
end
-
end
-
-
2
extend(Capybara::DSL)
-
end
-
# encoding: UTF-8
-
# frozen_string_literal: true
-
-
2
module Capybara
-
-
# @api private
-
2
module Helpers
-
2
extend self
-
-
##
-
#
-
# Normalizes whitespace space by stripping leading and trailing
-
# whitespace and replacing sequences of whitespace characters
-
# with a single space.
-
#
-
# @param [String] text Text to normalize
-
# @return [String] Normalized text
-
#
-
2
def normalize_whitespace(text)
-
text.to_s.gsub(/[[:space:]]+/, ' ').strip
-
end
-
-
##
-
#
-
# Escapes any characters that would have special meaning in a regexp
-
# if text is not a regexp
-
#
-
# @param [String] text Text to escape
-
# @return [String] Escaped text
-
#
-
2
def to_regexp(text)
-
text.is_a?(Regexp) ? text : Regexp.new(Regexp.escape(normalize_whitespace(text)))
-
end
-
-
##
-
#
-
# Injects a `<base>` tag into the given HTML code, pointing to
-
# `Capybara.asset_host`.
-
#
-
# @param [String] html HTML code to inject into
-
# @return [String] The modified HTML code
-
#
-
2
def inject_asset_host(html)
-
if Capybara.asset_host && Nokogiri::HTML(html).css("base").empty?
-
match = html.match(/<head[^<]*?>/)
-
if match
-
return html.clone.insert match.end(0), "<base href='#{Capybara.asset_host}' />"
-
end
-
end
-
-
html
-
end
-
-
##
-
#
-
# Checks if the given count matches the given count options.
-
# Defaults to true if no options are specified. If multiple
-
# options are provided, it tests that all conditions are met;
-
# however, if :count is supplied, all other options are ignored.
-
#
-
# @param [Integer] count The actual number. Should be coercible via Integer()
-
# @option [Range] between Count must be within the given range
-
# @option [Integer] count Count must be exactly this
-
# @option [Integer] maximum Count must be smaller than or equal to this value
-
# @option [Integer] minimum Count must be larger than or equal to this value
-
#
-
2
def matches_count?(count, options={})
-
return (Integer(options[:count]) == count) if options[:count]
-
return false if options[:maximum] && (Integer(options[:maximum]) < count)
-
return false if options[:minimum] && (Integer(options[:minimum]) > count)
-
return false if options[:between] && !(options[:between] === count)
-
return true
-
end
-
-
##
-
#
-
# Checks if a count of 0 is valid for the given options hash.
-
# Returns false if options hash does not specify any count options.
-
#
-
2
def expects_none?(options={})
-
if [:count, :maximum, :minimum, :between].any? { |k| options.has_key? k }
-
matches_count?(0,options)
-
else
-
false
-
end
-
end
-
-
##
-
#
-
# Generates a failure message given a description of the query and count
-
# options.
-
#
-
# @param [String] description Description of a query
-
# @option [Range] between Count should have been within the given range
-
# @option [Integer] count Count should have been exactly this
-
# @option [Integer] maximum Count should have been smaller than or equal to this value
-
# @option [Integer] minimum Count should have been larger than or equal to this value
-
#
-
2
def failure_message(description, options={})
-
message = String.new("expected to find #{description}")
-
if options[:count]
-
message << " #{options[:count]} #{declension('time', 'times', options[:count])}"
-
elsif options[:between]
-
message << " between #{options[:between].first} and #{options[:between].last} times"
-
elsif options[:maximum]
-
message << " at most #{options[:maximum]} #{declension('time', 'times', options[:maximum])}"
-
elsif options[:minimum]
-
message << " at least #{options[:minimum]} #{declension('time', 'times', options[:minimum])}"
-
end
-
message
-
end
-
-
##
-
#
-
# A poor man's `pluralize`. Given two declensions, one singular and one
-
# plural, as well as a count, this will pick the correct declension. This
-
# way we can generate grammatically correct error message.
-
#
-
# @param [String] singular The singular form of the word
-
# @param [String] plural The plural form of the word
-
# @param [Integer] count The number of items
-
#
-
2
def declension(singular, plural, count)
-
if count == 1
-
singular
-
else
-
plural
-
end
-
end
-
-
2
if defined?(Process::CLOCK_MONOTONIC)
-
2
def monotonic_time
-
32
Process.clock_gettime Process::CLOCK_MONOTONIC
-
end
-
else
-
def monotonic_time
-
Time.now.to_f
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
2
module Capybara
-
2
module Node
-
2
module Actions
-
-
##
-
#
-
# Finds a button or link by id, text or value and clicks it. Also looks at image
-
# alt text inside the link.
-
#
-
# @param [String] locator Text, id or value of link or button
-
#
-
2
def click_link_or_button(locator, options={})
-
find(:link_or_button, locator, options).click
-
end
-
2
alias_method :click_on, :click_link_or_button
-
-
##
-
#
-
# Finds a link by id, text or title and clicks it. Also looks at image
-
# alt text inside the link.
-
#
-
# @param [String] locator text, id, title or nested image's alt attribute
-
# @param options See {Capybara::Node::Finders#find_link}
-
#
-
2
def click_link(locator, options={})
-
3
find(:link, locator, options).click
-
end
-
-
##
-
#
-
# Finds a button on the page and clicks it.
-
# This can be any \<input> element of type submit, reset, image, button or it can be a
-
# \<button> element. All buttons can be found by their id, value, or title. \<button> elements can also be found
-
# by their text content, and image \<input> elements by their alt attribute
-
#
-
# @param [String] locator Which button to find
-
# @param options See {Capybara::Node::Finders#find_button}
-
2
def click_button(locator, options={})
-
4
find(:button, locator, options).click
-
end
-
-
##
-
#
-
# Locate a text field or text area and fill it in with the given text
-
# The field can be found via its name, id or label text.
-
#
-
# page.fill_in 'Name', :with => 'Bob'
-
#
-
# @param [String] locator Which field to fill in
-
# @param [Hash] options
-
# @option options [String] :with The value to fill in - required
-
# @option options [Hash] :fill_options Driver specific options regarding how to fill fields
-
#
-
2
def fill_in(locator, options={})
-
raise "Must pass a hash containing 'with'" if not options.is_a?(Hash) or not options.has_key?(:with)
-
with = options.delete(:with)
-
fill_options = options.delete(:fill_options)
-
find(:fillable_field, locator, options).set(with, fill_options)
-
end
-
-
##
-
#
-
# Find a radio button and mark it as checked. The radio button can be found
-
# via name, id or label text.
-
#
-
# page.choose('Male')
-
#
-
# @param [String] locator Which radio button to choose
-
#
-
2
def choose(locator, options={})
-
find(:radio_button, locator, options).set(true)
-
end
-
-
##
-
#
-
# Find a check box and mark it as checked. The check box can be found
-
# via name, id or label text.
-
#
-
# page.check('German')
-
#
-
# @param [String] locator Which check box to check
-
#
-
2
def check(locator, options={})
-
find(:checkbox, locator, options).set(true)
-
end
-
-
##
-
#
-
# Find a check box and mark uncheck it. The check box can be found
-
# via name, id or label text.
-
#
-
# page.uncheck('German')
-
#
-
# @param [String] locator Which check box to uncheck
-
#
-
2
def uncheck(locator, options={})
-
find(:checkbox, locator, options).set(false)
-
end
-
-
##
-
#
-
# If `:from` option is present, `select` finds a select box on the page
-
# and selects a particular option from it.
-
# Otherwise it finds an option inside current scope and selects it.
-
# If the select box is a multiple select, +select+ can be called multiple times to select more than
-
# one option.
-
# The select box can be found via its name, id or label text. The option can be found by its text.
-
#
-
# page.select 'March', :from => 'Month'
-
#
-
# @param [String] value Which option to select
-
# @option options [String] :from The id, name or label of the select box
-
#
-
2
def select(value, options={})
-
if options.has_key?(:from)
-
from = options.delete(:from)
-
find(:select, from, options).find(:option, value, options).select_option
-
else
-
find(:option, value, options).select_option
-
end
-
end
-
-
##
-
#
-
# Find a select box on the page and unselect a particular option from it. If the select
-
# box is a multiple select, +unselect+ can be called multiple times to unselect more than
-
# one option. The select box can be found via its name, id or label text.
-
#
-
# page.unselect 'March', :from => 'Month'
-
#
-
# @param [String] value Which option to unselect
-
# @param [Hash{:from => String}] options The id, name or label of the select box
-
#
-
2
def unselect(value, options={})
-
if options.has_key?(:from)
-
from = options.delete(:from)
-
find(:select, from, options).find(:option, value, options).unselect_option
-
else
-
find(:option, value, options).unselect_option
-
end
-
end
-
-
##
-
#
-
# Find a file field on the page and attach a file given its path. The file field can
-
# be found via its name, id or label text.
-
#
-
# page.attach_file(locator, '/path/to/file.png')
-
#
-
# @param [String] locator Which field to attach the file to
-
# @param [String] path The path of the file that will be attached, or an array of paths
-
#
-
# @option options [Symbol] match (Capybara.match) The matching strategy to use (:one, :first, :prefer_exact, :smart).
-
# @option options [Boolean] exact (Capybara.exact) Match the exact label name/contents or accept a partial match.
-
# @option options [Fixnum] wait (Capybara.default_max_wait_time) If using a Javascript driver, maximum number of seconds during which the element will be searched for.
-
# @option options [Boolean] multiple Match field which allows multiple file selection
-
#
-
2
def attach_file(locator, path, options={})
-
Array(path).each do |p|
-
raise Capybara::FileNotFound, "cannot attach file, #{p} does not exist" unless File.exist?(p.to_s)
-
end
-
find(:file_field, locator, options).set(path)
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
2
module Capybara
-
2
module Node
-
-
##
-
#
-
# A {Capybara::Node::Base} represents either an element on a page through the subclass
-
# {Capybara::Node::Element} or a document through {Capybara::Node::Document}.
-
#
-
# Both types of Node share the same methods, used for interacting with the
-
# elements on the page. These methods are divided into three categories,
-
# finders, actions and matchers. These are found in the modules
-
# {Capybara::Node::Finders}, {Capybara::Node::Actions} and {Capybara::Node::Matchers}
-
# respectively.
-
#
-
# A {Capybara::Session} exposes all methods from {Capybara::Node::Document} directly:
-
#
-
# session = Capybara::Session.new(:rack_test, my_app)
-
# session.visit('/')
-
# session.fill_in('Foo', :with => 'Bar') # from Capybara::Node::Actions
-
# bar = session.find('#bar') # from Capybara::Node::Finders
-
# bar.select('Baz', :from => 'Quox') # from Capybara::Node::Actions
-
# session.has_css?('#foobar') # from Capybara::Node::Matchers
-
#
-
2
class Base
-
2
attr_reader :session, :base, :parent
-
-
2
include Capybara::Node::Finders
-
2
include Capybara::Node::Actions
-
2
include Capybara::Node::Matchers
-
-
2
def initialize(session, base)
-
8
@session = session
-
8
@base = base
-
end
-
-
# overridden in subclasses, e.g. Capybara::Node::Element
-
2
def reload
-
self
-
end
-
-
##
-
#
-
# This method is Capybara's primary defence against asynchronicity
-
# problems. It works by attempting to run a given block of code until it
-
# succeeds. The exact behaviour of this method depends on a number of
-
# factors. Basically there are certain exceptions which, when raised
-
# from the block, instead of bubbling up, are caught, and the block is
-
# re-run.
-
#
-
# Certain drivers, such as RackTest, have no support for asynchronous
-
# processes, these drivers run the block, and any error raised bubbles up
-
# immediately. This allows faster turn around in the case where an
-
# expectation fails.
-
#
-
# Only exceptions that are {Capybara::ElementNotFound} or any subclass
-
# thereof cause the block to be rerun. Drivers may specify additional
-
# exceptions which also cause reruns. This usually occurs when a node is
-
# manipulated which no longer exists on the page. For example, the
-
# Selenium driver specifies
-
# `Selenium::WebDriver::Error::ObsoleteElementError`.
-
#
-
# As long as any of these exceptions are thrown, the block is re-run,
-
# until a certain amount of time passes. The amount of time defaults to
-
# {Capybara.default_max_wait_time} and can be overridden through the `seconds`
-
# argument. This time is compared with the system time to see how much
-
# time has passed. On rubies/platforms which don't support access to a monotonic process clock
-
# if the return value of `Time.now` is stubbed out, Capybara will raise `Capybara::FrozenInTime`.
-
#
-
# @param [Integer] seconds Number of seconds to retry this block
-
# @param options [Hash]
-
# @option options [Array<Exception>] :errors (driver.invalid_element_errors +
-
# [Capybara::ElementNotFound]) exception types that cause the block to be rerun
-
# @return [Object] The result of the given block
-
# @raise [Capybara::FrozenInTime] If the return value of `Time.now` appears stuck
-
#
-
2
def synchronize(seconds=Capybara.default_max_wait_time, options = {})
-
32
start_time = Capybara::Helpers.monotonic_time
-
-
32
if session.synchronized
-
18
yield
-
else
-
14
session.synchronized = true
-
14
begin
-
14
yield
-
rescue => e
-
session.raise_server_error!
-
raise e unless driver.wait?
-
raise e unless catch_error?(e, options[:errors])
-
raise e if (Capybara::Helpers.monotonic_time - start_time) >= seconds
-
sleep(0.05)
-
raise Capybara::FrozenInTime, "time appears to be frozen, Capybara does not work with libraries which freeze time, consider using time travelling instead" if Capybara::Helpers.monotonic_time == start_time
-
reload if Capybara.automatic_reload
-
retry
-
ensure
-
14
session.synchronized = false
-
14
end
-
end
-
end
-
-
# @api private
-
2
def find_css(css)
-
base.find_css(css)
-
end
-
-
# @api private
-
2
def find_xpath(xpath)
-
7
base.find_xpath(xpath)
-
end
-
-
2
protected
-
-
2
def catch_error?(error, errors = nil)
-
errors ||= (driver.invalid_element_errors + [Capybara::ElementNotFound])
-
errors.any? do |type|
-
error.is_a?(type)
-
end
-
end
-
-
2
def driver
-
session.driver
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
2
module Capybara
-
2
module Node
-
-
##
-
#
-
# A {Capybara::Document} represents an HTML document. Any operation
-
# performed on it will be performed on the entire document.
-
#
-
# @see Capybara::Node
-
#
-
2
class Document < Base
-
2
include Capybara::Node::DocumentMatchers
-
-
2
def inspect
-
%(#<Capybara::Document>)
-
end
-
-
##
-
#
-
# @return [String] The text of the document
-
#
-
2
def text(type=nil)
-
find(:xpath, '/html').text(type)
-
end
-
-
2
def title
-
session.driver.title
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
2
module Capybara
-
2
module Node
-
2
module DocumentMatchers
-
##
-
# Asserts that the page has the given title.
-
#
-
# @!macro title_query_params
-
# @overload $0(string, options = {})
-
# @param string [String] The string that title should include
-
# @overload $0(regexp, options = {})
-
# @param regexp [Regexp] The regexp that title should match to
-
# @option options [Numeric] :wait (Capybara.default_max_wait_time) Maximum time that Capybara will wait for title to eq/match given string/regexp argument
-
# @raise [Capybara::ExpectationNotMet] if the assertion hasn't succeeded during wait time
-
# @return [true]
-
#
-
2
def assert_title(title, options = {})
-
query = Capybara::Queries::TitleQuery.new(title, options)
-
synchronize(query.wait) do
-
unless query.resolves_for?(self)
-
raise Capybara::ExpectationNotMet, query.failure_message
-
end
-
end
-
return true
-
end
-
-
##
-
# Asserts that the page doesn't have the given title.
-
#
-
# @macro title_query_params
-
# @raise [Capybara::ExpectationNotMet] if the assertion hasn't succeeded during wait time
-
# @return [true]
-
#
-
2
def assert_no_title(title, options = {})
-
query = Capybara::Queries::TitleQuery.new(title, options)
-
synchronize(query.wait) do
-
if query.resolves_for?(self)
-
raise Capybara::ExpectationNotMet, query.negative_failure_message
-
end
-
end
-
return true
-
end
-
-
##
-
# Checks if the page has the given title.
-
#
-
# @macro title_query_params
-
# @return [Boolean]
-
#
-
2
def has_title?(title, options = {})
-
assert_title(title, options)
-
rescue Capybara::ExpectationNotMet
-
return false
-
end
-
-
##
-
# Checks if the page doesn't have the given title.
-
#
-
# @macro title_query_params
-
# @return [Boolean]
-
#
-
2
def has_no_title?(title, options = {})
-
assert_no_title(title, options)
-
rescue Capybara::ExpectationNotMet
-
return false
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
2
module Capybara
-
2
module Node
-
-
##
-
#
-
# A {Capybara::Node::Element} represents a single element on the page. It is possible
-
# to interact with the contents of this element the same as with a document:
-
#
-
# session = Capybara::Session.new(:rack_test, my_app)
-
#
-
# bar = session.find('#bar') # from Capybara::Node::Finders
-
# bar.select('Baz', :from => 'Quox') # from Capybara::Node::Actions
-
#
-
# {Capybara::Node::Element} also has access to HTML attributes and other properties of the
-
# element:
-
#
-
# bar.value
-
# bar.text
-
# bar[:title]
-
#
-
# @see Capybara::Node
-
#
-
2
class Element < Base
-
-
2
def initialize(session, base, parent, query)
-
7
super(session, base)
-
7
@parent = parent
-
7
@query = query
-
end
-
-
2
def allow_reload!
-
7
@allow_reload = true
-
end
-
-
##
-
#
-
# @return [Object] The native element from the driver, this allows access to driver specific methods
-
#
-
2
def native
-
synchronize { base.native }
-
end
-
-
##
-
#
-
# Retrieve the text of the element. If `Capybara.ignore_hidden_elements`
-
# is `true`, which it is by default, then this will return only text
-
# which is visible. The exact semantics of this may differ between
-
# drivers, but generally any text within elements with `display:none` is
-
# ignored. This behaviour can be overridden by passing `:all` to this
-
# method.
-
#
-
# @param [:all, :visible] type Whether to return only visible or all text
-
# @return [String] The text of the element
-
#
-
2
def text(type=nil)
-
type ||= :all unless Capybara.ignore_hidden_elements or Capybara.visible_text_only
-
synchronize do
-
if type == :all
-
base.all_text
-
else
-
base.visible_text
-
end
-
end
-
end
-
-
##
-
#
-
# Retrieve the given attribute
-
#
-
# element[:title] # => HTML title attribute
-
#
-
# @param [Symbol] attribute The attribute to retrieve
-
# @return [String] The value of the attribute
-
#
-
2
def [](attribute)
-
synchronize { base[attribute] }
-
end
-
-
##
-
#
-
# @return [String] The value of the form element
-
#
-
2
def value
-
synchronize { base.value }
-
end
-
-
##
-
#
-
# Set the value of the form element to the given value.
-
#
-
# @param [String] value The new value
-
# @param [Hash{}] options Driver specific options for how to set the value
-
#
-
2
def set(value, options={})
-
options ||= {}
-
-
driver_supports_options = (base.method(:set).arity != 1)
-
-
unless options.empty? || driver_supports_options
-
warn "Options passed to Capybara::Node#set but the driver doesn't support them"
-
end
-
-
synchronize do
-
if driver_supports_options
-
base.set(value, options)
-
else
-
base.set(value)
-
end
-
end
-
end
-
-
##
-
#
-
# Select this node if is an option element inside a select tag
-
#
-
2
def select_option
-
warn "Attempt to select disabled option: #{value || text}" if disabled?
-
synchronize { base.select_option }
-
end
-
-
##
-
#
-
# Unselect this node if is an option element inside a multiple select tag
-
#
-
2
def unselect_option
-
synchronize { base.unselect_option }
-
end
-
-
##
-
#
-
# Click the Element
-
#
-
2
def click
-
14
synchronize { base.click }
-
end
-
-
##
-
#
-
# Right Click the Element
-
#
-
2
def right_click
-
synchronize { base.right_click }
-
end
-
-
##
-
#
-
# Double Click the Element
-
#
-
2
def double_click
-
synchronize { base.double_click }
-
end
-
-
##
-
#
-
# Send Keystrokes to the Element
-
#
-
# @overload send_keys(keys, ...)
-
# @param [String, Symbol, Array<String,Symbol>] keys
-
#
-
# Examples:
-
#
-
# element.send_keys "foo" #=> value: 'foo'
-
# element.send_keys "tet", :left, "s" #=> value: 'test'
-
# element.send_keys [:control, 'a'], :space #=> value: ' ' - assuming ctrl-a selects all contents
-
#
-
# Symbols supported for keys
-
# :cancel
-
# :help
-
# :backspace
-
# :tab
-
# :clear
-
# :return
-
# :enter
-
# :shift
-
# :control
-
# :alt
-
# :pause
-
# :escape
-
# :space
-
# :page_up
-
# :page_down
-
# :end
-
# :home
-
# :left
-
# :up
-
# :right
-
# :down
-
# :insert
-
# :delete
-
# :semicolon
-
# :equals
-
# :numpad0
-
# :numpad1
-
# :numpad2
-
# :numpad3
-
# :numpad4
-
# :numpad5
-
# :numpad6
-
# :numpad7
-
# :numpad8
-
# :numpad9
-
# :multiply - numeric keypad *
-
# :add - numeric keypad +
-
# :separator - numeric keypad 'separator' key ??
-
# :subtract - numeric keypad -
-
# :decimal - numeric keypad .
-
# :divide - numeric keypad /
-
# :f1
-
# :f2
-
# :f3
-
# :f4
-
# :f5
-
# :f6
-
# :f7
-
# :f8
-
# :f9
-
# :f10
-
# :f11
-
# :f12
-
# :meta
-
# :command - alias of :meta
-
#
-
2
def send_keys(*args)
-
synchronize { base.send_keys(*args) }
-
end
-
-
##
-
#
-
# Hover on the Element
-
#
-
2
def hover
-
synchronize { base.hover }
-
end
-
-
##
-
#
-
# @return [String] The tag name of the element
-
#
-
2
def tag_name
-
synchronize { base.tag_name }
-
end
-
-
##
-
#
-
# Whether or not the element is visible. Not all drivers support CSS, so
-
# the result may be inaccurate.
-
#
-
# @return [Boolean] Whether the element is visible
-
#
-
2
def visible?
-
14
synchronize { base.visible? }
-
end
-
-
##
-
#
-
# Whether or not the element is checked.
-
#
-
# @return [Boolean] Whether the element is checked
-
#
-
2
def checked?
-
synchronize { base.checked? }
-
end
-
-
##
-
#
-
# Whether or not the element is selected.
-
#
-
# @return [Boolean] Whether the element is selected
-
#
-
2
def selected?
-
synchronize { base.selected? }
-
end
-
-
##
-
#
-
# Whether or not the element is disabled.
-
#
-
# @return [Boolean] Whether the element is disabled
-
#
-
2
def disabled?
-
8
synchronize { base.disabled? }
-
end
-
-
##
-
#
-
# An XPath expression describing where on the page the element can be found
-
#
-
# @return [String] An XPath expression
-
#
-
2
def path
-
synchronize { base.path }
-
end
-
-
##
-
#
-
# Trigger any event on the current element, for example mouseover or focus
-
# events. Does not work in Selenium.
-
#
-
# @param [String] event The name of the event to trigger
-
#
-
2
def trigger(event)
-
synchronize { base.trigger(event) }
-
end
-
-
##
-
#
-
# Drag the element to the given other element.
-
#
-
# source = page.find('#foo')
-
# target = page.find('#bar')
-
# source.drag_to(target)
-
#
-
# @param [Capybara::Node::Element] node The element to drag to
-
#
-
2
def drag_to(node)
-
synchronize { base.drag_to(node.base) }
-
end
-
-
2
def reload
-
if @allow_reload
-
begin
-
reloaded = parent.reload.first(@query.name, @query.locator, @query.options)
-
@base = reloaded.base if reloaded
-
rescue => e
-
raise e unless catch_error?(e)
-
end
-
end
-
self
-
end
-
-
2
def inspect
-
%(#<Capybara::Node::Element tag="#{tag_name}" path="#{path}">)
-
rescue NotSupportedByDriverError
-
%(#<Capybara::Node::Element tag="#{tag_name}">)
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
2
module Capybara
-
2
module Node
-
2
module Finders
-
-
##
-
#
-
# Find an {Capybara::Node::Element} based on the given arguments. +find+ will raise an error if the element
-
# is not found.
-
#
-
# @!macro waiting_behavior
-
# If the driver is capable of executing JavaScript, +$0+ will wait for a set amount of time
-
# and continuously retry finding the element until either the element is found or the time
-
# expires. The length of time +find+ will wait is controlled through {Capybara.default_max_wait_time}
-
# and defaults to 2 seconds.
-
# @option options [false, Numeric] wait (Capybara.default_max_wait_time) Maximum time to wait for matching element to appear.
-
#
-
# +find+ takes the same options as +all+.
-
#
-
# page.find('#foo').find('.bar')
-
# page.find(:xpath, '//div[contains(., "bar")]')
-
# page.find('li', :text => 'Quox').click_link('Delete')
-
#
-
# @param (see Capybara::Node::Finders#all)
-
#
-
# @option options [Boolean] match The matching strategy to use.
-
#
-
# @return [Capybara::Node::Element] The found element
-
# @raise [Capybara::ElementNotFound] If the element can't be found before time expires
-
#
-
2
def find(*args)
-
7
query = Capybara::Queries::SelectorQuery.new(*args)
-
synchronize(query.wait) do
-
7
if query.match == :smart or query.match == :prefer_exact
-
7
result = query.resolve_for(self, true)
-
7
result = query.resolve_for(self, false) if result.size == 0 && !query.exact?
-
else
-
result = query.resolve_for(self)
-
end
-
7
if query.match == :one or query.match == :smart and result.size > 1
-
raise Capybara::Ambiguous.new("Ambiguous match, found #{result.size} elements matching #{query.description}")
-
end
-
7
if result.size == 0
-
raise Capybara::ElementNotFound.new("Unable to find #{query.description}")
-
end
-
7
result.first
-
7
end.tap(&:allow_reload!)
-
end
-
-
##
-
#
-
# Find a form field on the page. The field can be found by its name, id or label text.
-
#
-
# @macro waiting_behavior
-
#
-
# @param [String] locator Which field to find
-
#
-
# @option options [Boolean] checked Match checked field?
-
# @option options [Boolean] unchecked Match unchecked field?
-
# @option options [Boolean, Symbol] disabled (false) Match disabled field?
-
# * true - only finds a disabled field
-
# * false - only finds an enabled field
-
# * :all - finds either an enabled or disabled field
-
# @option options [Boolean] readonly Match readonly field?
-
# @option options [String] with Value of field to match on
-
# @option options [String] type Type of field to match on
-
# @return [Capybara::Node::Element] The found element
-
#
-
2
def find_field(locator, options={})
-
find(:field, locator, options)
-
end
-
2
alias_method :field_labeled, :find_field
-
-
##
-
#
-
# Find a link on the page. The link can be found by its id or text.
-
#
-
# @macro waiting_behavior
-
#
-
# @param [String] locator Which link to find
-
# @option options [String,Regexp] href Value to match against the links href
-
# @return [Capybara::Node::Element] The found element
-
#
-
2
def find_link(locator, options={})
-
find(:link, locator, options)
-
end
-
-
##
-
#
-
# Find a button on the page.
-
# This can be any \<input> element of type submit, reset, image, button or it can be a
-
# \<button> element. All buttons can be found by their id, value, or title. \<button> elements can also be found
-
# by their text content, and image \<input> elements by their alt attribute
-
-
# @macro waiting_behavior
-
#
-
# @param [String] locator Which button to find
-
# @option options [Boolean, Symbol] disabled (false) Match disabled button?
-
# * true - only finds a disabled button
-
# * false - only finds an enabled button
-
# * :all - finds either an enabled or disabled button
-
# @return [Capybara::Node::Element] The found element
-
#
-
2
def find_button(locator, options={})
-
find(:button, locator, options)
-
end
-
-
##
-
#
-
# Find a element on the page, given its id.
-
#
-
# @macro waiting_behavior
-
#
-
# @param [String] id Which element to find
-
#
-
# @return [Capybara::Node::Element] The found element
-
#
-
2
def find_by_id(id, options={})
-
find(:id, id, options)
-
end
-
-
##
-
#
-
# Find all elements on the page matching the given selector
-
# and options.
-
#
-
# Both XPath and CSS expressions are supported, but Capybara
-
# does not try to automatically distinguish between them. The
-
# following statements are equivalent:
-
#
-
# page.all(:css, 'a#person_123')
-
# page.all(:xpath, '//a[@id="person_123"]')
-
#
-
#
-
# If the type of selector is left out, Capybara uses
-
# {Capybara.default_selector}. It's set to :css by default.
-
#
-
# page.all("a#person_123")
-
#
-
# Capybara.default_selector = :xpath
-
# page.all('//a[@id="person_123"]')
-
#
-
# The set of found elements can further be restricted by specifying
-
# options. It's possible to select elements by their text or visibility:
-
#
-
# page.all('a', :text => 'Home')
-
# page.all('#menu li', :visible => true)
-
#
-
# By default if no elements are found, an empty array is returned;
-
# however, expectations can be set on the number of elements to be found which
-
# will trigger Capybara's waiting behavior for the expectations to match.The
-
# expectations can be set using
-
#
-
# page.assert_selector('p#foo', :count => 4)
-
# page.assert_selector('p#foo', :maximum => 10)
-
# page.assert_selector('p#foo', :minimum => 1)
-
# page.assert_selector('p#foo', :between => 1..10)
-
#
-
# See {Capybara::Helpers#matches_count?} for additional information about
-
# count matching.
-
#
-
# @overload all([kind], locator, options)
-
# @param [:css, :xpath] kind The type of selector
-
# @param [String] locator The selector
-
# @option options [String, Regexp] text Only find elements which contain this text or match this regexp
-
# @option options [Boolean, Symbol] visible Only find elements with the specified visibility:
-
# * true - only finds visible elements.
-
# * false - finds invisible _and_ visible elements.
-
# * :all - same as false; finds visible and invisible elements.
-
# * :hidden - only finds invisible elements.
-
# * :visible - same as true; only finds visible elements.
-
# @option options [Integer] count Exact number of matches that are expected to be found
-
# @option options [Integer] maximum Maximum number of matches that are expected to be found
-
# @option options [Integer] minimum Minimum number of matches that are expected to be found
-
# @option options [Range] between Number of matches found must be within the given range
-
# @option options [Boolean] exact Control whether `is` expressions in the given XPath match exactly or partially
-
# @option options [Integer] wait (Capybara.default_max_wait_time) The time to wait for element count expectations to become true
-
# @return [Capybara::Result] A collection of found elements
-
#
-
2
def all(*args)
-
query = Capybara::Queries::SelectorQuery.new(*args)
-
synchronize(query.wait) do
-
result = query.resolve_for(self)
-
raise Capybara::ExpectationNotMet, result.failure_message unless result.matches_count?
-
result
-
end
-
end
-
2
alias_method :find_all, :all
-
-
##
-
#
-
# Find the first element on the page matching the given selector
-
# and options, or nil if no element matches. By default no waiting
-
# behavior occurs, however if {Capybara.wait_on_first_by_default} is set to true
-
# it will trigger Capybara's waiting behavior for a minimum of 1 matching element to be found and
-
# return the first. Waiting behavior can also be triggered by passing in any of the count
-
# expectation options.
-
#
-
# @overload first([kind], locator, options)
-
# @param [:css, :xpath] kind The type of selector
-
# @param [String] locator The selector
-
# @param [Hash] options Additional options; see {#all}
-
# @return [Capybara::Node::Element] The found element or nil
-
#
-
2
def first(*args)
-
if Capybara.wait_on_first_by_default
-
options = if args.last.is_a?(Hash) then args.pop.dup else {} end
-
args.push({minimum: 1}.merge(options))
-
end
-
all(*args).first
-
rescue Capybara::ExpectationNotMet
-
nil
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
2
module Capybara
-
2
module Node
-
2
module Matchers
-
-
##
-
#
-
# Checks if a given selector is on the page or current node.
-
#
-
# page.has_selector?('p#foo')
-
# page.has_selector?(:xpath, './/p[@id="foo"]')
-
# page.has_selector?(:foo)
-
#
-
# By default it will check if the expression occurs at least once,
-
# but a different number can be specified.
-
#
-
# page.has_selector?('p.foo', :count => 4)
-
#
-
# This will check if the expression occurs exactly 4 times.
-
#
-
# It also accepts all options that {Capybara::Node::Finders#all} accepts,
-
# such as :text and :visible.
-
#
-
# page.has_selector?('li', :text => 'Horse', :visible => true)
-
#
-
# has_selector? can also accept XPath expressions generated by the
-
# XPath gem:
-
#
-
# page.has_selector?(:xpath, XPath.descendant(:p))
-
#
-
# @param (see Capybara::Node::Finders#all)
-
# @param args
-
# @option args [Integer] :count (nil) Number of times the text should occur
-
# @option args [Integer] :minimum (nil) Minimum number of times the text should occur
-
# @option args [Integer] :maximum (nil) Maximum number of times the text should occur
-
# @option args [Range] :between (nil) Range of times that should contain number of times text occurs
-
# @return [Boolean] If the expression exists
-
#
-
2
def has_selector?(*args)
-
assert_selector(*args)
-
rescue Capybara::ExpectationNotMet
-
return false
-
end
-
-
##
-
#
-
# Checks if a given selector is not on the page or current node.
-
# Usage is identical to Capybara::Node::Matchers#has_selector?
-
#
-
# @param (see Capybara::Node::Finders#has_selector?)
-
# @return [Boolean]
-
#
-
2
def has_no_selector?(*args)
-
assert_no_selector(*args)
-
rescue Capybara::ExpectationNotMet
-
return false
-
end
-
-
##
-
#
-
# Checks if the current node matches given selector
-
# Usage is identical to Capybara::Node::Matchers#has_selector?
-
#
-
# @param (see Capybara::Node::Finders#has_selector?)
-
# @return [Boolean]
-
#
-
2
def matches_selector?(*args)
-
assert_matches_selector(*args)
-
rescue Capybara::ExpectationNotMet
-
return false
-
end
-
-
-
##
-
#
-
# Checks if the current node does not match given selector
-
# Usage is identical to Capybara::Node::Matchers#has_selector?
-
#
-
# @param (see Capybara::Node::Finders#has_selector?)
-
# @return [Boolean]
-
#
-
2
def not_matches_selector?(*args)
-
assert_not_matches_selector(*args)
-
rescue Capybara::ExpectationNotMet
-
return false
-
end
-
-
-
##
-
#
-
# Asserts that a given selector is on the page or current node.
-
#
-
# page.assert_selector('p#foo')
-
# page.assert_selector(:xpath, './/p[@id="foo"]')
-
# page.assert_selector(:foo)
-
#
-
# By default it will check if the expression occurs at least once,
-
# but a different number can be specified.
-
#
-
# page.assert_selector('p#foo', :count => 4)
-
#
-
# This will check if the expression occurs exactly 4 times. See
-
# {Capybara::Node::Finders#all} for other available result size options.
-
#
-
# If a :count of 0 is specified, it will behave like {#assert_no_selector};
-
# however, use of that method is preferred over this one.
-
#
-
# It also accepts all options that {Capybara::Node::Finders#all} accepts,
-
# such as :text and :visible.
-
#
-
# page.assert_selector('li', :text => 'Horse', :visible => true)
-
#
-
# `assert_selector` can also accept XPath expressions generated by the
-
# XPath gem:
-
#
-
# page.assert_selector(:xpath, XPath.descendant(:p))
-
#
-
# @param (see Capybara::Node::Finders#all)
-
# @option options [Integer] :count (nil) Number of times the expression should occur
-
# @raise [Capybara::ExpectationNotMet] If the selector does not exist
-
#
-
2
def assert_selector(*args)
-
query = Capybara::Queries::SelectorQuery.new(*args)
-
synchronize(query.wait) do
-
result = query.resolve_for(self)
-
matches_count = Capybara::Helpers.matches_count?(result.size, query.options)
-
unless matches_count && ((result.size > 0) || Capybara::Helpers.expects_none?(query.options))
-
raise Capybara::ExpectationNotMet, result.failure_message
-
end
-
end
-
return true
-
end
-
-
##
-
#
-
# Asserts that a given selector is not on the page or current node.
-
# Usage is identical to Capybara::Node::Matchers#assert_selector
-
#
-
# Query options such as :count, :minimum, :maximum, and :between are
-
# considered to be an integral part of the selector. This will return
-
# true, for example, if a page contains 4 anchors but the query expects 5:
-
#
-
# page.assert_no_selector('a', :minimum => 1) # Found, raises Capybara::ExpectationNotMet
-
# page.assert_no_selector('a', :count => 4) # Found, raises Capybara::ExpectationNotMet
-
# page.assert_no_selector('a', :count => 5) # Not Found, returns true
-
#
-
# @param (see Capybara::Node::Finders#assert_selector)
-
# @raise [Capybara::ExpectationNotMet] If the selector exists
-
#
-
2
def assert_no_selector(*args)
-
query = Capybara::Queries::SelectorQuery.new(*args)
-
synchronize(query.wait) do
-
result = query.resolve_for(self)
-
matches_count = Capybara::Helpers.matches_count?(result.size, query.options)
-
if matches_count && ((result.size > 0) || Capybara::Helpers.expects_none?(query.options))
-
raise Capybara::ExpectationNotMet, result.negative_failure_message
-
end
-
end
-
return true
-
end
-
2
alias_method :refute_selector, :assert_no_selector
-
-
##
-
#
-
# Asserts that the current_node matches a given selector
-
#
-
# node.assert_matches_selector('p#foo')
-
# node.assert_matches_selector(:xpath, '//p[@id="foo"]')
-
# node.assert_matches_selector(:foo)
-
#
-
# It also accepts all options that {Capybara::Node::Finders#all} accepts,
-
# such as :text and :visible.
-
#
-
# node.assert_matches_selector('li', :text => 'Horse', :visible => true)
-
#
-
# @param (see Capybara::Node::Finders#all)
-
# @raise [Capybara::ExpectationNotMet] If the selector does not match
-
#
-
2
def assert_matches_selector(*args)
-
query = Capybara::Queries::MatchQuery.new(*args)
-
synchronize(query.wait) do
-
result = query.resolve_for(self.parent)
-
unless result.include? self
-
raise Capybara::ExpectationNotMet, "Item does not match the provided selector"
-
end
-
end
-
return true
-
end
-
-
2
def assert_not_matches_selector(*args)
-
query = Capybara::Queries::MatchQuery.new(*args)
-
synchronize(query.wait) do
-
result = query.resolve_for(self.parent)
-
if result.include? self
-
raise Capybara::ExpectationNotMet, 'Item matched the provided selector'
-
end
-
end
-
return true
-
end
-
2
alias_method :refute_matches_selector, :assert_not_matches_selector
-
-
##
-
#
-
# Checks if a given XPath expression is on the page or current node.
-
#
-
# page.has_xpath?('.//p[@id="foo"]')
-
#
-
# By default it will check if the expression occurs at least once,
-
# but a different number can be specified.
-
#
-
# page.has_xpath?('.//p[@id="foo"]', :count => 4)
-
#
-
# This will check if the expression occurs exactly 4 times.
-
#
-
# It also accepts all options that {Capybara::Node::Finders#all} accepts,
-
# such as :text and :visible.
-
#
-
# page.has_xpath?('.//li', :text => 'Horse', :visible => true)
-
#
-
# has_xpath? can also accept XPath expressions generate by the
-
# XPath gem:
-
#
-
# xpath = XPath.generate { |x| x.descendant(:p) }
-
# page.has_xpath?(xpath)
-
#
-
# @param [String] path An XPath expression
-
# @param options (see Capybara::Node::Finders#all)
-
# @option options [Integer] :count (nil) Number of times the expression should occur
-
# @return [Boolean] If the expression exists
-
#
-
2
def has_xpath?(path, options={})
-
has_selector?(:xpath, path, options)
-
end
-
-
##
-
#
-
# Checks if a given XPath expression is not on the page or current node.
-
# Usage is identical to Capybara::Node::Matchers#has_xpath?
-
#
-
# @param (see Capybara::Node::Finders#has_xpath?)
-
# @return [Boolean]
-
#
-
2
def has_no_xpath?(path, options={})
-
has_no_selector?(:xpath, path, options)
-
end
-
-
##
-
#
-
# Checks if a given CSS selector is on the page or current node.
-
#
-
# page.has_css?('p#foo')
-
#
-
# By default it will check if the selector occurs at least once,
-
# but a different number can be specified.
-
#
-
# page.has_css?('p#foo', :count => 4)
-
#
-
# This will check if the selector occurs exactly 4 times.
-
#
-
# It also accepts all options that {Capybara::Node::Finders#all} accepts,
-
# such as :text and :visible.
-
#
-
# page.has_css?('li', :text => 'Horse', :visible => true)
-
#
-
# @param [String] path A CSS selector
-
# @param options (see Capybara::Node::Finders#all)
-
# @option options [Integer] :count (nil) Number of times the selector should occur
-
# @return [Boolean] If the selector exists
-
#
-
2
def has_css?(path, options={})
-
has_selector?(:css, path, options)
-
end
-
-
##
-
#
-
# Checks if a given CSS selector is not on the page or current node.
-
# Usage is identical to Capybara::Node::Matchers#has_css?
-
#
-
# @param (see Capybara::Node::Finders#has_css?)
-
# @return [Boolean]
-
#
-
2
def has_no_css?(path, options={})
-
has_no_selector?(:css, path, options)
-
end
-
-
##
-
#
-
# Checks if the page or current node has a link with the given
-
# text or id.
-
#
-
# @param [String] locator The text or id of a link to check for
-
# @param options
-
# @option options [String, Regexp] :href The value the href attribute must be
-
# @return [Boolean] Whether it exists
-
#
-
2
def has_link?(locator, options={})
-
has_selector?(:link, locator, options)
-
end
-
-
##
-
#
-
# Checks if the page or current node has no link with the given
-
# text or id.
-
#
-
# @param (see Capybara::Node::Finders#has_link?)
-
# @return [Boolean] Whether it doesn't exist
-
#
-
2
def has_no_link?(locator, options={})
-
has_no_selector?(:link, locator, options)
-
end
-
-
##
-
#
-
# Checks if the page or current node has a button with the given
-
# text, value or id.
-
#
-
# @param [String] locator The text, value or id of a button to check for
-
# @return [Boolean] Whether it exists
-
#
-
2
def has_button?(locator, options={})
-
has_selector?(:button, locator, options)
-
end
-
-
##
-
#
-
# Checks if the page or current node has no button with the given
-
# text, value or id.
-
#
-
# @param [String] locator The text, value or id of a button to check for
-
# @return [Boolean] Whether it doesn't exist
-
#
-
2
def has_no_button?(locator, options={})
-
has_no_selector?(:button, locator, options)
-
end
-
-
##
-
#
-
# Checks if the page or current node has a form field with the given
-
# label, name or id.
-
#
-
# For text fields and other textual fields, such as textareas and
-
# HTML5 email/url/etc. fields, it's possible to specify a :with
-
# option to specify the text the field should contain:
-
#
-
# page.has_field?('Name', :with => 'Jonas')
-
#
-
# It is also possible to filter by the field type attribute:
-
#
-
# page.has_field?('Email', :type => 'email')
-
#
-
# Note: 'textarea' and 'select' are valid type values, matching the associated tag names.
-
#
-
# @param [String] locator The label, name or id of a field to check for
-
# @option options [String] :with The text content of the field
-
# @option options [String] :type The type attribute of the field
-
# @return [Boolean] Whether it exists
-
#
-
2
def has_field?(locator, options={})
-
has_selector?(:field, locator, options)
-
end
-
-
##
-
#
-
# Checks if the page or current node has no form field with the given
-
# label, name or id. See {Capybara::Node::Matchers#has_field?}.
-
#
-
# @param [String] locator The label, name or id of a field to check for
-
# @option options [String] :with The text content of the field
-
# @option options [String] :type The type attribute of the field
-
# @return [Boolean] Whether it doesn't exist
-
#
-
2
def has_no_field?(locator, options={})
-
has_no_selector?(:field, locator, options)
-
end
-
-
##
-
#
-
# Checks if the page or current node has a radio button or
-
# checkbox with the given label, value or id, that is currently
-
# checked.
-
#
-
# @param [String] locator The label, name or id of a checked field
-
# @return [Boolean] Whether it exists
-
#
-
2
def has_checked_field?(locator, options={})
-
has_selector?(:field, locator, options.merge(:checked => true))
-
end
-
-
##
-
#
-
# Checks if the page or current node has no radio button or
-
# checkbox with the given label, value or id, that is currently
-
# checked.
-
#
-
# @param [String] locator The label, name or id of a checked field
-
# @return [Boolean] Whether it doesn't exist
-
#
-
2
def has_no_checked_field?(locator, options={})
-
has_no_selector?(:field, locator, options.merge(:checked => true))
-
end
-
-
##
-
#
-
# Checks if the page or current node has a radio button or
-
# checkbox with the given label, value or id, that is currently
-
# unchecked.
-
#
-
# @param [String] locator The label, name or id of an unchecked field
-
# @return [Boolean] Whether it exists
-
#
-
2
def has_unchecked_field?(locator, options={})
-
has_selector?(:field, locator, options.merge(:unchecked => true))
-
end
-
-
##
-
#
-
# Checks if the page or current node has no radio button or
-
# checkbox with the given label, value or id, that is currently
-
# unchecked.
-
#
-
# @param [String] locator The label, name or id of an unchecked field
-
# @return [Boolean] Whether it doesn't exist
-
#
-
2
def has_no_unchecked_field?(locator, options={})
-
has_no_selector?(:field, locator, options.merge(:unchecked => true))
-
end
-
-
##
-
#
-
# Checks if the page or current node has a select field with the
-
# given label, name or id.
-
#
-
# It can be specified which option should currently be selected:
-
#
-
# page.has_select?('Language', :selected => 'German')
-
#
-
# For multiple select boxes, several options may be specified:
-
#
-
# page.has_select?('Language', :selected => ['English', 'German'])
-
#
-
# It's also possible to check if the exact set of options exists for
-
# this select box:
-
#
-
# page.has_select?('Language', :options => ['English', 'German', 'Spanish'])
-
#
-
# You can also check for a partial set of options:
-
#
-
# page.has_select?('Language', :with_options => ['English', 'German'])
-
#
-
# @param [String] locator The label, name or id of a select box
-
# @option options [Array] :options Options which should be contained in this select box
-
# @option options [Array] :with_options Partial set of options which should be contained in this select box
-
# @option options [String, Array] :selected Options which should be selected
-
# @return [Boolean] Whether it exists
-
#
-
2
def has_select?(locator, options={})
-
has_selector?(:select, locator, options)
-
end
-
-
##
-
#
-
# Checks if the page or current node has no select field with the
-
# given label, name or id. See {Capybara::Node::Matchers#has_select?}.
-
#
-
# @param (see Capybara::Node::Matchers#has_select?)
-
# @return [Boolean] Whether it doesn't exist
-
#
-
2
def has_no_select?(locator, options={})
-
has_no_selector?(:select, locator, options)
-
end
-
-
##
-
#
-
# Checks if the page or current node has a table with the given id
-
# or caption:
-
#
-
# page.has_table?('People')
-
#
-
# @param [String] locator The id or caption of a table
-
# @return [Boolean] Whether it exist
-
#
-
2
def has_table?(locator, options={})
-
has_selector?(:table, locator, options)
-
end
-
-
##
-
#
-
# Checks if the page or current node has no table with the given id
-
# or caption. See {Capybara::Node::Matchers#has_table?}.
-
#
-
# @param (see Capybara::Node::Matchers#has_table?)
-
# @return [Boolean] Whether it doesn't exist
-
#
-
2
def has_no_table?(locator, options={})
-
has_no_selector?(:table, locator, options)
-
end
-
-
##
-
# Asserts that the page or current node has the given text content,
-
# ignoring any HTML tags.
-
#
-
# @!macro text_query_params
-
# @overload $0(type, text, options = {})
-
# @param [:all, :visible] type Whether to check for only visible or all text
-
# @param [String, Regexp] text The string/regexp to check for. If it's a string, text is expected to include it. If it's a regexp, text is expected to match it.
-
# @option options [Integer] :count (nil) Number of times the text is expected to occur
-
# @option options [Integer] :minimum (nil) Minimum number of times the text is expected to occur
-
# @option options [Integer] :maximum (nil) Maximum number of times the text is expected to occur
-
# @option options [Range] :between (nil) Range of times that is expected to contain number of times text occurs
-
# @option options [Numeric] :wait (Capybara.default_max_wait_time) Maximum time that Capybara will wait for text to eq/match given string/regexp argument
-
# @overload $0(text, options = {})
-
# @param [String, Regexp] text The string/regexp to check for. If it's a string, text is expected to include it. If it's a regexp, text is expected to match it.
-
# @option options [Integer] :count (nil) Number of times the text is expected to occur
-
# @option options [Integer] :minimum (nil) Minimum number of times the text is expected to occur
-
# @option options [Integer] :maximum (nil) Maximum number of times the text is expected to occur
-
# @option options [Range] :between (nil) Range of times that is expected to contain number of times text occurs
-
# @option options [Numeric] :wait (Capybara.default_max_wait_time) Maximum time that Capybara will wait for text to eq/match given string/regexp argument
-
# @raise [Capybara::ExpectationNotMet] if the assertion hasn't succeeded during wait time
-
# @return [true]
-
#
-
2
def assert_text(*args)
-
query = Capybara::Queries::TextQuery.new(*args)
-
synchronize(query.wait) do
-
count = query.resolve_for(self)
-
matches_count = Capybara::Helpers.matches_count?(count, query.options)
-
unless matches_count && ((count > 0) || Capybara::Helpers.expects_none?(query.options))
-
raise Capybara::ExpectationNotMet, query.failure_message
-
end
-
end
-
return true
-
end
-
-
##
-
# Asserts that the page or current node doesn't have the given text content,
-
# ignoring any HTML tags.
-
#
-
# @macro text_query_params
-
# @raise [Capybara::ExpectationNotMet] if the assertion hasn't succeeded during wait time
-
# @return [true]
-
#
-
2
def assert_no_text(*args)
-
query = Capybara::Queries::TextQuery.new(*args)
-
synchronize(query.wait) do
-
count = query.resolve_for(self)
-
matches_count = Capybara::Helpers.matches_count?(count, query.options)
-
if matches_count && ((count > 0) || Capybara::Helpers.expects_none?(query.options))
-
raise Capybara::ExpectationNotMet, query.negative_failure_message
-
end
-
end
-
return true
-
end
-
-
##
-
# Checks if the page or current node has the given text content,
-
# ignoring any HTML tags.
-
#
-
# Whitespaces are normalized in both node's text and passed text parameter.
-
# Note that whitespace isn't normalized in passed regexp as normalizing whitespace
-
# in regexp isn't easy and doesn't seem to be worth it.
-
#
-
# By default it will check if the text occurs at least once,
-
# but a different number can be specified.
-
#
-
# page.has_text?('lorem ipsum', between: 2..4)
-
#
-
# This will check if the text occurs from 2 to 4 times.
-
#
-
# @macro text_query_params
-
# @return [Boolean] Whether it exists
-
#
-
2
def has_text?(*args)
-
assert_text(*args)
-
rescue Capybara::ExpectationNotMet
-
return false
-
end
-
2
alias_method :has_content?, :has_text?
-
-
##
-
# Checks if the page or current node does not have the given text
-
# content, ignoring any HTML tags and normalizing whitespace.
-
#
-
# @macro text_query_params
-
# @return [Boolean] Whether it doesn't exist
-
#
-
2
def has_no_text?(*args)
-
assert_no_text(*args)
-
rescue Capybara::ExpectationNotMet
-
return false
-
end
-
2
alias_method :has_no_content?, :has_no_text?
-
-
2
def ==(other)
-
self.eql?(other) || (other.respond_to?(:base) && base == other.base)
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
2
module Capybara
-
# @api private
-
2
module Queries
-
2
class BaseQuery
-
2
COUNT_KEYS = [:count, :minimum, :maximum, :between]
-
-
2
attr_reader :options
-
-
2
def wait
-
7
if @options.has_key?(:wait)
-
@options[:wait] || 0
-
else
-
7
Capybara.default_max_wait_time
-
end
-
end
-
-
2
private
-
-
2
def assert_valid_keys
-
7
invalid_keys = @options.keys - valid_keys
-
7
unless invalid_keys.empty?
-
invalid_names = invalid_keys.map(&:inspect).join(", ")
-
valid_names = valid_keys.map(&:inspect).join(", ")
-
raise ArgumentError, "invalid keys #{invalid_names}, should be one of #{valid_names}"
-
end
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
2
require 'addressable/uri'
-
-
2
module Capybara
-
# @api private
-
2
module Queries
-
2
class CurrentPathQuery < BaseQuery
-
2
def initialize(expected_path, options = {})
-
@expected_path = expected_path
-
@options = {
-
url: false,
-
only_path: false }.merge(options)
-
assert_valid_keys
-
end
-
-
2
def resolves_for?(session)
-
@actual_path = if options[:url]
-
session.current_url
-
else
-
if options[:only_path]
-
::Addressable::URI.parse(session.current_url).path
-
else
-
::Addressable::URI.parse(session.current_url).request_uri
-
end
-
end
-
-
if @expected_path.is_a? Regexp
-
@actual_path.match(@expected_path)
-
else
-
::Addressable::URI.parse(@expected_path) == Addressable::URI.parse(@actual_path)
-
end
-
end
-
-
2
def failure_message
-
failure_message_helper
-
end
-
-
2
def negative_failure_message
-
failure_message_helper(' not')
-
end
-
-
2
private
-
-
2
def failure_message_helper(negated = '')
-
verb = (@expected_path.is_a?(Regexp))? 'match' : 'equal'
-
"expected #{@actual_path.inspect}#{negated} to #{verb} #{@expected_path.inspect}"
-
end
-
-
2
def valid_keys
-
[:wait, :url, :only_path]
-
end
-
-
2
def assert_valid_keys
-
super
-
if options[:url] && options[:only_path]
-
raise ArgumentError, "the :url and :only_path options cannot both be true"
-
end
-
end
-
end
-
end
-
end
-
2
module Capybara
-
2
module Queries
-
2
class MatchQuery < Capybara::Queries::SelectorQuery
-
2
VALID_KEYS = [:text, :visible, :exact, :wait]
-
-
2
def visible
-
if options.has_key?(:visible)
-
super
-
else
-
:all
-
end
-
end
-
-
2
private
-
-
2
def valid_keys
-
VALID_KEYS + @selector.custom_filters.keys
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
2
module Capybara
-
2
module Queries
-
2
class SelectorQuery < Queries::BaseQuery
-
2
attr_accessor :selector, :locator, :options, :expression, :find, :negative
-
-
2
VALID_KEYS = [:text, :visible, :between, :count, :maximum, :minimum, :exact, :match, :wait]
-
2
VALID_MATCH = [:first, :smart, :prefer_exact, :one]
-
-
2
def initialize(*args)
-
7
@options = if args.last.is_a?(Hash) then args.pop.dup else {} end
-
-
7
if args[0].is_a?(Symbol)
-
7
@selector = Selector.all[args.shift]
-
7
@locator = args.shift
-
else
-
@selector = Selector.all.values.find { |s| s.match?(args[0]) }
-
@locator = args.shift
-
end
-
7
@selector ||= Selector.all[Capybara.default_selector]
-
-
7
warn "Unused parameters passed to #{self.class.name} : #{args.to_s}" unless args.empty?
-
-
# for compatibility with Capybara 2.0
-
7
if Capybara.exact_options and @selector == Selector.all[:option]
-
@options[:exact] = true
-
end
-
-
7
@expression = @selector.call(@locator)
-
7
assert_valid_keys
-
end
-
-
2
def name; selector.name; end
-
2
def label; selector.label or selector.name; end
-
-
2
def description
-
@description = String.new("#{label} #{locator.inspect}")
-
@description << " with text #{options[:text].inspect}" if options[:text]
-
@description << selector.description(options)
-
@description
-
end
-
-
2
def matches_filters?(node)
-
7
if options[:text]
-
regexp = options[:text].is_a?(Regexp) ? options[:text] : Regexp.escape(options[:text].to_s)
-
return false if not node.text(visible).match(regexp)
-
end
-
7
case visible
-
7
when :visible then return false unless node.visible?
-
when :hidden then return false if node.visible?
-
end
-
7
selector.custom_filters.each do |name, filter|
-
7
if options.has_key?(name)
-
return false unless filter.matches?(node, options[name])
-
elsif filter.default?
-
4
return false unless filter.matches?(node, filter.default)
-
end
-
end
-
end
-
-
2
def visible
-
7
if options.has_key?(:visible)
-
case @options[:visible]
-
when true then :visible
-
when false then :all
-
else @options[:visible]
-
end
-
else
-
7
if Capybara.ignore_hidden_elements
-
7
:visible
-
else
-
:all
-
end
-
end
-
end
-
-
2
def exact?
-
if options.has_key?(:exact)
-
@options[:exact]
-
else
-
Capybara.exact
-
end
-
end
-
-
2
def match
-
28
if options.has_key?(:match)
-
@options[:match]
-
else
-
28
Capybara.match
-
end
-
end
-
-
2
def xpath(exact=nil)
-
7
exact = self.exact? if exact == nil
-
7
if @expression.respond_to?(:to_xpath) and exact
-
7
@expression.to_xpath(:exact)
-
else
-
@expression.to_s
-
end
-
end
-
-
2
def css
-
@expression
-
end
-
-
# @api private
-
2
def resolve_for(node, exact = nil)
-
7
node.synchronize do
-
7
children = if selector.format == :css
-
node.find_css(self.css)
-
else
-
7
node.find_xpath(self.xpath(exact))
-
end.map do |child|
-
7
if node.is_a?(Capybara::Node::Base)
-
7
Capybara::Node::Element.new(node.session, child, node, self)
-
else
-
Capybara::Node::Simple.new(child)
-
end
-
end
-
7
Capybara::Result.new(children, self)
-
end
-
end
-
-
2
private
-
-
2
def valid_keys
-
7
COUNT_KEYS + [:text, :visible, :exact, :match, :wait] + @selector.custom_filters.keys
-
end
-
-
2
def assert_valid_keys
-
7
super
-
7
unless VALID_MATCH.include?(match)
-
raise ArgumentError, "invalid option #{match.inspect} for :match, should be one of #{VALID_MATCH.map(&:inspect).join(", ")}"
-
end
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
2
module Capybara
-
# @api private
-
2
module Queries
-
2
class TextQuery < BaseQuery
-
2
def initialize(*args)
-
@type = (args.first.is_a?(Symbol) || args.first.nil?) ? args.shift : nil
-
@expected_text, @options = args
-
unless @expected_text.is_a?(Regexp)
-
@expected_text = Capybara::Helpers.normalize_whitespace(@expected_text)
-
end
-
@search_regexp = Capybara::Helpers.to_regexp(@expected_text)
-
@options ||= {}
-
assert_valid_keys
-
end
-
-
2
def resolve_for(node)
-
@actual_text = Capybara::Helpers.normalize_whitespace(node.text(@type))
-
@count = @actual_text.scan(@search_regexp).size
-
end
-
-
2
def failure_message
-
description =
-
if @expected_text.is_a?(Regexp)
-
"text matching #{@expected_text.inspect}"
-
else
-
"text #{@expected_text.inspect}"
-
end
-
-
message = Capybara::Helpers.failure_message(description, @options)
-
unless (COUNT_KEYS & @options.keys).empty?
-
message << " but found #{@count} #{Capybara::Helpers.declension('time', 'times', @count)}"
-
end
-
message << " in #{@actual_text.inspect}"
-
end
-
-
2
def negative_failure_message
-
failure_message.sub(/(to find)/, 'not \1')
-
end
-
-
2
private
-
-
2
def valid_keys
-
COUNT_KEYS + [:wait]
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
2
module Capybara
-
# @api private
-
2
module Queries
-
2
class TitleQuery < BaseQuery
-
2
def initialize(expected_title, options = {})
-
@expected_title = expected_title
-
@options = options
-
unless @expected_title.is_a?(Regexp)
-
@expected_title = Capybara::Helpers.normalize_whitespace(@expected_title)
-
end
-
@search_regexp = Capybara::Helpers.to_regexp(@expected_title)
-
assert_valid_keys
-
end
-
-
2
def resolves_for?(node)
-
@actual_title = node.title
-
@actual_title.match(@search_regexp)
-
end
-
-
2
def failure_message
-
failure_message_helper
-
end
-
-
2
def negative_failure_message
-
failure_message_helper(' not')
-
end
-
-
2
private
-
-
2
def failure_message_helper(negated = '')
-
verb = (@expected_title.is_a?(Regexp))? 'match' : 'include'
-
"expected #{@actual_title.inspect}#{negated} to #{verb} #{@expected_title.inspect}"
-
end
-
-
2
def valid_keys
-
[:wait]
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
2
require 'capybara/queries/selector_query'
-
2
module Capybara
-
# @deprecated This class and its methods are not supposed to be used by users of Capybara's public API.
-
# It may be removed in future versions of Capybara.
-
2
Query = Queries::SelectorQuery
-
end
-
# frozen_string_literal: true
-
2
class Capybara::RackTest::Browser
-
2
include ::Rack::Test::Methods
-
-
2
attr_reader :driver
-
2
attr_accessor :current_host
-
-
2
def initialize(driver)
-
6
@driver = driver
-
end
-
-
2
def app
-
6
driver.app
-
end
-
-
2
def options
-
16
driver.options
-
end
-
-
2
def visit(path, attributes = {})
-
6
reset_host!
-
6
process_and_follow_redirects(:get, path, attributes)
-
end
-
-
2
def submit(method, path, attributes)
-
4
path = request_path if not path or path.empty?
-
4
process_and_follow_redirects(method, path, attributes, {'HTTP_REFERER' => current_url})
-
end
-
-
2
def follow(method, path, attributes = {})
-
3
return if path.gsub(/^#{Regexp.escape(request_path)}/, '').start_with?('#') || path.downcase.start_with?('javascript:')
-
3
process_and_follow_redirects(method, path, attributes, {'HTTP_REFERER' => current_url})
-
end
-
-
2
def process_and_follow_redirects(method, path, attributes = {}, env = {})
-
13
process(method, path, attributes, env)
-
13
if driver.follow_redirects?
-
13
driver.redirect_limit.times do
-
65
process(:get, last_response["Location"], {}, env) if last_response.redirect?
-
end
-
13
raise Capybara::InfiniteRedirectError, "redirected more than #{driver.redirect_limit} times, check for infinite redirects." if last_response.redirect?
-
end
-
end
-
-
2
def process(method, path, attributes = {}, env = {})
-
13
new_uri = URI.parse(path)
-
13
method.downcase! unless method.is_a? Symbol
-
-
13
new_uri.path = request_path if path.start_with?("?")
-
13
new_uri.path = "/" if new_uri.path.empty?
-
13
new_uri.path = request_path.sub(%r(/[^/]*$), '/') + new_uri.path unless new_uri.path.start_with?('/')
-
13
new_uri.scheme ||= @current_scheme
-
13
new_uri.host ||= @current_host
-
13
new_uri.port ||= @current_port unless new_uri.default_port == @current_port
-
-
13
@current_scheme = new_uri.scheme
-
13
@current_host = new_uri.host
-
13
@current_port = new_uri.port
-
-
13
reset_cache!
-
13
send(method, new_uri.to_s, attributes, env.merge(options[:headers] || {}))
-
end
-
-
2
def current_url
-
7
last_request.url
-
rescue Rack::Test::Error
-
""
-
end
-
-
2
def reset_host!
-
6
uri = URI.parse(Capybara.app_host || Capybara.default_host)
-
6
@current_scheme = uri.scheme
-
6
@current_host = uri.host
-
6
@current_port = uri.port
-
end
-
-
2
def reset_cache!
-
13
@dom = nil
-
end
-
-
2
def dom
-
7
@dom ||= Capybara::HTML(html)
-
end
-
-
2
def find(format, selector)
-
if format==:css
-
dom.css(selector, Capybara::RackTest::CSSHandlers.new)
-
else
-
7
dom.xpath(selector)
-
14
end.map { |node| Capybara::RackTest::Node.new(self, node) }
-
end
-
-
2
def html
-
7
last_response.body
-
rescue Rack::Test::Error
-
""
-
end
-
-
2
def title
-
if dom.respond_to? :title
-
dom.title
-
else
-
#old versions of nokogiri don't have #title - remove in 3.0
-
dom.xpath('/html/head/title | /html/title').first.text
-
end
-
end
-
-
2
protected
-
-
2
def build_rack_mock_session
-
6
reset_host! unless current_host
-
6
Rack::MockSession.new(app, current_host)
-
end
-
-
2
def request_path
-
3
last_request.path
-
rescue Rack::Test::Error
-
"/"
-
end
-
end
-
# frozen_string_literal: true
-
2
class Capybara::RackTest::CSSHandlers < BasicObject
-
2
include ::Kernel
-
-
2
def disabled list
-
list.find_all { |node| node.has_attribute? 'disabled' }
-
end
-
2
def enabled list
-
list.find_all { |node| !node.has_attribute? 'disabled' }
-
end
-
end
-
# frozen_string_literal: true
-
2
require 'rack/test'
-
2
require 'rack/utils'
-
2
require 'mime/types'
-
2
require 'nokogiri'
-
2
require 'cgi'
-
-
2
class Capybara::RackTest::Driver < Capybara::Driver::Base
-
2
DEFAULT_OPTIONS = {
-
:respect_data_method => false,
-
:follow_redirects => true,
-
:redirect_limit => 5
-
}
-
2
attr_reader :app, :options
-
-
2
def initialize(app, options={})
-
1
raise ArgumentError, "rack-test requires a rack application, but none was given" unless app
-
1
@app = app
-
1
@options = DEFAULT_OPTIONS.merge(options)
-
end
-
-
2
def browser
-
13
@browser ||= Capybara::RackTest::Browser.new(self)
-
end
-
-
2
def follow_redirects?
-
13
@options[:follow_redirects]
-
end
-
-
2
def redirect_limit
-
13
@options[:redirect_limit]
-
end
-
-
2
def response
-
browser.last_response
-
end
-
-
2
def request
-
browser.last_request
-
end
-
-
2
def visit(path, attributes = {})
-
6
browser.visit(path, attributes)
-
end
-
-
2
def submit(method, path, attributes)
-
browser.submit(method, path, attributes)
-
end
-
-
2
def follow(method, path, attributes = {})
-
browser.follow(method, path, attributes)
-
end
-
-
2
def current_url
-
browser.current_url
-
end
-
-
2
def response_headers
-
response.headers
-
end
-
-
2
def status_code
-
response.status
-
end
-
-
2
def find_xpath(selector)
-
7
browser.find(:xpath, selector)
-
end
-
-
2
def find_css(selector)
-
browser.find(:css,selector)
-
end
-
-
2
def html
-
browser.html
-
end
-
-
2
def dom
-
browser.dom
-
end
-
-
2
def title
-
browser.title
-
end
-
-
2
def reset!
-
6
@browser = nil
-
end
-
-
# @deprecated This method is being removed
-
2
def browser_initialized?
-
super && !@browser.nil?
-
end
-
-
2
def get(*args, &block); browser.get(*args, &block); end
-
2
def post(*args, &block); browser.post(*args, &block); end
-
2
def put(*args, &block); browser.put(*args, &block); end
-
2
def delete(*args, &block); browser.delete(*args, &block); end
-
2
def header(key, value); browser.header(key, value); end
-
end
-
# frozen_string_literal: true
-
2
class Capybara::RackTest::Form < Capybara::RackTest::Node
-
# This only needs to inherit from Rack::Test::UploadedFile because Rack::Test checks for
-
# the class specifically when determining whether to construct the request as multipart.
-
# That check should be based solely on the form element's 'enctype' attribute value,
-
# which should probably be provided to Rack::Test in its non-GET request methods.
-
2
class NilUploadedFile < Rack::Test::UploadedFile
-
2
def initialize
-
2
@empty_file = Tempfile.new("nil_uploaded_file")
-
2
@empty_file.close
-
end
-
-
4
def original_filename; ""; end
-
4
def content_type; "application/octet-stream"; end
-
6
def path; @empty_file.path; end
-
end
-
-
2
def params(button)
-
4
params = make_params
-
-
4
form_element_types=[:input, :select, :textarea]
-
4
form_elements_xpath=XPath.generate do |x|
-
4
xpath=x.descendant(*form_element_types).where(~x.attr(:form))
-
4
xpath=xpath.union(x.anywhere(*form_element_types).where(x.attr(:form) == native[:id])) if native[:id]
-
4
xpath.where(~x.attr(:disabled))
-
end.to_s
-
-
4
native.xpath(form_elements_xpath).map do |field|
-
26
case field.name
-
when 'input'
-
24
if %w(radio checkbox).include? field['type']
-
if field['checked']
-
node=Capybara::RackTest::Node.new(self.driver, field)
-
merge_param!(params, field['name'].to_s, node.value.to_s)
-
end
-
elsif %w(submit image).include? field['type']
-
# TO DO identify the click button here (in document order, rather
-
# than leaving until the end of the params)
-
elsif field['type'] =='file'
-
2
if multipart?
-
2
file = \
-
2
if (value = field['value']).to_s.empty?
-
2
NilUploadedFile.new
-
else
-
content_type = MIME::Types.type_for(value).first.to_s
-
Rack::Test::UploadedFile.new(value, content_type)
-
end
-
2
merge_param!(params, field['name'].to_s, file)
-
else
-
merge_param!(params, field['name'].to_s, File.basename(field['value'].to_s))
-
end
-
else
-
18
merge_param!(params, field['name'].to_s, field['value'].to_s)
-
end
-
when 'select'
-
2
if field['multiple'] == 'multiple'
-
options = field.xpath(".//option[@selected]")
-
options.each do |option|
-
merge_param!(params, field['name'].to_s, (option['value'] || option.text).to_s)
-
end
-
else
-
2
option = field.xpath(".//option[@selected]").first
-
2
option ||= field.xpath('.//option').first
-
2
merge_param!(params, field['name'].to_s, (option['value'] || option.text).to_s) if option
-
end
-
when 'textarea'
-
merge_param!(params, field['name'].to_s, field.text.to_s.gsub(/\n/, "\r\n"))
-
end
-
end
-
4
merge_param!(params, button[:name], button[:value] || "") if button[:name]
-
-
4
params.to_params_hash
-
end
-
-
2
def submit(button)
-
4
action = (button && button['formaction']) || native['action']
-
4
method = (button && button['formmethod']) || request_method
-
4
driver.submit(method, action.to_s, params(button))
-
end
-
-
2
def multipart?
-
2
self[:enctype] == "multipart/form-data"
-
end
-
-
2
private
-
-
2
class ParamsHash < Hash
-
2
def to_params_hash
-
4
self
-
end
-
end
-
-
2
def request_method
-
4
self[:method] =~ /post/i ? :post : :get
-
end
-
-
2
def merge_param!(params, key, value)
-
26
if Rack::Utils.respond_to?(:default_query_parser)
-
Rack::Utils.default_query_parser.normalize_params(params, key, value, Rack::Utils.param_depth_limit)
-
else
-
26
Rack::Utils.normalize_params(params, key, value)
-
end
-
end
-
-
2
def make_params
-
4
if Rack::Utils.respond_to?(:default_query_parser)
-
Rack::Utils.default_query_parser.make_params
-
else
-
4
ParamsHash.new
-
end
-
end
-
end
-
# frozen_string_literal: true
-
2
require 'capybara/dsl'
-
-
2
Capybara.app = Rack::Builder.new do
-
2
map "/" do
-
2
if Gem::Version.new(Rails.version) >= Gem::Version.new("3.0")
-
2
run Rails.application
-
else # Rails 2
-
use Rails::Rack::Static
-
run ActionController::Dispatcher.new
-
end
-
end
-
end.to_app
-
-
2
Capybara.save_path = Rails.root.join('tmp/capybara')
-
-
# Override default rack_test driver to respect data-method attributes.
-
2
Capybara.register_driver :rack_test do |app|
-
1
Capybara::RackTest::Driver.new(app, :respect_data_method => true)
-
end
-
# frozen_string_literal: true
-
2
require 'forwardable'
-
-
2
module Capybara
-
-
##
-
# A {Capybara::Result} represents a collection of {Capybara::Node::Element} on the page. It is possible to interact with this
-
# collection similar to an Array because it implements Enumerable and offers the following Array methods through delegation:
-
#
-
# * []
-
# * each()
-
# * at()
-
# * size()
-
# * count()
-
# * length()
-
# * first()
-
# * last()
-
# * empty?()
-
#
-
# @see Capybara::Node::Element
-
#
-
2
class Result
-
2
include Enumerable
-
2
extend Forwardable
-
-
2
def initialize(elements, query)
-
7
@elements = elements
-
14
@result = elements.select { |node| query.matches_filters?(node) }
-
7
@rest = @elements - @result
-
7
@query = query
-
end
-
-
2
def_delegators :@result, :each, :[], :at, :size, :count, :length,
-
:first, :last, :values_at, :empty?, :inspect, :sample, :index
-
-
2
def matches_count?
-
Capybara::Helpers.matches_count?(@result.size, @query.options)
-
end
-
-
2
def failure_message
-
message = Capybara::Helpers.failure_message(@query.description, @query.options)
-
if count > 0
-
message << ", found #{count} #{Capybara::Helpers.declension("match", "matches", count)}: " << @result.map(&:text).map(&:inspect).join(", ")
-
else
-
message << " but there were no matches"
-
end
-
unless @rest.empty?
-
elements = @rest.map(&:text).map(&:inspect).join(", ")
-
message << ". Also found " << elements << ", which matched the selector but not all filters."
-
end
-
message
-
end
-
-
2
def negative_failure_message
-
failure_message.sub(/(to find)/, 'not \1')
-
end
-
end
-
end
-
# frozen_string_literal: true
-
1
require 'capybara/dsl'
-
1
require 'rspec/core'
-
1
require 'capybara/rspec/matchers'
-
1
require 'capybara/rspec/features'
-
-
1
RSpec.configure do |config|
-
1
config.include Capybara::DSL, :type => :feature
-
1
config.include Capybara::RSpecMatchers, :type => :feature
-
1
config.include Capybara::RSpecMatchers, :type => :view
-
-
# A work-around to support accessing the current example that works in both
-
# RSpec 2 and RSpec 3.
-
1
fetch_current_example = RSpec.respond_to?(:current_example) ?
-
proc { RSpec.current_example } : proc { |context| context.example }
-
-
# The before and after blocks must run instantaneously, because Capybara
-
# might not actually be used in all examples where it's included.
-
1
config.after do
-
21
if self.class.include?(Capybara::DSL)
-
Capybara.reset_sessions!
-
Capybara.use_default_driver
-
end
-
end
-
1
config.before do
-
21
if self.class.include?(Capybara::DSL)
-
example = fetch_current_example.call(self)
-
Capybara.current_driver = Capybara.javascript_driver if example.metadata[:js]
-
Capybara.current_driver = example.metadata[:driver] if example.metadata[:driver]
-
end
-
end
-
end
-
-
# frozen_string_literal: true
-
1
if RSpec::Core::Version::STRING.to_f >= 3.0
-
1
RSpec.shared_context "Capybara Features", :capybara_feature => true do
-
instance_eval do
-
alias background before
-
alias given let
-
alias given! let!
-
end
-
end
-
-
1
RSpec.configure do |config|
-
1
config.alias_example_group_to :feature, :capybara_feature => true, :type => :feature
-
1
config.alias_example_group_to :xfeature, :capybara_feature => true, :type => :feature, :skip => "Temporarily disabled with xfeature"
-
1
config.alias_example_group_to :ffeature, :capybara_feature => true, :type => :feature, :focus => true
-
1
config.alias_example_to :scenario
-
1
config.alias_example_to :xscenario, :skip => "Temporarily disabled with xscenario"
-
1
config.alias_example_to :fscenario, :focus => true
-
end
-
else
-
module Capybara
-
module Features
-
def self.included(base)
-
base.instance_eval do
-
alias :background :before
-
alias :scenario :it
-
alias :xscenario :xit
-
alias :given :let
-
alias :given! :let!
-
alias :feature :describe
-
end
-
end
-
end
-
end
-
-
-
def self.feature(*args, &block)
-
options = if args.last.is_a?(Hash) then args.pop else {} end
-
options[:capybara_feature] = true
-
options[:type] = :feature
-
options[:caller] ||= caller
-
args.push(options)
-
-
#call describe on RSpec in case user has expose_dsl_globally set to false
-
RSpec.describe(*args, &block)
-
end
-
-
RSpec.configuration.include Capybara::Features, :capybara_feature => true
-
end
-
# frozen_string_literal: true
-
2
module Capybara
-
2
module RSpecMatchers
-
2
class Matcher
-
2
include ::RSpec::Matchers::Composable if defined?(::RSpec::Expectations::Version) && (Gem::Version.new(RSpec::Expectations::Version::STRING) >= Gem::Version.new('3.0'))
-
-
2
def wrap(actual)
-
if actual.respond_to?("has_selector?")
-
actual
-
else
-
Capybara.string(actual.to_s)
-
end
-
end
-
end
-
-
2
class HaveSelector < Matcher
-
2
attr_reader :failure_message, :failure_message_when_negated
-
-
2
def initialize(*args)
-
@args = args
-
end
-
-
2
def matches?(actual)
-
wrap(actual).assert_selector(*@args)
-
rescue Capybara::ExpectationNotMet => e
-
@failure_message = e.message
-
return false
-
end
-
-
2
def does_not_match?(actual)
-
wrap(actual).assert_no_selector(*@args)
-
rescue Capybara::ExpectationNotMet => e
-
@failure_message_when_negated = e.message
-
return false
-
end
-
-
2
def description
-
"have #{query.description}"
-
end
-
-
2
def query
-
@query ||= Capybara::Queries::SelectorQuery.new(*@args)
-
end
-
-
# RSpec 2 compatibility:
-
2
alias_method :failure_message_for_should, :failure_message
-
2
alias_method :failure_message_for_should_not, :failure_message_when_negated
-
end
-
-
2
class HaveText < Matcher
-
2
attr_reader :type, :content, :options
-
-
2
attr_reader :failure_message, :failure_message_when_negated
-
-
2
def initialize(*args)
-
@args = args.dup
-
-
# are set just for backwards compatability
-
@type = args.shift if args.first.is_a?(Symbol)
-
@content = args.shift
-
@options = (args.first.is_a?(Hash))? args.first : {}
-
end
-
-
2
def matches?(actual)
-
wrap(actual).assert_text(*@args)
-
rescue Capybara::ExpectationNotMet => e
-
@failure_message = e.message
-
return false
-
end
-
-
2
def does_not_match?(actual)
-
wrap(actual).assert_no_text(*@args)
-
rescue Capybara::ExpectationNotMet => e
-
@failure_message_when_negated = e.message
-
return false
-
end
-
-
2
def description
-
"text #{format(content)}"
-
end
-
-
2
def format(content)
-
content = Capybara::Helpers.normalize_whitespace(content) unless content.is_a? Regexp
-
content.inspect
-
end
-
-
# RSpec 2 compatibility:
-
2
alias_method :failure_message_for_should, :failure_message
-
2
alias_method :failure_message_for_should_not, :failure_message_when_negated
-
end
-
-
2
class HaveTitle < Matcher
-
2
attr_reader :title
-
-
2
attr_reader :failure_message, :failure_message_when_negated
-
-
2
def initialize(*args)
-
@args = args
-
-
# are set just for backwards compatability
-
@title = args.first
-
end
-
-
2
def matches?(actual)
-
wrap(actual).assert_title(*@args)
-
rescue Capybara::ExpectationNotMet => e
-
@failure_message = e.message
-
return false
-
end
-
-
2
def does_not_match?(actual)
-
wrap(actual).assert_no_title(*@args)
-
rescue Capybara::ExpectationNotMet => e
-
@failure_message_when_negated = e.message
-
return false
-
end
-
-
2
def description
-
"have title #{title.inspect}"
-
end
-
-
# RSpec 2 compatibility:
-
2
alias_method :failure_message_for_should, :failure_message
-
2
alias_method :failure_message_for_should_not, :failure_message_when_negated
-
end
-
-
2
class HaveCurrentPath < Matcher
-
2
attr_reader :current_path
-
-
2
attr_reader :failure_message, :failure_message_when_negated
-
-
2
def initialize(*args)
-
@args = args
-
-
# are set just for backwards compatability
-
@current_path = args.first
-
end
-
-
2
def matches?(actual)
-
wrap(actual).assert_current_path(*@args)
-
rescue Capybara::ExpectationNotMet => e
-
@failure_message = e.message
-
return false
-
end
-
-
2
def does_not_match?(actual)
-
wrap(actual).assert_no_current_path(*@args)
-
rescue Capybara::ExpectationNotMet => e
-
@failure_message_when_negated = e.message
-
return false
-
end
-
-
2
def description
-
"have current path #{current_path.inspect}"
-
end
-
-
# RSpec 2 compatibility:
-
2
alias_method :failure_message_for_should, :failure_message
-
2
alias_method :failure_message_for_should_not, :failure_message_when_negated
-
end
-
-
2
class BecomeClosed
-
2
def initialize(options)
-
@wait_time = Capybara::Queries::SelectorQuery.new(options).wait
-
end
-
-
2
def matches?(window)
-
@window = window
-
start_time = Capybara::Helpers.monotonic_time
-
while window.exists?
-
return false if (Capybara::Helpers.monotonic_time - start_time) > @wait_time
-
sleep 0.05
-
end
-
true
-
end
-
-
2
def failure_message
-
"expected #{@window.inspect} to become closed after #{@wait_time} seconds"
-
end
-
-
2
def failure_message_when_negated
-
"expected #{@window.inspect} not to become closed after #{@wait_time} seconds"
-
end
-
-
# RSpec 2 compatibility:
-
2
alias_method :failure_message_for_should, :failure_message
-
2
alias_method :failure_message_for_should_not, :failure_message_when_negated
-
end
-
-
2
class MatchSelector < Matcher
-
2
attr_reader :failure_message, :failure_message_when_negated
-
-
2
def initialize(*args)
-
@args = args
-
end
-
-
2
def matches?(actual)
-
actual.assert_matches_selector(*@args)
-
rescue Capybara::ExpectationNotMet => e
-
@failure_message = e.message
-
return false
-
end
-
-
2
def does_not_match?(actual)
-
actual.assert_not_matches_selector(*@args)
-
rescue Capybara::ExpectationNotMet => e
-
@failure_message_when_negated = e.message
-
return false
-
end
-
-
2
def description
-
"match #{query.description}"
-
end
-
-
2
def query
-
@query ||= Capybara::Queries::MatchQuery.new(*@args)
-
end
-
-
# RSpec 2 compatibility:
-
2
alias_method :failure_message_for_should, :failure_message
-
2
alias_method :failure_message_for_should_not, :failure_message_when_negated
-
end
-
-
2
def have_selector(*args)
-
HaveSelector.new(*args)
-
end
-
-
2
def match_selector(*args)
-
MatchSelector.new(*args)
-
end
-
# defined_negated_matcher was added in RSpec 3.1 - it's syntactic sugar only since a user can do
-
# expect(page).not_to match_selector, so not sure we really need to support not_match_selector for prior to RSpec 3.1
-
2
::RSpec::Matchers.define_negated_matcher :not_match_selector, :match_selector if defined?(::RSpec::Expectations::Version) && (Gem::Version.new(RSpec::Expectations::Version::STRING) >= Gem::Version.new('3.1'))
-
-
-
2
def have_xpath(xpath, options={})
-
HaveSelector.new(:xpath, xpath, options)
-
end
-
-
2
def match_xpath(xpath, options={})
-
MatchSelector.new(:xpath, xpath, options)
-
end
-
-
2
def have_css(css, options={})
-
HaveSelector.new(:css, css, options)
-
end
-
-
2
def match_css(css, options={})
-
MatchSelector.new(:css, css, options)
-
end
-
-
2
def have_text(*args)
-
HaveText.new(*args)
-
end
-
2
alias_method :have_content, :have_text
-
-
2
def have_title(title, options = {})
-
HaveTitle.new(title, options)
-
end
-
-
2
def have_current_path(path, options = {})
-
HaveCurrentPath.new(path, options)
-
end
-
-
2
def have_link(locator, options={})
-
HaveSelector.new(:link, locator, options)
-
end
-
-
2
def have_button(locator, options={})
-
HaveSelector.new(:button, locator, options)
-
end
-
-
2
def have_field(locator, options={})
-
HaveSelector.new(:field, locator, options)
-
end
-
-
2
def have_checked_field(locator, options={})
-
HaveSelector.new(:field, locator, options.merge(:checked => true))
-
end
-
-
2
def have_unchecked_field(locator, options={})
-
HaveSelector.new(:field, locator, options.merge(:unchecked => true))
-
end
-
-
2
def have_select(locator, options={})
-
HaveSelector.new(:select, locator, options)
-
end
-
-
2
def have_table(locator, options={})
-
HaveSelector.new(:table, locator, options)
-
end
-
-
##
-
# Wait for window to become closed.
-
# @example
-
# expect(window).to become_closed(wait: 0.8)
-
# @param options [Hash] optional param
-
# @option options [Numeric] :wait (Capybara.default_max_wait_time) Maximum wait time
-
2
def become_closed(options = {})
-
BecomeClosed.new(options)
-
end
-
end
-
end
-
# frozen_string_literal: true
-
2
require 'capybara/selector/filter'
-
-
2
module Capybara
-
2
class Selector
-
-
2
attr_reader :name, :custom_filters, :format
-
-
2
class << self
-
2
def all
-
39
@selectors ||= {}
-
end
-
-
2
def add(name, &block)
-
32
all[name.to_sym] = Capybara::Selector.new(name.to_sym, &block)
-
end
-
-
2
def update(name, &block)
-
all[name.to_sym].instance_eval(&block)
-
end
-
-
2
def remove(name)
-
all.delete(name.to_sym)
-
end
-
end
-
-
2
def initialize(name, &block)
-
32
@name = name
-
32
@custom_filters = {}
-
32
@match = nil
-
32
@label = nil
-
32
@failure_message = nil
-
32
@description = nil
-
32
@format = nil
-
32
@expression = nil
-
32
instance_eval(&block)
-
end
-
-
2
def xpath(&block)
-
30
@format, @expression = :xpath, block if block
-
30
format == :xpath ? @expression : nil
-
end
-
-
2
def css(&block)
-
2
@format, @expression = :css, block if block
-
2
format == :css ? @expression : nil
-
end
-
-
2
def match(&block)
-
@match = block if block
-
@match
-
end
-
-
2
def label(label=nil)
-
12
@label = label if label
-
12
@label
-
end
-
-
2
def description(options={})
-
(@description && @description.call(options)).to_s
-
end
-
-
2
def call(locator)
-
7
if format
-
7
@expression.call(locator)
-
else
-
warn "Selector has no format"
-
end
-
end
-
-
2
def match?(locator)
-
@match and @match.call(locator)
-
end
-
-
2
def filter(name, options={}, &block)
-
60
@custom_filters[name] = Filter.new(name, block, options)
-
end
-
-
2
def describe &block
-
20
@description = block
-
end
-
-
2
private
-
-
2
def locate_field(xpath, locator)
-
locate_field = xpath[XPath.attr(:id).equals(locator) |
-
XPath.attr(:name).equals(locator) |
-
XPath.attr(:placeholder).equals(locator) |
-
XPath.attr(:id).equals(XPath.anywhere(:label)[XPath.string.n.is(locator)].attr(:for))]
-
locate_field += XPath.descendant(:label)[XPath.string.n.is(locator)].descendant(xpath)
-
locate_field
-
end
-
end
-
end
-
-
2
Capybara.add_selector(:xpath) do
-
2
xpath { |xpath| xpath }
-
end
-
-
2
Capybara.add_selector(:css) do
-
2
css { |css| css }
-
end
-
-
2
Capybara.add_selector(:id) do
-
2
xpath { |id| XPath.descendant[XPath.attr(:id) == id.to_s] }
-
end
-
-
2
Capybara.add_selector(:field) do
-
2
xpath do |locator|
-
xpath = XPath.descendant(:input, :textarea, :select)[~XPath.attr(:type).one_of('submit', 'image', 'hidden')]
-
xpath = locate_field(xpath, locator.to_s) unless locator.nil?
-
xpath
-
end
-
2
filter(:checked, boolean: true) { |node, value| not(value ^ node.checked?) }
-
2
filter(:unchecked, boolean: true) { |node, value| (value ^ node.checked?) }
-
2
filter(:disabled, default: false, boolean: true, skip_if: :all) { |node, value| not(value ^ node.disabled?) }
-
2
filter(:readonly, boolean: true) { |node, value| not(value ^ node[:readonly]) }
-
2
filter(:with) { |node, with| node.value == with.to_s }
-
2
filter(:type) do |node, type|
-
if ['textarea', 'select'].include?(type)
-
node.tag_name == type
-
else
-
node[:type] == type
-
end
-
end
-
2
filter(:multiple, boolean: true) { |node, value| !(value ^ node[:multiple]) }
-
2
describe do |options|
-
desc, states = String.new, []
-
desc << " of type #{options[:type].inspect}" if options[:type]
-
desc << " with value #{options[:with].to_s.inspect}" if options.has_key?(:with)
-
states << 'checked' if options[:checked] || (options.has_key?(:unchecked) && !options[:unchecked])
-
states << 'not checked' if options[:unchecked] || (options.has_key?(:checked) && !options[:checked])
-
states << 'disabled' if options[:disabled] == true
-
desc << " that is #{states.join(' and ')}" unless states.empty?
-
desc << " with the multiple attribute" if options[:multiple] == true
-
desc << " without the multiple attribute" if options[:multiple] === false
-
desc
-
end
-
end
-
-
2
Capybara.add_selector(:fieldset) do
-
2
xpath do |locator|
-
xpath = XPath.descendant(:fieldset)
-
xpath = xpath[XPath.attr(:id).equals(locator.to_s) | XPath.child(:legend)[XPath.string.n.is(locator.to_s)]] unless locator.nil?
-
xpath
-
end
-
end
-
-
2
Capybara.add_selector(:link) do
-
2
xpath do |locator|
-
3
xpath = XPath.descendant(:a)[XPath.attr(:href)]
-
3
unless locator.nil?
-
3
locator = locator.to_s
-
3
xpath = xpath[XPath.attr(:id).equals(locator) |
-
XPath.string.n.is(locator) |
-
XPath.attr(:title).is(locator) |
-
XPath.descendant(:img)[XPath.attr(:alt).is(locator)]]
-
end
-
3
xpath
-
end
-
-
2
filter(:href) do |node, href|
-
if href.is_a? Regexp
-
node[:href].match href
-
else
-
node.first(:xpath, XPath.axis(:self)[XPath.attr(:href).equals(href.to_s)], minimum: 0)
-
end
-
end
-
-
2
describe { |options| " with href #{options[:href].inspect}" if options[:href] }
-
end
-
-
2
Capybara.add_selector(:button) do
-
2
xpath do |locator|
-
4
input_btn_xpath = XPath.descendant(:input)[XPath.attr(:type).one_of('submit', 'reset', 'image', 'button')]
-
4
btn_xpath = XPath.descendant(:button)
-
4
image_btn_xpath = XPath.descendant(:input)[XPath.attr(:type).equals('image')]
-
-
4
unless locator.nil?
-
4
locator = locator.to_s
-
4
input_btn_xpath = input_btn_xpath[XPath.attr(:id).equals(locator) | XPath.attr(:value).is(locator) | XPath.attr(:title).is(locator)]
-
4
btn_xpath = btn_xpath[XPath.attr(:id).equals(locator) | XPath.attr(:value).is(locator) | XPath.string.n.is(locator) | XPath.attr(:title).is(locator)]
-
4
image_btn_xpath = image_btn_xpath[XPath.attr(:alt).is(locator)]
-
end
-
-
4
input_btn_xpath + btn_xpath + image_btn_xpath
-
end
-
-
6
filter(:disabled, default: false, boolean: true, skip_if: :all) { |node, value| not(value ^ node.disabled?) }
-
-
2
describe { |options| " that is disabled" if options[:disabled] == true }
-
end
-
-
2
Capybara.add_selector(:link_or_button) do
-
2
label "link or button"
-
2
xpath do |locator|
-
self.class.all.values_at(:link, :button).map {|selector| selector.xpath.call(locator)}.reduce(:+)
-
end
-
-
2
filter(:disabled, default: false, boolean: true) { |node, value| node.tag_name == "a" or not(value ^ node.disabled?) }
-
-
2
describe { |options| " that is disabled" if options[:disabled] }
-
end
-
-
2
Capybara.add_selector(:fillable_field) do
-
2
label "field"
-
2
xpath do |locator|
-
xpath = XPath.descendant(:input, :textarea)[~XPath.attr(:type).one_of('submit', 'image', 'radio', 'checkbox', 'hidden', 'file')]
-
xpath = locate_field(xpath, locator.to_s) unless locator.nil?
-
xpath
-
end
-
-
2
filter(:disabled, default: false, boolean: true, skip_if: :all) { |node, value| not(value ^ node.disabled?) }
-
2
filter(:multiple, boolean: true) { |node, value| !(value ^ node[:multiple]) }
-
-
2
describe do |options|
-
desc = String.new
-
desc << " that is disabled" if options[:disabled] == true
-
desc << " with the multiple attribute" if options[:multiple] == true
-
desc << " without the multiple attribute" if options[:multiple] === false
-
desc
-
end
-
end
-
-
2
Capybara.add_selector(:radio_button) do
-
2
label "radio button"
-
2
xpath do |locator|
-
xpath = XPath.descendant(:input)[XPath.attr(:type).equals('radio')]
-
xpath = locate_field(xpath, locator.to_s) unless locator.nil?
-
xpath
-
end
-
-
2
filter(:checked, boolean: true) { |node, value| not(value ^ node.checked?) }
-
2
filter(:unchecked, boolean: true) { |node, value| (value ^ node.checked?) }
-
2
filter(:option) { |node, value| node.value == value.to_s }
-
2
filter(:disabled, default: false, boolean: true, skip_if: :all) { |node, value| not(value ^ node.disabled?) }
-
-
2
describe do |options|
-
desc, states = String.new, []
-
desc << " with value #{options[:option].inspect}" if options[:option]
-
states << 'checked' if options[:checked] || (options.has_key?(:unchecked) && !options[:unchecked])
-
states << 'not checked' if options[:unchecked] || (options.has_key?(:checked) && !options[:checked])
-
states << 'disabled' if options[:disabled] == true
-
desc << " that is #{states.join(' and ')}" unless states.empty?
-
desc
-
end
-
end
-
-
2
Capybara.add_selector(:checkbox) do
-
2
xpath do |locator|
-
xpath = XPath.descendant(:input)[XPath.attr(:type).equals('checkbox')]
-
xpath = locate_field(xpath, locator.to_s) unless locator.nil?
-
xpath
-
end
-
-
2
filter(:checked, boolean: true) { |node, value| not(value ^ node.checked?) }
-
2
filter(:unchecked, boolean: true) { |node, value| (value ^ node.checked?) }
-
2
filter(:option) { |node, value| node.value == value.to_s }
-
2
filter(:disabled, default: false, boolean: true, skip_if: :all) { |node, value| not(value ^ node.disabled?) }
-
-
2
describe do |options|
-
desc, states = String.new, []
-
desc << " with value #{options[:option].inspect}" if options[:option]
-
states << 'checked' if options[:checked] || (options.has_key?(:unchecked) && !options[:unchecked])
-
states << 'not checked' if options[:unchecked] || (options.has_key?(:checked) && !options[:checked])
-
states << 'disabled' if options[:disabled] == true
-
desc << " that is #{states.join(' and ')}" unless states.empty?
-
desc
-
end
-
end
-
-
2
Capybara.add_selector(:select) do
-
2
label "select box"
-
2
xpath do |locator|
-
xpath = XPath.descendant(:select)
-
xpath = locate_field(xpath, locator.to_s) unless locator.nil?
-
xpath
-
end
-
-
2
filter(:options) do |node, options|
-
if node.visible?
-
actual = node.all(:xpath, './/option').map { |option| option.text }
-
else
-
actual = node.all(:xpath, './/option', visible: false).map { |option| option.text(:all) }
-
end
-
options.sort == actual.sort
-
end
-
2
filter(:with_options) do |node, options|
-
finder_settings = { minimum: 0 }
-
if !node.visible?
-
finder_settings[:visible] = false
-
end
-
options.all? { |option| node.first(:option, option, finder_settings) }
-
end
-
2
filter(:selected) do |node, selected|
-
actual = node.all(:xpath, './/option', visible: false).select { |option| option.selected? }.map { |option| option.text(:all) }
-
[selected].flatten.sort == actual.sort
-
end
-
2
filter(:disabled, default: false, boolean: true, skip_if: :all) { |node, value| not(value ^ node.disabled?) }
-
2
filter(:multiple, boolean: true) { |node, value| !(value ^ node[:multiple]) }
-
-
2
describe do |options|
-
desc = String.new
-
desc << " with options #{options[:options].inspect}" if options[:options]
-
desc << " with at least options #{options[:with_options].inspect}" if options[:with_options]
-
desc << " with #{options[:selected].inspect} selected" if options[:selected]
-
desc << " that is disabled" if options[:disabled] == true
-
desc << " that allows multiple selection" if options[:multiple] == true
-
desc << " that only allows single selection" if options[:multiple] === false
-
desc
-
end
-
end
-
-
2
Capybara.add_selector(:option) do
-
2
xpath do |locator|
-
xpath = XPath.descendant(:option)
-
xpath = xpath[XPath.string.n.is(locator.to_s)] unless locator.nil?
-
xpath
-
end
-
-
2
filter(:disabled, boolean: true) { |node, value| not(value ^ node.disabled?) }
-
2
filter(:selected, boolean: true) { |node, value| not(value ^ node.selected?) }
-
-
2
describe do |options|
-
desc = String.new
-
desc << " that is#{' not' unless options[:disabled]} disabled" if options.has_key?(:disabled)
-
desc << " that is#{' not' unless options[:selected]} selected" if options.has_key?(:selected)
-
desc
-
end
-
end
-
-
2
Capybara.add_selector(:file_field) do
-
2
label "file field"
-
2
xpath do |locator|
-
xpath = XPath.descendant(:input)[XPath.attr(:type).equals('file')]
-
xpath = locate_field(xpath, locator.to_s) unless locator.nil?
-
xpath
-
end
-
-
2
filter(:disabled, default: false, boolean: true, skip_if: :all) { |node, value| not(value ^ node.disabled?) }
-
2
filter(:multiple, boolean: true) { |node, value| !(value ^ node[:multiple]) }
-
-
2
describe do |options|
-
desc = String.new
-
desc << " that is disabled" if options[:disabled] == true
-
desc << " that allows multiple files" if options[:multiple] == true
-
desc << " that only allows a single file" if options[:multiple] === false
-
desc
-
end
-
end
-
-
2
Capybara.add_selector(:label) do
-
2
label "label"
-
2
xpath do |locator|
-
xpath = XPath.descendant(:label)
-
xpath = xpath[XPath.string.n.is(locator.to_s) | XPath.attr(:id).equals(locator.to_s)] unless locator.nil?
-
xpath
-
end
-
-
2
filter(:for) do |node, field_or_value|
-
if field_or_value.is_a? Capybara::Node::Element
-
if field_or_value[:id] && (field_or_value[:id] == node[:for])
-
true
-
else
-
field_or_value.find_xpath('./ancestor::label[1]').include? node.base
-
end
-
else
-
node[:for] == field_or_value.to_s
-
end
-
end
-
end
-
-
2
Capybara.add_selector(:table) do
-
2
xpath do |locator|
-
xpath = XPath.descendant(:table)
-
xpath = xpath[XPath.attr(:id).equals(locator.to_s) | XPath.descendant(:caption).is(locator.to_s)] unless locator.nil?
-
xpath
-
end
-
end
-
# frozen_string_literal: true
-
2
module Capybara
-
2
class Selector
-
2
class Filter
-
2
def initialize(name, block, options={})
-
60
@name = name
-
60
@block = block
-
60
@options = options
-
60
@options[:valid_values] = [true,false] if options[:boolean]
-
end
-
-
2
def default?
-
7
@options.has_key?(:default)
-
end
-
-
2
def default
-
4
@options[:default]
-
end
-
-
2
def matches?(node, value)
-
4
return true if skip?(value)
-
-
4
if !valid_value?(value)
-
msg = "Invalid value #{value.inspect} passed to filter #{@name} - "
-
if default?
-
warn msg + "defaulting to #{default}"
-
value = default
-
else
-
warn msg + "skipping"
-
return true
-
end
-
end
-
-
4
@block.call(node, value)
-
end
-
-
2
def skip?(value)
-
4
@options.has_key?(:skip_if) && value == @options[:skip_if]
-
end
-
-
2
private
-
-
2
def valid_value?(value)
-
4
!@options.has_key?(:valid_values) || Array(@options[:valid_values]).include?(value)
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
2
require "uri"
-
-
2
class Capybara::Selenium::Driver < Capybara::Driver::Base
-
2
DEFAULT_OPTIONS = {
-
:browser => :firefox
-
}
-
2
SPECIAL_OPTIONS = [:browser]
-
-
2
attr_reader :app, :options
-
-
2
def browser
-
unless @browser
-
@browser = Selenium::WebDriver.for(options[:browser], options.reject { |key,val| SPECIAL_OPTIONS.include?(key) })
-
-
main = Process.pid
-
at_exit do
-
# Store the exit status of the test run since it goes away after calling the at_exit proc...
-
@exit_status = $!.status if $!.is_a?(SystemExit)
-
quit if Process.pid == main
-
exit @exit_status if @exit_status # Force exit with stored status
-
end
-
end
-
@browser
-
end
-
-
2
def initialize(app, options={})
-
begin
-
require 'selenium-webdriver'
-
rescue LoadError => e
-
if e.message =~ /selenium-webdriver/
-
raise LoadError, "Capybara's selenium driver is unable to load `selenium-webdriver`, please install the gem and add `gem 'selenium-webdriver'` to your Gemfile if you are using bundler."
-
else
-
raise e
-
end
-
end
-
-
@app = app
-
@browser = nil
-
@exit_status = nil
-
@frame_handles = {}
-
@options = DEFAULT_OPTIONS.merge(options)
-
end
-
-
2
def visit(path)
-
browser.navigate.to(path)
-
end
-
-
2
def go_back
-
browser.navigate.back
-
end
-
-
2
def go_forward
-
browser.navigate.forward
-
end
-
-
2
def html
-
browser.page_source
-
end
-
-
2
def title
-
browser.title
-
end
-
-
2
def current_url
-
browser.current_url
-
end
-
-
2
def find_xpath(selector)
-
browser.find_elements(:xpath, selector).map { |node| Capybara::Selenium::Node.new(self, node) }
-
end
-
-
2
def find_css(selector)
-
browser.find_elements(:css, selector).map { |node| Capybara::Selenium::Node.new(self, node) }
-
end
-
-
2
def wait?; true; end
-
2
def needs_server?; true; end
-
-
2
def execute_script(script)
-
browser.execute_script script
-
end
-
-
2
def evaluate_script(script)
-
browser.execute_script "return #{script}"
-
end
-
-
2
def save_screenshot(path, options={})
-
browser.save_screenshot(path)
-
end
-
-
2
def reset!
-
# Use instance variable directly so we avoid starting the browser just to reset the session
-
if @browser
-
navigated = false
-
start_time = Capybara::Helpers.monotonic_time
-
begin
-
if !navigated
-
# Only trigger a navigation if we haven't done it already, otherwise it
-
# can trigger an endless series of unload modals
-
begin
-
@browser.manage.delete_all_cookies
-
rescue Selenium::WebDriver::Error::UnhandledError
-
# delete_all_cookies fails when we've previously gone
-
# to about:blank, so we rescue this error and do nothing
-
# instead.
-
end
-
@browser.navigate.to("about:blank")
-
end
-
navigated = true
-
-
#Ensure the page is empty and trigger an UnhandledAlertError for any modals that appear during unload
-
until find_xpath("/html/body/*").empty? do
-
raise Capybara::ExpectationNotMet.new('Timed out waiting for Selenium session reset') if (Capybara::Helpers.monotonic_time - start_time) >= 10
-
sleep 0.05
-
end
-
rescue Selenium::WebDriver::Error::UnhandledAlertError
-
# This error is thrown if an unhandled alert is on the page
-
# Firefox appears to automatically dismiss this alert, chrome does not
-
# We'll try to accept it
-
begin
-
@browser.switch_to.alert.accept
-
sleep 0.25 # allow time for the modal to be handled
-
rescue Selenium::WebDriver::Error::NoAlertPresentError
-
# The alert is now gone - nothing to do
-
end
-
# try cleaning up the browser again
-
retry
-
end
-
end
-
end
-
-
##
-
#
-
# Webdriver supports frame name, id, index(zero-based) or {Capybara::Node::Element} to find iframe
-
#
-
# @overload within_frame(index)
-
# @param [Integer] index index of a frame
-
# @overload within_frame(name_or_id)
-
# @param [String] name_or_id name or id of a frame
-
# @overload within_frame(element)
-
# @param [Capybara::Node::Base] a_node frame element
-
#
-
2
def within_frame(frame_handle)
-
frame_handle = frame_handle.native if frame_handle.is_a?(Capybara::Node::Base)
-
@frame_handles[browser.window_handle] ||= []
-
@frame_handles[browser.window_handle] << frame_handle
-
browser.switch_to.frame(frame_handle)
-
yield
-
ensure
-
# would love to use browser.switch_to.parent_frame here
-
# but it has an issue if the current frame is removed from within it
-
@frame_handles[browser.window_handle].pop
-
browser.switch_to.default_content
-
@frame_handles[browser.window_handle].each { |fh| browser.switch_to.frame(fh) }
-
end
-
-
2
def current_window_handle
-
browser.window_handle
-
end
-
-
2
def window_size(handle)
-
within_given_window(handle) do
-
size = browser.manage.window.size
-
[size.width, size.height]
-
end
-
end
-
-
2
def resize_window_to(handle, width, height)
-
within_given_window(handle) do
-
browser.manage.window.resize_to(width, height)
-
end
-
end
-
-
2
def maximize_window(handle)
-
within_given_window(handle) do
-
browser.manage.window.maximize
-
end
-
sleep 0.1 # work around for https://code.google.com/p/selenium/issues/detail?id=7405
-
end
-
-
2
def close_window(handle)
-
within_given_window(handle) do
-
browser.close
-
end
-
end
-
-
2
def window_handles
-
browser.window_handles
-
end
-
-
2
def open_new_window
-
browser.execute_script('window.open();')
-
end
-
-
2
def switch_to_window(handle)
-
browser.switch_to.window handle
-
end
-
-
# @api private
-
2
def find_window(locator)
-
handles = browser.window_handles
-
return locator if handles.include? locator
-
-
original_handle = browser.window_handle
-
handles.each do |handle|
-
switch_to_window(handle)
-
if (locator == browser.execute_script("return window.name") ||
-
browser.title.include?(locator) ||
-
browser.current_url.include?(locator))
-
switch_to_window(original_handle)
-
return handle
-
end
-
end
-
raise Capybara::ElementNotFound, "Could not find a window identified by #{locator}"
-
end
-
-
2
def within_window(locator)
-
handle = find_window(locator)
-
browser.switch_to.window(handle) { yield }
-
end
-
-
2
def accept_modal(type, options={}, &blk)
-
yield if block_given?
-
modal = find_modal(options)
-
modal.send_keys options[:with] if options[:with]
-
message = modal.text
-
modal.accept
-
message
-
end
-
-
2
def dismiss_modal(type, options={}, &blk)
-
yield if block_given?
-
modal = find_modal(options)
-
message = modal.text
-
modal.dismiss
-
message
-
end
-
-
2
def quit
-
@browser.quit if @browser
-
rescue Errno::ECONNREFUSED
-
# Browser must have already gone
-
ensure
-
@browser = nil
-
end
-
-
2
def invalid_element_errors
-
[Selenium::WebDriver::Error::StaleElementReferenceError,
-
Selenium::WebDriver::Error::UnhandledError,
-
Selenium::WebDriver::Error::ElementNotVisibleError,
-
Selenium::WebDriver::Error::InvalidSelectorError] # Work around a race condition that can occur with chromedriver and #go_back/#go_forward
-
end
-
-
2
def no_such_window_error
-
Selenium::WebDriver::Error::NoSuchWindowError
-
end
-
-
# @deprecated This method is being removed
-
2
def browser_initialized?
-
super && !@browser.nil?
-
end
-
-
2
private
-
-
2
def within_given_window(handle)
-
original_handle = self.current_window_handle
-
if handle == original_handle
-
yield
-
else
-
switch_to_window(handle)
-
result = yield
-
switch_to_window(original_handle)
-
result
-
end
-
end
-
-
2
def find_modal(options={})
-
# Selenium has its own built in wait (2 seconds)for a modal to show up, so this wait is really the minimum time
-
# Actual wait time may be longer than specified
-
wait = Selenium::WebDriver::Wait.new(
-
timeout: (options[:wait] || Capybara.default_max_wait_time),
-
ignore: Selenium::WebDriver::Error::NoAlertPresentError)
-
begin
-
wait.until do
-
alert = @browser.switch_to.alert
-
regexp = options[:text].is_a?(Regexp) ? options[:text] : Regexp.escape(options[:text].to_s)
-
alert.text.match(regexp) ? alert : nil
-
end
-
rescue Selenium::WebDriver::Error::TimeOutError
-
raise Capybara::ModalNotFound.new("Unable to find modal dialog#{" with #{options[:text]}" if options[:text]}")
-
end
-
end
-
-
end
-
# frozen_string_literal: true
-
2
class Capybara::Selenium::Node < Capybara::Driver::Node
-
2
def visible_text
-
# Selenium doesn't normalize Unicode whitespace.
-
Capybara::Helpers.normalize_whitespace(native.text)
-
end
-
-
2
def all_text
-
text = driver.browser.execute_script("return arguments[0].textContent", native)
-
Capybara::Helpers.normalize_whitespace(text)
-
end
-
-
2
def [](name)
-
native.attribute(name.to_s)
-
rescue Selenium::WebDriver::Error::WebDriverError
-
nil
-
end
-
-
2
def value
-
if tag_name == "select" and self[:multiple] and not self[:multiple] == "false"
-
native.find_elements(:xpath, ".//option").select { |n| n.selected? }.map { |n| n[:value] || n.text }
-
else
-
native[:value]
-
end
-
end
-
-
##
-
#
-
# Set the value of the form element to the given value.
-
#
-
# @param [String] value The new value
-
# @param [Hash{}] options Driver specific options for how to set the value
-
# @option options [Symbol,Array] :clear (nil) The method used to clear the previous value <br/>
-
# nil => clear via javascript <br/>
-
# :none => append the new value to the existing value <br/>
-
# :backspace => send backspace keystrokes to clear the field <br/>
-
# Array => an array of keys to send before the value being set, e.g. [[:command, 'a'], :backspace]
-
2
def set(value, options={})
-
tag_name = self.tag_name
-
type = self[:type]
-
if (Array === value) && !self[:multiple]
-
raise ArgumentError.new "Value cannot be an Array when 'multiple' attribute is not present. Not a #{value.class}"
-
end
-
if tag_name == 'input' and type == 'radio'
-
click
-
elsif tag_name == 'input' and type == 'checkbox'
-
click if value ^ native.attribute('checked').to_s.eql?("true")
-
elsif tag_name == 'input' and type == 'file'
-
path_names = value.to_s.empty? ? [] : value
-
native.send_keys(*path_names)
-
elsif tag_name == 'textarea' or tag_name == 'input'
-
if self[:readonly]
-
warn "Attempt to set readonly element with value: #{value} \n *This will raise an exception in a future version of Capybara"
-
elsif value.to_s.empty?
-
native.clear
-
else
-
if options[:clear] == :backspace
-
# Clear field by sending the correct number of backspace keys.
-
backspaces = [:backspace] * self.value.to_s.length
-
native.send_keys(*(backspaces + [value.to_s]))
-
elsif options[:clear] == :none
-
native.send_keys(value.to_s)
-
elsif options[:clear].is_a? Array
-
native.send_keys(*options[:clear], value.to_s)
-
else
-
# Clear field by JavaScript assignment of the value property.
-
# Script can change a readonly element which user input cannot, so
-
# don't execute if readonly.
-
driver.browser.execute_script "arguments[0].value = ''", native
-
native.send_keys(value.to_s)
-
end
-
end
-
elsif native.attribute('isContentEditable')
-
#ensure we are focused on the element
-
script = <<-JS
-
var range = document.createRange();
-
arguments[0].focus();
-
range.selectNodeContents(arguments[0]);
-
window.getSelection().addRange(range);
-
JS
-
driver.browser.execute_script script, native
-
native.send_keys(value.to_s)
-
end
-
end
-
-
2
def select_option
-
native.click unless selected?
-
end
-
-
2
def unselect_option
-
if select_node['multiple'] != 'multiple' and select_node['multiple'] != 'true'
-
raise Capybara::UnselectNotAllowed, "Cannot unselect option from single select box."
-
end
-
native.click if selected?
-
end
-
-
2
def click
-
native.click
-
end
-
-
2
def right_click
-
driver.browser.action.context_click(native).perform
-
end
-
-
2
def double_click
-
driver.browser.action.double_click(native).perform
-
end
-
-
2
def send_keys(*args)
-
native.send_keys(*args)
-
end
-
-
2
def hover
-
driver.browser.action.move_to(native).perform
-
end
-
-
2
def drag_to(element)
-
driver.browser.action.drag_and_drop(native, element.native).perform
-
end
-
-
2
def tag_name
-
native.tag_name.downcase
-
end
-
-
2
def visible?
-
displayed = native.displayed?
-
displayed and displayed != "false"
-
end
-
-
2
def selected?
-
selected = native.selected?
-
selected and selected != "false"
-
end
-
-
2
def disabled?
-
!native.enabled?
-
end
-
-
2
alias :checked? :selected?
-
-
2
def find_xpath(locator)
-
native.find_elements(:xpath, locator).map { |n| self.class.new(driver, n) }
-
end
-
-
2
def find_css(locator)
-
native.find_elements(:css, locator).map { |n| self.class.new(driver, n) }
-
end
-
-
2
def ==(other)
-
native == other.native
-
end
-
-
2
def path
-
path = find_xpath('ancestor::*').reverse
-
path.unshift self
-
-
result = []
-
while node = path.shift
-
parent = path.first
-
-
if parent
-
siblings = parent.find_xpath(node.tag_name)
-
if siblings.size == 1
-
result.unshift node.tag_name
-
else
-
index = siblings.index(node)
-
result.unshift "#{node.tag_name}[#{index+1}]"
-
end
-
else
-
result.unshift node.tag_name
-
end
-
end
-
-
'/' + result.join('/')
-
end
-
-
2
private
-
-
# a reference to the select node if this is an option node
-
2
def select_node
-
find_xpath('./ancestor::select').first
-
end
-
end
-
# frozen_string_literal: true
-
2
require 'uri'
-
2
require 'net/http'
-
2
require 'rack'
-
-
2
module Capybara
-
2
class Server
-
2
class Middleware
-
2
class Counter
-
2
attr_reader :value
-
-
2
def initialize
-
@value = 0
-
@mutex = Mutex.new
-
end
-
-
2
def increment
-
@mutex.synchronize { @value += 1 }
-
end
-
-
2
def decrement
-
@mutex.synchronize { @value -= 1 }
-
end
-
end
-
-
2
attr_accessor :error
-
-
2
def initialize(app)
-
@app = app
-
@counter = Counter.new
-
end
-
-
2
def pending_requests?
-
@counter.value > 0
-
end
-
-
2
def call(env)
-
if env["PATH_INFO"] == "/__identify__"
-
[200, {}, [@app.object_id.to_s]]
-
else
-
@counter.increment
-
begin
-
@app.call(env)
-
rescue *Capybara.server_errors => e
-
@error = e unless @error
-
raise e
-
ensure
-
@counter.decrement
-
end
-
end
-
end
-
end
-
-
2
class << self
-
2
def ports
-
@ports ||= {}
-
end
-
end
-
-
2
attr_reader :app, :port, :host
-
-
2
def initialize(app, port=Capybara.server_port, host=Capybara.server_host)
-
@app = app
-
@middleware = Middleware.new(@app)
-
@server_thread = nil # suppress warnings
-
@host, @port = host, port
-
@port ||= Capybara::Server.ports[Capybara.reuse_server ? @app.object_id : @middleware.object_id]
-
@port ||= find_available_port(host)
-
end
-
-
2
def reset_error!
-
@middleware.error = nil
-
end
-
-
2
def error
-
@middleware.error
-
end
-
-
2
def responsive?
-
return false if @server_thread && @server_thread.join(0)
-
-
res = Net::HTTP.start(host, @port) { |http| http.get('/__identify__') }
-
-
if res.is_a?(Net::HTTPSuccess) or res.is_a?(Net::HTTPRedirection)
-
return res.body == @app.object_id.to_s
-
end
-
rescue SystemCallError
-
return false
-
end
-
-
2
def wait_for_pending_requests
-
Timeout.timeout(60) { sleep(0.01) while @middleware.pending_requests? }
-
rescue Timeout::Error
-
raise "Requests did not finish in 60 seconds"
-
end
-
-
2
def boot
-
unless responsive?
-
Capybara::Server.ports[Capybara.reuse_server ? @app.object_id : @middleware.object_id] = @port
-
-
@server_thread = Thread.new do
-
Capybara.server.call(@middleware, @port, @host)
-
end
-
-
Timeout.timeout(60) { @server_thread.join(0.1) until responsive? }
-
end
-
rescue Timeout::Error
-
raise "Rack application timed out during boot"
-
else
-
self
-
end
-
-
2
private
-
-
2
def find_available_port(host)
-
server = TCPServer.new(host, 0)
-
server.addr[1]
-
ensure
-
server.close if server
-
end
-
-
end
-
end
-
# frozen_string_literal: true
-
2
require 'capybara/session/matchers'
-
-
2
module Capybara
-
-
##
-
#
-
# The Session class represents a single user's interaction with the system. The Session can use
-
# any of the underlying drivers. A session can be initialized manually like this:
-
#
-
# session = Capybara::Session.new(:culerity, MyRackApp)
-
#
-
# The application given as the second argument is optional. When running Capybara against an external
-
# page, you might want to leave it out:
-
#
-
# session = Capybara::Session.new(:culerity)
-
# session.visit('http://www.google.com')
-
#
-
# Session provides a number of methods for controlling the navigation of the page, such as +visit+,
-
# +current_path, and so on. It also delegate a number of methods to a Capybara::Document, representing
-
# the current HTML document. This allows interaction:
-
#
-
# session.fill_in('q', :with => 'Capybara')
-
# session.click_button('Search')
-
# expect(session).to have_content('Capybara')
-
#
-
# When using capybara/dsl, the Session is initialized automatically for you.
-
#
-
2
class Session
-
2
include Capybara::SessionMatchers
-
-
2
NODE_METHODS = [
-
:all, :first, :attach_file, :text, :check, :choose,
-
:click_link_or_button, :click_button, :click_link, :field_labeled,
-
:fill_in, :find, :find_all, :find_button, :find_by_id, :find_field, :find_link,
-
:has_content?, :has_text?, :has_css?, :has_no_content?, :has_no_text?,
-
:has_no_css?, :has_no_xpath?, :resolve, :has_xpath?, :select, :uncheck,
-
:has_link?, :has_no_link?, :has_button?, :has_no_button?, :has_field?,
-
:has_no_field?, :has_checked_field?, :has_unchecked_field?,
-
:has_no_table?, :has_table?, :unselect, :has_select?, :has_no_select?,
-
:has_selector?, :has_no_selector?, :click_on, :has_no_checked_field?,
-
:has_no_unchecked_field?, :query, :assert_selector, :assert_no_selector,
-
:refute_selector, :assert_text, :assert_no_text
-
]
-
# @api private
-
2
DOCUMENT_METHODS = [
-
:title, :assert_title, :assert_no_title, :has_title?, :has_no_title?
-
]
-
2
SESSION_METHODS = [
-
:body, :html, :source, :current_url, :current_host, :current_path,
-
:execute_script, :evaluate_script, :visit, :go_back, :go_forward,
-
:within, :within_fieldset, :within_table, :within_frame, :current_window,
-
:windows, :open_new_window, :switch_to_window, :within_window, :window_opened_by,
-
:save_page, :save_and_open_page, :save_screenshot,
-
:save_and_open_screenshot, :reset_session!, :response_headers,
-
:status_code, :current_scope,
-
:assert_current_path, :assert_no_current_path, :has_current_path?, :has_no_current_path?
-
] + DOCUMENT_METHODS
-
2
MODAL_METHODS = [
-
:accept_alert, :accept_confirm, :dismiss_confirm, :accept_prompt,
-
:dismiss_prompt
-
]
-
2
DSL_METHODS = NODE_METHODS + SESSION_METHODS + MODAL_METHODS
-
-
2
attr_reader :mode, :app, :server
-
2
attr_accessor :synchronized
-
-
2
def initialize(mode, app=nil)
-
1
@mode = mode
-
1
@app = app
-
1
if Capybara.run_server and @app and driver.needs_server?
-
@server = Capybara::Server.new(@app).boot
-
else
-
1
@server = nil
-
end
-
1
@touched = false
-
end
-
-
2
def driver
-
@driver ||= begin
-
1
unless Capybara.drivers.has_key?(mode)
-
other_drivers = Capybara.drivers.keys.map { |key| key.inspect }
-
raise Capybara::DriverNotFoundError, "no driver called #{mode.inspect} was found, available drivers: #{other_drivers.join(', ')}"
-
end
-
1
Capybara.drivers[mode].call(app)
-
14
end
-
end
-
-
##
-
#
-
# Reset the session (i.e. remove cookies and navigate to blank page)
-
#
-
# This method does not:
-
#
-
# * accept modal dialogs if they are present (Selenium driver now does, others may not)
-
# * clear browser cache/HTML 5 local storage/IndexedDB/Web SQL database/etc.
-
# * modify state of the driver/underlying browser in any other way
-
#
-
# as doing so will result in performance downsides and it's not needed to do everything from the list above for most apps.
-
#
-
# If you want to do anything from the list above on a general basis you can:
-
#
-
# * write RSpec/Cucumber/etc. after hook
-
# * monkeypatch this method
-
# * use Ruby's `prepend` method
-
#
-
2
def reset!
-
6
if @touched
-
6
driver.reset!
-
6
@touched = false
-
end
-
6
@server.wait_for_pending_requests if @server
-
6
raise_server_error!
-
end
-
2
alias_method :cleanup!, :reset!
-
2
alias_method :reset_session!, :reset!
-
-
##
-
#
-
# Raise errors encountered in the server
-
#
-
2
def raise_server_error!
-
12
raise @server.error if Capybara.raise_server_errors and @server and @server.error
-
ensure
-
12
@server.reset_error! if @server
-
end
-
-
##
-
#
-
# Returns a hash of response headers. Not supported by all drivers (e.g. Selenium)
-
#
-
# @return [Hash{String => String}] A hash of response headers.
-
#
-
2
def response_headers
-
driver.response_headers
-
end
-
-
##
-
#
-
# Returns the current HTTP status code as an Integer. Not supported by all drivers (e.g. Selenium)
-
#
-
# @return [Integer] Current HTTP status code
-
#
-
2
def status_code
-
driver.status_code
-
end
-
-
##
-
#
-
# @return [String] A snapshot of the DOM of the current document, as it looks right now (potentially modified by JavaScript).
-
#
-
2
def html
-
driver.html
-
end
-
2
alias_method :body, :html
-
2
alias_method :source, :html
-
-
##
-
#
-
# @return [String] Path of the current page, without any domain information
-
#
-
2
def current_path
-
path = URI.parse(current_url).path
-
path if path and not path.empty?
-
end
-
-
##
-
#
-
# @return [String] Host of the current page
-
#
-
2
def current_host
-
uri = URI.parse(current_url)
-
"#{uri.scheme}://#{uri.host}" if uri.host
-
end
-
-
##
-
#
-
# @return [String] Fully qualified URL of the current page
-
#
-
2
def current_url
-
driver.current_url
-
end
-
-
##
-
#
-
# Navigate to the given URL. The URL can either be a relative URL or an absolute URL
-
# The behaviour of either depends on the driver.
-
#
-
# session.visit('/foo')
-
# session.visit('http://google.com')
-
#
-
# For drivers which can run against an external application, such as the selenium driver
-
# giving an absolute URL will navigate to that page. This allows testing applications
-
# running on remote servers. For these drivers, setting {Capybara.app_host} will make the
-
# remote server the default. For example:
-
#
-
# Capybara.app_host = 'http://google.com'
-
# session.visit('/') # visits the google homepage
-
#
-
# If {Capybara.always_include_port} is set to true and this session is running against
-
# a rack application, then the port that the rack application is running on will automatically
-
# be inserted into the URL. Supposing the app is running on port `4567`, doing something like:
-
#
-
# visit("http://google.com/test")
-
#
-
# Will actually navigate to `http://google.com:4567/test`.
-
#
-
# @param [#to_s] visit_uri The URL to navigate to. The parameter will be cast to a String.
-
#
-
2
def visit(visit_uri)
-
6
raise_server_error!
-
6
@touched = true
-
-
6
visit_uri = URI.parse(visit_uri.to_s)
-
-
6
uri_base = if @server
-
visit_uri.port = @server.port if Capybara.always_include_port && (visit_uri.port == visit_uri.default_port)
-
URI.parse(Capybara.app_host || "http://#{@server.host}:#{@server.port}")
-
else
-
6
Capybara.app_host && URI.parse(Capybara.app_host)
-
end
-
-
# TODO - this is only for compatability with previous 2.x behavior that concatenated
-
# Capybara.app_host and a "relative" path - Consider removing in 3.0
-
# @abotalov brought up a good point about this behavior potentially being useful to people
-
# deploying to a subdirectory and/or single page apps where only the url fragment changes
-
6
if visit_uri.scheme.nil? && uri_base
-
visit_uri.path = uri_base.path + visit_uri.path
-
end
-
-
6
visit_uri = uri_base.merge(visit_uri) unless uri_base.nil?
-
-
6
driver.visit(visit_uri.to_s)
-
end
-
-
##
-
#
-
# Move back a single entry in the browser's history.
-
#
-
2
def go_back
-
driver.go_back
-
end
-
-
##
-
#
-
# Move forward a single entry in the browser's history.
-
#
-
2
def go_forward
-
driver.go_forward
-
end
-
-
##
-
#
-
# Executes the given block within the context of a node. `within` takes the
-
# same options as `find`, as well as a block. For the duration of the
-
# block, any command to Capybara will be handled as though it were scoped
-
# to the given element.
-
#
-
# within(:xpath, '//div[@id="delivery-address"]') do
-
# fill_in('Street', :with => '12 Main Street')
-
# end
-
#
-
# Just as with `find`, if multiple elements match the selector given to
-
# `within`, an error will be raised, and just as with `find`, this
-
# behaviour can be controlled through the `:match` and `:exact` options.
-
#
-
# It is possible to omit the first parameter, in that case, the selector is
-
# assumed to be of the type set in Capybara.default_selector.
-
#
-
# within('div#delivery-address') do
-
# fill_in('Street', :with => '12 Main Street')
-
# end
-
#
-
# Note that a lot of uses of `within` can be replaced more succinctly with
-
# chaining:
-
#
-
# find('div#delivery-address').fill_in('Street', :with => '12 Main Street')
-
#
-
# @overload within(*find_args)
-
# @param (see Capybara::Node::Finders#all)
-
#
-
# @overload within(a_node)
-
# @param [Capybara::Node::Base] a_node The node in whose scope the block should be evaluated
-
#
-
# @raise [Capybara::ElementNotFound] If the scope can't be found before time expires
-
#
-
2
def within(*args)
-
new_scope = if args.first.is_a?(Capybara::Node::Base) then args.first else find(*args) end
-
begin
-
scopes.push(new_scope)
-
yield
-
ensure
-
scopes.pop
-
end
-
end
-
-
##
-
#
-
# Execute the given block within the a specific fieldset given the id or legend of that fieldset.
-
#
-
# @param [String] locator Id or legend of the fieldset
-
#
-
2
def within_fieldset(locator)
-
within :fieldset, locator do
-
yield
-
end
-
end
-
-
##
-
#
-
# Execute the given block within the a specific table given the id or caption of that table.
-
#
-
# @param [String] locator Id or caption of the table
-
#
-
2
def within_table(locator)
-
within :table, locator do
-
yield
-
end
-
end
-
-
##
-
#
-
# Execute the given block within the given iframe using given frame name or index.
-
# May be supported by not all drivers. Drivers that support it, may provide additional options.
-
#
-
# @overload within_frame(index)
-
# @param [Integer] index index of a frame
-
# @overload within_frame(name)
-
# @param [String] name name of a frame
-
#
-
2
def within_frame(frame_handle)
-
scopes.push(nil)
-
driver.within_frame(frame_handle) do
-
yield
-
end
-
ensure
-
scopes.pop
-
end
-
-
##
-
# @return [Capybara::Window] current window
-
#
-
2
def current_window
-
Window.new(self, driver.current_window_handle)
-
end
-
-
##
-
# Get all opened windows.
-
# The order of windows in returned array is not defined.
-
# The driver may sort windows by their creation time but it's not required.
-
#
-
# @return [Array<Capybara::Window>] an array of all windows
-
#
-
2
def windows
-
driver.window_handles.map do |handle|
-
Window.new(self, handle)
-
end
-
end
-
-
##
-
# Open new window.
-
# Current window doesn't change as the result of this call.
-
# It should be switched to explicitly.
-
#
-
# @return [Capybara::Window] window that has been opened
-
#
-
2
def open_new_window
-
window_opened_by do
-
driver.open_new_window
-
end
-
end
-
-
##
-
# @overload switch_to_window(&block)
-
# Switches to the first window for which given block returns a value other than false or nil.
-
# If window that matches block can't be found, the window will be switched back and `WindowError` will be raised.
-
# @example
-
# window = switch_to_window { title == 'Page title' }
-
# @raise [Capybara::WindowError] if no window matches given block
-
# @overload switch_to_window(window)
-
# @param window [Capybara::Window] window that should be switched to
-
# @raise [Capybara::Driver::Base#no_such_window_error] if unexistent (e.g. closed) window was passed
-
#
-
# @return [Capybara::Window] window that has been switched to
-
# @raise [Capybara::ScopeError] if this method is invoked inside `within`,
-
# `within_frame` or `within_window` methods
-
# @raise [ArgumentError] if both or neither arguments were provided
-
#
-
2
def switch_to_window(window = nil, options= {})
-
options, window = window, nil if window.is_a? Hash
-
-
block_given = block_given?
-
if window && block_given
-
raise ArgumentError, "`switch_to_window` can take either a block or a window, not both"
-
elsif !window && !block_given
-
raise ArgumentError, "`switch_to_window`: either window or block should be provided"
-
elsif scopes.size > 1
-
raise Capybara::ScopeError, "`switch_to_window` is not supposed to be invoked from "\
-
"`within`'s, `within_frame`'s' or `within_window`'s' block."
-
end
-
-
if window
-
driver.switch_to_window(window.handle)
-
window
-
else
-
wait_time = Capybara::Queries::SelectorQuery.new(options).wait
-
document.synchronize(wait_time, errors: [Capybara::WindowError]) do
-
original_window_handle = driver.current_window_handle
-
begin
-
driver.window_handles.each do |handle|
-
driver.switch_to_window handle
-
if yield
-
return Window.new(self, handle)
-
end
-
end
-
rescue => e
-
driver.switch_to_window(original_window_handle)
-
raise e
-
else
-
driver.switch_to_window(original_window_handle)
-
raise Capybara::WindowError, "Could not find a window matching block/lambda"
-
end
-
end
-
end
-
end
-
-
##
-
# This method does the following:
-
#
-
# 1. Switches to the given window (it can be located by window instance/lambda/string).
-
# 2. Executes the given block (within window located at previous step).
-
# 3. Switches back (this step will be invoked even if exception will happen at second step)
-
#
-
# @overload within_window(window) { do_something }
-
# @param window [Capybara::Window] instance of `Capybara::Window` class
-
# that will be switched to
-
# @raise [driver#no_such_window_error] if unexistent (e.g. closed) window was passed
-
# @overload within_window(proc_or_lambda) { do_something }
-
# @param lambda [Proc] lambda. First window for which lambda
-
# returns a value other than false or nil will be switched to.
-
# @example
-
# within_window(->{ page.title == 'Page title' }) { click_button 'Submit' }
-
# @raise [Capybara::WindowError] if no window matching lambda was found
-
# @overload within_window(string) { do_something }
-
# @deprecated Pass window or lambda instead
-
# @param [String] handle, name, url or title of the window
-
#
-
# @raise [Capybara::ScopeError] if this method is invoked inside `within`,
-
# `within_frame` or `within_window` methods
-
# @return value returned by the block
-
#
-
2
def within_window(window_or_handle)
-
if window_or_handle.instance_of?(Capybara::Window)
-
original = current_window
-
switch_to_window(window_or_handle) unless original == window_or_handle
-
scopes << nil
-
begin
-
yield
-
ensure
-
@scopes.pop
-
switch_to_window(original) unless original == window_or_handle
-
end
-
elsif window_or_handle.is_a?(Proc)
-
original = current_window
-
switch_to_window { window_or_handle.call }
-
scopes << nil
-
begin
-
yield
-
ensure
-
@scopes.pop
-
switch_to_window(original)
-
end
-
else
-
offending_line = caller.first
-
file_line = offending_line.match(/^(.+?):(\d+)/)[0]
-
warn "DEPRECATION WARNING: Passing string argument to #within_window is deprecated. "\
-
"Pass window object or lambda. (called from #{file_line})"
-
begin
-
scopes << nil
-
driver.within_window(window_or_handle) { yield }
-
ensure
-
@scopes.pop
-
end
-
end
-
end
-
-
##
-
# Get the window that has been opened by the passed block.
-
# It will wait for it to be opened (in the same way as other Capybara methods wait).
-
# It's better to use this method than `windows.last`
-
# {https://dvcs.w3.org/hg/webdriver/raw-file/default/webdriver-spec.html#h_note_10 as order of windows isn't defined in some drivers}
-
#
-
# @param options [Hash]
-
# @option options [Numeric] :wait (Capybara.default_max_wait_time) maximum wait time
-
# @return [Capybara::Window] the window that has been opened within a block
-
# @raise [Capybara::WindowError] if block passed to window hasn't opened window
-
# or opened more than one window
-
#
-
2
def window_opened_by(options = {}, &block)
-
old_handles = driver.window_handles
-
block.call
-
-
wait_time = Capybara::Queries::SelectorQuery.new(options).wait
-
document.synchronize(wait_time, errors: [Capybara::WindowError]) do
-
opened_handles = (driver.window_handles - old_handles)
-
if opened_handles.size != 1
-
raise Capybara::WindowError, "block passed to #window_opened_by "\
-
"opened #{opened_handles.size} windows instead of 1"
-
end
-
Window.new(self, opened_handles.first)
-
end
-
end
-
-
##
-
#
-
# Execute the given script, not returning a result. This is useful for scripts that return
-
# complex objects, such as jQuery statements. +execute_script+ should be used over
-
# +evaluate_script+ whenever possible.
-
#
-
# @param [String] script A string of JavaScript to execute
-
#
-
2
def execute_script(script)
-
@touched = true
-
driver.execute_script(script)
-
end
-
-
##
-
#
-
# Evaluate the given JavaScript and return the result. Be careful when using this with
-
# scripts that return complex objects, such as jQuery statements. +execute_script+ might
-
# be a better alternative.
-
#
-
# @param [String] script A string of JavaScript to evaluate
-
# @return [Object] The result of the evaluated JavaScript (may be driver specific)
-
#
-
2
def evaluate_script(script)
-
@touched = true
-
driver.evaluate_script(script)
-
end
-
-
##
-
#
-
# Execute the block, accepting a alert.
-
#
-
# @!macro modal_params
-
# @overload $0(text, options = {}, &blk)
-
# @param text [String, Regexp] Text or regex to match against the text in the modal. If not provided any modal is matched
-
# @overload $0(options = {}, &blk)
-
# @option options [Numeric] :wait (Capybara.default_max_wait_time) Maximum time to wait for the modal to appear after executing the block.
-
# @return [String] the message shown in the modal
-
# @raise [Capybara::ModalNotFound] if modal dialog hasn't been found
-
#
-
2
def accept_alert(text_or_options=nil, options={}, &blk)
-
text_or_options, options = nil, text_or_options if text_or_options.is_a?(Hash)
-
options[:text] ||= text_or_options unless text_or_options.nil?
-
options[:wait] ||= Capybara.default_max_wait_time
-
-
driver.accept_modal(:alert, options, &blk)
-
end
-
-
##
-
#
-
# Execute the block, accepting a confirm.
-
#
-
# @macro modal_params
-
#
-
2
def accept_confirm(text_or_options=nil, options={}, &blk)
-
text_or_options, options = nil, text_or_options if text_or_options.is_a?(Hash)
-
options[:text] ||= text_or_options unless text_or_options.nil?
-
options[:wait] ||= Capybara.default_max_wait_time
-
-
driver.accept_modal(:confirm, options, &blk)
-
end
-
-
##
-
#
-
# Execute the block, dismissing a confirm.
-
#
-
# @macro modal_params
-
#
-
2
def dismiss_confirm(text_or_options=nil, options={}, &blk)
-
text_or_options, options = nil, text_or_options if text_or_options.is_a?(Hash)
-
options[:text] ||= text_or_options unless text_or_options.nil?
-
options[:wait] ||= Capybara.default_max_wait_time
-
-
driver.dismiss_modal(:confirm, options, &blk)
-
end
-
-
##
-
#
-
# Execute the block, accepting a prompt, optionally responding to the prompt.
-
#
-
# @macro modal_params
-
# @option options [String] :with Response to provide to the prompt
-
#
-
2
def accept_prompt(text_or_options=nil, options={}, &blk)
-
text_or_options, options = nil, text_or_options if text_or_options.is_a?(Hash)
-
options[:text] ||= text_or_options unless text_or_options.nil?
-
options[:wait] ||= Capybara.default_max_wait_time
-
-
driver.accept_modal(:prompt, options, &blk)
-
end
-
-
##
-
#
-
# Execute the block, dismissing a prompt.
-
#
-
# @macro modal_params
-
#
-
2
def dismiss_prompt(text_or_options=nil, options={}, &blk)
-
text_or_options, options = nil, text_or_options if text_or_options.is_a?(Hash)
-
options[:text] ||= text_or_options unless text_or_options.nil?
-
options[:wait] ||= Capybara.default_max_wait_time
-
-
driver.dismiss_modal(:prompt, options, &blk)
-
end
-
-
##
-
#
-
# Save a snapshot of the page. If `Capybara.asset_host` is set it will inject `base` tag
-
# pointing to `asset_host`.
-
#
-
# If invoked without arguments it will save file to `Capybara.save_path`
-
# and file will be given randomly generated filename. If invoked with a relative path
-
# the path will be relative to `Capybara.save_path`, which is different from
-
# the previous behavior with `Capybara.save_and_open_page_path` where the relative path was
-
# relative to Dir.pwd
-
#
-
# @param [String] path the path to where it should be saved
-
# @return [String] the path to which the file was saved
-
#
-
2
def save_page(path = nil)
-
path = prepare_path(path, 'html')
-
File.write(path, Capybara::Helpers.inject_asset_host(body), mode: 'wb')
-
path
-
end
-
-
##
-
#
-
# Save a snapshot of the page and open it in a browser for inspection.
-
#
-
# If invoked without arguments it will save file to `Capybara.save_path`
-
# and file will be given randomly generated filename. If invoked with a relative path
-
# the path will be relative to `Capybara.save_path`, which is different from
-
# the previous behavior with `Capybara.save_and_open_page_path` where the relative path was
-
# relative to Dir.pwd
-
#
-
# @param [String] path the path to where it should be saved
-
#
-
2
def save_and_open_page(path = nil)
-
path = save_page(path)
-
open_file(path)
-
end
-
-
##
-
#
-
# Save a screenshot of page.
-
#
-
# If invoked without arguments it will save file to `Capybara.save_path`
-
# and file will be given randomly generated filename. If invoked with a relative path
-
# the path will be relative to `Capybara.save_path`, which is different from
-
# the previous behavior with `Capybara.save_and_open_page_path` where the relative path was
-
# relative to Dir.pwd
-
#
-
# @param [String] path the path to where it should be saved
-
# @param [Hash] options a customizable set of options
-
# @return [String] the path to which the file was saved
-
2
def save_screenshot(path = nil, options = {})
-
path = prepare_path(path, 'png')
-
driver.save_screenshot(path, options)
-
path
-
end
-
-
##
-
#
-
# Save a screenshot of the page and open it for inspection.
-
#
-
# If invoked without arguments it will save file to `Capybara.save_path`
-
# and file will be given randomly generated filename. If invoked with a relative path
-
# the path will be relative to `Capybara.save_path`, which is different from
-
# the previous behavior with `Capybara.save_and_open_page_path` where the relative path was
-
# relative to Dir.pwd
-
#
-
# @param [String] path the path to where it should be saved
-
# @param [Hash] options a customizable set of options
-
#
-
2
def save_and_open_screenshot(path = nil, options = {})
-
path = save_screenshot(path, options)
-
open_file(path)
-
end
-
-
2
def document
-
7
@document ||= Capybara::Node::Document.new(self, driver)
-
end
-
-
2
NODE_METHODS.each do |method|
-
104
define_method method do |*args, &block|
-
7
@touched = true
-
7
current_scope.send(method, *args, &block)
-
end
-
end
-
-
2
DOCUMENT_METHODS.each do |method|
-
10
define_method method do |*args, &block|
-
document.send(method, *args, &block)
-
end
-
end
-
-
2
def inspect
-
%(#<Capybara::Session>)
-
end
-
-
2
def current_scope
-
7
scopes.last || document
-
end
-
-
2
private
-
-
2
def open_file(path)
-
begin
-
require "launchy"
-
Launchy.open(path)
-
rescue LoadError
-
warn "File saved to #{path}."
-
warn "Please install the launchy gem to open the file automatically."
-
end
-
end
-
-
2
def prepare_path(path, extension)
-
if Capybara.save_path || Capybara.save_and_open_page_path.nil?
-
path = File.expand_path(path || default_fn(extension), Capybara.save_path)
-
else
-
path = File.expand_path(default_fn(extension), Capybara.save_and_open_page_path) if path.nil?
-
end
-
FileUtils.mkdir_p(File.dirname(path))
-
path
-
end
-
-
2
def default_fn(extension)
-
timestamp = Time.new.strftime("%Y%m%d%H%M%S")
-
path = "capybara-#{timestamp}#{rand(10**10)}.#{extension}"
-
end
-
-
2
def scopes
-
7
@scopes ||= [nil]
-
end
-
end
-
end
-
# frozen_string_literal: true
-
2
module Capybara
-
2
module SessionMatchers
-
##
-
# Asserts that the page has the given path.
-
# By default this will compare against the path+query portion of the full url
-
#
-
# @!macro current_path_query_params
-
# @overload $0(string, options = {})
-
# @param string [String] The string that the current 'path' should equal
-
# @overload $0(regexp, options = {})
-
# @param regexp [Regexp] The regexp that the current 'path' should match to
-
# @option options [Numeric] :wait (Capybara.default_max_wait_time) Maximum time that Capybara will wait for the current path to eq/match given string/regexp argument
-
# @option options [Boolean] :url (false) Whether the compare should be done against the full url
-
# @option options [Boolean] :only_path (false) Whether the compare should be done against just the path protion of the url
-
# @raise [Capybara::ExpectationNotMet] if the assertion hasn't succeeded during wait time
-
# @return [true]
-
#
-
2
def assert_current_path(path, options={})
-
query = Capybara::Queries::CurrentPathQuery.new(path, options)
-
document.synchronize(query.wait) do
-
unless query.resolves_for?(self)
-
raise Capybara::ExpectationNotMet, query.failure_message
-
end
-
end
-
return true
-
end
-
-
##
-
# Asserts that the page doesn't have the given path.
-
#
-
# @macro current_path_query_params
-
# @raise [Capybara::ExpectationNotMet] if the assertion hasn't succeeded during wait time
-
# @return [true]
-
#
-
2
def assert_no_current_path(path, options={})
-
query = Capybara::Queries::CurrentPathQuery.new(path, options)
-
document.synchronize(query.wait) do
-
if query.resolves_for?(self)
-
raise Capybara::ExpectationNotMet, query.negative_failure_message
-
end
-
end
-
return true
-
end
-
-
##
-
# Checks if the page has the given path.
-
#
-
# @macro current_path_query_params
-
# @return [Boolean]
-
#
-
2
def has_current_path?(path, options={})
-
assert_current_path(path, options)
-
rescue Capybara::ExpectationNotMet
-
return false
-
end
-
-
##
-
# Checks if the page doesn't have the given path.
-
#
-
# @macro current_path_query_params
-
# @return [Boolean]
-
#
-
2
def has_no_current_path?(path, options={})
-
assert_no_current_path(path, options)
-
rescue Capybara::ExpectationNotMet
-
return false
-
end
-
end
-
end
-
# frozen_string_literal: true
-
2
module Capybara
-
2
VERSION = '2.7.1'
-
end
-
# frozen_string_literal: true
-
2
module Capybara
-
##
-
# The Window class represents a browser window.
-
#
-
# You can get an instance of the class by calling either of:
-
#
-
# * {Capybara::Session#windows}
-
# * {Capybara::Session#current_window}
-
# * {Capybara::Session#window_opened_by}
-
# * {Capybara::Session#switch_to_window}
-
#
-
# Note that some drivers (e.g. Selenium) support getting size of/resizing/closing only
-
# current window. So if you invoke such method for:
-
#
-
# * window that is current, Capybara will make 2 Selenium method invocations
-
# (get handle of current window + get size/resize/close).
-
# * window that is not current, Capybara will make 4 Selenium method invocations
-
# (get handle of current window + switch to given handle + get size/resize/close + switch to original handle)
-
#
-
2
class Window
-
# @return [String] a string that uniquely identifies window within session
-
2
attr_reader :handle
-
-
# @return [Capybara::Session] session that this window belongs to
-
2
attr_reader :session
-
-
# @api private
-
2
def initialize(session, handle)
-
@session = session
-
@driver = session.driver
-
@handle = handle
-
end
-
-
##
-
# @return [Boolean] whether the window is not closed
-
2
def exists?
-
@driver.window_handles.include?(@handle)
-
end
-
-
##
-
# @return [Boolean] whether the window is closed
-
2
def closed?
-
!exists?
-
end
-
-
##
-
# @return [Boolean] whether this window is the window in which commands are being executed
-
2
def current?
-
@driver.current_window_handle == @handle
-
rescue @driver.no_such_window_error
-
false
-
end
-
-
##
-
# Close window.
-
#
-
# If this method was called for window that is current, then after calling this method
-
# future invocations of other Capybara methods should raise
-
# `session.driver.no_such_window_error` until another window will be switched to.
-
#
-
# @!macro about_current
-
# If this method was called for window that is not current, then after calling this method
-
# current window shouldn remain the same as it was before calling this method.
-
#
-
2
def close
-
@driver.close_window(handle)
-
end
-
-
##
-
# Get window size.
-
#
-
# @macro about_current
-
# @return [Array<(Fixnum, Fixnum)>] an array with width and height
-
#
-
2
def size
-
@driver.window_size(handle)
-
end
-
-
##
-
# Resize window.
-
#
-
# @macro about_current
-
# @param width [String] the new window width in pixels
-
# @param height [String] the new window height in pixels
-
#
-
2
def resize_to(width, height)
-
@driver.resize_window_to(handle, width, height)
-
end
-
-
##
-
# Maximize window.
-
#
-
# If a particular driver (e.g. headless driver) doesn't have concept of maximizing it
-
# may not support this method.
-
#
-
# @macro about_current
-
#
-
2
def maximize
-
@driver.maximize_window(handle)
-
end
-
-
2
def eql?(other)
-
other.kind_of?(self.class) && @session == other.session && @handle == other.handle
-
end
-
2
alias_method :==, :eql?
-
-
2
def hash
-
@session.hash ^ @handle.hash
-
end
-
-
2
def inspect
-
"#<Window @handle=#{@handle.inspect}>"
-
end
-
-
2
private
-
-
2
def raise_unless_current(what)
-
unless current?
-
raise Capybara::WindowError, "#{what} not current window is not possible."
-
end
-
end
-
end
-
end
-
# encoding: utf-8
-
-
2
require 'fileutils'
-
2
require 'active_support/core_ext/object/blank'
-
2
require 'active_support/core_ext/class/attribute'
-
2
require 'active_support/concern'
-
-
2
module CarrierWave
-
-
2
class << self
-
2
attr_accessor :root, :base_path
-
-
2
def configure(&block)
-
CarrierWave::Uploader::Base.configure(&block)
-
end
-
-
2
def clean_cached_files!(seconds=60*60*24)
-
CarrierWave::Uploader::Base.clean_cached_files!(seconds)
-
end
-
end
-
-
end
-
-
2
if defined?(Merb)
-
-
CarrierWave.root = Merb.dir_for(:public)
-
Merb::BootLoader.before_app_loads do
-
# Setup path for uploaders and load all of them before classes are loaded
-
Merb.push_path(:uploaders, Merb.root / 'app' / 'uploaders', '*.rb')
-
Dir.glob(File.join(Merb.load_paths[:uploaders])).each {|f| require f }
-
end
-
-
elsif defined?(Rails)
-
-
2
module CarrierWave
-
2
class Railtie < Rails::Railtie
-
2
initializer "carrierwave.setup_paths" do
-
2
CarrierWave.root = Rails.root.join(Rails.public_path).to_s
-
2
CarrierWave.base_path = ENV['RAILS_RELATIVE_URL_ROOT']
-
end
-
-
2
initializer "carrierwave.active_record" do
-
2
ActiveSupport.on_load :active_record do
-
2
require 'carrierwave/orm/activerecord'
-
end
-
end
-
-
##
-
# Loads the Carrierwave locale files before the Rails application locales
-
# letting the Rails application overrite the carrierwave locale defaults
-
2
config.before_configuration do
-
2
I18n.load_path << File.join(File.dirname(__FILE__), "carrierwave", "locale", 'en.yml')
-
end
-
end
-
end
-
-
elsif defined?(Sinatra)
-
if defined?(Padrino) && defined?(PADRINO_ROOT)
-
CarrierWave.root = File.join(PADRINO_ROOT, "public")
-
else
-
-
CarrierWave.root = if Sinatra::Application.respond_to?(:public_folder)
-
# Sinatra >= 1.3
-
Sinatra::Application.public_folder
-
else
-
# Sinatra < 1.3
-
Sinatra::Application.public
-
end
-
end
-
end
-
-
2
require "carrierwave/utilities"
-
2
require "carrierwave/error"
-
2
require "carrierwave/sanitized_file"
-
2
require "carrierwave/mount"
-
2
require "carrierwave/processing"
-
2
require "carrierwave/version"
-
2
require "carrierwave/storage"
-
2
require "carrierwave/uploader"
-
2
require "carrierwave/compatibility/paperclip"
-
2
require "carrierwave/test/matchers"
-
# encoding: utf-8
-
-
2
module CarrierWave
-
2
module Compatibility
-
-
##
-
# Mix this module into an Uploader to make it mimic Paperclip's storage paths
-
# This will make your Uploader use the same default storage path as paperclip
-
# does. If you need to override it, you can override the +paperclip_path+ method
-
# and provide a Paperclip style path:
-
#
-
# class MyUploader < CarrierWave::Uploader::Base
-
# include CarrierWave::Compatibility::Paperclip
-
#
-
# def paperclip_path
-
# ":rails_root/public/uploads/:id/:attachment/:style_:basename.:extension"
-
# end
-
# end
-
#
-
# ---
-
#
-
# This file contains code taken from Paperclip
-
#
-
# LICENSE
-
#
-
# The MIT License
-
#
-
# Copyright (c) 2008 Jon Yurek and thoughtbot, inc.
-
#
-
# Permission is hereby granted, free of charge, to any person obtaining a copy
-
# of this software and associated documentation files (the "Software"), to deal
-
# in the Software without restriction, including without limitation the rights
-
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-
# copies of the Software, and to permit persons to whom the Software is
-
# furnished to do so, subject to the following conditions:
-
#
-
# The above copyright notice and this permission notice shall be included in
-
# all copies or substantial portions of the Software.
-
#
-
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-
# THE SOFTWARE.
-
#
-
2
module Paperclip
-
2
extend ActiveSupport::Concern
-
-
2
DEFAULT_MAPPINGS = {
-
:rails_root => lambda{|u, f| Rails.root.to_s },
-
:rails_env => lambda{|u, f| Rails.env },
-
:id_partition => lambda{|u, f| ("%09d" % u.model.id).scan(/\d{3}/).join("/")},
-
:id => lambda{|u, f| u.model.id },
-
:attachment => lambda{|u, f| u.mounted_as.to_s.downcase.pluralize },
-
:style => lambda{|u, f| u.paperclip_style },
-
:basename => lambda{|u, f| u.filename.gsub(/#{File.extname(u.filename)}$/, "") },
-
:extension => lambda{|u, d| File.extname(u.filename).gsub(/^\.+/, "")},
-
:class => lambda{|u, f| u.model.class.name.underscore.pluralize}
-
}
-
-
2
included do
-
attr_accessor :filename
-
class_attribute :mappings
-
self.mappings ||= DEFAULT_MAPPINGS.dup
-
end
-
-
2
def store_path(for_file=filename)
-
path = paperclip_path
-
self.filename = for_file
-
path ||= File.join(*[store_dir, paperclip_style.to_s, for_file].compact)
-
interpolate_paperclip_path(path)
-
end
-
-
2
def store_dir
-
":rails_root/public/system/:attachment/:id"
-
end
-
-
2
def paperclip_default_style
-
:original
-
end
-
-
2
def paperclip_path
-
end
-
-
2
def paperclip_style
-
version_name || paperclip_default_style
-
end
-
-
2
module ClassMethods
-
2
def interpolate(sym, &block)
-
mappings[sym] = block
-
end
-
end
-
-
2
private
-
2
def interpolate_paperclip_path(path)
-
mappings.each_pair.inject(path) do |agg, pair|
-
agg.gsub(":#{pair[0]}") { pair[1].call(self, self.paperclip_style).to_s }
-
end
-
end
-
end # Paperclip
-
end # Compatibility
-
end # CarrierWave
-
2
module CarrierWave
-
2
class UploadError < StandardError; end
-
2
class IntegrityError < UploadError; end
-
2
class InvalidParameter < UploadError; end
-
2
class ProcessingError < UploadError; end
-
2
class DownloadError < UploadError; end
-
end
-
# encoding: utf-8
-
-
2
module CarrierWave
-
-
##
-
# If a Class is extended with this module, it gains the mount_uploader
-
# method, which is used for mapping attributes to uploaders and allowing
-
# easy assignment.
-
#
-
# You can use mount_uploader with pretty much any class, however it is
-
# intended to be used with some kind of persistent storage, like an ORM.
-
# If you want to persist the uploaded files in a particular Class, it
-
# needs to implement a `read_uploader` and a `write_uploader` method.
-
#
-
2
module Mount
-
-
##
-
# === Returns
-
#
-
# [Hash{Symbol => CarrierWave}] what uploaders are mounted on which columns
-
#
-
2
def uploaders
-
1186
@uploaders ||= superclass.respond_to?(:uploaders) ? superclass.uploaders.dup : {}
-
end
-
-
2
def uploader_options
-
1186
@uploader_options ||= superclass.respond_to?(:uploader_options) ? superclass.uploader_options.dup : {}
-
end
-
-
##
-
# Return a particular option for a particular uploader
-
#
-
# === Parameters
-
#
-
# [column (Symbol)] The column the uploader is mounted at
-
# [option (Symbol)] The option, e.g. validate_integrity
-
#
-
# === Returns
-
#
-
# [Object] The option value
-
#
-
2
def uploader_option(column, option)
-
983
if uploader_options[column].has_key?(option)
-
uploader_options[column][option]
-
else
-
983
uploaders[column].send(option)
-
end
-
end
-
-
##
-
# Mounts the given uploader on the given column. This means that assigning
-
# and reading from the column will upload and retrieve files. Supposing
-
# that a User class has an uploader mounted on image, you can assign and
-
# retrieve files like this:
-
#
-
# @user.image # => <Uploader>
-
# @user.image.store!(some_file_object)
-
#
-
# @user.image.url # => '/some_url.png'
-
#
-
# It is also possible (but not recommended) to omit the uploader, which
-
# will create an anonymous uploader class.
-
#
-
# Passing a block makes it possible to customize the uploader. This can be
-
# convenient for brevity, but if there is any significatnt logic in the
-
# uploader, you should do the right thing and have it in its own file.
-
#
-
# === Added instance methods
-
#
-
# Supposing a class has used +mount_uploader+ to mount an uploader on a column
-
# named +image+, in that case the following methods will be added to the class:
-
#
-
# [image] Returns an instance of the uploader only if anything has been uploaded
-
# [image=] Caches the given file
-
#
-
# [image_url] Returns the url to the uploaded file
-
#
-
# [image_cache] Returns a string that identifies the cache location of the file
-
# [image_cache=] Retrieves the file from the cache based on the given cache name
-
#
-
# [remote_image_url] Returns previously cached remote url
-
# [remote_image_url=] Retrieve the file from the remote url
-
#
-
# [remove_image] An attribute reader that can be used with a checkbox to mark a file for removal
-
# [remove_image=] An attribute writer that can be used with a checkbox to mark a file for removal
-
# [remove_image?] Whether the file should be removed when store_image! is called.
-
#
-
# [store_image!] Stores a file that has been assigned with +image=+
-
# [remove_image!] Removes the uploaded file from the filesystem.
-
#
-
# [image_integrity_error] Returns an error object if the last file to be assigned caused an integrity error
-
# [image_processing_error] Returns an error object if the last file to be assigned caused a processing error
-
# [image_download_error] Returns an error object if the last file to be remotely assigned caused a download error
-
#
-
# [write_image_identifier] Uses the write_uploader method to set the identifier.
-
# [image_identifier] Reads out the identifier of the file
-
#
-
# === Parameters
-
#
-
# [column (Symbol)] the attribute to mount this uploader on
-
# [uploader (CarrierWave::Uploader)] the uploader class to mount
-
# [options (Hash{Symbol => Object})] a set of options
-
# [&block (Proc)] customize anonymous uploaders
-
#
-
# === Options
-
#
-
# [:mount_on => Symbol] if the name of the column to be serialized to differs you can override it using this option
-
# [:ignore_integrity_errors => Boolean] if set to true, integrity errors will result in caching failing silently
-
# [:ignore_processing_errors => Boolean] if set to true, processing errors will result in caching failing silently
-
#
-
# === Examples
-
#
-
# Mounting uploaders on different columns.
-
#
-
# class Song
-
# mount_uploader :lyrics, LyricsUploader
-
# mount_uploader :alternative_lyrics, LyricsUploader
-
# mount_uploader :file, SongUploader
-
# end
-
#
-
# This will add an anonymous uploader with only the default settings:
-
#
-
# class Data
-
# mount_uploader :csv
-
# end
-
#
-
# this will add an anonymous uploader overriding the store_dir:
-
#
-
# class Product
-
# mount_uploader :blueprint do
-
# def store_dir
-
# 'blueprints'
-
# end
-
# end
-
# end
-
#
-
2
def mount_uploader(column, uploader=nil, options={}, &block)
-
4
include CarrierWave::Mount::Extension
-
-
4
uploader = build_uploader(uploader, &block)
-
4
uploaders[column.to_sym] = uploader
-
4
uploader_options[column.to_sym] = options
-
-
# Make sure to write over accessors directly defined on the class.
-
# Simply super to the included module below.
-
4
class_eval <<-RUBY, __FILE__, __LINE__+1
-
def #{column}; super; end
-
def #{column}=(new_file); super; end
-
RUBY
-
-
# Mixing this in as a Module instead of class_evaling directly, so we
-
# can maintain the ability to super to any of these methods from within
-
# the class.
-
4
mod = Module.new
-
4
include mod
-
4
mod.class_eval <<-RUBY, __FILE__, __LINE__+1
-
-
def #{column}
-
_mounter(:#{column}).uploader
-
end
-
-
def #{column}=(new_file)
-
_mounter(:#{column}).cache(new_file)
-
end
-
-
def #{column}?
-
_mounter(:#{column}).present?
-
end
-
-
def #{column}_url(*args)
-
_mounter(:#{column}).url(*args)
-
end
-
-
def #{column}_cache
-
_mounter(:#{column}).cache_name
-
end
-
-
def #{column}_cache=(cache_name)
-
_mounter(:#{column}).cache_name = cache_name
-
end
-
-
def remote_#{column}_url
-
_mounter(:#{column}).remote_url
-
end
-
-
def remote_#{column}_url=(url)
-
_mounter(:#{column}).remote_url = url
-
end
-
-
def remove_#{column}
-
_mounter(:#{column}).remove
-
end
-
-
def remove_#{column}!
-
_mounter(:#{column}).remove!
-
end
-
-
def remove_#{column}=(value)
-
_mounter(:#{column}).remove = value
-
end
-
-
def remove_#{column}?
-
_mounter(:#{column}).remove?
-
end
-
-
def store_#{column}!
-
_mounter(:#{column}).store!
-
end
-
-
def #{column}_integrity_error
-
_mounter(:#{column}).integrity_error
-
end
-
-
def #{column}_processing_error
-
_mounter(:#{column}).processing_error
-
end
-
-
def #{column}_download_error
-
_mounter(:#{column}).download_error
-
end
-
-
def write_#{column}_identifier
-
_mounter(:#{column}).write_identifier
-
end
-
-
def #{column}_identifier
-
_mounter(:#{column}).identifier
-
end
-
-
def store_previous_model_for_#{column}
-
serialization_column = _mounter(:#{column}).serialization_column
-
-
if #{column}.remove_previously_stored_files_after_update && send(:"\#{serialization_column}_changed?")
-
@previous_model_for_#{column} ||= self.find_previous_model_for_#{column}
-
end
-
end
-
-
def find_previous_model_for_#{column}
-
self.class.find(to_key.first)
-
end
-
-
def remove_previously_stored_#{column}
-
if @previous_model_for_#{column} && @previous_model_for_#{column}.#{column}.path != #{column}.path
-
@previous_model_for_#{column}.#{column}.remove!
-
@previous_model_for_#{column} = nil
-
end
-
end
-
-
def mark_remove_#{column}_false
-
_mounter(:#{column}).remove = false
-
end
-
-
RUBY
-
end
-
-
2
private
-
-
2
def build_uploader(uploader, &block)
-
4
return uploader if uploader && !block_given?
-
-
uploader = Class.new(uploader || CarrierWave::Uploader::Base)
-
const_set("Uploader#{uploader.object_id}".gsub('-', '_'), uploader)
-
-
if block_given?
-
uploader.class_eval(&block)
-
uploader.recursively_apply_block_to_versions(&block)
-
end
-
-
uploader
-
end
-
-
2
module Extension
-
-
##
-
# overwrite this to read from a serialized attribute
-
#
-
2
def read_uploader(column); end
-
-
##
-
# overwrite this to write to a serialized attribute
-
#
-
2
def write_uploader(column, identifier); end
-
-
2
private
-
-
2
def _mounter(column)
-
# We cannot memoize in frozen objects :(
-
1556
return Mounter.new(self, column) if frozen?
-
1556
@_mounters ||= {}
-
1556
@_mounters[column] ||= Mounter.new(self, column)
-
end
-
-
end # Extension
-
-
# this is an internal class, used by CarrierWave::Mount so that
-
# we don't pollute the model with a lot of methods.
-
2
class Mounter #:nodoc:
-
2
attr_reader :column, :record, :remote_url, :integrity_error, :processing_error, :download_error
-
2
attr_accessor :remove
-
-
2
def initialize(record, column, options={})
-
195
@record = record
-
195
@column = column
-
195
@options = record.class.uploader_options[column]
-
end
-
-
2
def write_identifier
-
193
return if record.frozen?
-
-
193
if remove?
-
record.write_uploader(serialization_column, nil)
-
193
elsif uploader.identifier.present?
-
record.write_uploader(serialization_column, uploader.identifier)
-
end
-
end
-
-
2
def identifier
-
971
record.read_uploader(serialization_column)
-
end
-
-
2
def uploader
-
971
@uploader ||= record.class.uploaders[column].new(record, column)
-
971
@uploader.retrieve_from_store!(identifier) if @uploader.blank? && identifier.present?
-
-
971
@uploader
-
end
-
-
2
def cache(new_file)
-
uploader.cache!(new_file)
-
@integrity_error = nil
-
@processing_error = nil
-
rescue CarrierWave::IntegrityError => e
-
@integrity_error = e
-
raise e unless option(:ignore_integrity_errors)
-
rescue CarrierWave::ProcessingError => e
-
@processing_error = e
-
raise e unless option(:ignore_processing_errors)
-
end
-
-
2
def cache_name
-
uploader.cache_name
-
end
-
-
2
def cache_name=(cache_name)
-
uploader.retrieve_from_cache!(cache_name) unless uploader.cached?
-
rescue CarrierWave::InvalidParameter
-
end
-
-
2
def remote_url=(url)
-
return if url.blank?
-
-
@remote_url = url
-
@download_error = nil
-
@integrity_error = nil
-
-
uploader.download!(url)
-
-
rescue CarrierWave::DownloadError => e
-
@download_error = e
-
raise e unless option(:ignore_download_errors)
-
rescue CarrierWave::ProcessingError => e
-
@processing_error = e
-
raise e unless option(:ignore_processing_errors)
-
rescue CarrierWave::IntegrityError => e
-
@integrity_error = e
-
raise e unless option(:ignore_integrity_errors)
-
end
-
-
2
def store!
-
193
return if uploader.blank?
-
-
if remove?
-
uploader.remove!
-
else
-
uploader.store!
-
end
-
end
-
-
2
def url(*args)
-
uploader.url(*args)
-
end
-
-
2
def blank?
-
uploader.blank?
-
end
-
-
2
def remove?
-
193
remove.present? && remove !~ /\A0|false$\z/
-
end
-
-
2
def remove!
-
uploader.remove!
-
end
-
-
2
def serialization_column
-
971
option(:mount_on) || column
-
end
-
-
2
attr_accessor :uploader_options
-
-
2
private
-
-
2
def option(name)
-
971
self.uploader_options ||= {}
-
971
self.uploader_options[name] ||= record.class.uploader_option(column, name)
-
end
-
-
end # Mounter
-
-
end # Mount
-
end # CarrierWave
-
# encoding: utf-8
-
-
2
require 'active_record'
-
2
require 'carrierwave/validations/active_model'
-
-
2
module CarrierWave
-
2
module ActiveRecord
-
-
2
include CarrierWave::Mount
-
-
##
-
# See +CarrierWave::Mount#mount_uploader+ for documentation
-
#
-
2
def mount_uploader(column, uploader=nil, options={}, &block)
-
4
super
-
-
4
alias_method :read_uploader, :read_attribute
-
4
alias_method :write_uploader, :write_attribute
-
4
public :read_uploader
-
4
public :write_uploader
-
-
4
include CarrierWave::Validations::ActiveModel
-
-
4
validates_integrity_of column if uploader_option(column.to_sym, :validate_integrity)
-
4
validates_processing_of column if uploader_option(column.to_sym, :validate_processing)
-
4
validates_download_of column if uploader_option(column.to_sym, :validate_download)
-
-
4
after_save :"store_#{column}!"
-
4
before_save :"write_#{column}_identifier"
-
4
after_commit :"remove_#{column}!", :on => :destroy
-
4
after_commit :"mark_remove_#{column}_false", :on => :update
-
4
before_update :"store_previous_model_for_#{column}"
-
4
after_save :"remove_previously_stored_#{column}"
-
-
4
class_eval <<-RUBY, __FILE__, __LINE__+1
-
def #{column}=(new_file)
-
column = _mounter(:#{column}).serialization_column
-
send(:"\#{column}_will_change!")
-
super
-
end
-
-
def remote_#{column}_url=(url)
-
column = _mounter(:#{column}).serialization_column
-
send(:"\#{column}_will_change!")
-
super
-
end
-
-
def remove_#{column}!
-
super
-
_mounter(:#{column}).remove = true
-
_mounter(:#{column}).write_identifier
-
end
-
-
def serializable_hash(options=nil)
-
hash = {}
-
-
except = options && options[:except] && Array.wrap(options[:except]).map(&:to_s)
-
only = options && options[:only] && Array.wrap(options[:only]).map(&:to_s)
-
-
self.class.uploaders.each do |column, uploader|
-
if (!only && !except) || (only && only.include?(column.to_s)) || (!only && except && !except.include?(column.to_s))
-
hash[column.to_s] = _mounter(column).uploader.serializable_hash
-
end
-
end
-
super(options).merge(hash)
-
end
-
RUBY
-
-
end
-
-
end # ActiveRecord
-
end # CarrierWave
-
-
2
ActiveRecord::Base.extend CarrierWave::ActiveRecord
-
2
require "carrierwave/processing/rmagick"
-
2
require "carrierwave/processing/mini_magick"
-
2
require "carrierwave/processing/mime_types"
-
# encoding: utf-8
-
-
2
module CarrierWave
-
-
##
-
# This module simplifies the use of the mime-types gem to intelligently
-
# guess and set the content-type of a file. If you want to use this, you'll
-
# need to require this file:
-
#
-
# require 'carrierwave/processing/mime_types'
-
#
-
# And then include it in your uploader:
-
#
-
# class MyUploader < CarrierWave::Uploader::Base
-
# include CarrierWave::MimeTypes
-
# end
-
#
-
# You can now use the provided helper:
-
#
-
# class MyUploader < CarrierWave::Uploader::Base
-
# include CarrierWave::MimeTypes
-
#
-
# process :set_content_type
-
# end
-
#
-
2
module MimeTypes
-
2
extend ActiveSupport::Concern
-
-
2
included do
-
CarrierWave::Utilities::Deprecation.new "0.11.0", "CarrierWave::MimeTypes is deprecated and will be removed in the future, get the content_type from the SanitizedFile object directly."
-
begin
-
require "mime/types"
-
rescue LoadError => e
-
e.message << " (You may need to install the mime-types gem)"
-
raise e
-
end
-
end
-
-
2
module ClassMethods
-
2
def set_content_type(override=false)
-
process :set_content_type => override
-
end
-
end
-
-
2
GENERIC_CONTENT_TYPES = %w[application/octet-stream binary/octet-stream]
-
-
2
def generic_content_type?
-
GENERIC_CONTENT_TYPES.include? file.content_type
-
end
-
-
##
-
# Changes the file content_type using the mime-types gem
-
#
-
# === Parameters
-
#
-
# [override (Boolean)] whether or not to override the file's content_type
-
# if it is already set and not a generic content-type,
-
# false by default
-
#
-
2
def set_content_type(override=false)
-
if override || file.content_type.blank? || generic_content_type?
-
new_content_type = ::MIME::Types.type_for(file.original_filename).first.to_s
-
if file.respond_to?(:content_type=)
-
file.content_type = new_content_type
-
else
-
file.instance_variable_set(:@content_type, new_content_type)
-
end
-
end
-
rescue ::MIME::InvalidContentType => e
-
raise CarrierWave::ProcessingError, I18n.translate(:"errors.messages.mime_types_processing_error", :e => e)
-
end
-
-
end # MimeTypes
-
end # CarrierWave
-
# encoding: utf-8
-
-
2
module CarrierWave
-
-
##
-
# This module simplifies manipulation with MiniMagick by providing a set
-
# of convenient helper methods. If you want to use them, you'll need to
-
# require this file:
-
#
-
# require 'carrierwave/processing/mini_magick'
-
#
-
# And then include it in your uploader:
-
#
-
# class MyUploader < CarrierWave::Uploader::Base
-
# include CarrierWave::MiniMagick
-
# end
-
#
-
# You can now use the provided helpers:
-
#
-
# class MyUploader < CarrierWave::Uploader::Base
-
# include CarrierWave::MiniMagick
-
#
-
# process :resize_to_fit => [200, 200]
-
# end
-
#
-
# Or create your own helpers with the powerful manipulate! method. Check
-
# out the ImageMagick docs at http://www.imagemagick.org/script/command-line-options.php for more
-
# info
-
#
-
# class MyUploader < CarrierWave::Uploader::Base
-
# include CarrierWave::MiniMagick
-
#
-
# process :radial_blur => 10
-
#
-
# def radial_blur(amount)
-
# manipulate! do |img|
-
# img.radial_blur(amount)
-
# img = yield(img) if block_given?
-
# img
-
# end
-
# end
-
#
-
# === Note
-
#
-
# MiniMagick is a mini replacement for RMagick that uses the command line
-
# tool "mogrify" for image manipulation.
-
#
-
# You can find more information here:
-
#
-
# http://mini_magick.rubyforge.org/
-
# and
-
# https://github.com/minimagic/minimagick/
-
#
-
#
-
2
module MiniMagick
-
2
extend ActiveSupport::Concern
-
-
2
included do
-
begin
-
require "mini_magick"
-
rescue LoadError => e
-
e.message << " (You may need to install the mini_magick gem)"
-
raise e
-
end
-
end
-
-
2
module ClassMethods
-
2
def convert(format)
-
process :convert => format
-
end
-
-
2
def resize_to_limit(width, height)
-
process :resize_to_limit => [width, height]
-
end
-
-
2
def resize_to_fit(width, height)
-
process :resize_to_fit => [width, height]
-
end
-
-
2
def resize_to_fill(width, height, gravity='Center')
-
process :resize_to_fill => [width, height, gravity]
-
end
-
-
2
def resize_and_pad(width, height, background=:transparent, gravity=::Magick::CenterGravity)
-
process :resize_and_pad => [width, height, background, gravity]
-
end
-
end
-
-
##
-
# Changes the image encoding format to the given format
-
#
-
# See http://www.imagemagick.org/script/command-line-options.php#format
-
#
-
# === Parameters
-
#
-
# [format (#to_s)] an abreviation of the format
-
#
-
# === Yields
-
#
-
# [MiniMagick::Image] additional manipulations to perform
-
#
-
# === Examples
-
#
-
# image.convert(:png)
-
#
-
2
def convert(format)
-
@format = format
-
manipulate! do |img|
-
img.format(format.to_s.downcase)
-
img = yield(img) if block_given?
-
img
-
end
-
end
-
-
##
-
# Resize the image to fit within the specified dimensions while retaining
-
# the original aspect ratio. Will only resize the image if it is larger than the
-
# specified dimensions. The resulting image may be shorter or narrower than specified
-
# in the smaller dimension but will not be larger than the specified values.
-
#
-
# === Parameters
-
#
-
# [width (Integer)] the width to scale the image to
-
# [height (Integer)] the height to scale the image to
-
#
-
# === Yields
-
#
-
# [MiniMagick::Image] additional manipulations to perform
-
#
-
2
def resize_to_limit(width, height)
-
manipulate! do |img|
-
img.resize "#{width}x#{height}>"
-
img = yield(img) if block_given?
-
img
-
end
-
end
-
-
##
-
# Resize the image to fit within the specified dimensions while retaining
-
# the original aspect ratio. The image may be shorter or narrower than
-
# specified in the smaller dimension but will not be larger than the specified values.
-
#
-
# === Parameters
-
#
-
# [width (Integer)] the width to scale the image to
-
# [height (Integer)] the height to scale the image to
-
#
-
# === Yields
-
#
-
# [MiniMagick::Image] additional manipulations to perform
-
#
-
2
def resize_to_fit(width, height)
-
manipulate! do |img|
-
img.resize "#{width}x#{height}"
-
img = yield(img) if block_given?
-
img
-
end
-
end
-
-
##
-
# Resize the image to fit within the specified dimensions while retaining
-
# the aspect ratio of the original image. If necessary, crop the image in the
-
# larger dimension.
-
#
-
# === Parameters
-
#
-
# [width (Integer)] the width to scale the image to
-
# [height (Integer)] the height to scale the image to
-
# [gravity (String)] the current gravity suggestion (default: 'Center'; options: 'NorthWest', 'North', 'NorthEast', 'West', 'Center', 'East', 'SouthWest', 'South', 'SouthEast')
-
#
-
# === Yields
-
#
-
# [MiniMagick::Image] additional manipulations to perform
-
#
-
2
def resize_to_fill(width, height, gravity = 'Center')
-
manipulate! do |img|
-
cols, rows = img[:dimensions]
-
img.combine_options do |cmd|
-
if width != cols || height != rows
-
scale_x = width/cols.to_f
-
scale_y = height/rows.to_f
-
if scale_x >= scale_y
-
cols = (scale_x * (cols + 0.5)).round
-
rows = (scale_x * (rows + 0.5)).round
-
cmd.resize "#{cols}"
-
else
-
cols = (scale_y * (cols + 0.5)).round
-
rows = (scale_y * (rows + 0.5)).round
-
cmd.resize "x#{rows}"
-
end
-
end
-
cmd.gravity gravity
-
cmd.background "rgba(255,255,255,0.0)"
-
cmd.extent "#{width}x#{height}" if cols != width || rows != height
-
end
-
img = yield(img) if block_given?
-
img
-
end
-
end
-
-
##
-
# Resize the image to fit within the specified dimensions while retaining
-
# the original aspect ratio. If necessary, will pad the remaining area
-
# with the given color, which defaults to transparent (for gif and png,
-
# white for jpeg).
-
#
-
# See http://www.imagemagick.org/script/command-line-options.php#gravity
-
# for gravity options.
-
#
-
# === Parameters
-
#
-
# [width (Integer)] the width to scale the image to
-
# [height (Integer)] the height to scale the image to
-
# [background (String, :transparent)] the color of the background as a hexcode, like "#ff45de"
-
# [gravity (String)] how to position the image
-
#
-
# === Yields
-
#
-
# [MiniMagick::Image] additional manipulations to perform
-
#
-
2
def resize_and_pad(width, height, background=:transparent, gravity='Center')
-
manipulate! do |img|
-
img.combine_options do |cmd|
-
cmd.thumbnail "#{width}x#{height}>"
-
if background == :transparent
-
cmd.background "rgba(255, 255, 255, 0.0)"
-
else
-
cmd.background background
-
end
-
cmd.gravity gravity
-
cmd.extent "#{width}x#{height}"
-
end
-
img = yield(img) if block_given?
-
img
-
end
-
end
-
-
##
-
# Manipulate the image with MiniMagick. This method will load up an image
-
# and then pass each of its frames to the supplied block. It will then
-
# save the image to disk.
-
#
-
# === Gotcha
-
#
-
# This method assumes that the object responds to +current_path+.
-
# Any class that this module is mixed into must have a +current_path+ method.
-
# CarrierWave::Uploader does, so you won't need to worry about this in
-
# most cases.
-
#
-
# === Yields
-
#
-
# [MiniMagick::Image] manipulations to perform
-
#
-
# === Raises
-
#
-
# [CarrierWave::ProcessingError] if manipulation failed.
-
#
-
2
def manipulate!
-
cache_stored_file! if !cached?
-
image = ::MiniMagick::Image.open(current_path)
-
-
begin
-
image.format(@format.to_s.downcase) if @format
-
image = yield(image)
-
image.write(current_path)
-
image.run_command("identify", current_path)
-
ensure
-
image.destroy!
-
end
-
rescue ::MiniMagick::Error, ::MiniMagick::Invalid => e
-
default = I18n.translate(:"errors.messages.mini_magick_processing_error", :e => e, :locale => :en)
-
message = I18n.translate(:"errors.messages.mini_magick_processing_error", :e => e, :default => default)
-
raise CarrierWave::ProcessingError, message
-
end
-
-
end # MiniMagick
-
end # CarrierWave
-
# encoding: utf-8
-
-
2
module CarrierWave
-
-
##
-
# This module simplifies manipulation with RMagick by providing a set
-
# of convenient helper methods. If you want to use them, you'll need to
-
# require this file:
-
#
-
# require 'carrierwave/processing/rmagick'
-
#
-
# And then include it in your uploader:
-
#
-
# class MyUploader < CarrierWave::Uploader::Base
-
# include CarrierWave::RMagick
-
# end
-
#
-
# You can now use the provided helpers:
-
#
-
# class MyUploader < CarrierWave::Uploader::Base
-
# include CarrierWave::RMagick
-
#
-
# process :resize_to_fit => [200, 200]
-
# end
-
#
-
# Or create your own helpers with the powerful manipulate! method. Check
-
# out the RMagick docs at http://www.imagemagick.org/RMagick/doc/ for more
-
# info
-
#
-
# class MyUploader < CarrierWave::Uploader::Base
-
# include CarrierWave::RMagick
-
#
-
# process :do_stuff => 10.0
-
#
-
# def do_stuff(blur_factor)
-
# manipulate! do |img|
-
# img = img.sepiatone
-
# img = img.auto_orient
-
# img = img.radial_blur(blur_factor)
-
# end
-
# end
-
# end
-
#
-
# === Note
-
#
-
# You should be aware how RMagick handles memory. manipulate! takes care
-
# of freeing up memory for you, but for optimum memory usage you should
-
# use destructive operations as much as possible:
-
#
-
# DON'T DO THIS:
-
# img = img.resize_to_fit
-
#
-
# DO THIS INSTEAD:
-
# img.resize_to_fit!
-
#
-
# Read this for more information why:
-
#
-
# http://rubyforge.org/forum/forum.php?thread_id=1374&forum_id=1618
-
#
-
2
module RMagick
-
2
extend ActiveSupport::Concern
-
-
2
included do
-
begin
-
require "rmagick"
-
rescue LoadError
-
require "RMagick"
-
rescue LoadError => e
-
e.message << " (You may need to install the rmagick gem)"
-
raise e
-
end
-
end
-
-
2
module ClassMethods
-
2
def convert(format)
-
process :convert => format
-
end
-
-
2
def resize_to_limit(width, height)
-
process :resize_to_limit => [width, height]
-
end
-
-
2
def resize_to_fit(width, height)
-
process :resize_to_fit => [width, height]
-
end
-
-
2
def resize_to_fill(width, height, gravity=::Magick::CenterGravity)
-
process :resize_to_fill => [width, height, gravity]
-
end
-
-
2
def resize_and_pad(width, height, background=:transparent, gravity=::Magick::CenterGravity)
-
process :resize_and_pad => [width, height, background, gravity]
-
end
-
-
2
def resize_to_geometry_string(geometry_string)
-
process :resize_to_geometry_string => [geometry_string]
-
end
-
end
-
-
##
-
# Changes the image encoding format to the given format
-
#
-
# See even http://www.imagemagick.org/RMagick/doc/magick.html#formats
-
#
-
# === Parameters
-
#
-
# [format (#to_s)] an abreviation of the format
-
#
-
# === Yields
-
#
-
# [Magick::Image] additional manipulations to perform
-
#
-
# === Examples
-
#
-
# image.convert(:png)
-
#
-
2
def convert(format)
-
manipulate!(:format => format)
-
@format = format
-
end
-
-
##
-
# Resize the image to fit within the specified dimensions while retaining
-
# the original aspect ratio. Will only resize the image if it is larger than the
-
# specified dimensions. The resulting image may be shorter or narrower than specified
-
# in the smaller dimension but will not be larger than the specified values.
-
#
-
# === Parameters
-
#
-
# [width (Integer)] the width to scale the image to
-
# [height (Integer)] the height to scale the image to
-
#
-
# === Yields
-
#
-
# [Magick::Image] additional manipulations to perform
-
#
-
2
def resize_to_limit(width, height)
-
manipulate! do |img|
-
geometry = Magick::Geometry.new(width, height, 0, 0, Magick::GreaterGeometry)
-
new_img = img.change_geometry(geometry) do |new_width, new_height|
-
img.resize(new_width, new_height)
-
end
-
destroy_image(img)
-
new_img = yield(new_img) if block_given?
-
new_img
-
end
-
end
-
-
##
-
# From the RMagick documentation: "Resize the image to fit within the
-
# specified dimensions while retaining the original aspect ratio. The
-
# image may be shorter or narrower than specified in the smaller dimension
-
# but will not be larger than the specified values."
-
#
-
# See even http://www.imagemagick.org/RMagick/doc/image3.html#resize_to_fit
-
#
-
# === Parameters
-
#
-
# [width (Integer)] the width to scale the image to
-
# [height (Integer)] the height to scale the image to
-
#
-
# === Yields
-
#
-
# [Magick::Image] additional manipulations to perform
-
#
-
2
def resize_to_fit(width, height)
-
manipulate! do |img|
-
img.resize_to_fit!(width, height)
-
img = yield(img) if block_given?
-
img
-
end
-
end
-
-
##
-
# From the RMagick documentation: "Resize the image to fit within the
-
# specified dimensions while retaining the aspect ratio of the original
-
# image. If necessary, crop the image in the larger dimension."
-
#
-
# See even http://www.imagemagick.org/RMagick/doc/image3.html#resize_to_fill
-
#
-
# === Parameters
-
#
-
# [width (Integer)] the width to scale the image to
-
# [height (Integer)] the height to scale the image to
-
#
-
# === Yields
-
#
-
# [Magick::Image] additional manipulations to perform
-
#
-
2
def resize_to_fill(width, height, gravity=::Magick::CenterGravity)
-
manipulate! do |img|
-
img.crop_resized!(width, height, gravity)
-
img = yield(img) if block_given?
-
img
-
end
-
end
-
-
##
-
# Resize the image to fit within the specified dimensions while retaining
-
# the original aspect ratio. If necessary, will pad the remaining area
-
# with the given color, which defaults to transparent (for gif and png,
-
# white for jpeg).
-
#
-
# === Parameters
-
#
-
# [width (Integer)] the width to scale the image to
-
# [height (Integer)] the height to scale the image to
-
# [background (String, :transparent)] the color of the background as a hexcode, like "#ff45de"
-
# [gravity (Magick::GravityType)] how to position the image
-
#
-
# === Yields
-
#
-
# [Magick::Image] additional manipulations to perform
-
#
-
2
def resize_and_pad(width, height, background=:transparent, gravity=::Magick::CenterGravity)
-
manipulate! do |img|
-
img.resize_to_fit!(width, height)
-
new_img = ::Magick::Image.new(width, height) { self.background_color = background == :transparent ? 'rgba(255,255,255,0)' : background.to_s }
-
if background == :transparent
-
filled = new_img.matte_floodfill(1, 1)
-
else
-
filled = new_img.color_floodfill(1, 1, ::Magick::Pixel.from_color(background))
-
end
-
destroy_image(new_img)
-
filled.composite!(img, gravity, ::Magick::OverCompositeOp)
-
destroy_image(img)
-
filled = yield(filled) if block_given?
-
filled
-
end
-
end
-
-
##
-
# Resize the image per the provided geometry string.
-
#
-
# === Parameters
-
#
-
# [geometry_string (String)] the proportions in which to scale image
-
#
-
# === Yields
-
#
-
# [Magick::Image] additional manipulations to perform
-
#
-
2
def resize_to_geometry_string(geometry_string)
-
manipulate! do |img|
-
new_img = img.change_geometry(geometry_string) do |new_width, new_height|
-
img.resize(new_width, new_height)
-
end
-
destroy_image(img)
-
new_img = yield(new_img) if block_given?
-
new_img
-
end
-
end
-
-
##
-
# Manipulate the image with RMagick. This method will load up an image
-
# and then pass each of its frames to the supplied block. It will then
-
# save the image to disk.
-
#
-
# === Gotcha
-
#
-
# This method assumes that the object responds to +current_path+.
-
# Any class that this module is mixed into must have a +current_path+ method.
-
# CarrierWave::Uploader does, so you won't need to worry about this in
-
# most cases.
-
#
-
# === Yields
-
#
-
# [Magick::Image] manipulations to perform
-
# [Integer] Frame index if the image contains multiple frames
-
# [Hash] options, see below
-
#
-
# === Options
-
#
-
# The options argument to this method is also yielded as the third
-
# block argument.
-
#
-
# Currently, the following options are defined:
-
#
-
# ==== :write
-
# A hash of assignments to be evaluated in the block given to the RMagick write call.
-
#
-
# An example:
-
#
-
# manipulate! do |img, index, options|
-
# options[:write] = {
-
# :quality => 50,
-
# :depth => 8
-
# }
-
# img
-
# end
-
#
-
# This will translate to the following RMagick::Image#write call:
-
#
-
# image.write do |img|
-
# self.quality = 50
-
# self.depth = 8
-
# end
-
#
-
# ==== :read
-
# A hash of assignments to be given to the RMagick read call.
-
#
-
# The options available are identical to those for write, but are passed in directly, like this:
-
#
-
# manipulate! :read => { :density => 300 }
-
#
-
# ==== :format
-
# Specify the output format. If unset, the filename extension is used to determine the format.
-
#
-
# === Raises
-
#
-
# [CarrierWave::ProcessingError] if manipulation failed.
-
#
-
2
def manipulate!(options={}, &block)
-
cache_stored_file! if !cached?
-
-
read_block = create_info_block(options[:read])
-
image = ::Magick::Image.read(current_path, &read_block)
-
frames = ::Magick::ImageList.new
-
-
image.each_with_index do |frame, index|
-
frame = yield *[frame, index, options].take(block.arity) if block_given?
-
frames << frame if frame
-
end
-
frames.append(true) if block_given?
-
-
write_block = create_info_block(options[:write])
-
if options[:format] || @format
-
frames.write("#{options[:format] || @format}:#{current_path}", &write_block)
-
else
-
frames.write(current_path, &write_block)
-
end
-
destroy_image(frames)
-
rescue ::Magick::ImageMagickError => e
-
raise CarrierWave::ProcessingError, I18n.translate(:"errors.messages.rmagick_processing_error", :e => e, :default => I18n.translate(:"errors.messages.rmagick_processing_error", :e => e, :locale => :en))
-
end
-
-
2
private
-
-
2
def create_info_block(options)
-
return nil unless options
-
assignments = options.map { |k, v| "self.#{k} = #{v}" }
-
code = "lambda { |img| " + assignments.join(";") + "}"
-
eval code
-
end
-
-
2
def destroy_image(image)
-
image.destroy! if image.respond_to?(:destroy!)
-
end
-
-
end # RMagick
-
end # CarrierWave
-
# encoding: utf-8
-
-
2
require 'pathname'
-
2
require 'active_support/core_ext/string/multibyte'
-
2
require 'mime/types'
-
-
2
module CarrierWave
-
-
##
-
# SanitizedFile is a base class which provides a common API around all
-
# the different quirky Ruby File libraries. It has support for Tempfile,
-
# File, StringIO, Merb-style upload Hashes, as well as paths given as
-
# Strings and Pathnames.
-
#
-
# It's probably needlessly comprehensive and complex. Help is appreciated.
-
#
-
2
class SanitizedFile
-
-
2
attr_accessor :file
-
-
2
class << self
-
2
attr_writer :sanitize_regexp
-
-
2
def sanitize_regexp
-
@sanitize_regexp ||= /[^a-zA-Z0-9\.\-\+_]/
-
end
-
end
-
-
2
def initialize(file)
-
self.file = file
-
end
-
-
##
-
# Returns the filename as is, without sanitizing it.
-
#
-
# === Returns
-
#
-
# [String] the unsanitized filename
-
#
-
2
def original_filename
-
return @original_filename if @original_filename
-
if @file and @file.respond_to?(:original_filename)
-
@file.original_filename
-
elsif path
-
File.basename(path)
-
end
-
end
-
-
##
-
# Returns the filename, sanitized to strip out any evil characters.
-
#
-
# === Returns
-
#
-
# [String] the sanitized filename
-
#
-
2
def filename
-
sanitize(original_filename) if original_filename
-
end
-
-
2
alias_method :identifier, :filename
-
-
##
-
# Returns the part of the filename before the extension. So if a file is called 'test.jpeg'
-
# this would return 'test'
-
#
-
# === Returns
-
#
-
# [String] the first part of the filename
-
#
-
2
def basename
-
split_extension(filename)[0] if filename
-
end
-
-
##
-
# Returns the file extension
-
#
-
# === Returns
-
#
-
# [String] the extension
-
#
-
2
def extension
-
split_extension(filename)[1] if filename
-
end
-
-
##
-
# Returns the file's size.
-
#
-
# === Returns
-
#
-
# [Integer] the file's size in bytes.
-
#
-
2
def size
-
if is_path?
-
exists? ? File.size(path) : 0
-
elsif @file.respond_to?(:size)
-
@file.size
-
elsif path
-
exists? ? File.size(path) : 0
-
else
-
0
-
end
-
end
-
-
##
-
# Returns the full path to the file. If the file has no path, it will return nil.
-
#
-
# === Returns
-
#
-
# [String, nil] the path where the file is located.
-
#
-
2
def path
-
unless @file.blank?
-
if is_path?
-
File.expand_path(@file)
-
elsif @file.respond_to?(:path) and not @file.path.blank?
-
File.expand_path(@file.path)
-
end
-
end
-
end
-
-
##
-
# === Returns
-
#
-
# [Boolean] whether the file is supplied as a pathname or string.
-
#
-
2
def is_path?
-
!!((@file.is_a?(String) || @file.is_a?(Pathname)) && !@file.blank?)
-
end
-
-
##
-
# === Returns
-
#
-
# [Boolean] whether the file is valid and has a non-zero size
-
#
-
2
def empty?
-
@file.nil? || self.size.nil? || (self.size.zero? && ! self.exists?)
-
end
-
-
##
-
# === Returns
-
#
-
# [Boolean] Whether the file exists
-
#
-
2
def exists?
-
return File.exists?(self.path) if self.path
-
return false
-
end
-
-
##
-
# Returns the contents of the file.
-
#
-
# === Returns
-
#
-
# [String] contents of the file
-
#
-
2
def read
-
if @content
-
@content
-
elsif is_path?
-
File.open(@file, "rb") {|file| file.read}
-
else
-
@file.rewind if @file.respond_to?(:rewind)
-
@content = @file.read
-
@file.close if @file.respond_to?(:close) && @file.respond_to?(:closed?) && !@file.closed?
-
@content
-
end
-
end
-
-
##
-
# Moves the file to the given path
-
#
-
# === Parameters
-
#
-
# [new_path (String)] The path where the file should be moved.
-
# [permissions (Integer)] permissions to set on the file in its new location.
-
# [directory_permissions (Integer)] permissions to set on created directories.
-
#
-
2
def move_to(new_path, permissions=nil, directory_permissions=nil)
-
return if self.empty?
-
new_path = File.expand_path(new_path)
-
-
mkdir!(new_path, directory_permissions)
-
if exists?
-
FileUtils.mv(path, new_path) unless new_path == path
-
else
-
File.open(new_path, "wb") { |f| f.write(read) }
-
end
-
chmod!(new_path, permissions)
-
self.file = new_path
-
self
-
end
-
-
##
-
# Creates a copy of this file and moves it to the given path. Returns the copy.
-
#
-
# === Parameters
-
#
-
# [new_path (String)] The path where the file should be copied to.
-
# [permissions (Integer)] permissions to set on the copy
-
# [directory_permissions (Integer)] permissions to set on created directories.
-
#
-
# === Returns
-
#
-
# @return [CarrierWave::SanitizedFile] the location where the file will be stored.
-
#
-
2
def copy_to(new_path, permissions=nil, directory_permissions=nil)
-
return if self.empty?
-
new_path = File.expand_path(new_path)
-
-
mkdir!(new_path, directory_permissions)
-
if exists?
-
FileUtils.cp(path, new_path) unless new_path == path
-
else
-
File.open(new_path, "wb") { |f| f.write(read) }
-
end
-
chmod!(new_path, permissions)
-
self.class.new({:tempfile => new_path, :content_type => content_type})
-
end
-
-
##
-
# Removes the file from the filesystem.
-
#
-
2
def delete
-
FileUtils.rm(self.path) if exists?
-
end
-
-
##
-
# Returns a File object, or nil if it does not exist.
-
#
-
# === Returns
-
#
-
# [File] a File object representing the SanitizedFile
-
#
-
2
def to_file
-
return @file if @file.is_a?(File)
-
File.open(path, "rb") if exists?
-
end
-
-
##
-
# Returns the content type of the file.
-
#
-
# === Returns
-
#
-
# [String] the content type of the file
-
#
-
2
def content_type
-
return @content_type if @content_type
-
if @file.respond_to?(:content_type) and @file.content_type
-
@content_type = @file.content_type.to_s.chomp
-
elsif path
-
@content_type = ::MIME::Types.type_for(path).first.to_s
-
end
-
end
-
-
##
-
# Sets the content type of the file.
-
#
-
# === Returns
-
#
-
# [String] the content type of the file
-
#
-
2
def content_type=(type)
-
@content_type = type
-
end
-
-
##
-
# Used to sanitize the file name. Public to allow overriding for non-latin characters.
-
#
-
# === Returns
-
#
-
# [Regexp] the regexp for sanitizing the file name
-
#
-
2
def sanitize_regexp
-
CarrierWave::SanitizedFile.sanitize_regexp
-
end
-
-
2
private
-
-
2
def file=(file)
-
if file.is_a?(Hash)
-
@file = file["tempfile"] || file[:tempfile]
-
@original_filename = file["filename"] || file[:filename]
-
@content_type = file["content_type"] || file[:content_type]
-
else
-
@file = file
-
@original_filename = nil
-
@content_type = nil
-
end
-
end
-
-
# create the directory if it doesn't exist
-
2
def mkdir!(path, directory_permissions)
-
options = {}
-
options[:mode] = directory_permissions if directory_permissions
-
FileUtils.mkdir_p(File.dirname(path), options) unless File.exists?(File.dirname(path))
-
end
-
-
2
def chmod!(path, permissions)
-
File.chmod(permissions, path) if permissions
-
end
-
-
# Sanitize the filename, to prevent hacking
-
2
def sanitize(name)
-
name = name.gsub("\\", "/") # work-around for IE
-
name = File.basename(name)
-
name = name.gsub(sanitize_regexp,"_")
-
name = "_#{name}" if name =~ /\A\.+\z/
-
name = "unnamed" if name.size == 0
-
return name.mb_chars.to_s
-
end
-
-
2
def split_extension(filename)
-
# regular expressions to try for identifying extensions
-
extension_matchers = [
-
/\A(.+)\.(tar\.([glx]?z|bz2))\z/, # matches "something.tar.gz"
-
/\A(.+)\.([^\.]+)\z/ # matches "something.jpg"
-
]
-
-
extension_matchers.each do |regexp|
-
if filename =~ regexp
-
return $1, $2
-
end
-
end
-
return filename, "" # In case we weren't able to split the extension
-
end
-
-
end # SanitizedFile
-
end # CarrierWave
-
2
require "carrierwave/storage/abstract"
-
2
require "carrierwave/storage/file"
-
-
2
begin
-
2
require "fog"
-
rescue LoadError
-
end
-
-
2
require "carrierwave/storage/fog" if defined?(Fog)
-
# encoding: utf-8
-
-
2
module CarrierWave
-
2
module Storage
-
-
##
-
# This file serves mostly as a specification for Storage engines. There is no requirement
-
# that storage engines must be a subclass of this class.
-
#
-
2
class Abstract
-
-
2
attr_reader :uploader
-
-
2
def initialize(uploader)
-
193
@uploader = uploader
-
end
-
-
2
def identifier
-
193
uploader.filename
-
end
-
-
2
def store!(file)
-
end
-
-
2
def retrieve!(identifier)
-
end
-
-
end # Abstract
-
end # Storage
-
end # CarrierWave
-
# encoding: utf-8
-
-
2
module CarrierWave
-
2
module Storage
-
-
##
-
# File storage stores file to the Filesystem (surprising, no?). There's really not much
-
# to it, it uses the store_dir defined on the uploader as the storage location. That's
-
# pretty much it.
-
#
-
2
class File < Abstract
-
-
##
-
# Move the file to the uploader's store path.
-
#
-
# By default, store!() uses copy_to(), which operates by copying the file
-
# from the cache to the store, then deleting the file from the cache.
-
# If move_to_store() is overriden to return true, then store!() uses move_to(),
-
# which simply moves the file from cache to store. Useful for large files.
-
#
-
# === Parameters
-
#
-
# [file (CarrierWave::SanitizedFile)] the file to store
-
#
-
# === Returns
-
#
-
# [CarrierWave::SanitizedFile] a sanitized file
-
#
-
2
def store!(file)
-
path = ::File.expand_path(uploader.store_path, uploader.root)
-
if uploader.move_to_store
-
file.move_to(path, uploader.permissions, uploader.directory_permissions)
-
else
-
file.copy_to(path, uploader.permissions, uploader.directory_permissions)
-
end
-
end
-
-
##
-
# Retrieve the file from its store path
-
#
-
# === Parameters
-
#
-
# [identifier (String)] the filename of the file
-
#
-
# === Returns
-
#
-
# [CarrierWave::SanitizedFile] a sanitized file
-
#
-
2
def retrieve!(identifier)
-
path = ::File.expand_path(uploader.store_path(identifier), uploader.root)
-
CarrierWave::SanitizedFile.new(path)
-
end
-
-
end # File
-
end # Storage
-
end # CarrierWave
-
# encoding: utf-8
-
-
2
require "carrierwave/uploader/configuration"
-
2
require "carrierwave/uploader/callbacks"
-
2
require "carrierwave/uploader/proxy"
-
2
require "carrierwave/uploader/url"
-
2
require "carrierwave/uploader/mountable"
-
2
require "carrierwave/uploader/cache"
-
2
require "carrierwave/uploader/store"
-
2
require "carrierwave/uploader/download"
-
2
require "carrierwave/uploader/remove"
-
2
require "carrierwave/uploader/extension_whitelist"
-
2
require "carrierwave/uploader/extension_blacklist"
-
2
require "carrierwave/uploader/processing"
-
2
require "carrierwave/uploader/versions"
-
2
require "carrierwave/uploader/default_url"
-
-
2
require "carrierwave/uploader/serialization"
-
-
2
module CarrierWave
-
-
##
-
# See CarrierWave::Uploader::Base
-
#
-
2
module Uploader
-
-
##
-
# An uploader is a class that allows you to easily handle the caching and storage of
-
# uploaded files. Please refer to the README for configuration options.
-
#
-
# Once you have an uploader you can use it in isolation:
-
#
-
# my_uploader = MyUploader.new
-
# my_uploader.cache!(File.open(path_to_file))
-
# my_uploader.retrieve_from_store!('monkey.png')
-
#
-
# Alternatively, you can mount it on an ORM or other persistence layer, with
-
# +CarrierWave::Mount#mount_uploader+. There are extensions for activerecord and datamapper
-
# these are *very* simple (they are only a dozen lines of code), so adding your own should
-
# be trivial.
-
#
-
2
class Base
-
2
attr_reader :file
-
-
2
include CarrierWave::Uploader::Configuration
-
2
include CarrierWave::Uploader::Callbacks
-
2
include CarrierWave::Uploader::Proxy
-
2
include CarrierWave::Uploader::Url
-
2
include CarrierWave::Uploader::Mountable
-
2
include CarrierWave::Uploader::Cache
-
2
include CarrierWave::Uploader::Store
-
2
include CarrierWave::Uploader::Download
-
2
include CarrierWave::Uploader::Remove
-
2
include CarrierWave::Uploader::ExtensionWhitelist
-
2
include CarrierWave::Uploader::ExtensionBlacklist
-
2
include CarrierWave::Uploader::Processing
-
2
include CarrierWave::Uploader::Versions
-
2
include CarrierWave::Uploader::DefaultUrl
-
2
include CarrierWave::Uploader::Serialization
-
end # Base
-
-
end # Uploader
-
end # CarrierWave
-
# encoding: utf-8
-
-
2
module CarrierWave
-
-
2
class FormNotMultipart < UploadError
-
2
def message
-
"You tried to assign a String or a Pathname to an uploader, for security reasons, this is not allowed.\n\n If this is a file upload, please check that your upload form is multipart encoded."
-
end
-
end
-
-
2
class CacheCounter
-
2
@@counter = 0
-
-
2
def self.increment
-
@@counter += 1
-
end
-
end
-
-
##
-
# Generates a unique cache id for use in the caching system
-
#
-
# === Returns
-
#
-
# [String] a cache id in the format TIMEINT-PID-COUNTER-RND
-
#
-
2
def self.generate_cache_id
-
[Time.now.utc.to_i,
-
Process.pid,
-
'%04d' % (CarrierWave::CacheCounter.increment % 1000),
-
'%04d' % rand(9999)
-
].map(&:to_s).join('-')
-
end
-
-
2
module Uploader
-
2
module Cache
-
2
extend ActiveSupport::Concern
-
-
2
include CarrierWave::Uploader::Callbacks
-
2
include CarrierWave::Uploader::Configuration
-
-
2
module ClassMethods
-
-
##
-
# Removes cached files which are older than one day. You could call this method
-
# from a rake task to clean out old cached files.
-
#
-
# You can call this method directly on the module like this:
-
#
-
# CarrierWave.clean_cached_files!
-
#
-
# === Note
-
#
-
# This only works as long as you haven't done anything funky with your cache_dir.
-
# It's recommended that you keep cache files in one place only.
-
#
-
2
def clean_cached_files!(seconds=60*60*24)
-
Dir.glob(File.expand_path(File.join(cache_dir, '*'), CarrierWave.root)).each do |dir|
-
time = dir.scan(/(\d+)-\d+-\d+/).first.map { |t| t.to_i }
-
time = Time.at(*time)
-
if time < (Time.now.utc - seconds)
-
FileUtils.rm_rf(dir)
-
end
-
end
-
end
-
end
-
-
##
-
# Returns true if the uploader has been cached
-
#
-
# === Returns
-
#
-
# [Bool] whether the current file is cached
-
#
-
2
def cached?
-
@cache_id
-
end
-
-
##
-
# Caches the remotely stored file
-
#
-
# This is useful when about to process images. Most processing solutions
-
# require the file to be stored on the local filesystem.
-
#
-
2
def cache_stored_file!
-
cache!
-
end
-
-
2
def sanitized_file
-
_content = file.read
-
if _content.is_a?(File) # could be if storage is Fog
-
sanitized = CarrierWave::Storage::Fog.new(self).retrieve!(File.basename(_content.path))
-
sanitized.read if sanitized.exists?
-
-
else
-
sanitized = SanitizedFile.new :tempfile => StringIO.new(file.read),
-
:filename => File.basename(path), :content_type => file.content_type
-
end
-
sanitized
-
end
-
-
##
-
# Returns a String which uniquely identifies the currently cached file for later retrieval
-
#
-
# === Returns
-
#
-
# [String] a cache name, in the format TIMEINT-PID-COUNTER-RND/filename.txt
-
#
-
2
def cache_name
-
File.join(cache_id, full_original_filename) if cache_id and original_filename
-
end
-
-
##
-
# Caches the given file. Calls process! to trigger any process callbacks.
-
#
-
# By default, cache!() uses copy_to(), which operates by copying the file
-
# to the cache, then deleting the original file. If move_to_cache() is
-
# overriden to return true, then cache!() uses move_to(), which simply
-
# moves the file to the cache. Useful for large files.
-
#
-
# === Parameters
-
#
-
# [new_file (File, IOString, Tempfile)] any kind of file object
-
#
-
# === Raises
-
#
-
# [CarrierWave::FormNotMultipart] if the assigned parameter is a string
-
#
-
2
def cache!(new_file = sanitized_file)
-
new_file = CarrierWave::SanitizedFile.new(new_file)
-
-
unless new_file.empty?
-
raise CarrierWave::FormNotMultipart if new_file.is_path? && ensure_multipart_form
-
-
with_callbacks(:cache, new_file) do
-
self.cache_id = CarrierWave.generate_cache_id unless cache_id
-
-
@filename = new_file.filename
-
self.original_filename = new_file.filename
-
-
if move_to_cache
-
@file = new_file.move_to(cache_path, permissions, directory_permissions)
-
else
-
@file = new_file.copy_to(cache_path, permissions, directory_permissions)
-
end
-
end
-
end
-
end
-
-
##
-
# Retrieves the file with the given cache_name from the cache.
-
#
-
# === Parameters
-
#
-
# [cache_name (String)] uniquely identifies a cache file
-
#
-
# === Raises
-
#
-
# [CarrierWave::InvalidParameter] if the cache_name is incorrectly formatted.
-
#
-
2
def retrieve_from_cache!(cache_name)
-
with_callbacks(:retrieve_from_cache, cache_name) do
-
self.cache_id, self.original_filename = cache_name.to_s.split('/', 2)
-
@filename = original_filename
-
@file = CarrierWave::SanitizedFile.new(cache_path)
-
end
-
end
-
-
2
private
-
-
2
def cache_path
-
File.expand_path(File.join(cache_dir, cache_name), root)
-
end
-
-
2
attr_reader :cache_id, :original_filename
-
-
# We can override the full_original_filename method in other modules
-
2
alias_method :full_original_filename, :original_filename
-
-
2
def cache_id=(cache_id)
-
# Earlier version used 3 part cache_id. Thus we should allow for
-
# the cache_id to have both 3 part and 4 part formats.
-
raise CarrierWave::InvalidParameter, "invalid cache id" unless cache_id =~ /\A[\d]+\-[\d]+(\-[\d]{4})?\-[\d]{4}\z/
-
@cache_id = cache_id
-
end
-
-
2
def original_filename=(filename)
-
raise CarrierWave::InvalidParameter, "invalid filename" if filename =~ CarrierWave::SanitizedFile.sanitize_regexp
-
@original_filename = filename
-
end
-
-
end # Cache
-
end # Uploader
-
end # CarrierWave
-
# encoding: utf-8
-
-
2
module CarrierWave
-
2
module Uploader
-
2
module Callbacks
-
2
extend ActiveSupport::Concern
-
-
2
included do
-
2
class_attribute :_before_callbacks, :_after_callbacks,
-
:instance_writer => false
-
2
self._before_callbacks = Hash.new []
-
2
self._after_callbacks = Hash.new []
-
end
-
-
2
def with_callbacks(kind, *args)
-
self.class._before_callbacks[kind].each { |c| send c, *args }
-
yield
-
self.class._after_callbacks[kind].each { |c| send c, *args }
-
end
-
-
2
module ClassMethods
-
2
def before(kind, callback)
-
4
self._before_callbacks = self._before_callbacks.
-
merge kind => _before_callbacks[kind] + [callback]
-
end
-
-
2
def after(kind, callback)
-
14
self._after_callbacks = self._after_callbacks.
-
merge kind => _after_callbacks[kind] + [callback]
-
end
-
end # ClassMethods
-
-
end # Callbacks
-
end # Uploader
-
end # CarrierWave
-
# encoding: utf-8
-
-
2
module CarrierWave
-
2
module Uploader
-
2
module DefaultUrl
-
-
2
def url(*args)
-
super || default_url
-
end
-
-
##
-
# Override this method in your uploader to provide a default url
-
# in case no file has been cached/stored yet.
-
#
-
2
def default_url; end
-
-
end # DefaultPath
-
end # Uploader
-
end # CarrierWave
-
# encoding: utf-8
-
-
2
require 'open-uri'
-
-
2
module CarrierWave
-
2
module Uploader
-
2
module Download
-
2
extend ActiveSupport::Concern
-
-
2
include CarrierWave::Uploader::Callbacks
-
2
include CarrierWave::Uploader::Configuration
-
2
include CarrierWave::Uploader::Cache
-
-
2
class RemoteFile
-
2
def initialize(uri)
-
@uri = uri
-
end
-
-
2
def original_filename
-
filename = filename_from_header || File.basename(file.base_uri.path)
-
mime_type = MIME::Types[file.content_type].first
-
unless File.extname(filename).present? || mime_type.blank?
-
filename = "#{filename}.#{mime_type.extensions.first}"
-
end
-
filename
-
end
-
-
2
def respond_to?(*args)
-
super or file.respond_to?(*args)
-
end
-
-
2
def http?
-
@uri.scheme =~ /^https?$/
-
end
-
-
2
private
-
-
2
def file
-
if @file.blank?
-
@file = Kernel.open(@uri.to_s)
-
@file = @file.is_a?(String) ? StringIO.new(@file) : @file
-
end
-
@file
-
-
rescue Exception => e
-
raise CarrierWave::DownloadError, "could not download file: #{e.message}"
-
end
-
-
2
def filename_from_header
-
if file.meta.include? 'content-disposition'
-
match = file.meta['content-disposition'].match(/filename="?([^"]+)/)
-
return match[1] unless match.nil? || match[1].empty?
-
end
-
end
-
-
2
def method_missing(*args, &block)
-
file.send(*args, &block)
-
end
-
end
-
-
##
-
# Caches the file by downloading it from the given URL.
-
#
-
# === Parameters
-
#
-
# [url (String)] The URL where the remote file is stored
-
#
-
2
def download!(uri)
-
processed_uri = process_uri(uri)
-
file = RemoteFile.new(processed_uri)
-
raise CarrierWave::DownloadError, "trying to download a file which is not served over HTTP" unless file.http?
-
cache!(file)
-
end
-
-
##
-
# Processes the given URL by parsing and escaping it. Public to allow overriding.
-
#
-
# === Parameters
-
#
-
# [url (String)] The URL where the remote file is stored
-
#
-
2
def process_uri(uri)
-
URI.parse(uri)
-
rescue URI::InvalidURIError
-
uri_parts = uri.split('?')
-
# regexp from Ruby's URI::Parser#regexp[:UNSAFE], with [] specifically removed
-
encoded_uri = URI.encode(uri_parts.shift, /[^\-_.!~*'()a-zA-Z\d;\/?:@&=+$,]/)
-
encoded_uri << '?' << URI.encode(uri_parts.join('?')) if uri_parts.any?
-
URI.parse(encoded_uri) rescue raise CarrierWave::DownloadError, "couldn't parse URL"
-
end
-
-
end # Download
-
end # Uploader
-
end # CarrierWave
-
2
module CarrierWave
-
2
module Uploader
-
2
module ExtensionBlacklist
-
2
extend ActiveSupport::Concern
-
-
2
included do
-
2
before :cache, :check_blacklist!
-
end
-
-
##
-
# Override this method in your uploader to provide a black list of extensions which
-
# are prohibited to be uploaded. Compares the file's extension case insensitive.
-
# Furthermore, not only strings but Regexp are allowed as well.
-
#
-
# When using a Regexp in the black list, `\A` and `\z` are automatically added to
-
# the Regexp expression, also case insensitive.
-
#
-
# === Returns
-
-
# [NilClass, Array[String,Regexp]] a black list of extensions which are prohibited to be uploaded
-
#
-
# === Examples
-
#
-
# def extension_black_list
-
# %w(swf tiff)
-
# end
-
#
-
# Basically the same, but using a Regexp:
-
#
-
# def extension_black_list
-
# [/swf/, 'tiff']
-
# end
-
#
-
-
2
def extension_black_list; end
-
-
2
private
-
-
2
def check_blacklist!(new_file)
-
extension = new_file.extension.to_s
-
if extension_black_list and extension_black_list.detect { |item| extension =~ /\A#{item}\z/i }
-
raise CarrierWave::IntegrityError, I18n.translate(:"errors.messages.extension_black_list_error", :extension => new_file.extension.inspect, :prohibited_types => extension_black_list.join(", "))
-
end
-
end
-
end
-
end
-
end
-
# encoding: utf-8
-
-
2
module CarrierWave
-
2
module Uploader
-
2
module ExtensionWhitelist
-
2
extend ActiveSupport::Concern
-
-
2
included do
-
2
before :cache, :check_whitelist!
-
end
-
-
##
-
# Override this method in your uploader to provide a white list of extensions which
-
# are allowed to be uploaded. Compares the file's extension case insensitive.
-
# Furthermore, not only strings but Regexp are allowed as well.
-
#
-
# When using a Regexp in the white list, `\A` and `\z` are automatically added to
-
# the Regexp expression, also case insensitive.
-
#
-
# === Returns
-
#
-
# [NilClass, Array[String,Regexp]] a white list of extensions which are allowed to be uploaded
-
#
-
# === Examples
-
#
-
# def extension_white_list
-
# %w(jpg jpeg gif png)
-
# end
-
#
-
# Basically the same, but using a Regexp:
-
#
-
# def extension_white_list
-
# [/jpe?g/, 'gif', 'png']
-
# end
-
#
-
2
def extension_white_list; end
-
-
2
private
-
-
2
def check_whitelist!(new_file)
-
extension = new_file.extension.to_s
-
if extension_white_list and not extension_white_list.detect { |item| extension =~ /\A#{item}\z/i }
-
raise CarrierWave::IntegrityError, I18n.translate(:"errors.messages.extension_white_list_error", :extension => new_file.extension.inspect, :allowed_types => extension_white_list.join(", "))
-
end
-
end
-
-
end # ExtensionWhitelist
-
end # Uploader
-
end # CarrierWave
-
# encoding: utf-8
-
-
2
module CarrierWave
-
2
module Uploader
-
2
module Mountable
-
-
2
attr_reader :model, :mounted_as
-
-
##
-
# If a model is given as the first parameter, it will be stored in the uploader, and
-
# available throught +#model+. Likewise, mounted_as stores the name of the column
-
# where this instance of the uploader is mounted. These values can then be used inside
-
# your uploader.
-
#
-
# If you do not wish to mount your uploaders with the ORM extensions in -more then you
-
# can override this method inside your uploader. Just be sure to call +super+
-
#
-
# === Parameters
-
#
-
# [model (Object)] Any kind of model object
-
# [mounted_as (Symbol)] The name of the column where this uploader is mounted
-
#
-
# === Examples
-
#
-
# class MyUploader < CarrierWave::Uploader::Base
-
#
-
# def store_dir
-
# File.join('public', 'files', mounted_as, model.permalink)
-
# end
-
# end
-
#
-
2
def initialize(model=nil, mounted_as=nil)
-
195
@model = model
-
195
@mounted_as = mounted_as
-
end
-
-
end # Mountable
-
end # Uploader
-
end # CarrierWave
-
# encoding: utf-8
-
-
2
module CarrierWave
-
2
module Uploader
-
2
module Processing
-
2
extend ActiveSupport::Concern
-
-
2
include CarrierWave::Uploader::Callbacks
-
-
2
included do
-
2
class_attribute :processors, :instance_writer => false
-
2
self.processors = []
-
-
2
after :cache, :process!
-
end
-
-
2
module ClassMethods
-
-
##
-
# Adds a processor callback which applies operations as a file is uploaded.
-
# The argument may be the name of any method of the uploader, expressed as a symbol,
-
# or a list of such methods, or a hash where the key is a method and the value is
-
# an array of arguments to call the method with
-
#
-
# === Parameters
-
#
-
# args (*Symbol, Hash{Symbol => Array[]})
-
#
-
# === Examples
-
#
-
# class MyUploader < CarrierWave::Uploader::Base
-
#
-
# process :sepiatone, :vignette
-
# process :scale => [200, 200]
-
# process :scale => [200, 200], :if => :image?
-
# process :sepiatone, :if => :image?
-
#
-
# def sepiatone
-
# ...
-
# end
-
#
-
# def vignette
-
# ...
-
# end
-
#
-
# def scale(height, width)
-
# ...
-
# end
-
#
-
# def image?
-
# ...
-
# end
-
#
-
# end
-
#
-
2
def process(*args)
-
new_processors = args.inject({}) do |hash, arg|
-
arg = { arg => [] } unless arg.is_a?(Hash)
-
hash.merge!(arg)
-
end
-
-
condition = new_processors.delete(:if)
-
new_processors.each do |processor, processor_args|
-
self.processors += [[processor, processor_args, condition]]
-
end
-
end
-
-
end # ClassMethods
-
-
##
-
# Apply all process callbacks added through CarrierWave.process
-
#
-
2
def process!(new_file=nil)
-
return unless enable_processing
-
-
self.class.processors.each do |method, args, condition|
-
if(condition)
-
if condition.respond_to?(:call)
-
next unless condition.call(self, :args => args, :method => method, :file => new_file)
-
else
-
next unless self.send(condition, new_file)
-
end
-
end
-
self.send(method, *args)
-
end
-
end
-
-
end # Processing
-
end # Uploader
-
end # CarrierWave
-
# encoding: utf-8
-
-
2
module CarrierWave
-
2
module Uploader
-
2
module Proxy
-
-
##
-
# === Returns
-
#
-
# [Boolean] Whether the uploaded file is blank
-
#
-
2
def blank?
-
1749
file.blank?
-
end
-
-
##
-
# === Returns
-
#
-
# [String] the path where the file is currently located.
-
#
-
2
def current_path
-
file.path if file.respond_to?(:path)
-
end
-
-
2
alias_method :path, :current_path
-
-
##
-
# Returns a string that uniquely identifies the last stored file
-
#
-
# === Returns
-
#
-
# [String] uniquely identifies a file
-
#
-
2
def identifier
-
193
storage.identifier if storage.respond_to?(:identifier)
-
end
-
-
##
-
# Read the contents of the file
-
#
-
# === Returns
-
#
-
# [String] contents of the file
-
#
-
2
def read
-
file.read if file.respond_to?(:read)
-
end
-
-
##
-
# Fetches the size of the currently stored/cached file
-
#
-
# === Returns
-
#
-
# [Integer] size of the file
-
#
-
2
def size
-
file.respond_to?(:size) ? file.size : 0
-
end
-
-
##
-
# Return the size of the file when asked for its length
-
#
-
# === Returns
-
#
-
# [Integer] size of the file
-
#
-
# === Note
-
#
-
# This was added because of the way Rails handles length/size validations in 3.0.6 and above.
-
#
-
2
def length
-
size
-
end
-
-
##
-
# Read the content type of the file
-
#
-
# === Returns
-
#
-
# [String] content type of the file
-
#
-
2
def content_type
-
file.respond_to?(:content_type) ? file.content_type : nil
-
end
-
-
end # Proxy
-
end # Uploader
-
end # CarrierWave
-
# encoding: utf-8
-
-
2
module CarrierWave
-
2
module Uploader
-
2
module Remove
-
2
extend ActiveSupport::Concern
-
-
2
include CarrierWave::Uploader::Callbacks
-
-
##
-
# Removes the file and reset it
-
#
-
2
def remove!
-
with_callbacks(:remove) do
-
@file.delete if @file
-
@file = nil
-
@cache_id = nil
-
end
-
end
-
-
end # Remove
-
end # Uploader
-
end # CarrierWave
-
# encoding: utf-8
-
-
2
require "json"
-
2
require "active_support/core_ext/hash"
-
-
2
module CarrierWave
-
2
module Uploader
-
2
module Serialization
-
2
extend ActiveSupport::Concern
-
-
2
def serializable_hash(options = nil)
-
{"url" => url}.merge Hash[versions.map { |name, version| [name, { "url" => version.url }] }]
-
end
-
-
2
def as_json(options=nil)
-
Hash[mounted_as || "uploader", serializable_hash]
-
end
-
-
2
def to_json(options=nil)
-
JSON.generate(as_json)
-
end
-
-
2
def to_xml(options={})
-
merged_options = options.merge(:root => mounted_as || "uploader", :type => 'uploader')
-
serializable_hash.to_xml(merged_options)
-
end
-
-
end
-
end
-
end
-
# encoding: utf-8
-
-
2
module CarrierWave
-
2
module Uploader
-
2
module Store
-
2
extend ActiveSupport::Concern
-
-
2
include CarrierWave::Uploader::Callbacks
-
2
include CarrierWave::Uploader::Configuration
-
2
include CarrierWave::Uploader::Cache
-
-
##
-
# Override this in your Uploader to change the filename.
-
#
-
# Be careful using record ids as filenames. If the filename is stored in the database
-
# the record id will be nil when the filename is set. Don't use record ids unless you
-
# understand this limitation.
-
#
-
# Do not use the version_name in the filename, as it will prevent versions from being
-
# loaded correctly.
-
#
-
# === Returns
-
#
-
# [String] a filename
-
#
-
2
def filename
-
193
@filename
-
end
-
-
##
-
# Calculates the path where the file should be stored. If +for_file+ is given, it will be
-
# used as the filename, otherwise +CarrierWave::Uploader#filename+ is assumed.
-
#
-
# === Parameters
-
#
-
# [for_file (String)] name of the file <optional>
-
#
-
# === Returns
-
#
-
# [String] the store path
-
#
-
2
def store_path(for_file=filename)
-
File.join([store_dir, full_filename(for_file)].compact)
-
end
-
-
##
-
# Stores the file by passing it to this Uploader's storage engine.
-
#
-
# If new_file is omitted, a previously cached file will be stored.
-
#
-
# === Parameters
-
#
-
# [new_file (File, IOString, Tempfile)] any kind of file object
-
#
-
2
def store!(new_file=nil)
-
cache!(new_file) if new_file && ((@cache_id != parent_cache_id) || @cache_id.nil?)
-
if @file and @cache_id
-
with_callbacks(:store, new_file) do
-
new_file = storage.store!(@file)
-
@file.delete if (delete_tmp_file_after_storage && ! move_to_store)
-
delete_cache_id
-
@file = new_file
-
@cache_id = nil
-
end
-
end
-
end
-
-
##
-
# Deletes a cache id (tmp dir in cache)
-
#
-
2
def delete_cache_id
-
if @cache_id
-
path = File.expand_path(File.join(cache_dir, @cache_id), CarrierWave.root)
-
begin
-
Dir.rmdir(path)
-
rescue Errno::ENOENT
-
# Ignore: path does not exist
-
rescue Errno::ENOTDIR
-
# Ignore: path is not a dir
-
rescue Errno::ENOTEMPTY, Errno::EEXIST
-
# Ignore: dir is not empty
-
end
-
end
-
end
-
-
##
-
# Retrieves the file from the storage.
-
#
-
# === Parameters
-
#
-
# [identifier (String)] uniquely identifies the file to retrieve
-
#
-
2
def retrieve_from_store!(identifier)
-
with_callbacks(:retrieve_from_store, identifier) do
-
@file = storage.retrieve!(identifier)
-
end
-
end
-
-
2
private
-
-
2
def full_filename(for_file)
-
for_file
-
end
-
-
2
def storage
-
386
@storage ||= self.class.storage.new(self)
-
end
-
-
end # Store
-
end # Uploader
-
end # CarrierWave
-
# encoding: utf-8
-
-
2
module CarrierWave
-
2
module Uploader
-
2
module Url
-
2
extend ActiveSupport::Concern
-
2
include CarrierWave::Uploader::Configuration
-
2
include CarrierWave::Utilities::Uri
-
-
##
-
# === Parameters
-
#
-
# [Hash] optional, the query params (only AWS)
-
#
-
# === Returns
-
#
-
# [String] the location where this file is accessible via a url
-
#
-
2
def url(options = {})
-
if file.respond_to?(:url) and not file.url.blank?
-
file.method(:url).arity == 0 ? file.url : file.url(options)
-
elsif file.respond_to?(:path)
-
path = encode_path(file.path.gsub(File.expand_path(root), ''))
-
-
if host = asset_host
-
if host.respond_to? :call
-
"#{host.call(file)}#{path}"
-
else
-
"#{host}#{path}"
-
end
-
else
-
(base_path || "") + path
-
end
-
end
-
end
-
-
2
def to_s
-
url || ''
-
end
-
-
end # Url
-
end # Uploader
-
end # CarrierWave
-
# encoding: utf-8
-
-
2
module CarrierWave
-
2
module Uploader
-
2
module Versions
-
2
extend ActiveSupport::Concern
-
-
2
include CarrierWave::Uploader::Callbacks
-
-
2
included do
-
2
class_attribute :versions, :version_names, :instance_reader => false, :instance_writer => false
-
-
2
self.versions = {}
-
2
self.version_names = []
-
-
2
attr_accessor :parent_cache_id
-
-
2
after :cache, :assign_parent_cache_id
-
2
after :cache, :cache_versions!
-
2
after :store, :store_versions!
-
2
after :remove, :remove_versions!
-
2
after :retrieve_from_cache, :retrieve_versions_from_cache!
-
2
after :retrieve_from_store, :retrieve_versions_from_store!
-
end
-
-
2
module ClassMethods
-
-
##
-
# Adds a new version to this uploader
-
#
-
# === Parameters
-
#
-
# [name (#to_sym)] name of the version
-
# [options (Hash)] optional options hash
-
# [&block (Proc)] a block to eval on this version of the uploader
-
#
-
# === Examples
-
#
-
# class MyUploader < CarrierWave::Uploader::Base
-
#
-
# version :thumb do
-
# process :scale => [200, 200]
-
# end
-
#
-
# version :preview, :if => :image? do
-
# process :scale => [200, 200]
-
# end
-
#
-
# end
-
#
-
2
def version(name, options = {}, &block)
-
name = name.to_sym
-
build_version(name, options) unless versions[name]
-
-
versions[name][:uploader].class_eval(&block) if block
-
versions[name]
-
end
-
-
2
def recursively_apply_block_to_versions(&block)
-
versions.each do |name, version|
-
version[:uploader].class_eval(&block)
-
version[:uploader].recursively_apply_block_to_versions(&block)
-
end
-
end
-
-
2
private
-
-
2
def build_version(name, options)
-
uploader = Class.new(self)
-
const_set("Uploader#{uploader.object_id}".gsub('-', '_'), uploader)
-
uploader.version_names += [name]
-
uploader.versions = {}
-
uploader.processors = []
-
-
uploader.class_eval <<-RUBY, __FILE__, __LINE__ + 1
-
# Define the enable_processing method for versions so they get the
-
# value from the parent class unless explicitly overwritten
-
def self.enable_processing(value=nil)
-
self.enable_processing = value if value
-
if !@enable_processing.nil?
-
@enable_processing
-
else
-
superclass.enable_processing
-
end
-
end
-
-
# Regardless of what is set in the parent uploader, do not enforce the
-
# move_to_cache config option on versions because it moves the original
-
# file to the version's target file.
-
#
-
# If you want to enforce this setting on versions, override this method
-
# in each version:
-
#
-
# version :thumb do
-
# def move_to_cache
-
# true
-
# end
-
# end
-
#
-
def move_to_cache
-
false
-
end
-
RUBY
-
-
class_eval <<-RUBY
-
def #{name}
-
versions[:#{name}]
-
end
-
RUBY
-
-
# Add the current version hash to class attribute :versions
-
current_version = {
-
name => {
-
:uploader => uploader,
-
:options => options
-
}
-
}
-
self.versions = versions.merge(current_version)
-
end
-
-
end # ClassMethods
-
-
##
-
# Returns a hash mapping the name of each version of the uploader to an instance of it
-
#
-
# === Returns
-
#
-
# [Hash{Symbol => CarrierWave::Uploader}] a list of uploader instances
-
#
-
2
def versions
-
return @versions if @versions
-
@versions = {}
-
self.class.versions.each do |name, version|
-
@versions[name] = version[:uploader].new(model, mounted_as)
-
end
-
@versions
-
end
-
-
##
-
# === Returns
-
#
-
# [String] the name of this version of the uploader
-
#
-
2
def version_name
-
self.class.version_names.join('_').to_sym unless self.class.version_names.blank?
-
end
-
-
##
-
#
-
# === Parameters
-
#
-
# [name (#to_sym)] name of the version
-
#
-
# === Returns
-
#
-
# [Boolean] True when the version exists according to its :if condition
-
#
-
2
def version_exists?(name)
-
name = name.to_sym
-
-
return false unless self.class.versions.has_key?(name)
-
-
condition = self.class.versions[name][:options][:if]
-
if(condition)
-
if(condition.respond_to?(:call))
-
condition.call(self, :version => name, :file => file)
-
else
-
send(condition, file)
-
end
-
else
-
true
-
end
-
end
-
-
##
-
# When given a version name as a parameter, will return the url for that version
-
# This also works with nested versions.
-
# When given a query hash as a parameter, will return the url with signature that contains query params
-
# Query hash only works with AWS (S3 storage).
-
#
-
# === Example
-
#
-
# my_uploader.url # => /path/to/my/uploader.gif
-
# my_uploader.url(:thumb) # => /path/to/my/thumb_uploader.gif
-
# my_uploader.url(:thumb, :small) # => /path/to/my/thumb_small_uploader.gif
-
# my_uploader.url(:query => {"response-content-disposition" => "attachment"})
-
# my_uploader.url(:version, :sub_version, :query => {"response-content-disposition" => "attachment"})
-
#
-
# === Parameters
-
#
-
# [*args (Symbol)] any number of versions
-
# OR/AND
-
# [Hash] query params
-
#
-
# === Returns
-
#
-
# [String] the location where this file is accessible via a url
-
#
-
2
def url(*args)
-
if (version = args.first) && version.respond_to?(:to_sym)
-
raise ArgumentError, "Version #{version} doesn't exist!" if versions[version.to_sym].nil?
-
# recursively proxy to version
-
versions[version.to_sym].url(*args[1..-1])
-
elsif args.first
-
super(args.first)
-
else
-
super
-
end
-
end
-
-
##
-
# Recreate versions and reprocess them. This can be used to recreate
-
# versions if their parameters somehow have changed.
-
#
-
2
def recreate_versions!(*versions)
-
# Some files could possibly not be stored on the local disk. This
-
# doesn't play nicely with processing. Make sure that we're only
-
# processing a cached file
-
#
-
# The call to store! will trigger the necessary callbacks to both
-
# process this version and all sub-versions
-
if versions.any?
-
file = sanitized_file if !cached?
-
store_versions!(file, versions)
-
else
-
cache! if !cached?
-
store!
-
end
-
end
-
-
2
private
-
2
def assign_parent_cache_id(file)
-
active_versions.each do |name, uploader|
-
uploader.parent_cache_id = @cache_id
-
end
-
end
-
-
2
def active_versions
-
versions.select do |name, uploader|
-
version_exists?(name)
-
end
-
end
-
-
2
def full_filename(for_file)
-
[version_name, super(for_file)].compact.join('_')
-
end
-
-
2
def full_original_filename
-
[version_name, super].compact.join('_')
-
end
-
-
2
def cache_versions!(new_file)
-
# We might have processed the new_file argument after the callbacks were
-
# initialized, so get the actual file based off of the current state of
-
# our file
-
processed_parent = SanitizedFile.new :tempfile => self.file,
-
:filename => new_file.original_filename
-
-
active_versions.each do |name, v|
-
next if v.cached?
-
-
v.send(:cache_id=, cache_id)
-
# If option :from_version is present, create cache using cached file from
-
# version indicated
-
if self.class.versions[name][:options] && self.class.versions[name][:options][:from_version]
-
# Maybe the reference version has not been cached yet
-
unless versions[self.class.versions[name][:options][:from_version]].cached?
-
versions[self.class.versions[name][:options][:from_version]].cache!(processed_parent)
-
end
-
processed_version = SanitizedFile.new :tempfile => versions[self.class.versions[name][:options][:from_version]],
-
:filename => new_file.original_filename
-
v.cache!(processed_version)
-
else
-
v.cache!(processed_parent)
-
end
-
end
-
end
-
-
2
def store_versions!(new_file, versions=nil)
-
if versions
-
active = Hash[active_versions]
-
versions.each { |v| active[v].try(:store!, new_file) } unless active.empty?
-
else
-
active_versions.each { |name, v| v.store!(new_file) }
-
end
-
end
-
-
2
def remove_versions!
-
versions.each { |name, v| v.remove! }
-
end
-
-
2
def retrieve_versions_from_cache!(cache_name)
-
versions.each { |name, v| v.retrieve_from_cache!(cache_name) }
-
end
-
-
2
def retrieve_versions_from_store!(identifier)
-
versions.each { |name, v| v.retrieve_from_store!(identifier) }
-
end
-
-
end # Versions
-
end # Uploader
-
end # CarrierWave
-
# encoding: utf-8
-
-
2
require 'carrierwave/utilities/uri'
-
2
require 'carrierwave/utilities/deprecation'
-
-
2
module CarrierWave
-
2
module Utilities
-
end
-
end
-
# encoding: utf-8
-
2
require 'active_support/deprecation'
-
-
2
module CarrierWave
-
2
module Utilities
-
2
module Deprecation
-
-
2
def self.new version = '0.11.0', message = 'Carrierwave'
-
if ActiveSupport::VERSION::MAJOR < 4
-
ActiveSupport::Deprecation.warn("#{message} (will be removed from version #{version})")
-
else
-
ActiveSupport::Deprecation.new(version, message)
-
end
-
end
-
-
end # Deprecation
-
end # Utilities
-
end # CarrierWave
-
# encoding: utf-8
-
-
2
module CarrierWave
-
2
module Utilities
-
2
module Uri
-
-
2
private
-
2
def encode_path(path)
-
# based on Ruby < 2.0's URI.encode
-
safe_string = URI::REGEXP::PATTERN::UNRESERVED + '\/'
-
unsafe = Regexp.new("[^#{safe_string}]", false)
-
-
path.to_s.gsub(unsafe) do
-
us = $&
-
tmp = ''
-
us.each_byte do |uc|
-
tmp << sprintf('%%%02X', uc)
-
end
-
tmp
-
end
-
end
-
end # Uri
-
end # Utilities
-
end # CarrierWave
-
# encoding: utf-8
-
-
2
require 'active_model/validator'
-
2
require 'active_support/concern'
-
-
2
module CarrierWave
-
-
# == Active Model Presence Validator
-
2
module Validations
-
2
module ActiveModel
-
2
extend ActiveSupport::Concern
-
-
2
class ProcessingValidator < ::ActiveModel::EachValidator
-
-
2
def validate_each(record, attribute, value)
-
195
if e = record.send("#{attribute}_processing_error")
-
message = (e.message == e.class.to_s) ? :carrierwave_processing_error : e.message
-
record.errors.add(attribute, message)
-
end
-
end
-
end
-
-
2
class IntegrityValidator < ::ActiveModel::EachValidator
-
-
2
def validate_each(record, attribute, value)
-
195
if e = record.send("#{attribute}_integrity_error")
-
message = (e.message == e.class.to_s) ? :carrierwave_integrity_error : e.message
-
record.errors.add(attribute, message)
-
end
-
end
-
end
-
-
2
class DownloadValidator < ::ActiveModel::EachValidator
-
-
2
def validate_each(record, attribute, value)
-
195
if e = record.send("#{attribute}_download_error")
-
message = (e.message == e.class.to_s) ? :carrierwave_download_error : e.message
-
record.errors.add(attribute, message)
-
end
-
end
-
end
-
-
2
module HelperMethods
-
-
##
-
# Makes the record invalid if the file couldn't be uploaded due to an integrity error
-
#
-
# Accepts the usual parameters for validations in Rails (:if, :unless, etc...)
-
#
-
2
def validates_integrity_of(*attr_names)
-
4
validates_with IntegrityValidator, _merge_attributes(attr_names)
-
end
-
-
##
-
# Makes the record invalid if the file couldn't be processed (assuming the process failed
-
# with a CarrierWave::ProcessingError)
-
#
-
# Accepts the usual parameters for validations in Rails (:if, :unless, etc...)
-
#
-
2
def validates_processing_of(*attr_names)
-
4
validates_with ProcessingValidator, _merge_attributes(attr_names)
-
end
-
#
-
##
-
# Makes the record invalid if the remote file couldn't be downloaded
-
#
-
# Accepts the usual parameters for validations in Rails (:if, :unless, etc...)
-
#
-
2
def validates_download_of(*attr_names)
-
4
validates_with DownloadValidator, _merge_attributes(attr_names)
-
end
-
end
-
-
2
included do
-
4
extend HelperMethods
-
4
include HelperMethods
-
end
-
end
-
end
-
end
-
2
module CarrierWave
-
2
VERSION = "0.11.0"
-
end
-
2
require 'childprocess/errors'
-
2
require 'childprocess/abstract_process'
-
2
require 'childprocess/abstract_io'
-
2
require "fcntl"
-
-
2
module ChildProcess
-
-
2
@posix_spawn = false
-
-
2
class << self
-
2
def new(*args)
-
case os
-
when :macosx, :linux, :solaris, :bsd, :cygwin, :aix
-
if posix_spawn?
-
Unix::PosixSpawnProcess.new(args)
-
elsif jruby?
-
JRuby::Process.new(args)
-
else
-
Unix::ForkExecProcess.new(args)
-
end
-
when :windows
-
Windows::Process.new(args)
-
else
-
raise Error, "unsupported platform #{platform_name.inspect}"
-
end
-
end
-
2
alias_method :build, :new
-
-
2
def platform
-
4
if RUBY_PLATFORM == "java"
-
:jruby
-
4
elsif defined?(RUBY_ENGINE) && RUBY_ENGINE == "ironruby"
-
:ironruby
-
else
-
4
os
-
end
-
end
-
-
2
def platform_name
-
@platform_name ||= "#{arch}-#{os}"
-
end
-
-
2
def unix?
-
2
!windows?
-
end
-
-
2
def linux?
-
os == :linux
-
end
-
-
2
def jruby?
-
4
platform == :jruby
-
end
-
-
2
def windows?
-
4
os == :windows
-
end
-
-
2
def posix_spawn?
-
enabled = @posix_spawn || %w[1 true].include?(ENV['CHILDPROCESS_POSIX_SPAWN'])
-
return false unless enabled
-
-
require 'ffi'
-
begin
-
require "childprocess/unix/platform/#{ChildProcess.platform_name}"
-
rescue LoadError
-
raise ChildProcess::MissingPlatformError
-
end
-
-
require "childprocess/unix/lib"
-
require 'childprocess/unix/posix_spawn_process'
-
-
true
-
rescue ChildProcess::MissingPlatformError => ex
-
warn_once ex.message
-
false
-
end
-
-
#
-
# Set this to true to enable experimental use of posix_spawn.
-
#
-
-
2
def posix_spawn=(bool)
-
@posix_spawn = bool
-
end
-
-
2
def os
-
@os ||= (
-
2
require "rbconfig"
-
2
host_os = RbConfig::CONFIG['host_os'].downcase
-
-
2
case host_os
-
when /linux/
-
2
:linux
-
when /darwin|mac os/
-
:macosx
-
when /mswin|msys|mingw32/
-
:windows
-
when /cygwin/
-
:cygwin
-
when /solaris|sunos/
-
:solaris
-
when /bsd/
-
:bsd
-
when /aix/
-
:aix
-
else
-
raise Error, "unknown os: #{host_os.inspect}"
-
end
-
8
)
-
end
-
-
2
def arch
-
@arch ||= (
-
host_cpu = RbConfig::CONFIG['host_cpu'].downcase
-
case host_cpu
-
when /i[3456]86/
-
# Darwin always reports i686, even when running in 64bit mod
-
if os == :macosx && 0xfee1deadbeef.is_a?(Fixnum)
-
"x86_64"
-
else
-
"i386"
-
end
-
when /amd64|x86_64/
-
"x86_64"
-
when /ppc|powerpc/
-
"powerpc"
-
else
-
host_cpu
-
end
-
)
-
end
-
-
#
-
# By default, a child process will inherit open file descriptors from the
-
# parent process. This helper provides a cross-platform way of making sure
-
# that doesn't happen for the given file/io.
-
#
-
-
2
def close_on_exec(file)
-
if file.respond_to?(:close_on_exec=)
-
file.close_on_exec = true
-
elsif file.respond_to?(:fcntl) && defined?(Fcntl::FD_CLOEXEC)
-
file.fcntl Fcntl::F_SETFD, Fcntl::FD_CLOEXEC
-
-
if jruby? && posix_spawn?
-
# on JRuby, the fcntl call above apparently isn't enough when
-
# we're launching the process through posix_spawn.
-
fileno = JRuby.posix_fileno_for(file)
-
Unix::Lib.fcntl fileno, Fcntl::F_SETFD, Fcntl::FD_CLOEXEC
-
end
-
elsif windows?
-
Windows::Lib.dont_inherit file
-
else
-
raise Error, "not sure how to set close-on-exec for #{file.inspect} on #{platform_name.inspect}"
-
end
-
end
-
-
2
private
-
-
2
def warn_once(msg)
-
@warnings ||= {}
-
-
unless @warnings[msg]
-
@warnings[msg] = true
-
$stderr.puts msg
-
end
-
end
-
-
end # class << self
-
end # ChildProcess
-
-
2
require 'jruby' if ChildProcess.jruby?
-
-
2
require 'childprocess/unix' if ChildProcess.unix?
-
2
require 'childprocess/windows' if ChildProcess.windows?
-
2
require 'childprocess/jruby' if ChildProcess.jruby?
-
2
module ChildProcess
-
2
class AbstractIO
-
2
attr_reader :stderr, :stdout, :stdin
-
-
2
def inherit!
-
@stdout = STDOUT
-
@stderr = STDERR
-
end
-
-
2
def stderr=(io)
-
check_type io
-
@stderr = io
-
end
-
-
2
def stdout=(io)
-
check_type io
-
@stdout = io
-
end
-
-
#
-
# @api private
-
#
-
-
2
def _stdin=(io)
-
check_type io
-
@stdin = io
-
end
-
-
2
private
-
-
2
def check_type(io)
-
raise SubclassResponsibility, "check_type"
-
end
-
-
end
-
end
-
2
module ChildProcess
-
2
class AbstractProcess
-
2
POLL_INTERVAL = 0.1
-
-
2
attr_reader :exit_code
-
-
#
-
# Set this to true if you do not care about when or if the process quits.
-
#
-
2
attr_accessor :detach
-
-
#
-
# Set this to true if you want to write to the process' stdin (process.io.stdin)
-
#
-
2
attr_accessor :duplex
-
-
#
-
# Modify the child's environment variables
-
#
-
2
attr_reader :environment
-
-
#
-
# Set the child's current working directory.
-
#
-
2
attr_accessor :cwd
-
-
#
-
#
-
# Set this to true to make the child process the leader of a new process group
-
#
-
# This can be used to make sure that all grandchildren are killed
-
# when the child process dies.
-
#
-
2
attr_accessor :leader
-
-
#
-
# Create a new process with the given args.
-
#
-
# @api private
-
# @see ChildProcess.build
-
#
-
-
2
def initialize(args)
-
unless args.all? { |e| e.kind_of?(String) }
-
raise ArgumentError, "all arguments must be String: #{args.inspect}"
-
end
-
-
@args = args
-
@started = false
-
@exit_code = nil
-
@io = nil
-
@cwd = nil
-
@detach = false
-
@duplex = false
-
@leader = false
-
@environment = {}
-
end
-
-
#
-
# Returns a ChildProcess::AbstractIO subclass to configure the child's IO streams.
-
#
-
-
2
def io
-
raise SubclassResponsibility, "io"
-
end
-
-
#
-
# @return [Fixnum] the pid of the process after it has started
-
#
-
-
2
def pid
-
raise SubclassResponsibility, "pid"
-
end
-
-
#
-
# Launch the child process
-
#
-
# @return [AbstractProcess] self
-
#
-
-
2
def start
-
launch_process
-
@started = true
-
-
self
-
end
-
-
#
-
# Forcibly terminate the process, using increasingly harsher methods if possible.
-
#
-
# @param [Fixnum] timeout (3) Seconds to wait before trying the next method.
-
#
-
-
2
def stop(timeout = 3)
-
raise SubclassResponsibility, "stop"
-
end
-
-
#
-
# Block until the process has been terminated.
-
#
-
# @return [Fixnum] The exit status of the process
-
#
-
-
2
def wait
-
raise SubclassResponsibility, "wait"
-
end
-
-
#
-
# Did the process exit?
-
#
-
# @return [Boolean]
-
#
-
-
2
def exited?
-
raise SubclassResponsibility, "exited?"
-
end
-
-
#
-
# Is this process running?
-
#
-
# @return [Boolean]
-
#
-
-
2
def alive?
-
started? && !exited?
-
end
-
-
#
-
# Returns true if the process has exited and the exit code was not 0.
-
#
-
# @return [Boolean]
-
#
-
-
2
def crashed?
-
exited? && @exit_code != 0
-
end
-
-
#
-
# Wait for the process to exit, raising a ChildProcess::TimeoutError if
-
# the timeout expires.
-
#
-
-
2
def poll_for_exit(timeout)
-
log "polling #{timeout} seconds for exit"
-
-
end_time = Time.now + timeout
-
until (ok = exited?) || Time.now > end_time
-
sleep POLL_INTERVAL
-
end
-
-
unless ok
-
raise TimeoutError, "process still alive after #{timeout} seconds"
-
end
-
end
-
-
2
private
-
-
2
def launch_process
-
raise SubclassResponsibility, "launch_process"
-
end
-
-
2
def started?
-
@started
-
end
-
-
2
def detach?
-
@detach
-
end
-
-
2
def duplex?
-
@duplex
-
end
-
-
2
def leader?
-
@leader
-
end
-
-
2
def log(*args)
-
$stderr.puts "#{self.inspect} : #{args.inspect}" if $DEBUG
-
end
-
-
2
def assert_started
-
raise Error, "process not started" unless started?
-
end
-
-
end # AbstractProcess
-
end # ChildProcess
-
2
module ChildProcess
-
2
class Error < StandardError
-
end
-
-
2
class TimeoutError < Error
-
end
-
-
2
class SubclassResponsibility < Error
-
end
-
-
2
class InvalidEnvironmentVariable < Error
-
end
-
-
2
class LaunchError < Error
-
end
-
-
2
class MissingPlatformError < Error
-
2
def initialize
-
message = "posix_spawn is not yet supported on #{ChildProcess.platform_name} (#{RUBY_PLATFORM}), falling back to default implementation. " +
-
"If you believe this is an error, please file a bug at http://github.com/jarib/childprocess/issues"
-
-
super(message)
-
end
-
-
end
-
end
-
2
module ChildProcess
-
2
module Unix
-
end
-
end
-
-
2
require "childprocess/unix/io"
-
2
require "childprocess/unix/process"
-
2
require "childprocess/unix/fork_exec_process"
-
# PosixSpawnProcess + ffi is required on demand.
-
2
module ChildProcess
-
2
module Unix
-
2
class ForkExecProcess < Process
-
2
private
-
-
2
def launch_process
-
if @io
-
stdout = @io.stdout
-
stderr = @io.stderr
-
end
-
-
# pipe used to detect exec() failure
-
exec_r, exec_w = ::IO.pipe
-
ChildProcess.close_on_exec exec_w
-
-
if duplex?
-
reader, writer = ::IO.pipe
-
end
-
-
@pid = Kernel.fork {
-
# Children of the forked process will inherit its process group
-
# This is to make sure that all grandchildren dies when this Process instance is killed
-
::Process.setpgid 0, 0 if leader?
-
-
if @cwd
-
Dir.chdir(@cwd)
-
end
-
-
exec_r.close
-
set_env
-
-
STDOUT.reopen(stdout || "/dev/null")
-
STDERR.reopen(stderr || "/dev/null")
-
-
if duplex?
-
STDIN.reopen(reader)
-
writer.close
-
end
-
-
executable, *args = @args
-
-
begin
-
Kernel.exec([executable, executable], *args)
-
rescue SystemCallError => ex
-
exec_w << ex.message
-
end
-
}
-
-
exec_w.close
-
-
if duplex?
-
io._stdin = writer
-
reader.close
-
end
-
-
# if we don't eventually get EOF, exec() failed
-
unless exec_r.eof?
-
raise LaunchError, exec_r.read || "executing command with #{@args.inspect} failed"
-
end
-
-
::Process.detach(@pid) if detach?
-
end
-
-
2
def set_env
-
@environment.each { |k, v| ENV[k.to_s] = v.nil? ? nil : v.to_s }
-
end
-
-
end # Process
-
end # Unix
-
end # ChildProcess
-
2
module ChildProcess
-
2
module Unix
-
2
class IO < AbstractIO
-
2
private
-
-
2
def check_type(io)
-
unless io.respond_to? :to_io
-
raise ArgumentError, "expected #{io.inspect} to respond to :to_io"
-
end
-
-
result = io.to_io
-
unless result && result.kind_of?(::IO)
-
raise TypeError, "expected IO, got #{result.inspect}:#{result.class}"
-
end
-
end
-
-
end # IO
-
end # Unix
-
end # ChildProcess
-
-
-
2
module ChildProcess
-
2
module Unix
-
2
class Process < AbstractProcess
-
2
attr_reader :pid
-
-
2
def io
-
@io ||= Unix::IO.new
-
end
-
-
2
def stop(timeout = 3)
-
assert_started
-
send_term
-
-
begin
-
return poll_for_exit(timeout)
-
rescue TimeoutError
-
# try next
-
end
-
-
send_kill
-
wait
-
rescue Errno::ECHILD, Errno::ESRCH
-
# handle race condition where process dies between timeout
-
# and send_kill
-
true
-
end
-
-
2
def exited?
-
return true if @exit_code
-
-
assert_started
-
pid, status = ::Process.waitpid2(_pid, ::Process::WNOHANG | ::Process::WUNTRACED)
-
pid = nil if pid == 0 # may happen on jruby
-
-
log(:pid => pid, :status => status)
-
-
if pid
-
set_exit_code(status)
-
end
-
-
!!pid
-
rescue Errno::ECHILD
-
# may be thrown for detached processes
-
true
-
end
-
-
2
def wait
-
assert_started
-
-
if exited?
-
exit_code
-
else
-
_, status = ::Process.waitpid2 _pid
-
set_exit_code(status)
-
end
-
end
-
-
2
private
-
-
2
def send_term
-
send_signal 'TERM'
-
end
-
-
2
def send_kill
-
send_signal 'KILL'
-
end
-
-
2
def send_signal(sig)
-
assert_started
-
-
log "sending #{sig}"
-
::Process.kill sig, _pid
-
end
-
-
2
def set_exit_code(status)
-
@exit_code = status.exitstatus || status.termsig
-
end
-
-
2
def _pid
-
if leader?
-
-@pid # negative pid == process group
-
else
-
@pid
-
end
-
end
-
-
end # Process
-
end # Unix
-
end # ChildProcess
-
2
require 'climate_control/modifier'
-
2
require 'climate_control/version'
-
-
2
module ClimateControl
-
2
def self.modify(environment_overrides, &block)
-
Modifier.new(environment_overrides, &block).process
-
end
-
end
-
2
require 'active_support/core_ext/hash/keys'
-
-
2
module ClimateControl
-
2
class Modifier
-
2
def initialize(environment_overrides = {}, &block)
-
@environment_overrides = environment_overrides.dup.stringify_keys!
-
@block = block
-
end
-
-
2
def process
-
begin
-
prepare_environment_for_block
-
run_block
-
ensure
-
cache_environment_after_block
-
delete_keys_that_do_not_belong
-
revert_changed_keys
-
end
-
end
-
-
2
private
-
-
2
def prepare_environment_for_block
-
@original_env = clone_environment
-
copy_overrides_to_environment
-
@env_with_overrides_before_block = clone_environment
-
end
-
-
2
def run_block
-
@block.call
-
end
-
-
2
def copy_overrides_to_environment
-
@environment_overrides.each do |key, value|
-
ENV[key] = value
-
end
-
end
-
-
2
def keys_to_remove
-
@environment_overrides.keys
-
end
-
-
2
def keys_changed_by_block
-
@keys_changed_by_block ||= OverlappingKeysWithChangedValues.new(@env_with_overrides_before_block, @env_after_block).keys
-
end
-
-
2
def cache_environment_after_block
-
@env_after_block = clone_environment
-
end
-
-
2
def delete_keys_that_do_not_belong
-
(keys_to_remove - keys_changed_by_block).each {|key| ENV.delete(key) }
-
end
-
-
2
def revert_changed_keys
-
(@original_env.keys - keys_changed_by_block).each do |key|
-
ENV[key] = @original_env[key]
-
end
-
end
-
-
2
def clone_environment
-
ENV.to_hash
-
end
-
-
2
class OverlappingKeysWithChangedValues
-
2
def initialize(hash_1, hash_2)
-
@hash_1 = hash_1
-
@hash_2 = hash_2
-
end
-
-
2
def keys
-
overlapping_keys.select do |overlapping_key|
-
@hash_1[overlapping_key] != @hash_2[overlapping_key]
-
end
-
end
-
-
2
private
-
-
2
def overlapping_keys
-
@hash_2.keys & @hash_1.keys
-
end
-
end
-
end
-
end
-
2
module ClimateControl
-
2
VERSION = '0.0.3'
-
end
-
# coding: UTF-8
-
-
2
require 'rbconfig'
-
2
require 'cocaine/os_detector'
-
2
require 'cocaine/command_line'
-
2
require 'cocaine/command_line/output'
-
2
require 'cocaine/command_line/multi_pipe'
-
2
require 'cocaine/command_line/runners'
-
2
require 'cocaine/exceptions'
-
-
2
module Cocaine
-
end
-
# coding: UTF-8
-
-
2
module Cocaine
-
2
class CommandLine
-
2
class << self
-
2
attr_accessor :logger, :runner
-
-
2
def path
-
@supplemental_path
-
end
-
-
2
def path=(supplemental_path)
-
@supplemental_path = Array(supplemental_path).
-
flatten.
-
join(OS.path_separator)
-
end
-
-
2
def environment
-
@supplemental_environment ||= {}
-
end
-
-
2
def runner
-
@runner || best_runner
-
end
-
-
2
def runner_options
-
@default_runner_options ||= {}
-
end
-
-
2
def fake!
-
@runner = FakeRunner.new
-
end
-
-
2
def unfake!
-
@runner = nil
-
end
-
-
2
private
-
-
2
def best_runner
-
[PosixRunner, ProcessRunner, BackticksRunner].detect do |runner|
-
runner.supported?
-
end.new
-
end
-
end
-
-
2
@environment = {}
-
-
2
attr_reader :exit_status, :runner
-
-
2
def initialize(binary, params = "", options = {})
-
@binary = binary.dup
-
@params = params.dup
-
@options = options.dup
-
@runner = @options.delete(:runner) || self.class.runner
-
@logger = @options.delete(:logger) || self.class.logger
-
@swallow_stderr = @options.delete(:swallow_stderr)
-
@expected_outcodes = @options.delete(:expected_outcodes) || [0]
-
@environment = @options.delete(:environment) || {}
-
@runner_options = @options.delete(:runner_options) || {}
-
end
-
-
2
def command(interpolations = {})
-
cmd = [path_prefix, @binary, interpolate(@params, interpolations)]
-
cmd << bit_bucket if @swallow_stderr
-
cmd.join(" ").strip
-
end
-
-
2
def run(interpolations = {})
-
@exit_status = nil
-
begin
-
full_command = command(interpolations)
-
log("#{colored("Command")} :: #{full_command}")
-
@output = execute(full_command)
-
rescue Errno::ENOENT => e
-
raise Cocaine::CommandNotFoundError, e.message
-
ensure
-
@exit_status = $?.respond_to?(:exitstatus) ? $?.exitstatus : 0
-
end
-
-
if @exit_status == 127
-
raise Cocaine::CommandNotFoundError
-
end
-
-
unless @expected_outcodes.include?(@exit_status)
-
message = [
-
"Command '#{full_command}' returned #{@exit_status}. Expected #{@expected_outcodes.join(", ")}",
-
"Here is the command output: STDOUT:\n", command_output,
-
"\nSTDERR:\n", command_error_output
-
].join("\n")
-
raise Cocaine::ExitStatusError, message
-
end
-
command_output
-
end
-
-
2
def command_output
-
output.output
-
end
-
-
2
def command_error_output
-
output.error_output
-
end
-
-
2
def output
-
@output || Output.new
-
end
-
-
2
private
-
-
2
def colored(text, ansi_color = "\e[32m")
-
if @logger && @logger.respond_to?(:tty?) && @logger.tty?
-
"#{ansi_color}#{text}\e[0m"
-
else
-
text
-
end
-
end
-
-
2
def log(text)
-
if @logger
-
@logger.info(text)
-
end
-
end
-
-
2
def path_prefix
-
if !self.class.path.nil? && !self.class.path.empty?
-
os_path_prefix
-
end
-
end
-
-
2
def os_path_prefix
-
if OS.unix?
-
unix_path_prefix
-
else
-
windows_path_prefix
-
end
-
end
-
-
2
def unix_path_prefix
-
"PATH=#{self.class.path}#{OS.path_separator}$PATH;"
-
end
-
-
2
def windows_path_prefix
-
"SET PATH=#{self.class.path}#{OS.path_separator}%PATH% &"
-
end
-
-
2
def execute(command)
-
runner.call(command, environment, runner_options)
-
end
-
-
2
def environment
-
self.class.environment.merge(@environment)
-
end
-
-
2
def runner_options
-
self.class.runner_options.merge(@runner_options)
-
end
-
-
2
def interpolate(pattern, interpolations)
-
interpolations = stringify_keys(interpolations)
-
pattern.gsub(/:\{?(\w+)\b\}?/) do |match|
-
key = match.tr(":{}", "")
-
if interpolations.key?(key)
-
shell_quote_all_values(interpolations[key])
-
else
-
match
-
end
-
end
-
end
-
-
2
def stringify_keys(hash)
-
Hash[hash.map{ |k, v| [k.to_s, v] }]
-
end
-
-
2
def shell_quote_all_values(values)
-
Array(values).map(&method(:shell_quote)).join(" ")
-
end
-
-
2
def shell_quote(string)
-
return "" if string.nil?
-
string = string.to_s if string.respond_to? :to_s
-
-
if OS.unix?
-
if string.empty?
-
"''"
-
else
-
string.split("'", -1).map{|m| "'#{m}'" }.join("\\'")
-
end
-
else
-
%{"#{string}"}
-
end
-
end
-
-
2
def bit_bucket
-
OS.unix? ? "2>/dev/null" : "2>NUL"
-
end
-
end
-
end
-
2
module Cocaine
-
2
class CommandLine
-
2
class MultiPipe
-
2
def initialize
-
@stdout_in, @stdout_out = IO.pipe
-
@stderr_in, @stderr_out = IO.pipe
-
end
-
-
2
def pipe_options
-
{ out: @stdout_out, err: @stderr_out }
-
end
-
-
2
def output
-
Output.new(@stdout_output, @stderr_output)
-
end
-
-
2
def read_and_then(&block)
-
close_write
-
read
-
block.call
-
close_read
-
end
-
-
2
private
-
-
2
def close_write
-
@stdout_out.close
-
@stderr_out.close
-
end
-
-
2
def read
-
@stdout_output = read_stream(@stdout_in)
-
@stderr_output = read_stream(@stderr_in)
-
end
-
-
2
def close_read
-
@stdout_in.close
-
@stderr_in.close
-
end
-
-
2
def read_stream(io)
-
result = ""
-
while partial_result = io.read(8192)
-
result << partial_result
-
end
-
result
-
end
-
end
-
end
-
end
-
2
class Cocaine::CommandLine::Output
-
2
def initialize(output = nil, error_output = nil)
-
@output = output
-
@error_output = error_output
-
end
-
-
2
attr_reader :output, :error_output
-
-
2
def to_s
-
output.to_s
-
end
-
end
-
# coding: UTF-8
-
-
2
require 'cocaine/command_line/runners/backticks_runner'
-
2
require 'cocaine/command_line/runners/process_runner'
-
2
require 'cocaine/command_line/runners/posix_runner'
-
2
require 'cocaine/command_line/runners/popen_runner'
-
2
require 'cocaine/command_line/runners/fake_runner'
-
# coding: UTF-8
-
-
2
require 'climate_control'
-
-
2
module Cocaine
-
2
class CommandLine
-
2
class BackticksRunner
-
2
def self.supported?
-
true
-
end
-
-
2
def supported?
-
self.class.supported?
-
end
-
-
2
def call(command, env = {}, options = {})
-
with_modified_environment(env) do
-
Output.new(`#{command}`)
-
end
-
end
-
-
2
private
-
-
2
def with_modified_environment(env, &block)
-
ClimateControl.modify(env, &block)
-
end
-
-
end
-
end
-
end
-
# coding: UTF-8
-
-
2
module Cocaine
-
2
class CommandLine
-
2
class FakeRunner
-
2
def self.supported?
-
false
-
end
-
-
2
def supported?
-
self.class.supported?
-
end
-
-
2
attr_reader :commands
-
-
2
def initialize
-
@commands = []
-
end
-
-
2
def call(command, env = {}, options = {})
-
commands << [command, env]
-
Output.new("")
-
end
-
-
2
def ran?(predicate_command)
-
@commands.any?{|(command, _)| command =~ Regexp.new(predicate_command) }
-
end
-
end
-
end
-
end
-
# coding: UTF-8
-
-
2
module Cocaine
-
2
class CommandLine
-
2
class PopenRunner
-
2
def self.supported?
-
true
-
end
-
-
2
def supported?
-
self.class.supported?
-
end
-
-
2
def call(command, env = {}, options = {})
-
with_modified_environment(env) do
-
IO.popen(command, "r", options) do |pipe|
-
Output.new(pipe.read)
-
end
-
end
-
end
-
-
2
private
-
-
2
def with_modified_environment(env, &block)
-
ClimateControl.modify(env, &block)
-
end
-
end
-
end
-
end
-
# coding: UTF-8
-
-
2
module Cocaine
-
2
class CommandLine
-
2
class PosixRunner
-
2
def self.available?
-
return @available unless @available.nil?
-
-
@available = posix_spawn_gem_available?
-
end
-
-
2
def self.supported?
-
available? && !OS.java?
-
end
-
-
2
def supported?
-
self.class.supported?
-
end
-
-
2
def call(command, env = {}, options = {})
-
pipe = MultiPipe.new
-
pid = spawn(env, command, options.merge(pipe.pipe_options))
-
pipe.read_and_then do
-
waitpid(pid)
-
end
-
pipe.output
-
end
-
-
2
private
-
-
2
def spawn(*args)
-
POSIX::Spawn.spawn(*args)
-
end
-
-
2
def waitpid(pid)
-
Process.waitpid(pid)
-
end
-
-
2
def self.posix_spawn_gem_available?
-
require 'posix/spawn'
-
true
-
rescue LoadError
-
false
-
end
-
-
2
private_class_method :posix_spawn_gem_available?
-
end
-
end
-
end
-
# coding: UTF-8
-
-
2
module Cocaine
-
2
class CommandLine
-
2
class ProcessRunner
-
2
def self.available?
-
Process.respond_to?(:spawn)
-
end
-
-
2
def self.supported?
-
available? && !OS.java?
-
end
-
-
2
def supported?
-
self.class.supported?
-
end
-
-
2
def call(command, env = {}, options = {})
-
pipe = MultiPipe.new
-
pid = spawn(env, command, options.merge(pipe.pipe_options))
-
pipe.read_and_then do
-
waitpid(pid)
-
end
-
pipe.output
-
end
-
-
2
private
-
-
2
def spawn(*args)
-
Process.spawn(*args)
-
end
-
-
2
def waitpid(pid)
-
Process.waitpid(pid)
-
rescue Errno::ECHILD
-
# In JRuby, waiting on a finished pid raises.
-
end
-
-
end
-
end
-
end
-
# coding: UTF-8
-
-
2
module Cocaine
-
2
class CommandLineError < StandardError; end
-
2
class CommandNotFoundError < CommandLineError; end
-
2
class ExitStatusError < CommandLineError; end
-
2
class InterpolationError < CommandLineError; end
-
end
-
# coding: UTF-8
-
-
2
module Cocaine
-
2
class OSDetector
-
2
def java?
-
arch =~ /java/
-
end
-
-
2
def unix?
-
RbConfig::CONFIG['host_os'] !~ /mswin|mingw/
-
end
-
-
2
def windows?
-
!unix?
-
end
-
-
2
def path_separator
-
File::PATH_SEPARATOR
-
end
-
-
2
def arch
-
RUBY_PLATFORM
-
end
-
end
-
-
2
OS = OSDetector.new
-
end
-
2
require 'coffee-script'
-
2
require 'coffee/rails/engine'
-
2
require 'coffee/rails/template_handler'
-
2
require 'coffee/rails/version'
-
2
require 'rails/engine'
-
-
2
module Coffee
-
2
module Rails
-
2
class Engine < ::Rails::Engine
-
2
config.app_generators.javascript_engine :coffee
-
end
-
end
-
end
-
2
module Coffee
-
2
module Rails
-
2
class TemplateHandler
-
2
def self.erb_handler
-
@@erb_handler ||= ActionView::Template.registered_template_handler(:erb)
-
end
-
-
2
def self.call(template)
-
compiled_source = erb_handler.call(template)
-
"CoffeeScript.compile(begin;#{compiled_source};end)"
-
end
-
end
-
end
-
end
-
-
2
ActiveSupport.on_load(:action_view) do
-
2
ActionView::Template.register_template_handler :coffee, Coffee::Rails::TemplateHandler
-
end
-
2
module Coffee
-
2
module Rails
-
2
VERSION = "4.0.1"
-
end
-
end
-
2
require 'coffee_script'
-
2
require 'execjs'
-
2
require 'coffee_script/source'
-
-
2
module CoffeeScript
-
2
Error = ExecJS::Error
-
2
EngineError = ExecJS::RuntimeError
-
2
CompilationError = ExecJS::ProgramError
-
-
2
module Source
-
2
def self.path
-
@path ||= ENV['COFFEESCRIPT_SOURCE_PATH'] || bundled_path
-
end
-
-
2
def self.path=(path)
-
@contents = @version = @bare_option = @context = nil
-
@path = path
-
end
-
-
2
COMPILE_FUNCTION_SOURCE = <<-JS
-
;function compile(script, options) {
-
try {
-
return CoffeeScript.compile(script, options);
-
} catch (err) {
-
if (err instanceof SyntaxError && err.location) {
-
throw new SyntaxError([
-
err.filename || "[stdin]",
-
err.location.first_line + 1,
-
err.location.first_column + 1
-
].join(":") + ": " + err.message)
-
} else {
-
throw err;
-
}
-
}
-
}
-
JS
-
-
2
def self.contents
-
@contents ||= File.read(path) + COMPILE_FUNCTION_SOURCE
-
end
-
-
2
def self.version
-
@version ||= contents[/CoffeeScript Compiler v([\d.]+)/, 1]
-
end
-
-
2
def self.bare_option
-
@bare_option ||= contents.match(/noWrap/) ? 'noWrap' : 'bare'
-
end
-
-
2
def self.context
-
@context ||= ExecJS.compile(contents)
-
end
-
end
-
-
2
class << self
-
2
def engine
-
end
-
-
2
def engine=(engine)
-
end
-
-
2
def version
-
Source.version
-
end
-
-
# Compile a script (String or IO) to JavaScript.
-
2
def compile(script, options = {})
-
script = script.read if script.respond_to?(:read)
-
-
if options.key?(:bare)
-
elsif options.key?(:no_wrap)
-
options[:bare] = options[:no_wrap]
-
else
-
options[:bare] = false
-
end
-
-
# Stringify keys
-
options = options.inject({}) { |h, (k, v)| h[k.to_s] = v; h }
-
Source.context.call("compile", script, options)
-
end
-
end
-
end
-
2
module CoffeeScript
-
2
module Source
-
2
def self.bundled_path
-
File.expand_path("../coffee-script.js", __FILE__)
-
end
-
end
-
end
-
1
require 'fileutils'
-
1
require 'cucumber/formatter/console'
-
1
require 'cucumber/formatter/io'
-
1
require 'cucumber/gherkin/formatter/escaping'
-
-
1
module Cucumber
-
1
module Formatter
-
# The formatter used for <tt>--format pretty</tt> (the default formatter).
-
#
-
# This formatter prints features to plain text - exactly how they were parsed,
-
# just prettier. That means with proper indentation and alignment of table columns.
-
#
-
# If the output is STDOUT (and not a file), there are bright colours to watch too.
-
#
-
1
class Pretty
-
1
include FileUtils
-
1
include Console
-
1
include Io
-
1
include Cucumber::Gherkin::Formatter::Escaping
-
1
attr_writer :indent
-
1
attr_reader :runtime
-
-
1
def initialize(runtime, path_or_io, options)
-
1
@runtime, @io, @options = runtime, ensure_io(path_or_io), options
-
1
@exceptions = []
-
1
@indent = 0
-
1
@prefixes = options[:prefixes] || {}
-
1
@delayed_messages = []
-
1
@previous_step_keyword = nil
-
1
@snippets_input = []
-
end
-
-
1
def before_features(features)
-
1
print_profile_information
-
end
-
-
1
def after_features(features)
-
1
print_summary(features)
-
end
-
-
1
def before_feature(feature)
-
1
@exceptions = []
-
1
@indent = 0
-
end
-
-
1
def comment_line(comment_line)
-
@io.puts(comment_line.indent(@indent))
-
@io.flush
-
end
-
-
1
def after_tags(tags)
-
7
if @indent == 1
-
@io.puts
-
@io.flush
-
end
-
end
-
-
1
def tag_name(tag_name)
-
tag = format_string(tag_name, :tag).indent(@indent)
-
@io.print(tag)
-
@io.flush
-
@indent = 1
-
end
-
-
1
def feature_name(keyword, name)
-
1
@io.puts("#{keyword}: #{name}")
-
1
@io.puts
-
1
@io.flush
-
end
-
-
1
def before_feature_element(feature_element)
-
6
@indent = 2
-
6
@scenario_indent = 2
-
end
-
-
1
def after_feature_element(feature_element)
-
6
print_messages
-
6
@io.puts
-
6
@io.flush
-
end
-
-
1
def before_background(background)
-
1
@indent = 2
-
1
@scenario_indent = 2
-
1
@in_background = true
-
end
-
-
1
def after_background(background)
-
1
print_messages
-
1
@in_background = nil
-
1
@io.puts
-
1
@io.flush
-
end
-
-
1
def background_name(keyword, name, file_colon_line, source_indent)
-
1
print_feature_element_name(keyword, name, file_colon_line, source_indent)
-
end
-
-
1
def before_examples_array(examples_array)
-
@indent = 4
-
@io.puts
-
@visiting_first_example_name = true
-
end
-
-
1
def examples_name(keyword, name)
-
@io.puts unless @visiting_first_example_name
-
@visiting_first_example_name = false
-
@io.puts(" #{keyword}: #{name}")
-
@io.flush
-
@indent = 6
-
@scenario_indent = 6
-
end
-
-
1
def before_outline_table(outline_table)
-
@table = outline_table
-
end
-
-
1
def after_outline_table(outline_table)
-
@table = nil
-
@indent = 4
-
end
-
-
1
def scenario_name(keyword, name, file_colon_line, source_indent)
-
6
print_feature_element_name(keyword, name, file_colon_line, source_indent)
-
end
-
-
1
def before_step(step)
-
40
@current_step = step
-
40
@indent = 6
-
40
print_messages
-
end
-
-
1
def before_step_result(keyword, step_match, multiline_arg, status, exception, source_indent, background, file_colon_line)
-
40
@hide_this_step = false
-
40
if exception
-
if @exceptions.include?(exception)
-
@hide_this_step = true
-
return
-
end
-
@exceptions << exception
-
end
-
40
if status != :failed && @in_background ^ background
-
@hide_this_step = true
-
return
-
end
-
40
@status = status
-
end
-
-
1
def step_name(keyword, step_match, status, source_indent, background, file_colon_line)
-
40
return if @hide_this_step
-
40
source_indent = nil unless @options[:source]
-
40
name_to_report = format_step(keyword, step_match, status, source_indent)
-
40
@io.puts(name_to_report.indent(@scenario_indent + 2))
-
40
print_messages
-
end
-
-
1
def doc_string(string)
-
return if @options[:no_multiline] || @hide_this_step
-
s = %{"""\n#{string}\n"""}.indent(@indent)
-
s = s.split("\n").map{|l| l =~ /^\s+$/ ? '' : l}.join("\n")
-
@io.puts(format_string(s, @current_step.status))
-
@io.flush
-
end
-
-
1
def exception(exception, status)
-
return if @hide_this_step
-
print_messages
-
print_exception(exception, status, @indent)
-
@io.flush
-
end
-
-
1
def before_multiline_arg(multiline_arg)
-
8
return if @options[:no_multiline] || @hide_this_step
-
8
@table = multiline_arg
-
end
-
-
1
def after_multiline_arg(multiline_arg)
-
8
@table = nil
-
end
-
-
1
def before_table_row(table_row)
-
40
return if !@table || @hide_this_step
-
40
@col_index = 0
-
40
@io.print ' |'.indent(@indent-2)
-
end
-
-
1
def after_table_row(table_row)
-
40
return if !@table || @hide_this_step
-
40
print_table_row_messages
-
40
@io.puts
-
40
if table_row.exception && !@exceptions.include?(table_row.exception)
-
print_exception(table_row.exception, table_row.status, @indent)
-
end
-
end
-
-
1
def after_table_cell(cell)
-
120
return unless @table
-
120
@col_index += 1
-
end
-
-
1
def table_cell_value(value, status)
-
120
return if !@table || @hide_this_step
-
120
status ||= @status || :passed
-
120
width = @table.col_width(@col_index)
-
120
cell_text = escape_cell(value.to_s || '')
-
120
padded = cell_text + (' ' * (width - cell_text.unpack('U*').length))
-
120
prefix = cell_prefix(status)
-
120
@io.print(' ' + format_string("#{prefix}#{padded}", status) + ::Cucumber::Term::ANSIColor.reset(" |"))
-
120
@io.flush
-
end
-
-
1
def before_test_case(test_case)
-
6
@previous_step_keyword = nil
-
end
-
-
1
def after_test_step(test_step, result)
-
140
collect_snippet_data(test_step, result)
-
end
-
-
1
private
-
-
1
def print_feature_element_name(keyword, name, file_colon_line, source_indent)
-
7
@io.puts if @scenario_indent == 6
-
7
names = name.empty? ? [name] : name.split("\n")
-
7
line = "#{keyword}: #{names[0]}".indent(@scenario_indent)
-
7
@io.print(line)
-
7
if @options[:source]
-
7
line_comment = "# #{file_colon_line}".indent(source_indent)
-
7
@io.print(format_string(line_comment, :comment))
-
end
-
7
@io.puts
-
7
names[1..-1].each {|s| @io.puts "#{s}"}
-
7
@io.flush
-
end
-
-
1
def cell_prefix(status)
-
120
@prefixes[status]
-
end
-
-
1
def print_summary(features)
-
1
print_stats(features, @options)
-
1
print_snippets(@options)
-
1
print_passing_wip(@options)
-
end
-
end
-
end
-
end
-
3
env_caller = File.dirname(caller.detect{ |f| f =~ /\/env\.rb:/ }) if caller.detect{ |f| f =~ /\/env\.rb:/ }
-
1
if env_caller
-
1
require 'rails'
-
1
require 'cucumber/rails/application'
-
1
ENV['RAILS_ENV'] ||= 'test'
-
1
ENV['RAILS_ROOT'] ||= File.expand_path(env_caller + '/../..')
-
1
require File.expand_path(ENV['RAILS_ROOT'] + '/config/environment')
-
1
require 'cucumber/rails/action_controller'
-
-
1
if defined?(ActiveRecord::Base)
-
1
require 'rails/test_help'
-
else
-
require 'action_dispatch/testing/test_process'
-
require 'action_dispatch/testing/integration'
-
end
-
-
1
unless Rails.application.config.cache_classes
-
warn "WARNING: You have set Rails' config.cache_classes to false (most likely in config/environments/cucumber.rb). This setting is known to cause problems with database transactions. Set config.cache_classes to true if you want to use transactions."
-
end
-
-
1
require 'cucumber/rails/world'
-
1
require 'cucumber/rails/hooks'
-
1
require 'cucumber/rails/capybara'
-
1
require 'cucumber/rails/database'
-
-
1
MultiTest.disable_autorun
-
else
-
warn "WARNING: Cucumber-rails required outside of env.rb. The rest of loading is being deferred until env.rb is called.
-
To avoid this warning, move 'gem \'cucumber-rails\', :require => false' under only group :test in your Gemfile.
-
If already in the :test group, be sure you are specifying ':require => false'."
-
end
-
1
ActionController::Base.class_eval do
-
1
cattr_accessor :allow_rescue
-
end
-
-
1
class ActionDispatch::ShowExceptions
-
1
alias __cucumber_orig_call__ call
-
-
1
def call(env)
-
13
env['action_dispatch.show_exceptions'] = !!ActionController::Base.allow_rescue
-
13
__cucumber_orig_call__(env)
-
end
-
end
-
1
require 'rails/application'
-
-
# Make sure the ActionDispatch::ShowExceptions middleware is always enabled,
-
# regardless of what is in config/environments/test.rb
-
# Instead we are overriding ActionDispatch::ShowExceptions to be able to
-
# toggle whether or not exceptions are raised.
-
1
class Rails::Application
-
1
alias __cucumber_orig_initialize__ initialize!
-
-
1
def initialize!
-
1
ad = config.action_dispatch
-
1
def ad.show_exceptions
-
1
true
-
end
-
1
__cucumber_orig_initialize__
-
end
-
end
-
1
require 'capybara'
-
1
require 'capybara/rails'
-
1
require 'capybara/cucumber'
-
1
require 'capybara/session'
-
1
require 'cucumber/rails/capybara/javascript_emulation'
-
1
require 'cucumber/rails/capybara/select_dates_and_times'
-
1
module Cucumber
-
1
module Rails
-
1
module Capybara
-
1
module JavascriptEmulation
-
1
def self.included(base)
-
1
base.class_eval do
-
1
alias_method :click_without_javascript_emulation, :click
-
1
alias_method :click, :click_with_javascript_emulation
-
end
-
end
-
-
1
def click_with_javascript_emulation
-
7
if link_with_non_get_http_method?
-
::Capybara::RackTest::Form.new(driver, js_form(element_node.document, self[:href], emulated_method)).submit(self)
-
else
-
7
click_without_javascript_emulation
-
end
-
end
-
-
1
private
-
-
1
def csrf?
-
csrf_param_node && csrf_token_node
-
end
-
-
1
def csrf_param_node
-
element_node.document.at_xpath("//meta[@name='csrf-param']")
-
end
-
-
1
def csrf_param
-
csrf_param_node['content']
-
end
-
-
1
def csrf_token_node
-
element_node.document.at_xpath("//meta[@name='csrf-token']")
-
end
-
-
1
def csrf_token
-
csrf_token_node['content']
-
end
-
-
1
def js_form(document, action, emulated_method, method = 'POST')
-
js_form = document.create_element('form')
-
js_form['action'] = action
-
js_form['method'] = method
-
-
if emulated_method and emulated_method.downcase != method.downcase
-
input = document.create_element('input')
-
input['type'] = 'hidden'
-
input['name'] = '_method'
-
input['value'] = emulated_method
-
js_form.add_child(input)
-
end
-
-
# rails will wipe the session if the CSRF token is not sent
-
# with non-GET requests
-
if csrf? && emulated_method.downcase != 'get'
-
input = document.create_element('input')
-
input['type'] = 'hidden'
-
input['name'] = csrf_param
-
input['value'] = csrf_token
-
js_form.add_child(input)
-
end
-
-
js_form
-
end
-
-
1
def link_with_non_get_http_method?
-
7
if ::Rails.version.to_f >= 3.0
-
7
tag_name == 'a' && element_node['data-method'] && element_node['data-method'] =~ /(?:delete|put|post)/
-
else
-
tag_name == 'a' && element_node['onclick'] && element_node['onclick'] =~ /var f = document\.createElement\('form'\); f\.style\.display = 'none';/
-
end
-
end
-
-
1
def emulated_method
-
if ::Rails.version.to_f >= 3.0
-
element_node['data-method']
-
else
-
element_node['onclick'][/m\.setAttribute\('value', '([^']*)'\)/, 1]
-
end
-
end
-
-
1
def element_node
-
3
if self.respond_to? :native
-
3
self.native
-
else
-
warn 'DEPRECATED: cucumber-rails loves you, just not your version of Capybara. Please update Capybara to >= 0.4.0'
-
self.node
-
end
-
end
-
end
-
end
-
end
-
end
-
-
1
class Capybara::RackTest::Node
-
1
include ::Cucumber::Rails::Capybara::JavascriptEmulation
-
end
-
-
1
Before('~@no-js-emulation') do
-
# Enable javascript emulation
-
6
::Capybara::RackTest::Node.class_eval do
-
6
alias_method :click, :click_with_javascript_emulation
-
end
-
end
-
-
1
Before('@no-js-emulation') do
-
# Disable javascript emulation
-
::Capybara::RackTest::Node.class_eval do
-
alias_method :click, :click_without_javascript_emulation
-
end
-
end
-
1
module Cucumber
-
1
module Rails
-
1
module Capybara
-
# This module defines methods for selecting dates and times
-
1
module SelectDatesAndTimes
-
# Select a Rails date. Options hash must include :from => +label+
-
1
def select_date(date, options)
-
date = Date.parse(date)
-
base_dom_id = get_base_dom_id_from_label_tag(options[:from])
-
-
find(:xpath, ".//select[@id='#{base_dom_id}_1i']").select(date.year.to_s)
-
find(:xpath, ".//select[@id='#{base_dom_id}_2i']").select(I18n.l date, format: '%B')
-
find(:xpath, ".//select[@id='#{base_dom_id}_3i']").select(date.day.to_s)
-
end
-
-
# Select a Rails time. Options hash must include :from => +label+
-
1
def select_time(time, options)
-
time = Time.zone.parse(time)
-
base_dom_id = get_base_dom_id_from_label_tag(options[:from])
-
-
find(:xpath, ".//select[@id='#{base_dom_id}_4i']").select(time.hour.to_s.rjust(2, '0'))
-
find(:xpath, ".//select[@id='#{base_dom_id}_5i']").select(time.min.to_s.rjust(2, '0'))
-
end
-
-
# Select a Rails datetime. Options hash must include :from => +label+
-
1
def select_datetime(datetime, options)
-
select_date(datetime, options)
-
select_time(datetime, options)
-
end
-
-
1
private
-
-
# @example "event_starts_at_"
-
1
def get_base_dom_id_from_label_tag(field)
-
find(:xpath, ".//label[contains(., '#{field}')]")['for'].gsub(/(_[1-5]i)$/, '')
-
end
-
end
-
end
-
end
-
end
-
-
1
World(::Cucumber::Rails::Capybara::SelectDatesAndTimes)
-
1
require 'cucumber/rails/hooks/active_record'
-
1
require 'cucumber/rails/hooks/database_cleaner'
-
1
require 'cucumber/rails/hooks/allow_rescue'
-
1
require 'cucumber/rails/hooks/mail'
-
1
if defined?(ActiveRecord::Base)
-
1
class ActiveRecord::Base
-
1
class_attribute :shared_connection
-
-
1
def self.connection
-
4230
self.shared_connection || retrieve_connection
-
end
-
end
-
-
1
Before('@javascript') do
-
Cucumber::Rails::Database.before_js if Cucumber::Rails::Database.autorun_database_cleaner
-
end
-
-
1
Before('~@javascript') do
-
6
Cucumber::Rails::Database.before_non_js if Cucumber::Rails::Database.autorun_database_cleaner
-
end
-
-
1
After do
-
6
Cucumber::Rails::Database.after if Cucumber::Rails::Database.autorun_database_cleaner
-
end
-
end
-
1
Before('@allow-rescue') do
-
@__orig_allow_rescue = ActionController::Base.allow_rescue
-
ActionController::Base.allow_rescue = true
-
end
-
-
1
After('@allow-rescue') do
-
ActionController::Base.allow_rescue = @__orig_allow_rescue
-
end
-
1
begin
-
1
require 'database_cleaner'
-
-
1
Before('~@no-database-cleaner') do
-
6
DatabaseCleaner.start if Cucumber::Rails::Database.autorun_database_cleaner
-
end
-
-
1
After('~@no-database-cleaner') do
-
6
DatabaseCleaner.clean if Cucumber::Rails::Database.autorun_database_cleaner
-
end
-
-
rescue LoadError => ignore_if_database_cleaner_not_present
-
end
-
1
if defined?(ActionMailer::Base)
-
1
Before do
-
6
ActionMailer::Base.deliveries = []
-
end
-
end
-
1
begin
-
# Try to load it so we can assign @_result below if needed.
-
1
require 'test/unit/testresult'
-
rescue LoadError => ignore
-
end
-
-
1
module Cucumber #:nodoc:
-
1
module Rails #:nodoc:
-
1
class World < ActionDispatch::IntegrationTest #:nodoc:
-
1
include Rack::Test::Methods
-
1
include ActiveSupport::Testing::SetupAndTeardown if ActiveSupport::Testing.const_defined?('SetupAndTeardown')
-
-
1
def initialize #:nodoc:
-
6
@_result = Test::Unit::TestResult.new if defined?(Test::Unit::TestResult)
-
end
-
-
1
unless defined?(ActiveRecord::Base)
-
def self.fixture_table_names; []; end # Workaround for projects that don't use ActiveRecord
-
end
-
end
-
end
-
end
-
-
1
World do
-
6
Cucumber::Rails::World.new
-
end
-
# fake file to prevent bundler automatically load the gem
-
2
$LOAD_PATH.unshift(File.expand_path(File.dirname(__FILE__))) unless $LOAD_PATH.include?(File.expand_path(File.dirname(__FILE__)))
-
2
require 'database_cleaner/configuration'
-
-
2
module DatabaseCleaner
-
2
def self.can_detect_orm?
-
DatabaseCleaner::Base.autodetect_orm
-
end
-
end
-
1
require 'database_cleaner/generic/base'
-
1
require 'active_record'
-
1
require 'erb'
-
-
1
module DatabaseCleaner
-
1
module ActiveRecord
-
-
1
def self.available_strategies
-
%w[truncation transaction deletion]
-
end
-
-
1
def self.config_file_location=(path)
-
@config_file_location = path
-
end
-
-
1
def self.config_file_location
-
@config_file_location ||= "#{DatabaseCleaner.app_root}/config/database.yml"
-
end
-
-
1
module Base
-
1
include ::DatabaseCleaner::Generic::Base
-
-
1
attr_accessor :connection_hash
-
-
1
def db=(desired_db)
-
3
@db = desired_db
-
3
load_config
-
end
-
-
1
def db
-
5
@db ||= super
-
end
-
-
1
def load_config
-
3
if self.db != :default && self.db.is_a?(Symbol) && File.file?(ActiveRecord.config_file_location)
-
connection_details = YAML::load(ERB.new(IO.read(ActiveRecord.config_file_location)).result)
-
@connection_hash = valid_config(connection_details)[self.db.to_s]
-
end
-
end
-
-
1
def valid_config(connection_file)
-
if !::ActiveRecord::Base.configurations.nil? && !::ActiveRecord::Base.configurations.empty?
-
if connection_file != ::ActiveRecord::Base.configurations
-
return ::ActiveRecord::Base.configurations
-
end
-
end
-
connection_file
-
end
-
-
1
def connection_class
-
@connection_class ||= if db && !db.is_a?(Symbol)
-
db
-
elsif connection_hash
-
lookup_from_connection_pool || establish_connection
-
else
-
1
::ActiveRecord::Base
-
24
end
-
end
-
-
1
private
-
-
1
def lookup_from_connection_pool
-
if ::ActiveRecord::Base.respond_to?(:descendants)
-
database_name = connection_hash["database"] || connection_hash[:database]
-
models = ::ActiveRecord::Base.descendants
-
models.detect { |m| m.connection_pool.spec.config[:database] == database_name }
-
end
-
end
-
-
1
def establish_connection
-
::ActiveRecord::Base.establish_connection(connection_hash)
-
end
-
-
end
-
end
-
end
-
1
require 'database_cleaner/active_record/base'
-
1
require 'database_cleaner/generic/transaction'
-
-
1
module DatabaseCleaner::ActiveRecord
-
1
class Transaction
-
1
include ::DatabaseCleaner::ActiveRecord::Base
-
1
include ::DatabaseCleaner::Generic::Transaction
-
-
1
def start
-
# Hack to make sure that the connection is properly setup for
-
# the clean code.
-
6
connection_class.connection.transaction{ }
-
-
6
if connection_maintains_transaction_count?
-
if connection_class.connection.respond_to?(:increment_open_transactions)
-
connection_class.connection.increment_open_transactions
-
else
-
connection_class.__send__(:increment_open_transactions)
-
end
-
end
-
6
if connection_class.connection.respond_to?(:begin_transaction)
-
6
connection_class.connection.begin_transaction :joinable => false
-
else
-
connection_class.connection.begin_db_transaction
-
end
-
end
-
-
-
1
def clean
-
6
connection_class.connection_pool.connections.each do |connection|
-
6
next unless connection.open_transactions > 0
-
-
6
if connection.respond_to?(:rollback_transaction)
-
6
connection.rollback_transaction
-
else
-
connection.rollback_db_transaction
-
end
-
-
# The below is for handling after_commit hooks.. see https://github.com/bmabey/database_cleaner/issues/99
-
6
if connection.respond_to?(:rollback_transaction_records, true)
-
connection.send(:rollback_transaction_records, true)
-
end
-
-
6
if connection_maintains_transaction_count?
-
if connection.respond_to?(:decrement_open_transactions)
-
connection.decrement_open_transactions
-
else
-
connection_class.__send__(:decrement_open_transactions)
-
end
-
end
-
end
-
end
-
-
1
def connection_maintains_transaction_count?
-
12
ActiveRecord::VERSION::MAJOR < 4
-
end
-
-
end
-
end
-
2
require 'database_cleaner/null_strategy'
-
2
module DatabaseCleaner
-
2
class Base
-
2
include Comparable
-
-
2
def <=>(other)
-
(self.orm <=> other.orm) == 0 ? self.db <=> other.db : self.orm <=> other.orm
-
end
-
-
2
def initialize(desired_orm = nil,opts = {})
-
2
if [:autodetect, nil, "autodetect"].include?(desired_orm)
-
1
autodetect
-
else
-
1
self.orm = desired_orm
-
end
-
2
self.db = opts[:connection] || opts[:model] if opts.has_key?(:connection) || opts.has_key?(:model)
-
2
set_default_orm_strategy
-
end
-
-
2
def db=(desired_db)
-
self.strategy_db = desired_db
-
@db = desired_db
-
end
-
-
2
def strategy_db=(desired_db)
-
if strategy.respond_to? :db=
-
strategy.db = desired_db
-
elsif desired_db!= :default
-
raise ArgumentError, "You must provide a strategy object that supports non default databases when you specify a database"
-
end
-
end
-
-
2
def db
-
3
@db ||= :default
-
end
-
-
2
def create_strategy(*args)
-
3
strategy, *strategy_args = args
-
3
orm_strategy(strategy).new(*strategy_args)
-
end
-
-
2
def clean_with(*args)
-
strategy = create_strategy(*args)
-
set_strategy_db strategy, self.db
-
-
strategy.clean
-
strategy
-
end
-
-
2
alias clean_with! clean_with
-
-
2
def set_strategy_db(strategy, desired_db)
-
3
if strategy.respond_to? :db=
-
3
strategy.db = desired_db
-
elsif desired_db != :default
-
raise ArgumentError, "You must provide a strategy object that supports non default databases when you specify a database"
-
end
-
end
-
-
2
def strategy=(args)
-
3
strategy, *strategy_args = args
-
3
if strategy.is_a?(Symbol)
-
3
@strategy = create_strategy(*args)
-
elsif strategy_args.empty?
-
@strategy = strategy
-
else
-
raise ArgumentError, "You must provide a strategy object, or a symbol for a known strategy along with initialization params."
-
end
-
-
3
set_strategy_db @strategy, self.db
-
-
3
@strategy
-
end
-
-
2
def strategy
-
12
@strategy ||= NullStrategy
-
end
-
-
2
def orm=(desired_orm)
-
1
@orm = desired_orm.to_sym
-
end
-
-
2
def orm
-
9
@orm || autodetect
-
end
-
-
2
def start
-
6
strategy.start
-
end
-
-
2
def clean
-
6
strategy.clean
-
end
-
-
2
alias clean! clean
-
-
2
def cleaning(&block)
-
strategy.cleaning(&block)
-
end
-
-
2
def auto_detected?
-
!!@autodetected
-
end
-
-
2
def autodetect_orm
-
1
if defined? ::ActiveRecord
-
1
:active_record
-
elsif defined? ::DataMapper
-
:data_mapper
-
elsif defined? ::MongoMapper
-
:mongo_mapper
-
elsif defined? ::Mongoid
-
:mongoid
-
elsif defined? ::CouchPotato
-
:couch_potato
-
elsif defined? ::Sequel
-
:sequel
-
elsif defined? ::Moped
-
:moped
-
elsif defined? ::Ohm
-
:ohm
-
elsif defined? ::Redis
-
:redis
-
elsif defined? ::Neo4j
-
:neo4j
-
end
-
end
-
-
2
private
-
-
2
def orm_module
-
3
::DatabaseCleaner.orm_module(orm)
-
end
-
-
2
def orm_strategy(strategy)
-
3
require "database_cleaner/#{orm.to_s}/#{strategy.to_s}"
-
3
orm_module.const_get(strategy.to_s.capitalize)
-
rescue LoadError
-
if orm_module.respond_to? :available_strategies
-
raise UnknownStrategySpecified, "The '#{strategy}' strategy does not exist for the #{orm} ORM! Available strategies: #{orm_module.available_strategies.join(', ')}"
-
else
-
raise UnknownStrategySpecified, "The '#{strategy}' strategy does not exist for the #{orm} ORM!"
-
end
-
end
-
-
2
def autodetect
-
1
@autodetected = true
-
-
@orm ||= autodetect_orm ||
-
1
raise(NoORMDetected, "No known ORM was detected! Is ActiveRecord, DataMapper, Sequel, MongoMapper, Mongoid, Moped, or CouchPotato, Redis or Ohm loaded?")
-
end
-
-
2
def set_default_orm_strategy
-
2
case orm
-
when :active_record, :data_mapper, :sequel
-
2
self.strategy = :transaction
-
when :mongo_mapper, :mongoid, :couch_potato, :moped, :ohm, :redis
-
self.strategy = :truncation
-
when :neo4j
-
self.strategy = :transaction
-
end
-
end
-
end
-
end
-
1
module ::DatabaseCleaner
-
1
module Generic
-
1
module Base
-
-
1
def self.included(base)
-
1
base.extend(ClassMethods)
-
end
-
-
1
def db
-
:default
-
end
-
-
1
def cleaning(&block)
-
begin
-
start
-
yield
-
ensure
-
clean
-
end
-
end
-
-
1
module ClassMethods
-
1
def available_strategies
-
%W[]
-
end
-
end
-
end
-
end
-
end
-
1
module DatabaseCleaner
-
1
module Generic
-
1
module Transaction
-
1
def initialize(opts = {})
-
3
if !opts.empty?
-
raise ArgumentError, "Options are not available for transaction strategies."
-
end
-
end
-
end
-
end
-
end
-
2
module DatabaseCleaner
-
2
class NullStrategy
-
2
def self.start
-
# no-op
-
end
-
-
2
def self.db=(connection)
-
# no-op
-
end
-
-
2
def self.clean
-
# no-op
-
end
-
end
-
end
-
2
module DeviseHelper
-
# A simple way to show error messages for the current devise resource. If you need
-
# to customize this method, you can either overwrite it in your application helpers or
-
# copy the views to your application.
-
#
-
# This method is intended to stay simple and it is unlikely that we are going to change
-
# it to add more behavior or options.
-
2
def devise_error_messages!
-
return "" if resource.errors.empty?
-
-
messages = resource.errors.full_messages.map { |msg| content_tag(:li, msg) }.join
-
sentence = I18n.t("errors.messages.not_saved",
-
count: resource.errors.count,
-
resource: resource.class.model_name.human.downcase)
-
-
html = <<-HTML
-
<div id="error_explanation">
-
<h2>#{sentence}</h2>
-
<ul>#{messages}</ul>
-
</div>
-
HTML
-
-
html.html_safe
-
end
-
end
-
2
require 'rails'
-
2
require 'active_support/core_ext/numeric/time'
-
2
require 'active_support/dependencies'
-
2
require 'orm_adapter'
-
2
require 'set'
-
2
require 'securerandom'
-
2
require 'responders'
-
-
2
module Devise
-
2
autoload :Delegator, 'devise/delegator'
-
2
autoload :Encryptor, 'devise/encryptor'
-
2
autoload :FailureApp, 'devise/failure_app'
-
2
autoload :OmniAuth, 'devise/omniauth'
-
2
autoload :ParameterFilter, 'devise/parameter_filter'
-
2
autoload :BaseSanitizer, 'devise/parameter_sanitizer'
-
2
autoload :ParameterSanitizer, 'devise/parameter_sanitizer'
-
2
autoload :TestHelpers, 'devise/test_helpers'
-
2
autoload :TimeInflector, 'devise/time_inflector'
-
2
autoload :TokenGenerator, 'devise/token_generator'
-
-
2
module Controllers
-
2
autoload :Helpers, 'devise/controllers/helpers'
-
2
autoload :Rememberable, 'devise/controllers/rememberable'
-
2
autoload :ScopedViews, 'devise/controllers/scoped_views'
-
2
autoload :SignInOut, 'devise/controllers/sign_in_out'
-
2
autoload :StoreLocation, 'devise/controllers/store_location'
-
2
autoload :UrlHelpers, 'devise/controllers/url_helpers'
-
end
-
-
2
module Hooks
-
2
autoload :Proxy, 'devise/hooks/proxy'
-
end
-
-
2
module Mailers
-
2
autoload :Helpers, 'devise/mailers/helpers'
-
end
-
-
2
module Strategies
-
2
autoload :Base, 'devise/strategies/base'
-
2
autoload :Authenticatable, 'devise/strategies/authenticatable'
-
end
-
-
# Constants which holds devise configuration for extensions. Those should
-
# not be modified by the "end user" (this is why they are constants).
-
2
ALL = []
-
2
CONTROLLERS = ActiveSupport::OrderedHash.new
-
2
ROUTES = ActiveSupport::OrderedHash.new
-
2
STRATEGIES = ActiveSupport::OrderedHash.new
-
2
URL_HELPERS = ActiveSupport::OrderedHash.new
-
-
# Strategies that do not require user input.
-
2
NO_INPUT = []
-
-
# True values used to check params
-
2
TRUE_VALUES = [true, 1, '1', 't', 'T', 'true', 'TRUE']
-
-
# Secret key used by the key generator
-
2
mattr_accessor :secret_key
-
2
@@secret_key = nil
-
-
# Custom domain or key for cookies. Not set by default
-
2
mattr_accessor :rememberable_options
-
2
@@rememberable_options = {}
-
-
# The number of times to encrypt password.
-
2
mattr_accessor :stretches
-
2
@@stretches = 10
-
-
# The default key used when authenticating over http auth.
-
2
mattr_accessor :http_authentication_key
-
2
@@http_authentication_key = nil
-
-
# Keys used when authenticating a user.
-
2
mattr_accessor :authentication_keys
-
2
@@authentication_keys = [:email]
-
-
# Request keys used when authenticating a user.
-
2
mattr_accessor :request_keys
-
2
@@request_keys = []
-
-
# Keys that should be case-insensitive.
-
2
mattr_accessor :case_insensitive_keys
-
2
@@case_insensitive_keys = [:email]
-
-
# Keys that should have whitespace stripped.
-
2
mattr_accessor :strip_whitespace_keys
-
2
@@strip_whitespace_keys = []
-
-
# If http authentication is enabled by default.
-
2
mattr_accessor :http_authenticatable
-
2
@@http_authenticatable = false
-
-
# If http headers should be returned for ajax requests. True by default.
-
2
mattr_accessor :http_authenticatable_on_xhr
-
2
@@http_authenticatable_on_xhr = true
-
-
# If params authenticatable is enabled by default.
-
2
mattr_accessor :params_authenticatable
-
2
@@params_authenticatable = true
-
-
# The realm used in Http Basic Authentication.
-
2
mattr_accessor :http_authentication_realm
-
2
@@http_authentication_realm = "Application"
-
-
# Email regex used to validate email formats. It simply asserts that
-
# an one (and only one) @ exists in the given string. This is mainly
-
# to give user feedback and not to assert the e-mail validity.
-
2
mattr_accessor :email_regexp
-
2
@@email_regexp = /\A[^@\s]+@([^@\s]+\.)+[^@\W]+\z/
-
-
# Range validation for password length
-
2
mattr_accessor :password_length
-
2
@@password_length = 6..128
-
-
# The time the user will be remembered without asking for credentials again.
-
2
mattr_accessor :remember_for
-
2
@@remember_for = 2.weeks
-
-
# TODO: extend_remember_period is no longer used
-
# If true, extends the user's remember period when remembered via cookie.
-
2
mattr_accessor :extend_remember_period
-
2
@@extend_remember_period = false
-
-
# If true, all the remember me tokens are going to be invalidated when the user signs out.
-
2
mattr_accessor :expire_all_remember_me_on_sign_out
-
2
@@expire_all_remember_me_on_sign_out = true
-
-
# Time interval you can access your account before confirming your account.
-
# nil - allows unconfirmed access for unlimited time
-
2
mattr_accessor :allow_unconfirmed_access_for
-
2
@@allow_unconfirmed_access_for = 0.days
-
-
# Time interval the confirmation token is valid. nil = unlimited
-
2
mattr_accessor :confirm_within
-
2
@@confirm_within = nil
-
-
# Defines which key will be used when confirming an account.
-
2
mattr_accessor :confirmation_keys
-
2
@@confirmation_keys = [:email]
-
-
# Defines if email should be reconfirmable.
-
# False by default for backwards compatibility.
-
2
mattr_accessor :reconfirmable
-
2
@@reconfirmable = false
-
-
# Time interval to timeout the user session without activity.
-
2
mattr_accessor :timeout_in
-
2
@@timeout_in = 30.minutes
-
-
# Used to encrypt password. Please generate one with rake secret.
-
2
mattr_accessor :pepper
-
2
@@pepper = nil
-
-
# Used to enable sending notification to user when their password is changed
-
2
mattr_accessor :send_password_change_notification
-
2
@@send_password_change_notification = false
-
-
# Scoped views. Since it relies on fallbacks to render default views, it's
-
# turned off by default.
-
2
mattr_accessor :scoped_views
-
2
@@scoped_views = false
-
-
# Defines which strategy can be used to lock an account.
-
# Values: :failed_attempts, :none
-
2
mattr_accessor :lock_strategy
-
2
@@lock_strategy = :failed_attempts
-
-
# Defines which key will be used when locking and unlocking an account
-
2
mattr_accessor :unlock_keys
-
2
@@unlock_keys = [:email]
-
-
# Defines which strategy can be used to unlock an account.
-
# Values: :email, :time, :both
-
2
mattr_accessor :unlock_strategy
-
2
@@unlock_strategy = :both
-
-
# Number of authentication tries before locking an account
-
2
mattr_accessor :maximum_attempts
-
2
@@maximum_attempts = 20
-
-
# Time interval to unlock the account if :time is defined as unlock_strategy.
-
2
mattr_accessor :unlock_in
-
2
@@unlock_in = 1.hour
-
-
# Defines which key will be used when recovering the password for an account
-
2
mattr_accessor :reset_password_keys
-
2
@@reset_password_keys = [:email]
-
-
# Time interval you can reset your password with a reset password key
-
2
mattr_accessor :reset_password_within
-
2
@@reset_password_within = 6.hours
-
-
# When set to false, resetting a password does not automatically sign in a user
-
2
mattr_accessor :sign_in_after_reset_password
-
2
@@sign_in_after_reset_password = true
-
-
# The default scope which is used by warden.
-
2
mattr_accessor :default_scope
-
2
@@default_scope = nil
-
-
# Address which sends Devise e-mails.
-
2
mattr_accessor :mailer_sender
-
2
@@mailer_sender = nil
-
-
# Skip session storage for the following strategies
-
2
mattr_accessor :skip_session_storage
-
2
@@skip_session_storage = []
-
-
# Which formats should be treated as navigational.
-
2
mattr_accessor :navigational_formats
-
2
@@navigational_formats = ["*/*", :html]
-
-
# When set to true, signing out a user signs out all other scopes.
-
2
mattr_accessor :sign_out_all_scopes
-
2
@@sign_out_all_scopes = true
-
-
# The default method used while signing out
-
2
mattr_accessor :sign_out_via
-
2
@@sign_out_via = :get
-
-
# The parent controller all Devise controllers inherits from.
-
# Defaults to ApplicationController. This should be set early
-
# in the initialization process and should be set to a string.
-
2
mattr_accessor :parent_controller
-
2
@@parent_controller = "ApplicationController"
-
-
# The parent mailer all Devise mailers inherit from.
-
# Defaults to ActionMailer::Base. This should be set early
-
# in the initialization process and should be set to a string.
-
2
mattr_accessor :parent_mailer
-
2
@@parent_mailer = "ActionMailer::Base"
-
-
# The router Devise should use to generate routes. Defaults
-
# to :main_app. Should be overridden by engines in order
-
# to provide custom routes.
-
2
mattr_accessor :router_name
-
2
@@router_name = nil
-
-
# Set the OmniAuth path prefix so it can be overridden when
-
# Devise is used in a mountable engine
-
2
mattr_accessor :omniauth_path_prefix
-
2
@@omniauth_path_prefix = nil
-
-
# Set if we should clean up the CSRF Token on authentication
-
2
mattr_accessor :clean_up_csrf_token_on_authentication
-
2
@@clean_up_csrf_token_on_authentication = true
-
-
# PRIVATE CONFIGURATION
-
-
# Store scopes mappings.
-
2
mattr_reader :mappings
-
2
@@mappings = ActiveSupport::OrderedHash.new
-
-
# OmniAuth configurations.
-
2
mattr_reader :omniauth_configs
-
2
@@omniauth_configs = ActiveSupport::OrderedHash.new
-
-
# Define a set of modules that are called when a mapping is added.
-
2
mattr_reader :helpers
-
2
@@helpers = Set.new
-
2
@@helpers << Devise::Controllers::Helpers
-
-
# Private methods to interface with Warden.
-
2
mattr_accessor :warden_config
-
2
@@warden_config = nil
-
2
@@warden_config_blocks = []
-
-
# When true, enter in paranoid mode to avoid user enumeration.
-
2
mattr_accessor :paranoid
-
2
@@paranoid = false
-
-
# When true, warn user if they just used next-to-last attempt of authentication
-
2
mattr_accessor :last_attempt_warning
-
2
@@last_attempt_warning = true
-
-
# Stores the token generator
-
2
mattr_accessor :token_generator
-
2
@@token_generator = nil
-
-
# Default way to setup Devise. Run rails generate devise_install to create
-
# a fresh initializer with all configuration values.
-
2
def self.setup
-
2
yield self
-
end
-
-
2
class Getter
-
2
def initialize name
-
2
@name = name
-
end
-
-
2
def get
-
ActiveSupport::Dependencies.constantize(@name)
-
end
-
end
-
-
2
def self.ref(arg)
-
2
if defined?(ActiveSupport::Dependencies::ClassCache)
-
2
ActiveSupport::Dependencies::reference(arg)
-
2
Getter.new(arg)
-
else
-
ActiveSupport::Dependencies.ref(arg)
-
end
-
end
-
-
2
def self.available_router_name
-
router_name || :main_app
-
end
-
-
2
def self.omniauth_providers
-
omniauth_configs.keys
-
end
-
-
# Get the mailer class from the mailer reference object.
-
2
def self.mailer
-
@@mailer_ref.get
-
end
-
-
# Set the mailer reference object to access the mailer.
-
2
def self.mailer=(class_name)
-
2
@@mailer_ref = ref(class_name)
-
end
-
2
self.mailer = "Devise::Mailer"
-
-
# Small method that adds a mapping to Devise.
-
2
def self.add_mapping(resource, options)
-
mapping = Devise::Mapping.new(resource, options)
-
@@mappings[mapping.name] = mapping
-
@@default_scope ||= mapping.name
-
@@helpers.each { |h| h.define_helpers(mapping) }
-
mapping
-
end
-
-
# Register available devise modules. For the standard modules that Devise provides, this method is
-
# called from lib/devise/modules.rb. Third-party modules need to be added explicitly using this method.
-
#
-
# Note that adding a module using this method does not cause it to be used in the authentication
-
# process. That requires that the module be listed in the arguments passed to the 'devise' method
-
# in the model class definition.
-
#
-
# == Options:
-
#
-
# +model+ - String representing the load path to a custom *model* for this module (to autoload.)
-
# +controller+ - Symbol representing the name of an existing or custom *controller* for this module.
-
# +route+ - Symbol representing the named *route* helper for this module.
-
# +strategy+ - Symbol representing if this module got a custom *strategy*.
-
# +insert_at+ - Integer representing the order in which this module's model will be included
-
#
-
# All values, except :model, accept also a boolean and will have the same name as the given module
-
# name.
-
#
-
# == Examples:
-
#
-
# Devise.add_module(:party_module)
-
# Devise.add_module(:party_module, strategy: true, controller: :sessions)
-
# Devise.add_module(:party_module, model: 'party_module/model')
-
# Devise.add_module(:party_module, insert_at: 0)
-
#
-
2
def self.add_module(module_name, options = {})
-
20
options.assert_valid_keys(:strategy, :model, :controller, :route, :no_input, :insert_at)
-
-
20
ALL.insert (options[:insert_at] || -1), module_name
-
-
20
if strategy = options[:strategy]
-
4
strategy = (strategy == true ? module_name : strategy)
-
4
STRATEGIES[module_name] = strategy
-
end
-
-
20
if controller = options[:controller]
-
12
controller = (controller == true ? module_name : controller)
-
12
CONTROLLERS[module_name] = controller
-
end
-
-
20
NO_INPUT << strategy if options[:no_input]
-
-
20
if route = options[:route]
-
12
case route
-
when TrueClass
-
key, value = module_name, []
-
when Symbol
-
2
key, value = route, []
-
when Hash
-
10
key, value = route.keys.first, route.values.flatten
-
else
-
raise ArgumentError, ":route should be true, a Symbol or a Hash"
-
end
-
-
12
URL_HELPERS[key] ||= []
-
12
URL_HELPERS[key].concat(value)
-
12
URL_HELPERS[key].uniq!
-
-
12
ROUTES[module_name] = key
-
end
-
-
20
if options[:model]
-
20
path = (options[:model] == true ? "devise/models/#{module_name}" : options[:model])
-
20
camelized = ActiveSupport::Inflector.camelize(module_name.to_s)
-
20
Devise::Models.send(:autoload, camelized.to_sym, path)
-
end
-
-
20
Devise::Mapping.add_module module_name
-
end
-
-
# Sets warden configuration using a block that will be invoked on warden
-
# initialization.
-
#
-
# Devise.setup do |config|
-
# config.allow_unconfirmed_access_for = 2.days
-
#
-
# config.warden do |manager|
-
# # Configure warden to use other strategies, like oauth.
-
# manager.oauth(:twitter)
-
# end
-
# end
-
2
def self.warden(&block)
-
@@warden_config_blocks << block
-
end
-
-
# Specify an OmniAuth provider.
-
#
-
# config.omniauth :github, APP_ID, APP_SECRET
-
#
-
2
def self.omniauth(provider, *args)
-
@@helpers << Devise::OmniAuth::UrlHelpers
-
config = Devise::OmniAuth::Config.new(provider, args)
-
@@omniauth_configs[config.strategy_name.to_sym] = config
-
end
-
-
# Include helpers in the given scope to AC and AV.
-
2
def self.include_helpers(scope)
-
2
ActiveSupport.on_load(:action_controller) do
-
2
include scope::Helpers if defined?(scope::Helpers)
-
2
include scope::UrlHelpers
-
end
-
-
2
ActiveSupport.on_load(:action_view) do
-
2
include scope::UrlHelpers
-
end
-
end
-
-
# Regenerates url helpers considering Devise.mapping
-
2
def self.regenerate_helpers!
-
2
Devise::Controllers::UrlHelpers.remove_helpers!
-
2
Devise::Controllers::UrlHelpers.generate_helpers!
-
end
-
-
# A method used internally to complete the setup of warden manager after routes are loaded.
-
# See lib/devise/rails/routes.rb - ActionDispatch::Routing::RouteSet#finalize_with_devise!
-
2
def self.configure_warden! #:nodoc:
-
@@warden_configured ||= begin
-
2
warden_config.failure_app = Devise::Delegator.new
-
2
warden_config.default_scope = Devise.default_scope
-
2
warden_config.intercept_401 = false
-
-
2
Devise.mappings.each_value do |mapping|
-
warden_config.scope_defaults mapping.name, strategies: mapping.strategies
-
-
warden_config.serialize_into_session(mapping.name) do |record|
-
mapping.to.serialize_into_session(record)
-
end
-
-
warden_config.serialize_from_session(mapping.name) do |key|
-
# Previous versions contained an additional entry at the beginning of
-
# key with the record's class name.
-
args = key[-2, 2]
-
mapping.to.serialize_from_session(*args)
-
end
-
end
-
-
2
@@warden_config_blocks.map { |block| block.call Devise.warden_config }
-
2
true
-
2
end
-
end
-
-
# Generate a friendly string randomly to be used as token.
-
# By default, length is 20 characters.
-
2
def self.friendly_token(length = 20)
-
# To calculate real characters, we must perform this operation.
-
# See SecureRandom.urlsafe_base64
-
rlength = (length * 3) / 4
-
SecureRandom.urlsafe_base64(rlength).tr('lIO0', 'sxyz')
-
end
-
-
# constant-time comparison algorithm to prevent timing attacks
-
2
def self.secure_compare(a, b)
-
return false if a.blank? || b.blank? || a.bytesize != b.bytesize
-
l = a.unpack "C#{a.bytesize}"
-
-
res = 0
-
b.each_byte { |byte| res |= byte ^ l.shift }
-
res == 0
-
end
-
end
-
-
2
require 'warden'
-
2
require 'devise/mapping'
-
2
require 'devise/models'
-
2
require 'devise/modules'
-
2
require 'devise/rails'
-
2
module Devise
-
2
module Controllers
-
# Those helpers are convenience methods added to ApplicationController.
-
2
module Helpers
-
2
extend ActiveSupport::Concern
-
2
include Devise::Controllers::SignInOut
-
2
include Devise::Controllers::StoreLocation
-
-
2
included do
-
2
if respond_to?(:helper_method)
-
2
helper_method :warden, :signed_in?, :devise_controller?
-
end
-
end
-
-
2
module ClassMethods
-
# Define authentication filters and accessor helpers for a group of mappings.
-
# These methods are useful when you are working with multiple mappings that
-
# share some functionality. They are pretty much the same as the ones
-
# defined for normal mappings.
-
#
-
# Example:
-
#
-
# inside BlogsController (or any other controller, it doesn't matter which):
-
# devise_group :blogger, contains: [:user, :admin]
-
#
-
# Generated methods:
-
# authenticate_blogger! # Redirects unless user or admin are signed in
-
# blogger_signed_in? # Checks whether there is either a user or an admin signed in
-
# current_blogger # Currently signed in user or admin
-
# current_bloggers # Currently signed in user and admin
-
#
-
# Use:
-
# before_filter :authenticate_blogger! # Redirects unless either a user or an admin are authenticated
-
# before_filter ->{ authenticate_blogger! :admin } # Redirects to the admin login page
-
# current_blogger :user # Preferably returns a User if one is signed in
-
#
-
2
def devise_group(group_name, opts={})
-
mappings = "[#{ opts[:contains].map { |m| ":#{m}" }.join(',') }]"
-
-
class_eval <<-METHODS, __FILE__, __LINE__ + 1
-
def authenticate_#{group_name}!(favourite=nil, opts={})
-
unless #{group_name}_signed_in?
-
mappings = #{mappings}
-
mappings.unshift mappings.delete(favourite.to_sym) if favourite
-
mappings.each do |mapping|
-
opts[:scope] = mapping
-
warden.authenticate!(opts) if !devise_controller? || opts.delete(:force)
-
end
-
end
-
end
-
-
def #{group_name}_signed_in?
-
#{mappings}.any? do |mapping|
-
warden.authenticate?(scope: mapping)
-
end
-
end
-
-
def current_#{group_name}(favourite=nil)
-
mappings = #{mappings}
-
mappings.unshift mappings.delete(favourite.to_sym) if favourite
-
mappings.each do |mapping|
-
current = warden.authenticate(scope: mapping)
-
return current if current
-
end
-
nil
-
end
-
-
def current_#{group_name.to_s.pluralize}
-
#{mappings}.map do |mapping|
-
warden.authenticate(scope: mapping)
-
end.compact
-
end
-
-
if respond_to?(:helper_method)
-
helper_method "current_#{group_name}", "current_#{group_name.to_s.pluralize}", "#{group_name}_signed_in?"
-
end
-
METHODS
-
end
-
-
2
def log_process_action(payload)
-
24
payload[:status] ||= 401 unless payload[:exception]
-
24
super
-
end
-
end
-
-
# Define authentication filters and accessor helpers based on mappings.
-
# These filters should be used inside the controllers as before_filters,
-
# so you can control the scope of the user who should be signed in to
-
# access that specific controller/action.
-
# Example:
-
#
-
# Roles:
-
# User
-
# Admin
-
#
-
# Generated methods:
-
# authenticate_user! # Signs user in or redirect
-
# authenticate_admin! # Signs admin in or redirect
-
# user_signed_in? # Checks whether there is a user signed in or not
-
# admin_signed_in? # Checks whether there is an admin signed in or not
-
# current_user # Current signed in user
-
# current_admin # Current signed in admin
-
# user_session # Session data available only to the user scope
-
# admin_session # Session data available only to the admin scope
-
#
-
# Use:
-
# before_filter :authenticate_user! # Tell devise to use :user map
-
# before_filter :authenticate_admin! # Tell devise to use :admin map
-
#
-
2
def self.define_helpers(mapping) #:nodoc:
-
mapping = mapping.name
-
-
class_eval <<-METHODS, __FILE__, __LINE__ + 1
-
def authenticate_#{mapping}!(opts={})
-
opts[:scope] = :#{mapping}
-
warden.authenticate!(opts) if !devise_controller? || opts.delete(:force)
-
end
-
-
def #{mapping}_signed_in?
-
!!current_#{mapping}
-
end
-
-
def current_#{mapping}
-
@current_#{mapping} ||= warden.authenticate(scope: :#{mapping})
-
end
-
-
def #{mapping}_session
-
current_#{mapping} && warden.session(:#{mapping})
-
end
-
METHODS
-
-
ActiveSupport.on_load(:action_controller) do
-
if respond_to?(:helper_method)
-
helper_method "current_#{mapping}", "#{mapping}_signed_in?", "#{mapping}_session"
-
end
-
end
-
end
-
-
# The main accessor for the warden proxy instance
-
2
def warden
-
request.env['warden']
-
end
-
-
# Return true if it's a devise_controller. false to all controllers unless
-
# the controllers defined inside devise. Useful if you want to apply a before
-
# filter to all controllers, except the ones in devise:
-
#
-
# before_filter :my_filter, unless: :devise_controller?
-
2
def devise_controller?
-
is_a?(::DeviseController)
-
end
-
-
# Setup a param sanitizer to filter parameters using strong_parameters. See
-
# lib/devise/parameter_sanitizer.rb for more info. Override this
-
# method in your application controller to use your own parameter sanitizer.
-
2
def devise_parameter_sanitizer
-
@devise_parameter_sanitizer ||= if defined?(ActionController::StrongParameters)
-
Devise::ParameterSanitizer.new(resource_class, resource_name, params)
-
else
-
Devise::BaseSanitizer.new(resource_class, resource_name, params)
-
end
-
end
-
-
# Tell warden that params authentication is allowed for that specific page.
-
2
def allow_params_authentication!
-
request.env["devise.allow_params_authentication"] = true
-
end
-
-
# The scope root url to be used when they're signed in. By default, it first
-
# tries to find a resource_root_path, otherwise it uses the root_path.
-
2
def signed_in_root_path(resource_or_scope)
-
scope = Devise::Mapping.find_scope!(resource_or_scope)
-
router_name = Devise.mappings[scope].router_name
-
-
home_path = "#{scope}_root_path"
-
-
context = router_name ? send(router_name) : self
-
-
if context.respond_to?(home_path, true)
-
context.send(home_path)
-
elsif context.respond_to?(:root_path)
-
context.root_path
-
elsif respond_to?(:root_path)
-
root_path
-
else
-
"/"
-
end
-
end
-
-
# The default url to be used after signing in. This is used by all Devise
-
# controllers and you can overwrite it in your ApplicationController to
-
# provide a custom hook for a custom resource.
-
#
-
# By default, it first tries to find a valid resource_return_to key in the
-
# session, then it fallbacks to resource_root_path, otherwise it uses the
-
# root path. For a user scope, you can define the default url in
-
# the following way:
-
#
-
# get '/users' => 'users#index', as: :user_root # creates user_root_path
-
#
-
# namespace :user do
-
# root 'users#index' # creates user_root_path
-
# end
-
#
-
# If the resource root path is not defined, root_path is used. However,
-
# if this default is not enough, you can customize it, for example:
-
#
-
# def after_sign_in_path_for(resource)
-
# stored_location_for(resource) ||
-
# if resource.is_a?(User) && resource.can_publish?
-
# publisher_url
-
# else
-
# super
-
# end
-
# end
-
#
-
2
def after_sign_in_path_for(resource_or_scope)
-
stored_location_for(resource_or_scope) || signed_in_root_path(resource_or_scope)
-
end
-
-
# Method used by sessions controller to sign out a user. You can overwrite
-
# it in your ApplicationController to provide a custom hook for a custom
-
# scope. Notice that differently from +after_sign_in_path_for+ this method
-
# receives a symbol with the scope, and not the resource.
-
#
-
# By default it is the root_path.
-
2
def after_sign_out_path_for(resource_or_scope)
-
scope = Devise::Mapping.find_scope!(resource_or_scope)
-
router_name = Devise.mappings[scope].router_name
-
context = router_name ? send(router_name) : self
-
context.respond_to?(:root_path) ? context.root_path : "/"
-
end
-
-
# Sign in a user and tries to redirect first to the stored location and
-
# then to the url specified by after_sign_in_path_for. It accepts the same
-
# parameters as the sign_in method.
-
2
def sign_in_and_redirect(resource_or_scope, *args)
-
options = args.extract_options!
-
scope = Devise::Mapping.find_scope!(resource_or_scope)
-
resource = args.last || resource_or_scope
-
sign_in(scope, resource, options)
-
redirect_to after_sign_in_path_for(resource)
-
end
-
-
# Sign out a user and tries to redirect to the url specified by
-
# after_sign_out_path_for.
-
2
def sign_out_and_redirect(resource_or_scope)
-
scope = Devise::Mapping.find_scope!(resource_or_scope)
-
redirect_path = after_sign_out_path_for(scope)
-
Devise.sign_out_all_scopes ? sign_out : sign_out(scope)
-
redirect_to redirect_path
-
end
-
-
# Overwrite Rails' handle unverified request to sign out all scopes,
-
# clear run strategies and remove cached variables.
-
2
def handle_unverified_request
-
super # call the default behaviour which resets/nullifies/raises
-
request.env["devise.skip_storage"] = true
-
sign_out_all_scopes(false)
-
end
-
-
2
def request_format
-
@request_format ||= request.format.try(:ref)
-
end
-
-
2
def is_navigational_format?
-
Devise.navigational_formats.include?(request_format)
-
end
-
-
# Check if flash messages should be emitted. Default is to do it on
-
# navigational formats
-
2
def is_flashing_format?
-
is_navigational_format?
-
end
-
-
2
private
-
-
2
def expire_session_data_after_sign_in!
-
ActiveSupport::Deprecation.warn "expire_session_data_after_sign_in! is deprecated " \
-
"in favor of expire_data_after_sign_in!"
-
expire_data_after_sign_in!
-
end
-
-
2
def expire_data_after_sign_out!
-
Devise.mappings.each { |_,m| instance_variable_set("@current_#{m.name}", nil) }
-
super
-
end
-
end
-
end
-
end
-
2
module Devise
-
2
module Controllers
-
# Provide sign in and sign out functionality.
-
# Included by default in all controllers.
-
2
module SignInOut
-
# Return true if the given scope is signed in session. If no scope given, return
-
# true if any scope is signed in. Does not run authentication hooks.
-
2
def signed_in?(scope=nil)
-
[scope || Devise.mappings.keys].flatten.any? do |_scope|
-
warden.authenticate?(scope: _scope)
-
end
-
end
-
-
# Sign in a user that already was authenticated. This helper is useful for logging
-
# users in after sign up.
-
#
-
# All options given to sign_in is passed forward to the set_user method in warden.
-
# The only exception is the :bypass option, which bypass warden callbacks and stores
-
# the user straight in session. This option is useful in cases the user is already
-
# signed in, but we want to refresh the credentials in session.
-
#
-
# Examples:
-
#
-
# sign_in :user, @user # sign_in(scope, resource)
-
# sign_in @user # sign_in(resource)
-
# sign_in @user, event: :authentication # sign_in(resource, options)
-
# sign_in @user, store: false # sign_in(resource, options)
-
# sign_in @user, bypass: true # sign_in(resource, options)
-
#
-
2
def sign_in(resource_or_scope, *args)
-
options = args.extract_options!
-
scope = Devise::Mapping.find_scope!(resource_or_scope)
-
resource = args.last || resource_or_scope
-
-
expire_data_after_sign_in!
-
-
if options[:bypass]
-
warden.session_serializer.store(resource, scope)
-
elsif warden.user(scope) == resource && !options.delete(:force)
-
# Do nothing. User already signed in and we are not forcing it.
-
true
-
else
-
warden.set_user(resource, options.merge!(scope: scope))
-
end
-
end
-
-
# Sign out a given user or scope. This helper is useful for signing out a user
-
# after deleting accounts. Returns true if there was a logout and false if there
-
# is no user logged in on the referred scope
-
#
-
# Examples:
-
#
-
# sign_out :user # sign_out(scope)
-
# sign_out @user # sign_out(resource)
-
#
-
2
def sign_out(resource_or_scope=nil)
-
return sign_out_all_scopes unless resource_or_scope
-
scope = Devise::Mapping.find_scope!(resource_or_scope)
-
user = warden.user(scope: scope, run_callbacks: false) # If there is no user
-
-
warden.raw_session.inspect # Without this inspect here. The session does not clear.
-
warden.logout(scope)
-
warden.clear_strategies_cache!(scope: scope)
-
instance_variable_set(:"@current_#{scope}", nil)
-
-
!!user
-
end
-
-
# Sign out all active users or scopes. This helper is useful for signing out all roles
-
# in one click. This signs out ALL scopes in warden. Returns true if there was at least one logout
-
# and false if there was no user logged in on all scopes.
-
2
def sign_out_all_scopes(lock=true)
-
users = Devise.mappings.keys.map { |s| warden.user(scope: s, run_callbacks: false) }
-
-
warden.logout
-
expire_data_after_sign_out!
-
warden.clear_strategies_cache!
-
warden.lock! if lock
-
-
users.any?
-
end
-
-
2
private
-
-
2
def expire_data_after_sign_in!
-
# session.keys will return an empty array if the session is not yet loaded.
-
# This is a bug in both Rack and Rails.
-
# A call to #empty? forces the session to be loaded.
-
session.empty?
-
session.keys.grep(/^devise\./).each { |k| session.delete(k) }
-
end
-
-
2
alias :expire_data_after_sign_out! :expire_data_after_sign_in!
-
end
-
end
-
end
-
2
require "uri"
-
-
2
module Devise
-
2
module Controllers
-
# Provide the ability to store a location.
-
# Used to redirect back to a desired path after sign in.
-
# Included by default in all controllers.
-
2
module StoreLocation
-
# Returns and delete (if it's navigational format) the url stored in the session for
-
# the given scope. Useful for giving redirect backs after sign up:
-
#
-
# Example:
-
#
-
# redirect_to stored_location_for(:user) || root_path
-
#
-
2
def stored_location_for(resource_or_scope)
-
session_key = stored_location_key_for(resource_or_scope)
-
-
if is_navigational_format?
-
session.delete(session_key)
-
else
-
session[session_key]
-
end
-
end
-
-
# Stores the provided location to redirect the user after signing in.
-
# Useful in combination with the `stored_location_for` helper.
-
#
-
# Example:
-
#
-
# store_location_for(:user, dashboard_path)
-
# redirect_to user_omniauth_authorize_path(:facebook)
-
#
-
2
def store_location_for(resource_or_scope, location)
-
session_key = stored_location_key_for(resource_or_scope)
-
uri = parse_uri(location)
-
if uri
-
path = [uri.path.sub(/\A\/+/, '/'), uri.query].compact.join('?')
-
path = [path, uri.fragment].compact.join('#')
-
session[session_key] = path
-
end
-
end
-
-
2
private
-
-
2
def parse_uri(location)
-
location && URI.parse(location)
-
rescue URI::InvalidURIError
-
nil
-
end
-
-
2
def stored_location_key_for(resource_or_scope)
-
scope = Devise::Mapping.find_scope!(resource_or_scope)
-
"#{scope}_return_to"
-
end
-
end
-
end
-
end
-
2
module Devise
-
2
module Controllers
-
# Create url helpers to be used with resource/scope configuration. Acts as
-
# proxies to the generated routes created by devise.
-
# Resource param can be a string or symbol, a class, or an instance object.
-
# Example using a :user resource:
-
#
-
# new_session_path(:user) => new_user_session_path
-
# session_path(:user) => user_session_path
-
# destroy_session_path(:user) => destroy_user_session_path
-
#
-
# new_password_path(:user) => new_user_password_path
-
# password_path(:user) => user_password_path
-
# edit_password_path(:user) => edit_user_password_path
-
#
-
# new_confirmation_path(:user) => new_user_confirmation_path
-
# confirmation_path(:user) => user_confirmation_path
-
#
-
# Those helpers are included by default to ActionController::Base.
-
#
-
# In case you want to add such helpers to another class, you can do
-
# that as long as this new class includes both url_helpers and
-
# mounted_helpers. Example:
-
#
-
# include Rails.application.routes.url_helpers
-
# include Rails.application.routes.mounted_helpers
-
#
-
2
module UrlHelpers
-
2
def self.remove_helpers!
-
2
self.instance_methods.map(&:to_s).grep(/_(url|path)$/).each do |method|
-
56
remove_method method
-
end
-
end
-
-
2
def self.generate_helpers!(routes=nil)
-
routes ||= begin
-
2
mappings = Devise.mappings.values.map(&:used_helpers).flatten.uniq
-
2
Devise::URL_HELPERS.slice(*mappings)
-
4
end
-
-
4
routes.each do |module_name, actions|
-
12
[:path, :url].each do |path_or_url|
-
24
actions.each do |action|
-
56
action = action ? "#{action}_" : ""
-
56
method = :"#{action}#{module_name}_#{path_or_url}"
-
-
56
define_method method do |resource_or_scope, *args|
-
scope = Devise::Mapping.find_scope!(resource_or_scope)
-
router_name = Devise.mappings[scope].router_name
-
context = router_name ? send(router_name) : _devise_route_context
-
context.send("#{action}#{scope}_#{module_name}_#{path_or_url}", *args)
-
end
-
end
-
end
-
end
-
end
-
-
2
generate_helpers!(Devise::URL_HELPERS)
-
-
2
private
-
-
2
def _devise_route_context
-
@_devise_route_context ||= send(Devise.available_router_name)
-
end
-
end
-
end
-
end
-
2
module Devise
-
# Checks the scope in the given environment and returns the associated failure app.
-
2
class Delegator
-
2
def call(env)
-
failure_app(env).call(env)
-
end
-
-
2
def failure_app(env)
-
app = env["warden.options"] &&
-
(scope = env["warden.options"][:scope]) &&
-
Devise.mappings[scope.to_sym].failure_app
-
-
app || Devise::FailureApp
-
end
-
end
-
end
-
# Deny user access whenever their account is not active yet.
-
# We need this as hook to validate the user activity on each request
-
# and in case the user is using other strategies beside Devise ones.
-
2
Warden::Manager.after_set_user do |record, warden, options|
-
if record && record.respond_to?(:active_for_authentication?) && !record.active_for_authentication?
-
scope = options[:scope]
-
warden.logout(scope)
-
throw :warden, scope: scope, message: record.inactive_message
-
end
-
end
-
2
Warden::Manager.after_authentication do |record, warden, options|
-
clean_up_for_winning_strategy = !warden.winning_strategy.respond_to?(:clean_up_csrf?) ||
-
warden.winning_strategy.clean_up_csrf?
-
if Devise.clean_up_csrf_token_on_authentication && clean_up_for_winning_strategy
-
warden.request.session.try(:delete, :_csrf_token)
-
end
-
end
-
2
module Devise
-
# Responsible for handling devise mappings and routes configuration. Each
-
# resource configured by devise_for in routes is actually creating a mapping
-
# object. You can refer to devise_for in routes for usage options.
-
#
-
# The required value in devise_for is actually not used internally, but it's
-
# inflected to find all other values.
-
#
-
# map.devise_for :users
-
# mapping = Devise.mappings[:user]
-
#
-
# mapping.name #=> :user
-
# # is the scope used in controllers and warden, given in the route as :singular.
-
#
-
# mapping.as #=> "users"
-
# # how the mapping should be search in the path, given in the route as :as.
-
#
-
# mapping.to #=> User
-
# # is the class to be loaded from routes, given in the route as :class_name.
-
#
-
# mapping.modules #=> [:authenticatable]
-
# # is the modules included in the class
-
#
-
2
class Mapping #:nodoc:
-
2
attr_reader :singular, :scoped_path, :path, :controllers, :path_names,
-
:class_name, :sign_out_via, :format, :used_routes, :used_helpers,
-
:failure_app, :router_name
-
-
2
alias :name :singular
-
-
# Receives an object and find a scope for it. If a scope cannot be found,
-
# raises an error. If a symbol is given, it's considered to be the scope.
-
2
def self.find_scope!(obj)
-
obj = obj.devise_scope if obj.respond_to?(:devise_scope)
-
case obj
-
when String, Symbol
-
return obj.to_sym
-
when Class
-
Devise.mappings.each_value { |m| return m.name if obj <= m.to }
-
else
-
Devise.mappings.each_value { |m| return m.name if obj.is_a?(m.to) }
-
end
-
-
raise "Could not find a valid mapping for #{obj.inspect}"
-
end
-
-
2
def self.find_by_path!(path, path_type=:fullpath)
-
Devise.mappings.each_value { |m| return m if path.include?(m.send(path_type)) }
-
raise "Could not find a valid mapping for path #{path.inspect}"
-
end
-
-
2
def initialize(name, options) #:nodoc:
-
@scoped_path = options[:as] ? "#{options[:as]}/#{name}" : name.to_s
-
@singular = (options[:singular] || @scoped_path.tr('/', '_').singularize).to_sym
-
-
@class_name = (options[:class_name] || name.to_s.classify).to_s
-
@klass = Devise.ref(@class_name)
-
-
@path = (options[:path] || name).to_s
-
@path_prefix = options[:path_prefix]
-
-
@sign_out_via = options[:sign_out_via] || Devise.sign_out_via
-
@format = options[:format]
-
-
@router_name = options[:router_name]
-
-
default_failure_app(options)
-
default_controllers(options)
-
default_path_names(options)
-
default_used_route(options)
-
default_used_helpers(options)
-
end
-
-
# Return modules for the mapping.
-
2
def modules
-
@modules ||= to.respond_to?(:devise_modules) ? to.devise_modules : []
-
end
-
-
# Gives the class the mapping points to.
-
2
def to
-
@klass.get
-
end
-
-
2
def strategies
-
@strategies ||= STRATEGIES.values_at(*self.modules).compact.uniq.reverse
-
end
-
-
2
def no_input_strategies
-
self.strategies & Devise::NO_INPUT
-
end
-
-
2
def routes
-
@routes ||= ROUTES.values_at(*self.modules).compact.uniq
-
end
-
-
2
def authenticatable?
-
@authenticatable ||= self.modules.any? { |m| m.to_s =~ /authenticatable/ }
-
end
-
-
2
def fullpath
-
"/#{@path_prefix}/#{@path}".squeeze("/")
-
end
-
-
# Create magic predicates for verifying what module is activated by this map.
-
# Example:
-
#
-
# def confirmable?
-
# self.modules.include?(:confirmable)
-
# end
-
#
-
2
def self.add_module(m)
-
20
class_eval <<-METHOD, __FILE__, __LINE__ + 1
-
def #{m}?
-
self.modules.include?(:#{m})
-
end
-
METHOD
-
end
-
-
2
private
-
-
2
def default_failure_app(options)
-
@failure_app = options[:failure_app] || Devise::FailureApp
-
if @failure_app.is_a?(String)
-
ref = Devise.ref(@failure_app)
-
@failure_app = lambda { |env| ref.get.call(env) }
-
end
-
end
-
-
2
def default_controllers(options)
-
mod = options[:module] || "devise"
-
@controllers = Hash.new { |h,k| h[k] = "#{mod}/#{k}" }
-
@controllers.merge!(options[:controllers]) if options[:controllers]
-
@controllers.each { |k,v| @controllers[k] = v.to_s }
-
end
-
-
2
def default_path_names(options)
-
@path_names = Hash.new { |h,k| h[k] = k.to_s }
-
@path_names[:registration] = ""
-
@path_names.merge!(options[:path_names]) if options[:path_names]
-
end
-
-
2
def default_constraints(options)
-
@constraints = Hash.new
-
@constraints.merge!(options[:constraints]) if options[:constraints]
-
end
-
-
2
def default_defaults(options)
-
@defaults = Hash.new
-
@defaults.merge!(options[:defaults]) if options[:defaults]
-
end
-
-
2
def default_used_route(options)
-
singularizer = lambda { |s| s.to_s.singularize.to_sym }
-
-
if options.has_key?(:only)
-
@used_routes = self.routes & Array(options[:only]).map(&singularizer)
-
elsif options[:skip] == :all
-
@used_routes = []
-
else
-
@used_routes = self.routes - Array(options[:skip]).map(&singularizer)
-
end
-
end
-
-
2
def default_used_helpers(options)
-
singularizer = lambda { |s| s.to_s.singularize.to_sym }
-
-
if options[:skip_helpers] == true
-
@used_helpers = @used_routes
-
elsif skip = options[:skip_helpers]
-
@used_helpers = self.routes - Array(skip).map(&singularizer)
-
else
-
@used_helpers = self.routes
-
end
-
end
-
end
-
end
-
2
module Devise
-
2
module Models
-
2
class MissingAttribute < StandardError
-
2
def initialize(attributes)
-
@attributes = attributes
-
end
-
-
2
def message
-
"The following attribute(s) is (are) missing on your model: #{@attributes.join(", ")}"
-
end
-
end
-
-
# Creates configuration values for Devise and for the given module.
-
#
-
# Devise::Models.config(Devise::DatabaseAuthenticatable, :stretches)
-
#
-
# The line above creates:
-
#
-
# 1) An accessor called Devise.stretches, which value is used by default;
-
#
-
# 2) Some class methods for your model Model.stretches and Model.stretches=
-
# which have higher priority than Devise.stretches;
-
#
-
# 3) And an instance method stretches.
-
#
-
# To add the class methods you need to have a module ClassMethods defined
-
# inside the given class.
-
#
-
2
def self.config(mod, *accessors) #:nodoc:
-
4
class << mod; attr_accessor :available_configs; end
-
2
mod.available_configs = accessors
-
-
2
accessors.each do |accessor|
-
16
mod.class_eval <<-METHOD, __FILE__, __LINE__ + 1
-
def #{accessor}
-
if defined?(@#{accessor})
-
@#{accessor}
-
elsif superclass.respond_to?(:#{accessor})
-
superclass.#{accessor}
-
else
-
Devise.#{accessor}
-
end
-
end
-
-
def #{accessor}=(value)
-
@#{accessor} = value
-
end
-
METHOD
-
end
-
end
-
-
2
def self.check_fields!(klass)
-
failed_attributes = []
-
instance = klass.new
-
-
klass.devise_modules.each do |mod|
-
constant = const_get(mod.to_s.classify)
-
-
constant.required_fields(klass).each do |field|
-
failed_attributes << field unless instance.respond_to?(field)
-
end
-
end
-
-
if failed_attributes.any?
-
fail Devise::Models::MissingAttribute.new(failed_attributes)
-
end
-
end
-
-
# Include the chosen devise modules in your model:
-
#
-
# devise :database_authenticatable, :confirmable, :recoverable
-
#
-
# You can also give any of the devise configuration values in form of a hash,
-
# with specific values for this model. Please check your Devise initializer
-
# for a complete description on those values.
-
#
-
2
def devise(*modules)
-
options = modules.extract_options!.dup
-
-
selected_modules = modules.map(&:to_sym).uniq.sort_by do |s|
-
Devise::ALL.index(s) || -1 # follow Devise::ALL order
-
end
-
-
devise_modules_hook! do
-
include Devise::Models::Authenticatable
-
-
selected_modules.each do |m|
-
mod = Devise::Models.const_get(m.to_s.classify)
-
-
if mod.const_defined?("ClassMethods")
-
class_mod = mod.const_get("ClassMethods")
-
extend class_mod
-
-
if class_mod.respond_to?(:available_configs)
-
available_configs = class_mod.available_configs
-
available_configs.each do |config|
-
next unless options.key?(config)
-
send(:"#{config}=", options.delete(config))
-
end
-
end
-
end
-
-
include mod
-
end
-
-
self.devise_modules |= selected_modules
-
options.each { |key, value| send(:"#{key}=", value) }
-
end
-
end
-
-
# The hook which is called inside devise.
-
# So your ORM can include devise compatibility stuff.
-
2
def devise_modules_hook!
-
yield
-
end
-
end
-
end
-
-
2
require 'devise/models/authenticatable'
-
2
require 'active_model/version'
-
2
require 'devise/hooks/activatable'
-
2
require 'devise/hooks/csrf_cleaner'
-
-
2
module Devise
-
2
module Models
-
# Authenticatable module. Holds common settings for authentication.
-
#
-
# == Options
-
#
-
# Authenticatable adds the following options to devise_for:
-
#
-
# * +authentication_keys+: parameters used for authentication. By default [:email].
-
#
-
# * +http_authentication_key+: map the username passed via HTTP Auth to this parameter. Defaults to
-
# the first element in +authentication_keys+.
-
#
-
# * +request_keys+: parameters from the request object used for authentication.
-
# By specifying a symbol (which should be a request method), it will automatically be
-
# passed to find_for_authentication method and considered in your model lookup.
-
#
-
# For instance, if you set :request_keys to [:subdomain], :subdomain will be considered
-
# as key on authentication. This can also be a hash where the value is a boolean specifying
-
# if the value is required or not.
-
#
-
# * +http_authenticatable+: if this model allows http authentication. By default false.
-
# It also accepts an array specifying the strategies that should allow http.
-
#
-
# * +params_authenticatable+: if this model allows authentication through request params. By default true.
-
# It also accepts an array specifying the strategies that should allow params authentication.
-
#
-
# * +skip_session_storage+: By default Devise will store the user in session.
-
# By default is set to skip_session_storage: [:http_auth].
-
#
-
# == active_for_authentication?
-
#
-
# After authenticating a user and in each request, Devise checks if your model is active by
-
# calling model.active_for_authentication?. This method is overwritten by other devise modules. For instance,
-
# :confirmable overwrites .active_for_authentication? to only return true if your model was confirmed.
-
#
-
# You can overwrite this method yourself, but if you do, don't forget to call super:
-
#
-
# def active_for_authentication?
-
# super && special_condition_is_valid?
-
# end
-
#
-
# Whenever active_for_authentication? returns false, Devise asks the reason why your model is inactive using
-
# the inactive_message method. You can overwrite it as well:
-
#
-
# def inactive_message
-
# special_condition_is_valid? ? super : :special_condition_is_not_valid
-
# end
-
#
-
2
module Authenticatable
-
2
extend ActiveSupport::Concern
-
-
2
BLACKLIST_FOR_SERIALIZATION = [:encrypted_password, :reset_password_token, :reset_password_sent_at,
-
:remember_created_at, :sign_in_count, :current_sign_in_at, :last_sign_in_at, :current_sign_in_ip,
-
:last_sign_in_ip, :password_salt, :confirmation_token, :confirmed_at, :confirmation_sent_at,
-
:remember_token, :unconfirmed_email, :failed_attempts, :unlock_token, :locked_at]
-
-
2
included do
-
class_attribute :devise_modules, instance_writer: false
-
self.devise_modules ||= []
-
-
before_validation :downcase_keys
-
before_validation :strip_whitespace
-
end
-
-
2
def self.required_fields(klass)
-
[]
-
end
-
-
# Check if the current object is valid for authentication. This method and
-
# find_for_authentication are the methods used in a Warden::Strategy to check
-
# if a model should be signed in or not.
-
#
-
# However, you should not overwrite this method, you should overwrite active_for_authentication?
-
# and inactive_message instead.
-
2
def valid_for_authentication?
-
block_given? ? yield : true
-
end
-
-
2
def unauthenticated_message
-
:invalid
-
end
-
-
2
def active_for_authentication?
-
true
-
end
-
-
2
def inactive_message
-
:inactive
-
end
-
-
2
def authenticatable_salt
-
end
-
-
# Redefine serializable_hash in models for more secure defaults.
-
# By default, it removes from the serializable model all attributes that
-
# are *not* accessible. You can remove this default by using :force_except
-
# and passing a new list of attributes you want to exempt. All attributes
-
# given to :except will simply add names to exempt to Devise internal list.
-
2
def serializable_hash(options = nil)
-
options ||= {}
-
options[:except] = Array(options[:except])
-
-
if options[:force_except]
-
options[:except].concat Array(options[:force_except])
-
else
-
options[:except].concat BLACKLIST_FOR_SERIALIZATION
-
end
-
-
super(options)
-
end
-
-
2
protected
-
-
2
def devise_mailer
-
Devise.mailer
-
end
-
-
# This is an internal method called every time Devise needs
-
# to send a notification/mail. This can be overridden if you
-
# need to customize the e-mail delivery logic. For instance,
-
# if you are using a queue to deliver e-mails (delayed job,
-
# sidekiq, resque, etc), you must add the delivery to the queue
-
# just after the transaction was committed. To achieve this,
-
# you can override send_devise_notification to store the
-
# deliveries until the after_commit callback is triggered:
-
#
-
# class User
-
# devise :database_authenticatable, :confirmable
-
#
-
# after_commit :send_pending_notifications
-
#
-
# protected
-
#
-
# def send_devise_notification(notification, *args)
-
# # If the record is new or changed then delay the
-
# # delivery until the after_commit callback otherwise
-
# # send now because after_commit will not be called.
-
# if new_record? || changed?
-
# pending_notifications << [notification, args]
-
# else
-
# devise_mailer.send(notification, self, *args).deliver
-
# end
-
# end
-
#
-
# def send_pending_notifications
-
# pending_notifications.each do |notification, args|
-
# devise_mailer.send(notification, self, *args).deliver
-
# end
-
#
-
# # Empty the pending notifications array because the
-
# # after_commit hook can be called multiple times which
-
# # could cause multiple emails to be sent.
-
# pending_notifications.clear
-
# end
-
#
-
# def pending_notifications
-
# @pending_notifications ||= []
-
# end
-
# end
-
#
-
2
def send_devise_notification(notification, *args)
-
message = devise_mailer.send(notification, self, *args)
-
# Remove once we move to Rails 4.2+ only.
-
if message.respond_to?(:deliver_now)
-
message.deliver_now
-
else
-
message.deliver
-
end
-
end
-
-
2
def downcase_keys
-
self.class.case_insensitive_keys.each { |k| apply_to_attribute_or_variable(k, :downcase) }
-
end
-
-
2
def strip_whitespace
-
self.class.strip_whitespace_keys.each { |k| apply_to_attribute_or_variable(k, :strip) }
-
end
-
-
2
def apply_to_attribute_or_variable(attr, method)
-
if self[attr]
-
self[attr] = self[attr].try(method)
-
-
# Use respond_to? here to avoid a regression where globally
-
# configured strip_whitespace_keys or case_insensitive_keys were
-
# attempting to strip or downcase when a model didn't have the
-
# globally configured key.
-
elsif respond_to?(attr) && respond_to?("#{attr}=")
-
new_value = send(attr).try(method)
-
send("#{attr}=", new_value)
-
end
-
end
-
-
2
module ClassMethods
-
2
Devise::Models.config(self, :authentication_keys, :request_keys, :strip_whitespace_keys,
-
:case_insensitive_keys, :http_authenticatable, :params_authenticatable, :skip_session_storage,
-
:http_authentication_key)
-
-
2
def serialize_into_session(record)
-
[record.to_key, record.authenticatable_salt]
-
end
-
-
2
def serialize_from_session(key, salt)
-
record = to_adapter.get(key)
-
record if record && record.authenticatable_salt == salt
-
end
-
-
2
def params_authenticatable?(strategy)
-
params_authenticatable.is_a?(Array) ?
-
params_authenticatable.include?(strategy) : params_authenticatable
-
end
-
-
2
def http_authenticatable?(strategy)
-
http_authenticatable.is_a?(Array) ?
-
http_authenticatable.include?(strategy) : http_authenticatable
-
end
-
-
# Find first record based on conditions given (ie by the sign in form).
-
# This method is always called during an authentication process but
-
# it may be wrapped as well. For instance, database authenticatable
-
# provides a `find_for_database_authentication` that wraps a call to
-
# this method. This allows you to customize both database authenticatable
-
# or the whole authenticate stack by customize `find_for_authentication.`
-
#
-
# Overwrite to add customized conditions, create a join, or maybe use a
-
# namedscope to filter records while authenticating.
-
# Example:
-
#
-
# def self.find_for_authentication(tainted_conditions)
-
# find_first_by_auth_conditions(tainted_conditions, active: true)
-
# end
-
#
-
# Finally, notice that Devise also queries for users in other scenarios
-
# besides authentication, for example when retrieving an user to send
-
# an e-mail for password reset. In such cases, find_for_authentication
-
# is not called.
-
2
def find_for_authentication(tainted_conditions)
-
find_first_by_auth_conditions(tainted_conditions)
-
end
-
-
2
def find_first_by_auth_conditions(tainted_conditions, opts={})
-
to_adapter.find_first(devise_parameter_filter.filter(tainted_conditions).merge(opts))
-
end
-
-
# Find or initialize a record setting an error if it can't be found.
-
2
def find_or_initialize_with_error_by(attribute, value, error=:invalid) #:nodoc:
-
find_or_initialize_with_errors([attribute], { attribute => value }, error)
-
end
-
-
# Find or initialize a record with group of attributes based on a list of required attributes.
-
2
def find_or_initialize_with_errors(required_attributes, attributes, error=:invalid) #:nodoc:
-
attributes = attributes.slice(*required_attributes).with_indifferent_access
-
attributes.delete_if { |key, value| value.blank? }
-
-
if attributes.size == required_attributes.size
-
record = find_first_by_auth_conditions(attributes)
-
end
-
-
unless record
-
record = new
-
-
required_attributes.each do |key|
-
value = attributes[key]
-
record.send("#{key}=", value)
-
record.errors.add(key, value.present? ? error : :blank)
-
end
-
end
-
-
record
-
end
-
-
2
protected
-
-
2
def devise_parameter_filter
-
@devise_parameter_filter ||= Devise::ParameterFilter.new(case_insensitive_keys, strip_whitespace_keys)
-
end
-
end
-
end
-
end
-
end
-
2
require 'active_support/core_ext/object/with_options'
-
-
2
Devise.with_options model: true do |d|
-
# Strategies first
-
2
d.with_options strategy: true do |s|
-
2
routes = [nil, :new, :destroy]
-
2
s.add_module :database_authenticatable, controller: :sessions, route: { session: routes }
-
2
s.add_module :rememberable, no_input: true
-
end
-
-
# Other authentications
-
2
d.add_module :omniauthable, controller: :omniauth_callbacks, route: :omniauth_callback
-
-
# Misc after
-
2
routes = [nil, :new, :edit]
-
2
d.add_module :recoverable, controller: :passwords, route: { password: routes }
-
2
d.add_module :registerable, controller: :registrations, route: { registration: (routes << :cancel) }
-
2
d.add_module :validatable
-
-
# The ones which can sign out after
-
2
routes = [nil, :new]
-
2
d.add_module :confirmable, controller: :confirmations, route: { confirmation: routes }
-
2
d.add_module :lockable, controller: :unlocks, route: { unlock: routes }
-
2
d.add_module :timeoutable
-
-
# Stats for last, so we make sure the user is really signed in
-
2
d.add_module :trackable
-
end
-
2
require 'orm_adapter/adapters/active_record'
-
-
2
ActiveRecord::Base.extend Devise::Models
-
2
require 'devise/rails/routes'
-
2
require 'devise/rails/warden_compat'
-
-
2
module Devise
-
2
class Engine < ::Rails::Engine
-
2
config.devise = Devise
-
-
# Initialize Warden and copy its configurations.
-
2
config.app_middleware.use Warden::Manager do |config|
-
2
Devise.warden_config = config
-
end
-
-
# Force routes to be loaded if we are doing any eager load.
-
2
config.before_eager_load { |app| app.reload_routes! }
-
-
2
initializer "devise.url_helpers" do
-
2
Devise.include_helpers(Devise::Controllers)
-
end
-
-
2
initializer "devise.omniauth", after: :load_config_initializers, before: :build_middleware_stack do |app|
-
2
Devise.omniauth_configs.each do |provider, config|
-
app.middleware.use config.strategy_class, *config.args do |strategy|
-
config.strategy = strategy
-
end
-
end
-
-
2
if Devise.omniauth_configs.any?
-
Devise.include_helpers(Devise::OmniAuth)
-
end
-
end
-
-
2
initializer "devise.secret_key" do |app|
-
2
if app.respond_to?(:secrets)
-
2
Devise.secret_key ||= app.secrets.secret_key_base
-
elsif app.config.respond_to?(:secret_key_base)
-
Devise.secret_key ||= app.config.secret_key_base
-
end
-
-
2
Devise.token_generator ||=
-
if secret_key = Devise.secret_key
-
2
Devise::TokenGenerator.new(
-
Devise::CachingKeyGenerator.new(Devise::KeyGenerator.new(secret_key))
-
)
-
end
-
end
-
-
2
initializer "devise.fix_routes_proxy_missing_respond_to_bug" do
-
# Deprecate: Remove once we move to Rails 4 only.
-
2
ActionDispatch::Routing::RoutesProxy.class_eval do
-
2
def respond_to?(method, include_private = false)
-
super || routes.url_helpers.respond_to?(method)
-
end
-
end
-
end
-
end
-
end
-
2
require "active_support/core_ext/object/try"
-
2
require "active_support/core_ext/hash/slice"
-
-
2
module ActionDispatch::Routing
-
2
class RouteSet #:nodoc:
-
# Ensure Devise modules are included only after loading routes, because we
-
# need devise_for mappings already declared to create filters and helpers.
-
2
def finalize_with_devise!
-
2
result = finalize_without_devise!
-
-
@devise_finalized ||= begin
-
2
if Devise.router_name.nil? && defined?(@devise_finalized) && self != Rails.application.try(:routes)
-
warn "[DEVISE] We have detected that you are using devise_for inside engine routes. " \
-
"In this case, you probably want to set Devise.router_name = MOUNT_POINT, where " \
-
"MOUNT_POINT is a symbol representing where this engine will be mounted at. For " \
-
"now Devise will default the mount point to :main_app. You can explicitly set it" \
-
" to :main_app as well in case you want to keep the current behavior."
-
end
-
-
2
Devise.configure_warden!
-
2
Devise.regenerate_helpers!
-
2
true
-
2
end
-
-
2
result
-
end
-
2
alias_method_chain :finalize!, :devise
-
end
-
-
2
class Mapper
-
# Includes devise_for method for routes. This method is responsible to
-
# generate all needed routes for devise, based on what modules you have
-
# defined in your model.
-
#
-
# ==== Examples
-
#
-
# Let's say you have an User model configured to use authenticatable,
-
# confirmable and recoverable modules. After creating this inside your routes:
-
#
-
# devise_for :users
-
#
-
# This method is going to look inside your User model and create the
-
# needed routes:
-
#
-
# # Session routes for Authenticatable (default)
-
# new_user_session GET /users/sign_in {controller:"devise/sessions", action:"new"}
-
# user_session POST /users/sign_in {controller:"devise/sessions", action:"create"}
-
# destroy_user_session DELETE /users/sign_out {controller:"devise/sessions", action:"destroy"}
-
#
-
# # Password routes for Recoverable, if User model has :recoverable configured
-
# new_user_password GET /users/password/new(.:format) {controller:"devise/passwords", action:"new"}
-
# edit_user_password GET /users/password/edit(.:format) {controller:"devise/passwords", action:"edit"}
-
# user_password PUT /users/password(.:format) {controller:"devise/passwords", action:"update"}
-
# POST /users/password(.:format) {controller:"devise/passwords", action:"create"}
-
#
-
# # Confirmation routes for Confirmable, if User model has :confirmable configured
-
# new_user_confirmation GET /users/confirmation/new(.:format) {controller:"devise/confirmations", action:"new"}
-
# user_confirmation GET /users/confirmation(.:format) {controller:"devise/confirmations", action:"show"}
-
# POST /users/confirmation(.:format) {controller:"devise/confirmations", action:"create"}
-
#
-
# ==== Routes integration
-
#
-
# +devise_for+ is meant to play nicely with other routes methods. For example,
-
# by calling +devise_for+ inside a namespace, it automatically nests your devise
-
# controllers:
-
#
-
# namespace :publisher do
-
# devise_for :account
-
# end
-
#
-
# The snippet above will use publisher/sessions controller instead of devise/sessions
-
# controller. You can revert this change or configure it directly by passing the :module
-
# option described below to +devise_for+.
-
#
-
# Also note that when you use a namespace it will affect all the helpers and methods
-
# for controllers and views. For example, using the above setup you'll end with
-
# following methods: current_publisher_account, authenticate_publisher_account!,
-
# publisher_account_signed_in, etc.
-
#
-
# The only aspect not affect by the router configuration is the model name. The
-
# model name can be explicitly set via the :class_name option.
-
#
-
# ==== Options
-
#
-
# You can configure your routes with some options:
-
#
-
# * class_name: setup a different class to be looked up by devise, if it cannot be
-
# properly found by the route name.
-
#
-
# devise_for :users, class_name: 'Account'
-
#
-
# * path: allows you to setup path name that will be used, as rails routes does.
-
# The following route configuration would setup your route as /accounts instead of /users:
-
#
-
# devise_for :users, path: 'accounts'
-
#
-
# * singular: setup the singular name for the given resource. This is used as the helper methods
-
# names in controller ("authenticate_#{singular}!", "#{singular}_signed_in?", "current_#{singular}"
-
# and "#{singular}_session"), as the scope name in routes and as the scope given to warden.
-
#
-
# devise_for :admins, singular: :manager
-
#
-
# devise_scope :manager do
-
# ...
-
# end
-
#
-
# class ManagerController < ApplicationController
-
# before_filter authenticate_manager!
-
#
-
# def show
-
# @manager = current_manager
-
# ...
-
# end
-
# end
-
#
-
# * path_names: configure different path names to overwrite defaults :sign_in, :sign_out, :sign_up,
-
# :password, :confirmation, :unlock.
-
#
-
# devise_for :users, path_names: {
-
# sign_in: 'login', sign_out: 'logout',
-
# password: 'secret', confirmation: 'verification',
-
# registration: 'register', edit: 'edit/profile'
-
# }
-
#
-
# * controllers: the controller which should be used. All routes by default points to Devise controllers.
-
# However, if you want them to point to custom controller, you should do:
-
#
-
# devise_for :users, controllers: { sessions: "users/sessions" }
-
#
-
# * failure_app: a rack app which is invoked whenever there is a failure. Strings representing a given
-
# are also allowed as parameter.
-
#
-
# * sign_out_via: the HTTP method(s) accepted for the :sign_out action (default: :get),
-
# if you wish to restrict this to accept only :post or :delete requests you should do:
-
#
-
# devise_for :users, sign_out_via: [:post, :delete]
-
#
-
# You need to make sure that your sign_out controls trigger a request with a matching HTTP method.
-
#
-
# * module: the namespace to find controllers (default: "devise", thus
-
# accessing devise/sessions, devise/registrations, and so on). If you want
-
# to namespace all at once, use module:
-
#
-
# devise_for :users, module: "users"
-
#
-
# * skip: tell which controller you want to skip routes from being created.
-
# It accepts :all as an option, meaning it will not generate any route at all:
-
#
-
# devise_for :users, skip: :sessions
-
#
-
# * only: the opposite of :skip, tell which controllers only to generate routes to:
-
#
-
# devise_for :users, only: :sessions
-
#
-
# * skip_helpers: skip generating Devise url helpers like new_session_path(@user).
-
# This is useful to avoid conflicts with previous routes and is false by default.
-
# It accepts true as option, meaning it will skip all the helpers for the controllers
-
# given in :skip but it also accepts specific helpers to be skipped:
-
#
-
# devise_for :users, skip: [:registrations, :confirmations], skip_helpers: true
-
# devise_for :users, skip_helpers: [:registrations, :confirmations]
-
#
-
# * format: include "(.:format)" in the generated routes? true by default, set to false to disable:
-
#
-
# devise_for :users, format: false
-
#
-
# * constraints: works the same as Rails' constraints
-
#
-
# * defaults: works the same as Rails' defaults
-
#
-
# * router_name: allows application level router name to be overwritten for the current scope
-
#
-
# ==== Scoping
-
#
-
# Following Rails 3 routes DSL, you can nest devise_for calls inside a scope:
-
#
-
# scope "/my" do
-
# devise_for :users
-
# end
-
#
-
# However, since Devise uses the request path to retrieve the current user,
-
# this has one caveat: If you are using a dynamic segment, like so ...
-
#
-
# scope ":locale" do
-
# devise_for :users
-
# end
-
#
-
# you are required to configure default_url_options in your
-
# ApplicationController class, so Devise can pick it:
-
#
-
# class ApplicationController < ActionController::Base
-
# def self.default_url_options
-
# { locale: I18n.locale }
-
# end
-
# end
-
#
-
# ==== Adding custom actions to override controllers
-
#
-
# You can pass a block to devise_for that will add any routes defined in the block to Devise's
-
# list of known actions. This is important if you add a custom action to a controller that
-
# overrides an out of the box Devise controller.
-
# For example:
-
#
-
# class RegistrationsController < Devise::RegistrationsController
-
# def update
-
# # do something different here
-
# end
-
#
-
# def deactivate
-
# # not a standard action
-
# # deactivate code here
-
# end
-
# end
-
#
-
# In order to get Devise to recognize the deactivate action, your devise_scope entry should look like this:
-
#
-
# devise_scope :owner do
-
# post "deactivate", to: "registrations#deactivate", as: "deactivate_registration"
-
# end
-
#
-
2
def devise_for(*resources)
-
@devise_finalized = false
-
raise_no_secret_key unless Devise.secret_key
-
options = resources.extract_options!
-
-
options[:as] ||= @scope[:as] if @scope[:as].present?
-
options[:module] ||= @scope[:module] if @scope[:module].present?
-
options[:path_prefix] ||= @scope[:path] if @scope[:path].present?
-
options[:path_names] = (@scope[:path_names] || {}).merge(options[:path_names] || {})
-
options[:constraints] = (@scope[:constraints] || {}).merge(options[:constraints] || {})
-
options[:defaults] = (@scope[:defaults] || {}).merge(options[:defaults] || {})
-
options[:options] = @scope[:options] || {}
-
options[:options][:format] = false if options[:format] == false
-
-
resources.map!(&:to_sym)
-
-
resources.each do |resource|
-
mapping = Devise.add_mapping(resource, options)
-
-
begin
-
raise_no_devise_method_error!(mapping.class_name) unless mapping.to.respond_to?(:devise)
-
rescue NameError => e
-
raise unless mapping.class_name == resource.to_s.classify
-
warn "[WARNING] You provided devise_for #{resource.inspect} but there is " \
-
"no model #{mapping.class_name} defined in your application"
-
next
-
rescue NoMethodError => e
-
raise unless e.message.include?("undefined method `devise'")
-
raise_no_devise_method_error!(mapping.class_name)
-
end
-
-
if options[:controllers] && options[:controllers][:omniauth_callbacks]
-
unless mapping.omniauthable?
-
raise ArgumentError, "Mapping omniauth_callbacks on a resource that is not omniauthable\n" \
-
"Please add `devise :omniauthable` to the `#{mapping.class_name}` model"
-
end
-
end
-
-
routes = mapping.used_routes
-
-
devise_scope mapping.name do
-
with_devise_exclusive_scope mapping.fullpath, mapping.name, options do
-
routes.each { |mod| send("devise_#{mod}", mapping, mapping.controllers) }
-
end
-
end
-
end
-
end
-
-
# Allow you to add authentication request from the router.
-
# Takes an optional scope and block to provide constraints
-
# on the model instance itself.
-
#
-
# authenticate do
-
# resources :post
-
# end
-
#
-
# authenticate(:admin) do
-
# resources :users
-
# end
-
#
-
# authenticate :user, lambda {|u| u.role == "admin"} do
-
# root to: "admin/dashboard#show", as: :user_root
-
# end
-
#
-
2
def authenticate(scope=nil, block=nil)
-
constraints_for(:authenticate!, scope, block) do
-
yield
-
end
-
end
-
-
# Allow you to route based on whether a scope is authenticated. You
-
# can optionally specify which scope and a block. The block accepts
-
# a model and allows extra constraints to be done on the instance.
-
#
-
# authenticated :admin do
-
# root to: 'admin/dashboard#show', as: :admin_root
-
# end
-
#
-
# authenticated do
-
# root to: 'dashboard#show', as: :authenticated_root
-
# end
-
#
-
# authenticated :user, lambda {|u| u.role == "admin"} do
-
# root to: "admin/dashboard#show", as: :user_root
-
# end
-
#
-
# root to: 'landing#show'
-
#
-
2
def authenticated(scope=nil, block=nil)
-
constraints_for(:authenticate?, scope, block) do
-
yield
-
end
-
end
-
-
# Allow you to route based on whether a scope is *not* authenticated.
-
# You can optionally specify which scope.
-
#
-
# unauthenticated do
-
# as :user do
-
# root to: 'devise/registrations#new'
-
# end
-
# end
-
#
-
# root to: 'dashboard#show'
-
#
-
2
def unauthenticated(scope=nil)
-
constraint = lambda do |request|
-
not request.env["warden"].authenticate? scope: scope
-
end
-
-
constraints(constraint) do
-
yield
-
end
-
end
-
-
# Sets the devise scope to be used in the controller. If you have custom routes,
-
# you are required to call this method (also aliased as :as) in order to specify
-
# to which controller it is targetted.
-
#
-
# as :user do
-
# get "sign_in", to: "devise/sessions#new"
-
# end
-
#
-
# Notice you cannot have two scopes mapping to the same URL. And remember, if
-
# you try to access a devise controller without specifying a scope, it will
-
# raise ActionNotFound error.
-
#
-
# Also be aware of that 'devise_scope' and 'as' use the singular form of the
-
# noun where other devise route commands expect the plural form. This would be a
-
# good and working example.
-
#
-
# devise_scope :user do
-
# get "/some/route" => "some_devise_controller"
-
# end
-
# devise_for :users
-
#
-
# Notice and be aware of the differences above between :user and :users
-
2
def devise_scope(scope)
-
constraint = lambda do |request|
-
request.env["devise.mapping"] = Devise.mappings[scope]
-
true
-
end
-
-
constraints(constraint) do
-
yield
-
end
-
end
-
2
alias :as :devise_scope
-
-
2
protected
-
-
2
def devise_session(mapping, controllers) #:nodoc:
-
resource :session, only: [], controller: controllers[:sessions], path: "" do
-
get :new, path: mapping.path_names[:sign_in], as: "new"
-
post :create, path: mapping.path_names[:sign_in]
-
match :destroy, path: mapping.path_names[:sign_out], as: "destroy", via: mapping.sign_out_via
-
end
-
end
-
-
2
def devise_password(mapping, controllers) #:nodoc:
-
resource :password, only: [:new, :create, :edit, :update],
-
path: mapping.path_names[:password], controller: controllers[:passwords]
-
end
-
-
2
def devise_confirmation(mapping, controllers) #:nodoc:
-
resource :confirmation, only: [:new, :create, :show],
-
path: mapping.path_names[:confirmation], controller: controllers[:confirmations]
-
end
-
-
2
def devise_unlock(mapping, controllers) #:nodoc:
-
if mapping.to.unlock_strategy_enabled?(:email)
-
resource :unlock, only: [:new, :create, :show],
-
path: mapping.path_names[:unlock], controller: controllers[:unlocks]
-
end
-
end
-
-
2
def devise_registration(mapping, controllers) #:nodoc:
-
path_names = {
-
new: mapping.path_names[:sign_up],
-
edit: mapping.path_names[:edit],
-
cancel: mapping.path_names[:cancel]
-
}
-
-
options = {
-
only: [:new, :create, :edit, :update, :destroy],
-
path: mapping.path_names[:registration],
-
path_names: path_names,
-
controller: controllers[:registrations]
-
}
-
-
resource :registration, options do
-
get :cancel
-
end
-
end
-
-
2
def devise_omniauth_callback(mapping, controllers) #:nodoc:
-
if mapping.fullpath =~ /:[a-zA-Z_]/
-
raise <<-ERROR
-
Devise does not support scoping OmniAuth callbacks under a dynamic segment
-
and you have set #{mapping.fullpath.inspect}. You can work around by passing
-
`skip: :omniauth_callbacks` to the `devise_for` call and extract omniauth
-
options to another `devise_for` call outside the scope. Here is an example:
-
-
devise_for :users, only: :omniauth_callbacks, controllers: {omniauth_callbacks: 'users/omniauth_callbacks'}
-
-
scope '/(:locale)', locale: /ru|en/ do
-
devise_for :users, skip: :omniauth_callbacks
-
end
-
ERROR
-
end
-
-
path, @scope[:path] = @scope[:path], nil
-
path_prefix = Devise.omniauth_path_prefix || "/#{mapping.fullpath}/auth".squeeze("/")
-
-
set_omniauth_path_prefix!(path_prefix)
-
-
providers = Regexp.union(mapping.to.omniauth_providers.map(&:to_s))
-
-
match "#{path_prefix}/:provider",
-
constraints: { provider: providers },
-
to: "#{controllers[:omniauth_callbacks]}#passthru",
-
as: :omniauth_authorize,
-
via: [:get, :post]
-
-
match "#{path_prefix}/:action/callback",
-
constraints: { action: providers },
-
to: "#{controllers[:omniauth_callbacks]}#:action",
-
as: :omniauth_callback,
-
via: [:get, :post]
-
ensure
-
@scope[:path] = path
-
end
-
-
2
def with_devise_exclusive_scope(new_path, new_as, options) #:nodoc:
-
current_scope = @scope.dup
-
-
exclusive = { as: new_as, path: new_path, module: nil }
-
exclusive.merge!(options.slice(:constraints, :defaults, :options))
-
-
exclusive.each_pair { |key, value| @scope[key] = value }
-
yield
-
ensure
-
@scope = current_scope
-
end
-
-
2
def constraints_for(method_to_apply, scope=nil, block=nil)
-
constraint = lambda do |request|
-
request.env['warden'].send(method_to_apply, scope: scope) &&
-
(block.nil? || block.call(request.env["warden"].user(scope)))
-
end
-
-
constraints(constraint) do
-
yield
-
end
-
end
-
-
2
def set_omniauth_path_prefix!(path_prefix) #:nodoc:
-
if ::OmniAuth.config.path_prefix && ::OmniAuth.config.path_prefix != path_prefix
-
raise "Wrong OmniAuth configuration. If you are getting this exception, it means that either:\n\n" \
-
"1) You are manually setting OmniAuth.config.path_prefix and it doesn't match the Devise one\n" \
-
"2) You are setting :omniauthable in more than one model\n" \
-
"3) You changed your Devise routes/OmniAuth setting and haven't restarted your server"
-
else
-
::OmniAuth.config.path_prefix = path_prefix
-
end
-
end
-
-
2
def raise_no_secret_key #:nodoc:
-
raise <<-ERROR
-
Devise.secret_key was not set. Please add the following to your Devise initializer:
-
-
config.secret_key = '#{SecureRandom.hex(64)}'
-
-
Please ensure you restarted your application after installing Devise or setting the key.
-
ERROR
-
end
-
-
2
def raise_no_devise_method_error!(klass) #:nodoc:
-
raise "#{klass} does not respond to 'devise' method. This usually means you haven't " \
-
"loaded your ORM file or it's being loaded too late. To fix it, be sure to require 'devise/orm/YOUR_ORM' " \
-
"inside 'config/initializers/devise.rb' or before your application definition in 'config/application.rb'"
-
end
-
end
-
end
-
2
module Warden::Mixins::Common
-
2
def request
-
@request ||= ActionDispatch::Request.new(env)
-
end
-
-
# Deprecate: Remove this check once we move to Rails 4 only.
-
2
NULL_STORE =
-
defined?(ActionController::RequestForgeryProtection::ProtectionMethods::NullSession::NullSessionHash) ?
-
ActionController::RequestForgeryProtection::ProtectionMethods::NullSession::NullSessionHash : nil
-
-
2
def reset_session!
-
# Calling reset_session on NULL_STORE causes it fail.
-
# This is a bug that needs to be fixed in Rails.
-
unless NULL_STORE && request.session.is_a?(NULL_STORE)
-
request.reset_session
-
end
-
end
-
-
2
def cookies
-
request.cookie_jar
-
end
-
end
-
# Deprecate: Copied verbatim from Rails source, remove once we move to Rails 4 only.
-
2
require 'thread_safe'
-
2
require 'openssl'
-
2
require 'securerandom'
-
-
2
module Devise
-
2
class TokenGenerator
-
2
def initialize(key_generator, digest="SHA256")
-
2
@key_generator = key_generator
-
2
@digest = digest
-
end
-
-
2
def digest(klass, column, value)
-
value.present? && OpenSSL::HMAC.hexdigest(@digest, key_for(column), value.to_s)
-
end
-
-
2
def generate(klass, column)
-
key = key_for(column)
-
-
loop do
-
raw = Devise.friendly_token
-
enc = OpenSSL::HMAC.hexdigest(@digest, key, raw)
-
break [raw, enc] unless klass.to_adapter.find_first({ column => enc })
-
end
-
end
-
-
2
private
-
-
2
def key_for(column)
-
@key_generator.generate_key("Devise #{column}")
-
end
-
end
-
-
# KeyGenerator is a simple wrapper around OpenSSL's implementation of PBKDF2
-
# It can be used to derive a number of keys for various purposes from a given secret.
-
# This lets Rails applications have a single secure secret, but avoid reusing that
-
# key in multiple incompatible contexts.
-
2
class KeyGenerator
-
2
def initialize(secret, options = {})
-
2
@secret = secret
-
# The default iterations are higher than required for our key derivation uses
-
# on the off chance someone uses this for password storage
-
2
@iterations = options[:iterations] || 2**16
-
end
-
-
# Returns a derived key suitable for use. The default key_size is chosen
-
# to be compatible with the default settings of ActiveSupport::MessageVerifier.
-
# i.e. OpenSSL::Digest::SHA1#block_length
-
2
def generate_key(salt, key_size=64)
-
OpenSSL::PKCS5.pbkdf2_hmac_sha1(@secret, salt, @iterations, key_size)
-
end
-
end
-
-
# CachingKeyGenerator is a wrapper around KeyGenerator which allows users to avoid
-
# re-executing the key generation process when it's called using the same salt and
-
# key_size
-
2
class CachingKeyGenerator
-
2
def initialize(key_generator)
-
2
@key_generator = key_generator
-
2
@cache_keys = ThreadSafe::Cache.new
-
end
-
-
# Returns a derived key suitable for use. The default key_size is chosen
-
# to be compatible with the default settings of ActiveSupport::MessageVerifier.
-
# i.e. OpenSSL::Digest::SHA1#block_length
-
2
def generate_key(salt, key_size=64)
-
@cache_keys["#{salt}#{key_size}"] ||= @key_generator.generate_key(salt, key_size)
-
end
-
end
-
end
-
##
-
## $Release: 2.7.0 $
-
## copyright(c) 2006-2011 kuwata-lab.com all rights reserved.
-
##
-
-
##
-
## an implementation of eRuby
-
##
-
## ex.
-
## input = <<'END'
-
## <ul>
-
## <% for item in @list %>
-
## <li><%= item %>
-
## <%== item %></li>
-
## <% end %>
-
## </ul>
-
## END
-
## list = ['<aaa>', 'b&b', '"ccc"']
-
## eruby = Erubis::Eruby.new(input)
-
## puts "--- code ---"
-
## puts eruby.src
-
## puts "--- result ---"
-
## context = Erubis::Context.new() # or new(:list=>list)
-
## context[:list] = list
-
## puts eruby.evaluate(context)
-
##
-
## result:
-
## --- source ---
-
## _buf = ''; _buf << '<ul>
-
## '; for item in @list
-
## _buf << ' <li>'; _buf << ( item ).to_s; _buf << '
-
## '; _buf << ' '; _buf << Erubis::XmlHelper.escape_xml( item ); _buf << '</li>
-
## '; end
-
## _buf << '</ul>
-
## ';
-
## _buf.to_s
-
## --- result ---
-
## <ul>
-
## <li><aaa>
-
## <aaa></li>
-
## <li>b&b
-
## b&b</li>
-
## <li>"ccc"
-
## "ccc"</li>
-
## </ul>
-
##
-
-
-
2
module Erubis
-
2
VERSION = ('$Release: 2.7.0 $' =~ /([.\d]+)/) && $1
-
end
-
-
2
require 'erubis/engine'
-
#require 'erubis/generator'
-
#require 'erubis/converter'
-
#require 'erubis/evaluator'
-
#require 'erubis/error'
-
#require 'erubis/context'
-
#requier 'erubis/util'
-
2
require 'erubis/helper'
-
2
require 'erubis/enhancer'
-
#require 'erubis/tiny'
-
2
require 'erubis/engine/eruby'
-
#require 'erubis/engine/enhanced' # enhanced eruby engines
-
#require 'erubis/engine/optimized' # generates optimized ruby code
-
#require 'erubis/engine/ephp'
-
#require 'erubis/engine/ec'
-
#require 'erubis/engine/ejava'
-
#require 'erubis/engine/escheme'
-
#require 'erubis/engine/eperl'
-
#require 'erubis/engine/ejavascript'
-
-
2
require 'erubis/local-setting'
-
##
-
## $Release: 2.7.0 $
-
## copyright(c) 2006-2011 kuwata-lab.com all rights reserved.
-
##
-
-
-
2
module Erubis
-
-
-
##
-
## context object for Engine#evaluate
-
##
-
## ex.
-
## template = <<'END'
-
## Hello <%= @user %>!
-
## <% for item in @list %>
-
## - <%= item %>
-
## <% end %>
-
## END
-
##
-
## context = Erubis::Context.new(:user=>'World', :list=>['a','b','c'])
-
## # or
-
## # context = Erubis::Context.new
-
## # context[:user] = 'World'
-
## # context[:list] = ['a', 'b', 'c']
-
##
-
## eruby = Erubis::Eruby.new(template)
-
## print eruby.evaluate(context)
-
##
-
2
class Context
-
2
include Enumerable
-
-
2
def initialize(hash=nil)
-
hash.each do |name, value|
-
self[name] = value
-
end if hash
-
end
-
-
2
def [](key)
-
return instance_variable_get("@#{key}")
-
end
-
-
2
def []=(key, value)
-
return instance_variable_set("@#{key}", value)
-
end
-
-
2
def keys
-
return instance_variables.collect { |name| name[1..-1] }
-
end
-
-
2
def each
-
instance_variables.each do |name|
-
key = name[1..-1]
-
value = instance_variable_get(name)
-
yield(key, value)
-
end
-
end
-
-
2
def to_hash
-
hash = {}
-
self.keys.each { |key| hash[key] = self[key] }
-
return hash
-
end
-
-
2
def update(context_or_hash)
-
arg = context_or_hash
-
if arg.is_a?(Hash)
-
arg.each do |key, val|
-
self[key] = val
-
end
-
else
-
arg.instance_variables.each do |varname|
-
key = varname[1..-1]
-
val = arg.instance_variable_get(varname)
-
self[key] = val
-
end
-
end
-
end
-
-
end
-
-
-
end
-
##
-
## $Release: 2.7.0 $
-
## copyright(c) 2006-2011 kuwata-lab.com all rights reserved.
-
##
-
-
2
require 'erubis/util'
-
-
2
module Erubis
-
-
-
##
-
## convert
-
##
-
2
module Converter
-
-
2
attr_accessor :preamble, :postamble, :escape
-
-
2
def self.supported_properties # :nodoc:
-
return [
-
[:preamble, nil, "preamble (no preamble when false)"],
-
[:postamble, nil, "postamble (no postamble when false)"],
-
[:escape, nil, "escape expression or not in default"],
-
]
-
end
-
-
2
def init_converter(properties={})
-
6
@preamble = properties[:preamble]
-
6
@postamble = properties[:postamble]
-
6
@escape = properties[:escape]
-
end
-
-
## convert input string into target language
-
2
def convert(input)
-
6
codebuf = "" # or []
-
6
@preamble.nil? ? add_preamble(codebuf) : (@preamble && (codebuf << @preamble))
-
6
convert_input(codebuf, input)
-
6
@postamble.nil? ? add_postamble(codebuf) : (@postamble && (codebuf << @postamble))
-
6
@_proc = nil # clear cached proc object
-
6
return codebuf # or codebuf.join()
-
end
-
-
2
protected
-
-
##
-
## detect spaces at beginning of line
-
##
-
2
def detect_spaces_at_bol(text, is_bol)
-
5
lspace = nil
-
5
if text.empty?
-
lspace = "" if is_bol
-
elsif text[-1] == ?\n
-
lspace = ""
-
else
-
5
rindex = text.rindex(?\n)
-
5
if rindex
-
5
s = text[rindex+1..-1]
-
5
if s =~ /\A[ \t]*\z/
-
5
lspace = s
-
#text = text[0..rindex]
-
5
text[rindex+1..-1] = ''
-
end
-
else
-
if is_bol && text =~ /\A[ \t]*\z/
-
#lspace = text
-
#text = nil
-
lspace = text.dup
-
text[0..-1] = ''
-
end
-
end
-
end
-
5
return lspace
-
end
-
-
##
-
## (abstract) convert input to code
-
##
-
2
def convert_input(codebuf, input)
-
not_implemented
-
end
-
-
end
-
-
-
2
module Basic
-
end
-
-
-
##
-
## basic converter which supports '<% ... %>' notation.
-
##
-
2
module Basic::Converter
-
2
include Erubis::Converter
-
-
2
def self.supported_properties # :nodoc:
-
return [
-
[:pattern, '<% %>', "embed pattern"],
-
[:trim, true, "trim spaces around <% ... %>"],
-
]
-
end
-
-
2
attr_accessor :pattern, :trim
-
-
2
def init_converter(properties={})
-
6
super(properties)
-
6
@pattern = properties[:pattern]
-
6
@trim = properties[:trim] != false
-
end
-
-
2
protected
-
-
## return regexp of pattern to parse eRuby script
-
2
def pattern_regexp(pattern)
-
2
@prefix, @postfix = pattern.split() # '<% %>' => '<%', '%>'
-
#return /(.*?)(^[ \t]*)?#{@prefix}(=+|\#)?(.*?)-?#{@postfix}([ \t]*\r?\n)?/m
-
#return /(^[ \t]*)?#{@prefix}(=+|\#)?(.*?)-?#{@postfix}([ \t]*\r?\n)?/m
-
2
return /#{@prefix}(=+|-|\#|%)?(.*?)([-=])?#{@postfix}([ \t]*\r?\n)?/m
-
end
-
2
module_function :pattern_regexp
-
-
#DEFAULT_REGEXP = /(.*?)(^[ \t]*)?<%(=+|\#)?(.*?)-?%>([ \t]*\r?\n)?/m
-
#DEFAULT_REGEXP = /(^[ \t]*)?<%(=+|\#)?(.*?)-?%>([ \t]*\r?\n)?/m
-
#DEFAULT_REGEXP = /<%(=+|\#)?(.*?)-?%>([ \t]*\r?\n)?/m
-
2
DEFAULT_REGEXP = pattern_regexp('<% %>')
-
-
2
public
-
-
2
def convert_input(src, input)
-
6
pat = @pattern
-
6
regexp = pat.nil? || pat == '<% %>' ? DEFAULT_REGEXP : pattern_regexp(pat)
-
6
pos = 0
-
6
is_bol = true # is beginning of line
-
6
input.scan(regexp) do |indicator, code, tailch, rspace|
-
42
match = Regexp.last_match()
-
42
len = match.begin(0) - pos
-
42
text = input[pos, len]
-
42
pos = match.end(0)
-
42
ch = indicator ? indicator[0] : nil
-
42
lspace = ch == ?= ? nil : detect_spaces_at_bol(text, is_bol)
-
42
is_bol = rspace ? true : false
-
42
add_text(src, text) if text && !text.empty?
-
## * when '<%= %>', do nothing
-
## * when '<% %>' or '<%# %>', delete spaces iff only spaces are around '<% %>'
-
42
if ch == ?= # <%= %>
-
37
rspace = nil if tailch && !tailch.empty?
-
37
add_text(src, lspace) if lspace
-
37
add_expr(src, code, indicator)
-
37
add_text(src, rspace) if rspace
-
elsif ch == ?\# # <%# %>
-
n = code.count("\n") + (rspace ? 1 : 0)
-
if @trim && lspace && rspace
-
add_stmt(src, "\n" * n)
-
else
-
add_text(src, lspace) if lspace
-
add_stmt(src, "\n" * n)
-
add_text(src, rspace) if rspace
-
end
-
elsif ch == ?% # <%% %>
-
s = "#{lspace}#{@prefix||='<%'}#{code}#{tailch}#{@postfix||='%>'}#{rspace}"
-
add_text(src, s)
-
else # <% %>
-
5
if @trim && lspace && rspace
-
5
add_stmt(src, "#{lspace}#{code}#{rspace}")
-
else
-
add_text(src, lspace) if lspace
-
add_stmt(src, code)
-
add_text(src, rspace) if rspace
-
end
-
end
-
end
-
#rest = $' || input # ruby1.8
-
6
rest = pos == 0 ? input : input[pos..-1] # ruby1.9
-
6
add_text(src, rest)
-
end
-
-
## add expression code to src
-
2
def add_expr(src, code, indicator)
-
37
case indicator
-
when '='
-
37
@escape ? add_expr_escaped(src, code) : add_expr_literal(src, code)
-
when '=='
-
@escape ? add_expr_literal(src, code) : add_expr_escaped(src, code)
-
when '==='
-
add_expr_debug(src, code)
-
end
-
end
-
-
end
-
-
-
2
module PI
-
end
-
-
##
-
## Processing Instructions (PI) converter for XML.
-
## this class converts '<?rb ... ?>' and '${...}' notation.
-
##
-
2
module PI::Converter
-
2
include Erubis::Converter
-
-
2
def self.desc # :nodoc:
-
"use processing instructions (PI) instead of '<% %>'"
-
end
-
-
2
def self.supported_properties # :nodoc:
-
return [
-
[:trim, true, "trim spaces around <% ... %>"],
-
[:pi, 'rb', "PI (Processing Instrunctions) name"],
-
[:embchar, '@', "char for embedded expression pattern('@{...}@')"],
-
[:pattern, '<% %>', "embed pattern"],
-
]
-
end
-
-
2
attr_accessor :pi, :prefix
-
-
2
def init_converter(properties={})
-
super(properties)
-
@trim = properties.fetch(:trim, true)
-
@pi = properties[:pi] if properties[:pi]
-
@embchar = properties[:embchar] || '@'
-
@pattern = properties[:pattern]
-
@pattern = '<% %>' if @pattern.nil? #|| @pattern == true
-
end
-
-
2
def convert(input)
-
code = super(input)
-
return @header || @footer ? "#{@header}#{code}#{@footer}" : code
-
end
-
-
2
protected
-
-
2
def convert_input(codebuf, input)
-
unless @regexp
-
@pi ||= 'e'
-
ch = Regexp.escape(@embchar)
-
if @pattern
-
left, right = @pattern.split(' ')
-
@regexp = /<\?#{@pi}(?:-(\w+))?(\s.*?)\?>([ \t]*\r?\n)?|#{ch}(!*)?\{(.*?)\}#{ch}|#{left}(=+)(.*?)#{right}/m
-
else
-
@regexp = /<\?#{@pi}(?:-(\w+))?(\s.*?)\?>([ \t]*\r?\n)?|#{ch}(!*)?\{(.*?)\}#{ch}/m
-
end
-
end
-
#
-
is_bol = true
-
pos = 0
-
input.scan(@regexp) do |pi_arg, stmt, rspace,
-
indicator1, expr1, indicator2, expr2|
-
match = Regexp.last_match
-
len = match.begin(0) - pos
-
text = input[pos, len]
-
pos = match.end(0)
-
lspace = stmt ? detect_spaces_at_bol(text, is_bol) : nil
-
is_bol = stmt && rspace ? true : false
-
add_text(codebuf, text) # unless text.empty?
-
#
-
if stmt
-
if @trim && lspace && rspace
-
add_pi_stmt(codebuf, "#{lspace}#{stmt}#{rspace}", pi_arg)
-
else
-
add_text(codebuf, lspace) if lspace
-
add_pi_stmt(codebuf, stmt, pi_arg)
-
add_text(codebuf, rspace) if rspace
-
end
-
else
-
add_pi_expr(codebuf, expr1 || expr2, indicator1 || indicator2)
-
end
-
end
-
#rest = $' || input # ruby1.8
-
rest = pos == 0 ? input : input[pos..-1] # ruby1.9
-
add_text(codebuf, rest)
-
end
-
-
#--
-
#def convert_input(codebuf, input)
-
# parse_stmts(codebuf, input)
-
# #parse_stmts2(codebuf, input)
-
#end
-
#
-
#def parse_stmts(codebuf, input)
-
# #regexp = pattern_regexp(@pattern)
-
# @pi ||= 'e'
-
# @stmt_pattern ||= /<\?#{@pi}(?:-(\w+))?(\s.*?)\?>([ \t]*\r?\n)?/m
-
# is_bol = true
-
# pos = 0
-
# input.scan(@stmt_pattern) do |pi_arg, code, rspace|
-
# match = Regexp.last_match
-
# len = match.begin(0) - pos
-
# text = input[pos, len]
-
# pos = match.end(0)
-
# lspace = detect_spaces_at_bol(text, is_bol)
-
# is_bol = rspace ? true : false
-
# parse_exprs(codebuf, text) # unless text.empty?
-
# if @trim && lspace && rspace
-
# add_pi_stmt(codebuf, "#{lspace}#{code}#{rspace}", pi_arg)
-
# else
-
# add_text(codebuf, lspace)
-
# add_pi_stmt(codebuf, code, pi_arg)
-
# add_text(codebuf, rspace)
-
# end
-
# end
-
# rest = $' || input
-
# parse_exprs(codebuf, rest)
-
#end
-
#
-
#def parse_exprs(codebuf, input)
-
# unless @expr_pattern
-
# ch = Regexp.escape(@embchar)
-
# if @pattern
-
# left, right = @pattern.split(' ')
-
# @expr_pattern = /#{ch}(!*)?\{(.*?)\}#{ch}|#{left}(=+)(.*?)#{right}/
-
# else
-
# @expr_pattern = /#{ch}(!*)?\{(.*?)\}#{ch}/
-
# end
-
# end
-
# pos = 0
-
# input.scan(@expr_pattern) do |indicator1, code1, indicator2, code2|
-
# indicator = indicator1 || indicator2
-
# code = code1 || code2
-
# match = Regexp.last_match
-
# len = match.begin(0) - pos
-
# text = input[pos, len]
-
# pos = match.end(0)
-
# add_text(codebuf, text) # unless text.empty?
-
# add_pi_expr(codebuf, code, indicator)
-
# end
-
# rest = $' || input
-
# add_text(codebuf, rest)
-
#end
-
#++
-
-
2
def add_pi_stmt(codebuf, code, pi_arg) # :nodoc:
-
case pi_arg
-
when nil ; add_stmt(codebuf, code)
-
when 'header' ; @header = code
-
when 'footer' ; @footer = code
-
when 'comment'; add_stmt(codebuf, "\n" * code.count("\n"))
-
when 'value' ; add_expr_literal(codebuf, code)
-
else ; add_stmt(codebuf, code)
-
end
-
end
-
-
2
def add_pi_expr(codebuf, code, indicator) # :nodoc:
-
case indicator
-
when nil, '', '==' # @{...}@ or <%== ... %>
-
@escape == false ? add_expr_literal(codebuf, code) : add_expr_escaped(codebuf, code)
-
when '!', '=' # @!{...}@ or <%= ... %>
-
@escape == false ? add_expr_escaped(codebuf, code) : add_expr_literal(codebuf, code)
-
when '!!', '===' # @!!{...}@ or <%=== ... %>
-
add_expr_debug(codebuf, code)
-
else
-
# ignore
-
end
-
end
-
-
end
-
-
-
end
-
##
-
## $Release: 2.7.0 $
-
## copyright(c) 2006-2011 kuwata-lab.com all rights reserved.
-
##
-
-
-
2
require 'erubis/generator'
-
2
require 'erubis/converter'
-
2
require 'erubis/evaluator'
-
2
require 'erubis/context'
-
-
-
2
module Erubis
-
-
-
##
-
## (abstract) abstract engine class.
-
## subclass must include evaluator and converter module.
-
##
-
2
class Engine
-
#include Evaluator
-
#include Converter
-
#include Generator
-
-
2
def initialize(input=nil, properties={})
-
#@input = input
-
6
init_generator(properties)
-
6
init_converter(properties)
-
6
init_evaluator(properties)
-
6
@src = convert(input) if input
-
end
-
-
-
##
-
## convert input string and set it to @src
-
##
-
2
def convert!(input)
-
@src = convert(input)
-
end
-
-
-
##
-
## load file, write cache file, and return engine object.
-
## this method create code cache file automatically.
-
## cachefile name can be specified with properties[:cachename],
-
## or filname + 'cache' is used as default.
-
##
-
2
def self.load_file(filename, properties={})
-
cachename = properties[:cachename] || (filename + '.cache')
-
properties[:filename] = filename
-
timestamp = File.mtime(filename)
-
if test(?f, cachename) && timestamp == File.mtime(cachename)
-
engine = self.new(nil, properties)
-
engine.src = File.read(cachename)
-
else
-
input = File.open(filename, 'rb') {|f| f.read }
-
engine = self.new(input, properties)
-
tmpname = cachename + rand().to_s[1,8]
-
File.open(tmpname, 'wb') {|f| f.write(engine.src) }
-
File.rename(tmpname, cachename)
-
File.utime(timestamp, timestamp, cachename)
-
end
-
engine.src.untaint # ok?
-
return engine
-
end
-
-
-
##
-
## helper method to convert and evaluate input text with context object.
-
## context may be Binding, Hash, or Object.
-
##
-
2
def process(input, context=nil, filename=nil)
-
code = convert(input)
-
filename ||= '(erubis)'
-
if context.is_a?(Binding)
-
return eval(code, context, filename)
-
else
-
context = Context.new(context) if context.is_a?(Hash)
-
return context.instance_eval(code, filename)
-
end
-
end
-
-
-
##
-
## helper method evaluate Proc object with contect object.
-
## context may be Binding, Hash, or Object.
-
##
-
2
def process_proc(proc_obj, context=nil, filename=nil)
-
if context.is_a?(Binding)
-
filename ||= '(erubis)'
-
return eval(proc_obj, context, filename)
-
else
-
context = Context.new(context) if context.is_a?(Hash)
-
return context.instance_eval(&proc_obj)
-
end
-
end
-
-
-
end # end of class Engine
-
-
-
##
-
## (abstract) base engine class for Eruby, Eperl, Ejava, and so on.
-
## subclass must include generator.
-
##
-
2
class Basic::Engine < Engine
-
2
include Evaluator
-
2
include Basic::Converter
-
2
include Generator
-
end
-
-
-
2
class PI::Engine < Engine
-
2
include Evaluator
-
2
include PI::Converter
-
2
include Generator
-
end
-
-
-
end
-
##
-
## $Release: 2.7.0 $
-
## copyright(c) 2006-2011 kuwata-lab.com all rights reserved.
-
##
-
-
-
2
module Erubis
-
-
-
##
-
## switch '<%= ... %>' to escaped and '<%== ... %>' to unescaped
-
##
-
## ex.
-
## class XmlEruby < Eruby
-
## include EscapeEnhancer
-
## end
-
##
-
## this is language-indenedent.
-
##
-
2
module EscapeEnhancer
-
-
2
def self.desc # :nodoc:
-
"switch '<%= %>' to escaped and '<%== %>' to unescaped"
-
end
-
-
#--
-
#def self.included(klass)
-
# klass.class_eval <<-END
-
# alias _add_expr_literal add_expr_literal
-
# alias _add_expr_escaped add_expr_escaped
-
# alias add_expr_literal _add_expr_escaped
-
# alias add_expr_escaped _add_expr_literal
-
# END
-
#end
-
#++
-
-
2
def add_expr(src, code, indicator)
-
case indicator
-
when '='
-
@escape ? add_expr_literal(src, code) : add_expr_escaped(src, code)
-
when '=='
-
@escape ? add_expr_escaped(src, code) : add_expr_literal(src, code)
-
when '==='
-
add_expr_debug(src, code)
-
end
-
end
-
-
end
-
-
-
#--
-
## (obsolete)
-
#module FastEnhancer
-
#end
-
#++
-
-
-
##
-
## use $stdout instead of string
-
##
-
## this is only for Eruby.
-
##
-
2
module StdoutEnhancer
-
-
2
def self.desc # :nodoc:
-
"use $stdout instead of array buffer or string buffer"
-
end
-
-
2
def add_preamble(src)
-
src << "#{@bufvar} = $stdout;"
-
end
-
-
2
def add_postamble(src)
-
src << "\n''\n"
-
end
-
-
end
-
-
-
##
-
## use print statement instead of '_buf << ...'
-
##
-
## this is only for Eruby.
-
##
-
2
module PrintOutEnhancer
-
-
2
def self.desc # :nodoc:
-
"use print statement instead of '_buf << ...'"
-
end
-
-
2
def add_preamble(src)
-
end
-
-
2
def add_text(src, text)
-
src << " print '#{escape_text(text)}';" unless text.empty?
-
end
-
-
2
def add_expr_literal(src, code)
-
src << " print((#{code}).to_s);"
-
end
-
-
2
def add_expr_escaped(src, code)
-
src << " print #{escaped_expr(code)};"
-
end
-
-
2
def add_postamble(src)
-
src << "\n" unless src[-1] == ?\n
-
end
-
-
end
-
-
-
##
-
## enable print function
-
##
-
## Notice: use Eruby#evaluate() and don't use Eruby#result()
-
## to be enable print function.
-
##
-
## this is only for Eruby.
-
##
-
2
module PrintEnabledEnhancer
-
-
2
def self.desc # :nodoc:
-
"enable to use print function in '<% %>'"
-
end
-
-
2
def add_preamble(src)
-
src << "@_buf = "
-
super
-
end
-
-
2
def print(*args)
-
args.each do |arg|
-
@_buf << arg.to_s
-
end
-
end
-
-
2
def evaluate(context=nil)
-
_src = @src
-
if context.is_a?(Hash)
-
context.each do |key, val| instance_variable_set("@#{key}", val) end
-
elsif context
-
context.instance_variables.each do |name|
-
instance_variable_set(name, context.instance_variable_get(name))
-
end
-
end
-
return instance_eval(_src, (@filename || '(erubis)'))
-
end
-
-
end
-
-
-
##
-
## return array instead of string
-
##
-
## this is only for Eruby.
-
##
-
2
module ArrayEnhancer
-
-
2
def self.desc # :nodoc:
-
"return array instead of string"
-
end
-
-
2
def add_preamble(src)
-
src << "#{@bufvar} = [];"
-
end
-
-
2
def add_postamble(src)
-
src << "\n" unless src[-1] == ?\n
-
src << "#{@bufvar}\n"
-
end
-
-
end
-
-
-
##
-
## use an Array object as buffer (included in Eruby by default)
-
##
-
## this is only for Eruby.
-
##
-
2
module ArrayBufferEnhancer
-
-
2
def self.desc # :nodoc:
-
"use an Array object for buffering (included in Eruby class)"
-
end
-
-
2
def add_preamble(src)
-
src << "_buf = [];"
-
end
-
-
2
def add_postamble(src)
-
src << "\n" unless src[-1] == ?\n
-
src << "_buf.join\n"
-
end
-
-
end
-
-
-
##
-
## use String class for buffering
-
##
-
## this is only for Eruby.
-
##
-
2
module StringBufferEnhancer
-
-
2
def self.desc # :nodoc:
-
"use a String object for buffering"
-
end
-
-
2
def add_preamble(src)
-
src << "#{@bufvar} = '';"
-
end
-
-
2
def add_postamble(src)
-
src << "\n" unless src[-1] == ?\n
-
src << "#{@bufvar}.to_s\n"
-
end
-
-
end
-
-
-
##
-
## use StringIO class for buffering
-
##
-
## this is only for Eruby.
-
##
-
2
module StringIOEnhancer # :nodoc:
-
-
2
def self.desc # :nodoc:
-
"use a StringIO object for buffering"
-
end
-
-
2
def add_preamble(src)
-
src << "#{@bufvar} = StringIO.new;"
-
end
-
-
2
def add_postamble(src)
-
src << "\n" unless src[-1] == ?\n
-
src << "#{@bufvar}.string\n"
-
end
-
-
end
-
-
-
##
-
## set buffer variable name to '_erbout' as well as '_buf'
-
##
-
## this is only for Eruby.
-
##
-
2
module ErboutEnhancer
-
-
2
def self.desc # :nodoc:
-
"set '_erbout = _buf = \"\";' to be compatible with ERB."
-
end
-
-
2
def add_preamble(src)
-
src << "_erbout = #{@bufvar} = '';"
-
end
-
-
2
def add_postamble(src)
-
src << "\n" unless src[-1] == ?\n
-
src << "#{@bufvar}.to_s\n"
-
end
-
-
end
-
-
-
##
-
## remove text and leave code, especially useful when debugging.
-
##
-
## ex.
-
## $ erubis -s -E NoText file.eruby | more
-
##
-
## this is language independent.
-
##
-
2
module NoTextEnhancer
-
-
2
def self.desc # :nodoc:
-
"remove text and leave code (useful when debugging)"
-
end
-
-
2
def add_text(src, text)
-
src << ("\n" * text.count("\n"))
-
if text[-1] != ?\n
-
text =~ /^(.*?)\z/
-
src << (' ' * $1.length)
-
end
-
end
-
-
end
-
-
-
##
-
## remove code and leave text, especially useful when validating HTML tags.
-
##
-
## ex.
-
## $ erubis -s -E NoCode file.eruby | tidy -errors
-
##
-
## this is language independent.
-
##
-
2
module NoCodeEnhancer
-
-
2
def self.desc # :nodoc:
-
"remove code and leave text (useful when validating HTML)"
-
end
-
-
2
def add_preamble(src)
-
end
-
-
2
def add_postamble(src)
-
end
-
-
2
def add_text(src, text)
-
src << text
-
end
-
-
2
def add_expr(src, code, indicator)
-
src << "\n" * code.count("\n")
-
end
-
-
2
def add_stmt(src, code)
-
src << "\n" * code.count("\n")
-
end
-
-
end
-
-
-
##
-
## get convert faster, but spaces around '<%...%>' are not trimmed.
-
##
-
## this is language-independent.
-
##
-
2
module SimplifyEnhancer
-
-
2
def self.desc # :nodoc:
-
"get convert faster but leave spaces around '<% %>'"
-
end
-
-
#DEFAULT_REGEXP = /(^[ \t]*)?<%(=+|\#)?(.*?)-?%>([ \t]*\r?\n)?/m
-
2
SIMPLE_REGEXP = /<%(=+|\#)?(.*?)-?%>/m
-
-
2
def convert(input)
-
src = ""
-
add_preamble(src)
-
#regexp = pattern_regexp(@pattern)
-
pos = 0
-
input.scan(SIMPLE_REGEXP) do |indicator, code|
-
match = Regexp.last_match
-
index = match.begin(0)
-
text = input[pos, index - pos]
-
pos = match.end(0)
-
add_text(src, text)
-
if !indicator # <% %>
-
add_stmt(src, code)
-
elsif indicator[0] == ?\# # <%# %>
-
n = code.count("\n")
-
add_stmt(src, "\n" * n)
-
else # <%= %>
-
add_expr(src, code, indicator)
-
end
-
end
-
#rest = $' || input # ruby1.8
-
rest = pos == 0 ? input : input[pos..-1] # ruby1.9
-
add_text(src, rest)
-
add_postamble(src)
-
return src
-
end
-
-
end
-
-
-
##
-
## enable to use other embedded expression pattern (default is '\[= =\]').
-
##
-
## notice! this is an experimental. spec may change in the future.
-
##
-
## ex.
-
## input = <<END
-
## <% for item in list %>
-
## <%= item %> : <%== item %>
-
## [= item =] : [== item =]
-
## <% end %>
-
## END
-
##
-
## class BiPatternEruby
-
## include BiPatternEnhancer
-
## end
-
## eruby = BiPatternEruby.new(input, :bipattern=>'\[= =\]')
-
## list = ['<a>', 'b&b', '"c"']
-
## print eruby.result(binding())
-
##
-
## ## output
-
## <a> : <a>
-
## <a> : <a>
-
## b&b : b&b
-
## b&b : b&b
-
## "c" : "c"
-
## "c" : "c"
-
##
-
## this is language independent.
-
##
-
2
module BiPatternEnhancer
-
-
2
def self.desc # :nodoc:
-
"another embedded expression pattern (default '\[= =\]')."
-
end
-
-
2
def initialize(input, properties={})
-
self.bipattern = properties[:bipattern] # or '\$\{ \}'
-
super
-
end
-
-
## when pat is nil then '\[= =\]' is used
-
2
def bipattern=(pat) # :nodoc:
-
@bipattern = pat || '\[= =\]'
-
pre, post = @bipattern.split()
-
@bipattern_regexp = /(.*?)#{pre}(=*)(.*?)#{post}/m
-
end
-
-
2
def add_text(src, text)
-
return unless text
-
m = nil
-
text.scan(@bipattern_regexp) do |txt, indicator, code|
-
m = Regexp.last_match
-
super(src, txt)
-
add_expr(src, code, '=' + indicator)
-
end
-
#rest = $' || text # ruby1.8
-
rest = m ? text[m.end(0)..-1] : text # ruby1.9
-
super(src, rest)
-
end
-
-
end
-
-
-
##
-
## regards lines starting with '^[ \t]*%' as program code
-
##
-
## in addition you can specify prefix character (default '%')
-
##
-
## this is language-independent.
-
##
-
2
module PrefixedLineEnhancer
-
-
2
def self.desc # :nodoc:
-
"regard lines matched to '^[ \t]*%' as program code"
-
end
-
-
2
def init_generator(properties={})
-
super
-
@prefixchar = properties[:prefixchar]
-
end
-
-
2
def add_text(src, text)
-
unless @prefixrexp
-
@prefixchar ||= '%'
-
@prefixrexp = Regexp.compile("^([ \\t]*)\\#{@prefixchar}(.*?\\r?\\n)")
-
end
-
pos = 0
-
text2 = ''
-
text.scan(@prefixrexp) do
-
space = $1
-
line = $2
-
space, line = '', $1 unless $2
-
match = Regexp.last_match
-
len = match.begin(0) - pos
-
str = text[pos, len]
-
pos = match.end(0)
-
if text2.empty?
-
text2 = str
-
else
-
text2 << str
-
end
-
if line[0, 1] == @prefixchar
-
text2 << space << line
-
else
-
super(src, text2)
-
text2 = ''
-
add_stmt(src, space + line)
-
end
-
end
-
#rest = pos == 0 ? text : $' # ruby1.8
-
rest = pos == 0 ? text : text[pos..-1] # ruby1.9
-
unless text2.empty?
-
text2 << rest if rest
-
rest = text2
-
end
-
super(src, rest)
-
end
-
-
end
-
-
-
##
-
## regards lines starting with '%' as program code
-
##
-
## this is for compatibility to eruby and ERB.
-
##
-
## this is language-independent.
-
##
-
2
module PercentLineEnhancer
-
2
include PrefixedLineEnhancer
-
-
2
def self.desc # :nodoc:
-
"regard lines starting with '%' as program code"
-
end
-
-
#--
-
#def init_generator(properties={})
-
# super
-
# @prefixchar = '%'
-
# @prefixrexp = /^\%(.*?\r?\n)/
-
#end
-
#++
-
-
2
def add_text(src, text)
-
unless @prefixrexp
-
@prefixchar = '%'
-
@prefixrexp = /^\%(.*?\r?\n)/
-
end
-
super(src, text)
-
end
-
-
end
-
-
-
##
-
## [experimental] allow header and footer in eRuby script
-
##
-
## ex.
-
## ====================
-
## ## without header and footer
-
## $ cat ex1.eruby
-
## <% def list_items(list) %>
-
## <% for item in list %>
-
## <li><%= item %></li>
-
## <% end %>
-
## <% end %>
-
##
-
## $ erubis -s ex1.eruby
-
## _buf = []; def list_items(list)
-
## ; for item in list
-
## ; _buf << '<li>'; _buf << ( item ).to_s; _buf << '</li>
-
## '; end
-
## ; end
-
## ;
-
## _buf.join
-
##
-
## ## with header and footer
-
## $ cat ex2.eruby
-
## <!--#header:
-
## def list_items(list)
-
## #-->
-
## <% for item in list %>
-
## <li><%= item %></li>
-
## <% end %>
-
## <!--#footer:
-
## end
-
## #-->
-
##
-
## $ erubis -s -c HeaderFooterEruby ex4.eruby
-
##
-
## def list_items(list)
-
## _buf = []; _buf << '
-
## '; for item in list
-
## ; _buf << '<li>'; _buf << ( item ).to_s; _buf << '</li>
-
## '; end
-
## ; _buf << '
-
## ';
-
## _buf.join
-
## end
-
##
-
## ====================
-
##
-
## this is language-independent.
-
##
-
2
module HeaderFooterEnhancer
-
-
2
def self.desc # :nodoc:
-
"allow header/footer in document (ex. '<!--#header: #-->')"
-
end
-
-
2
HEADER_FOOTER_PATTERN = /(.*?)(^[ \t]*)?<!--\#(\w+):(.*?)\#-->([ \t]*\r?\n)?/m
-
-
2
def add_text(src, text)
-
m = nil
-
text.scan(HEADER_FOOTER_PATTERN) do |txt, lspace, word, content, rspace|
-
m = Regexp.last_match
-
flag_trim = @trim && lspace && rspace
-
super(src, txt)
-
content = "#{lspace}#{content}#{rspace}" if flag_trim
-
super(src, lspace) if !flag_trim && lspace
-
instance_variable_set("@#{word}", content)
-
super(src, rspace) if !flag_trim && rspace
-
end
-
#rest = $' || text # ruby1.8
-
rest = m ? text[m.end(0)..-1] : text # ruby1.9
-
super(src, rest)
-
end
-
-
2
attr_accessor :header, :footer
-
-
2
def convert(input)
-
source = super
-
return @src = "#{@header}#{source}#{@footer}"
-
end
-
-
end
-
-
-
##
-
## delete indentation of HTML.
-
##
-
## this is language-independent.
-
##
-
2
module DeleteIndentEnhancer
-
-
2
def self.desc # :nodoc:
-
"delete indentation of HTML."
-
end
-
-
2
def convert_input(src, input)
-
input = input.gsub(/^[ \t]+</, '<')
-
super(src, input)
-
end
-
-
end
-
-
-
##
-
## convert "<h1><%=title%></h1>" into "_buf << %Q`<h1>#{title}</h1>`"
-
##
-
## this is only for Eruby.
-
##
-
2
module InterpolationEnhancer
-
-
2
def self.desc # :nodoc:
-
"convert '<p><%=text%></p>' into '_buf << %Q`<p>\#{text}</p>`'"
-
end
-
-
2
def convert_input(src, input)
-
pat = @pattern
-
regexp = pat.nil? || pat == '<% %>' ? Basic::Converter::DEFAULT_REGEXP : pattern_regexp(pat)
-
pos = 0
-
is_bol = true # is beginning of line
-
str = ''
-
input.scan(regexp) do |indicator, code, tailch, rspace|
-
match = Regexp.last_match()
-
len = match.begin(0) - pos
-
text = input[pos, len]
-
pos = match.end(0)
-
ch = indicator ? indicator[0] : nil
-
lspace = ch == ?= ? nil : detect_spaces_at_bol(text, is_bol)
-
is_bol = rspace ? true : false
-
_add_text_to_str(str, text)
-
## * when '<%= %>', do nothing
-
## * when '<% %>' or '<%# %>', delete spaces iff only spaces are around '<% %>'
-
if ch == ?= # <%= %>
-
rspace = nil if tailch && !tailch.empty?
-
str << lspace if lspace
-
add_expr(str, code, indicator)
-
str << rspace if rspace
-
elsif ch == ?\# # <%# %>
-
n = code.count("\n") + (rspace ? 1 : 0)
-
if @trim && lspace && rspace
-
add_text(src, str)
-
str = ''
-
add_stmt(src, "\n" * n)
-
else
-
str << lspace if lspace
-
add_text(src, str)
-
str = ''
-
add_stmt(src, "\n" * n)
-
str << rspace if rspace
-
end
-
else # <% %>
-
if @trim && lspace && rspace
-
add_text(src, str)
-
str = ''
-
add_stmt(src, "#{lspace}#{code}#{rspace}")
-
else
-
str << lspace if lspace
-
add_text(src, str)
-
str = ''
-
add_stmt(src, code)
-
str << rspace if rspace
-
end
-
end
-
end
-
#rest = $' || input # ruby1.8
-
rest = pos == 0 ? input : input[pos..-1] # ruby1.9
-
_add_text_to_str(str, rest)
-
add_text(src, str)
-
end
-
-
2
def add_text(src, text)
-
return if !text || text.empty?
-
#src << " _buf << %Q`" << text << "`;"
-
if text[-1] == ?\n
-
text[-1] = "\\n"
-
src << " #{@bufvar} << %Q`#{text}`\n"
-
else
-
src << " #{@bufvar} << %Q`#{text}`;"
-
end
-
end
-
-
2
def _add_text_to_str(str, text)
-
return if !text || text.empty?
-
str << text.gsub(/[`\#\\]/, '\\\\\&')
-
end
-
-
2
def add_expr_escaped(str, code)
-
str << "\#{#{escaped_expr(code)}}"
-
end
-
-
2
def add_expr_literal(str, code)
-
str << "\#{#{code}}"
-
end
-
-
end
-
-
-
end
-
##
-
## $Release: 2.7.0 $
-
## copyright(c) 2006-2011 kuwata-lab.com all rights reserved.
-
##
-
-
2
module Erubis
-
-
-
##
-
## base error class
-
##
-
2
class ErubisError < StandardError
-
end
-
-
-
##
-
## raised when method or function is not supported
-
##
-
2
class NotSupportedError < ErubisError
-
end
-
-
-
end
-
##
-
## $Release: 2.7.0 $
-
## copyright(c) 2006-2011 kuwata-lab.com all rights reserved.
-
##
-
-
2
require 'erubis/error'
-
2
require 'erubis/context'
-
-
-
2
module Erubis
-
-
2
EMPTY_BINDING = binding()
-
-
-
##
-
## evaluate code
-
##
-
2
module Evaluator
-
-
2
def self.supported_properties # :nodoc:
-
return []
-
end
-
-
2
attr_accessor :src, :filename
-
-
2
def init_evaluator(properties)
-
6
@filename = properties[:filename]
-
end
-
-
2
def result(*args)
-
raise NotSupportedError.new("evaluation of code except Ruby is not supported.")
-
end
-
-
2
def evaluate(*args)
-
raise NotSupportedError.new("evaluation of code except Ruby is not supported.")
-
end
-
-
end
-
-
-
##
-
## evaluator for Ruby
-
##
-
2
module RubyEvaluator
-
2
include Evaluator
-
-
2
def self.supported_properties # :nodoc:
-
list = Evaluator.supported_properties
-
return list
-
end
-
-
## eval(@src) with binding object
-
2
def result(_binding_or_hash=TOPLEVEL_BINDING)
-
_arg = _binding_or_hash
-
if _arg.is_a?(Hash)
-
_b = binding()
-
eval _arg.collect{|k,v| "#{k} = _arg[#{k.inspect}]; "}.join, _b
-
elsif _arg.is_a?(Binding)
-
_b = _arg
-
elsif _arg.nil?
-
_b = binding()
-
else
-
raise ArgumentError.new("#{self.class.name}#result(): argument should be Binding or Hash but passed #{_arg.class.name} object.")
-
end
-
return eval(@src, _b, (@filename || '(erubis'))
-
end
-
-
## invoke context.instance_eval(@src)
-
2
def evaluate(_context=Context.new)
-
_context = Context.new(_context) if _context.is_a?(Hash)
-
#return _context.instance_eval(@src, @filename || '(erubis)')
-
#@_proc ||= eval("proc { #{@src} }", Erubis::EMPTY_BINDING, @filename || '(erubis)')
-
@_proc ||= eval("proc { #{@src} }", binding(), @filename || '(erubis)')
-
return _context.instance_eval(&@_proc)
-
end
-
-
## if object is an Class or Module then define instance method to it,
-
## else define singleton method to it.
-
2
def def_method(object, method_name, filename=nil)
-
m = object.is_a?(Module) ? :module_eval : :instance_eval
-
object.__send__(m, "def #{method_name}; #{@src}; end", filename || @filename || '(erubis)')
-
end
-
-
-
end
-
-
-
end
-
##
-
## $Release: 2.7.0 $
-
## copyright(c) 2006-2011 kuwata-lab.com all rights reserved.
-
##
-
-
2
require 'erubis/util'
-
-
2
module Erubis
-
-
-
##
-
## code generator, called by Converter module
-
##
-
2
module Generator
-
-
2
def self.supported_properties() # :nodoc:
-
return [
-
[:escapefunc, nil, "escape function name"],
-
]
-
end
-
-
2
attr_accessor :escapefunc
-
-
2
def init_generator(properties={})
-
6
@escapefunc = properties[:escapefunc]
-
end
-
-
-
## (abstract) escape text string
-
##
-
## ex.
-
## def escape_text(text)
-
## return text.dump
-
## # or return "'" + text.gsub(/['\\]/, '\\\\\&') + "'"
-
## end
-
2
def escape_text(text)
-
not_implemented
-
end
-
-
## return escaped expression code (ex. 'h(...)' or 'htmlspecialchars(...)')
-
2
def escaped_expr(code)
-
code.strip!
-
return "#{@escapefunc}(#{code})"
-
end
-
-
## (abstract) add @preamble to src
-
2
def add_preamble(src)
-
not_implemented
-
end
-
-
## (abstract) add text string to src
-
2
def add_text(src, text)
-
not_implemented
-
end
-
-
## (abstract) add statement code to src
-
2
def add_stmt(src, code)
-
not_implemented
-
end
-
-
## (abstract) add expression literal code to src. this is called by add_expr().
-
2
def add_expr_literal(src, code)
-
not_implemented
-
end
-
-
## (abstract) add escaped expression code to src. this is called by add_expr().
-
2
def add_expr_escaped(src, code)
-
not_implemented
-
end
-
-
## (abstract) add expression code to src for debug. this is called by add_expr().
-
2
def add_expr_debug(src, code)
-
not_implemented
-
end
-
-
## (abstract) add @postamble to src
-
2
def add_postamble(src)
-
not_implemented
-
end
-
-
-
end
-
-
-
end
-
##
-
## $Release: 2.7.0 $
-
## copyright(c) 2006-2011 kuwata-lab.com all rights reserved.
-
##
-
-
-
2
module Erubis
-
-
##
-
## helper for xml
-
##
-
2
module XmlHelper
-
-
2
module_function
-
-
2
ESCAPE_TABLE = {
-
'&' => '&',
-
'<' => '<',
-
'>' => '>',
-
'"' => '"',
-
"'" => ''',
-
}
-
-
2
def escape_xml(value)
-
value.to_s.gsub(/[&<>"]/) { |s| ESCAPE_TABLE[s] } # or /[&<>"']/
-
#value.to_s.gsub(/[&<>"]/) { ESCAPE_TABLE[$&] }
-
end
-
-
2
def escape_xml2(value)
-
return value.to_s.gsub(/\&/,'&').gsub(/</,'<').gsub(/>/,'>').gsub(/"/,'"')
-
end
-
-
2
alias h escape_xml
-
2
alias html_escape escape_xml
-
-
2
def url_encode(str)
-
return str.gsub(/[^-_.a-zA-Z0-9]+/) { |s|
-
s.unpack('C*').collect { |i| "%%%02X" % i }.join
-
}
-
end
-
-
2
alias u url_encode
-
-
end
-
-
-
end
-
##
-
## $Release: 2.7.0 $
-
## copyright(c) 2006-2011 kuwata-lab.com all rights reserved.
-
##
-
-
##
-
## you can add site-local settings here.
-
## this files is required by erubis.rb
-
##
-
##
-
## $Release: 2.7.0 $
-
## copyright(c) 2006-2011 kuwata-lab.com all rights reserved.
-
##
-
-
2
module Kernel
-
-
##
-
## raise NotImplementedError
-
##
-
2
def not_implemented #:doc:
-
backtrace = caller()
-
method_name = (backtrace.shift =~ /`(\w+)'$/) && $1
-
mesg = "class #{self.class.name} must implement abstract method '#{method_name}()'."
-
#mesg = "#{self.class.name}##{method_name}() is not implemented."
-
err = NotImplementedError.new mesg
-
err.set_backtrace backtrace
-
raise err
-
end
-
2
private :not_implemented
-
-
end
-
2
require "execjs/module"
-
2
require "execjs/runtimes"
-
-
2
module ExecJS
-
2
self.runtime ||= Runtimes.autodetect
-
end
-
2
require "execjs/runtime"
-
-
2
module ExecJS
-
2
class DisabledRuntime < Runtime
-
2
def name
-
"Disabled"
-
end
-
-
2
def exec(source)
-
raise Error, "ExecJS disabled"
-
end
-
-
2
def eval(source)
-
raise Error, "ExecJS disabled"
-
end
-
-
2
def compile(source)
-
raise Error, "ExecJS disabled"
-
end
-
-
2
def deprecated?
-
true
-
end
-
-
2
def available?
-
true
-
end
-
end
-
end
-
2
require "execjs/runtime"
-
2
require "json"
-
-
2
module ExecJS
-
2
class DuktapeRuntime < Runtime
-
2
class Context < Runtime::Context
-
2
def initialize(runtime, source = "")
-
@ctx = Duktape::Context.new(complex_object: nil)
-
@ctx.exec_string(encode(source), '(execjs)')
-
rescue Exception => e
-
raise wrap_error(e)
-
end
-
-
2
def exec(source, options = {})
-
return unless /\S/ =~ source
-
@ctx.eval_string("(function(){#{encode(source)}})()", '(execjs)')
-
rescue Exception => e
-
raise wrap_error(e)
-
end
-
-
2
def eval(source, options = {})
-
return unless /\S/ =~ source
-
@ctx.eval_string("(#{encode(source)})", '(execjs)')
-
rescue Exception => e
-
raise wrap_error(e)
-
end
-
-
2
def call(identifier, *args)
-
@ctx.call_prop(identifier.split("."), *args)
-
rescue Exception => e
-
raise wrap_error(e)
-
end
-
-
2
private
-
2
def wrap_error(e)
-
klass = case e
-
when Duktape::SyntaxError
-
RuntimeError
-
when Duktape::Error
-
ProgramError
-
when Duktape::InternalError
-
RuntimeError
-
end
-
-
if klass
-
re = / \(line (\d+)\)$/
-
lineno = e.message[re, 1] || 1
-
error = klass.new(e.message.sub(re, ""))
-
error.set_backtrace(["(execjs):#{lineno}"] + e.backtrace)
-
error
-
else
-
e
-
end
-
end
-
end
-
-
2
def name
-
"Duktape"
-
end
-
-
2
def available?
-
2
require "duktape"
-
true
-
rescue LoadError
-
2
false
-
end
-
end
-
end
-
2
module ExecJS
-
# Encodes strings as UTF-8
-
2
module Encoding
-
2
if RUBY_ENGINE == 'jruby' || RUBY_ENGINE == 'rbx'
-
# workaround for jruby bug http://jira.codehaus.org/browse/JRUBY-6588
-
# workaround for rbx bug https://github.com/rubinius/rubinius/issues/1729
-
def encode(string)
-
if string.encoding.name == 'ASCII-8BIT'
-
data = string.dup
-
data.force_encoding('UTF-8')
-
-
unless data.valid_encoding?
-
raise ::Encoding::UndefinedConversionError, "Could not encode ASCII-8BIT data #{string.dump} as UTF-8"
-
end
-
else
-
data = string.encode('UTF-8')
-
end
-
data
-
end
-
else
-
2
def encode(string)
-
string.encode('UTF-8')
-
end
-
end
-
end
-
end
-
2
require "tmpdir"
-
2
require "execjs/runtime"
-
-
2
module ExecJS
-
2
class ExternalRuntime < Runtime
-
2
class Context < Runtime::Context
-
2
def initialize(runtime, source = "")
-
source = encode(source)
-
-
@runtime = runtime
-
@source = source
-
-
# Test compile context source
-
exec("")
-
end
-
-
2
def eval(source, options = {})
-
source = encode(source)
-
-
if /\S/ =~ source
-
exec("return eval(#{::JSON.generate("(#{source})", quirks_mode: true)})")
-
end
-
end
-
-
2
def exec(source, options = {})
-
source = encode(source)
-
source = "#{@source}\n#{source}" if @source != ""
-
source = @runtime.compile_source(source)
-
-
tmpfile = write_to_tempfile(source)
-
-
if ExecJS.cygwin?
-
filepath = `cygpath -m #{tmpfile.path}`.rstrip
-
else
-
filepath = tmpfile.path
-
end
-
-
begin
-
extract_result(@runtime.exec_runtime(filepath), filepath)
-
ensure
-
File.unlink(tmpfile)
-
end
-
end
-
-
2
def call(identifier, *args)
-
eval "#{identifier}.apply(this, #{::JSON.generate(args)})"
-
end
-
-
2
protected
-
# See Tempfile.create on Ruby 2.1
-
2
def create_tempfile(basename)
-
tmpfile = nil
-
Dir::Tmpname.create(basename) do |tmpname|
-
mode = File::WRONLY | File::CREAT | File::EXCL
-
tmpfile = File.open(tmpname, mode, 0600)
-
end
-
tmpfile
-
end
-
-
2
def write_to_tempfile(contents)
-
tmpfile = create_tempfile(['execjs', 'js'])
-
tmpfile.write(contents)
-
tmpfile.close
-
tmpfile
-
end
-
-
2
def extract_result(output, filename)
-
status, value, stack = output.empty? ? [] : ::JSON.parse(output, create_additions: false)
-
if status == "ok"
-
value
-
else
-
stack ||= ""
-
real_filename = File.realpath(filename)
-
stack = stack.split("\n").map do |line|
-
line.sub(" at ", "")
-
.sub(real_filename, "(execjs)")
-
.sub(filename, "(execjs)")
-
.strip
-
end
-
stack.reject! { |line| ["eval code", "eval@[native code]"].include?(line) }
-
stack.shift unless stack[0].to_s.include?("(execjs)")
-
error_class = value =~ /SyntaxError:/ ? RuntimeError : ProgramError
-
error = error_class.new(value)
-
error.set_backtrace(stack + caller)
-
raise error
-
end
-
end
-
end
-
-
2
attr_reader :name
-
-
2
def initialize(options)
-
8
@name = options[:name]
-
8
@command = options[:command]
-
8
@runner_path = options[:runner_path]
-
8
@encoding = options[:encoding]
-
8
@deprecated = !!options[:deprecated]
-
8
@binary = nil
-
-
8
@popen_options = {}
-
8
@popen_options[:external_encoding] = @encoding if @encoding
-
8
@popen_options[:internal_encoding] = ::Encoding.default_internal || 'UTF-8'
-
-
8
if @runner_path
-
8
instance_eval generate_compile_method(@runner_path)
-
end
-
end
-
-
2
def available?
-
4
require 'json'
-
4
binary ? true : false
-
end
-
-
2
def deprecated?
-
8
@deprecated
-
end
-
-
2
private
-
2
def binary
-
4
@binary ||= which(@command)
-
end
-
-
2
def locate_executable(command)
-
4
commands = Array(command)
-
4
if ExecJS.windows? && File.extname(command) == ""
-
ENV['PATHEXT'].split(File::PATH_SEPARATOR).each { |p|
-
commands << (command + p)
-
}
-
end
-
-
4
commands.find { |cmd|
-
4
if File.executable? cmd
-
cmd
-
else
-
4
path = ENV['PATH'].split(File::PATH_SEPARATOR).find { |p|
-
42
full_path = File.join(p, cmd)
-
42
File.executable?(full_path) && File.file?(full_path)
-
}
-
4
path && File.expand_path(cmd, path)
-
end
-
}
-
end
-
-
2
protected
-
2
def generate_compile_method(path)
-
<<-RUBY
-
def compile_source(source)
-
<<-RUNNER
-
8
#{IO.read(path)}
-
RUNNER
-
end
-
RUBY
-
end
-
-
2
def json2_source
-
@json2_source ||= IO.read(ExecJS.root + "/support/json2.js")
-
end
-
-
2
def encode_source(source)
-
encoded_source = encode_unicode_codepoints(source)
-
::JSON.generate("(function(){ #{encoded_source} })()", quirks_mode: true)
-
end
-
-
2
def encode_unicode_codepoints(str)
-
str.gsub(/[\u0080-\uffff]/) do |ch|
-
"\\u%04x" % ch.codepoints.to_a
-
end
-
end
-
-
2
if ExecJS.windows?
-
def exec_runtime(filename)
-
path = Dir::Tmpname.create(['execjs', 'json']) {}
-
begin
-
command = binary.split(" ") << filename
-
`#{shell_escape(*command)} 2>&1 > #{path}`
-
output = File.open(path, 'rb', @popen_options) { |f| f.read }
-
ensure
-
File.unlink(path) if path
-
end
-
-
if $?.success?
-
output
-
else
-
raise exec_runtime_error(output)
-
end
-
end
-
-
def shell_escape(*args)
-
# see http://technet.microsoft.com/en-us/library/cc723564.aspx#XSLTsection123121120120
-
args.map { |arg|
-
arg = %Q("#{arg.gsub('"','""')}") if arg.match(/[&|()<>^ "]/)
-
arg
-
}.join(" ")
-
end
-
elsif RUBY_ENGINE == 'jruby'
-
require 'shellwords'
-
-
def exec_runtime(filename)
-
command = "#{Shellwords.join(binary.split(' ') << filename)} 2>&1"
-
io = IO.popen(command, @popen_options)
-
output = io.read
-
io.close
-
-
if $?.success?
-
output
-
else
-
raise exec_runtime_error(output)
-
end
-
end
-
else
-
2
def exec_runtime(filename)
-
io = IO.popen(binary.split(' ') << filename, @popen_options.merge({err: [:child, :out]}))
-
output = io.read
-
io.close
-
-
if $?.success?
-
output
-
else
-
raise exec_runtime_error(output)
-
end
-
end
-
end
-
# Internally exposed for Context.
-
2
public :exec_runtime
-
-
2
def exec_runtime_error(output)
-
error = RuntimeError.new(output)
-
lines = output.split("\n")
-
lineno = lines[0][/:(\d+)$/, 1] if lines[0]
-
lineno ||= 1
-
error.set_backtrace(["(execjs):#{lineno}"] + caller)
-
error
-
end
-
-
2
def which(command)
-
2
Array(command).find do |name|
-
4
name, args = name.split(/\s+/, 2)
-
4
path = locate_executable(name)
-
-
4
next unless path
-
-
2
args ? "#{path} #{args}" : path
-
end
-
end
-
end
-
end
-
2
require "execjs/version"
-
2
require "rbconfig"
-
-
2
module ExecJS
-
2
class Error < ::StandardError; end
-
2
class RuntimeError < Error; end
-
2
class ProgramError < Error; end
-
2
class RuntimeUnavailable < RuntimeError; end
-
-
2
class << self
-
2
attr_reader :runtime
-
-
2
def runtime=(runtime)
-
2
raise RuntimeUnavailable, "#{runtime.name} is unavailable on this system" unless runtime.available?
-
2
@runtime = runtime
-
end
-
-
2
def exec(source)
-
runtime.exec(source)
-
end
-
-
2
def eval(source)
-
runtime.eval(source)
-
end
-
-
2
def compile(source)
-
runtime.compile(source)
-
end
-
-
2
def root
-
8
@root ||= File.expand_path("..", __FILE__)
-
end
-
-
2
def windows?
-
6
@windows ||= RbConfig::CONFIG["host_os"] =~ /mswin|mingw/
-
end
-
-
2
def cygwin?
-
@cygwin ||= RbConfig::CONFIG["host_os"] =~ /cygwin/
-
end
-
end
-
end
-
2
require "execjs/runtime"
-
-
2
module ExecJS
-
2
class RubyRacerRuntime < Runtime
-
2
class Context < Runtime::Context
-
2
def initialize(runtime, source = "")
-
source = encode(source)
-
-
lock do
-
@v8_context = ::V8::Context.new
-
-
begin
-
@v8_context.eval(source)
-
rescue ::V8::JSError => e
-
raise wrap_error(e)
-
end
-
end
-
end
-
-
2
def exec(source, options = {})
-
source = encode(source)
-
-
if /\S/ =~ source
-
eval "(function(){#{source}})()", options
-
end
-
end
-
-
2
def eval(source, options = {})
-
source = encode(source)
-
-
if /\S/ =~ source
-
lock do
-
begin
-
unbox @v8_context.eval("(#{source})")
-
rescue ::V8::JSError => e
-
raise wrap_error(e)
-
end
-
end
-
end
-
end
-
-
2
def call(properties, *args)
-
lock do
-
begin
-
unbox @v8_context.eval(properties).call(*args)
-
rescue ::V8::JSError => e
-
raise wrap_error(e)
-
end
-
end
-
end
-
-
2
def unbox(value)
-
case value
-
when ::V8::Function
-
nil
-
when ::V8::Array
-
value.map { |v| unbox(v) }
-
when ::V8::Object
-
value.inject({}) do |vs, (k, v)|
-
vs[k] = unbox(v) unless v.is_a?(::V8::Function)
-
vs
-
end
-
when String
-
value.force_encoding('UTF-8')
-
else
-
value
-
end
-
end
-
-
2
private
-
2
def lock
-
result, exception = nil, nil
-
V8::C::Locker() do
-
begin
-
result = yield
-
rescue Exception => e
-
exception = e
-
end
-
end
-
-
if exception
-
raise exception
-
else
-
result
-
end
-
end
-
-
2
def wrap_error(e)
-
error_class = e.value["name"] == "SyntaxError" ? RuntimeError : ProgramError
-
-
stack = e.value["stack"] || ""
-
stack = stack.split("\n")
-
stack.shift
-
stack = [e.message[/<eval>:\d+:\d+/, 0]].compact if stack.empty?
-
stack = stack.map { |line| line.sub(" at ", "").sub("<eval>", "(execjs)").strip }
-
-
error = error_class.new(e.value.to_s)
-
error.set_backtrace(stack + caller)
-
error
-
end
-
end
-
-
2
def name
-
"therubyracer (V8)"
-
end
-
-
2
def available?
-
2
require "v8"
-
true
-
rescue LoadError
-
2
false
-
end
-
end
-
end
-
2
require "execjs/runtime"
-
-
2
module ExecJS
-
2
class RubyRhinoRuntime < Runtime
-
2
class Context < Runtime::Context
-
2
def initialize(runtime, source = "")
-
source = encode(source)
-
-
@rhino_context = ::Rhino::Context.new
-
fix_memory_limit! @rhino_context
-
@rhino_context.eval(source)
-
rescue Exception => e
-
raise wrap_error(e)
-
end
-
-
2
def exec(source, options = {})
-
source = encode(source)
-
-
if /\S/ =~ source
-
eval "(function(){#{source}})()", options
-
end
-
end
-
-
2
def eval(source, options = {})
-
source = encode(source)
-
-
if /\S/ =~ source
-
unbox @rhino_context.eval("(#{source})")
-
end
-
rescue Exception => e
-
raise wrap_error(e)
-
end
-
-
2
def call(properties, *args)
-
unbox @rhino_context.eval(properties).call(*args)
-
rescue Exception => e
-
raise wrap_error(e)
-
end
-
-
2
def unbox(value)
-
case value = ::Rhino::to_ruby(value)
-
when Java::OrgMozillaJavascript::NativeFunction
-
nil
-
when Java::OrgMozillaJavascript::NativeObject
-
value.inject({}) do |vs, (k, v)|
-
case v
-
when Java::OrgMozillaJavascript::NativeFunction, ::Rhino::JS::Function
-
nil
-
else
-
vs[k] = unbox(v)
-
end
-
vs
-
end
-
when Array
-
value.map { |v| unbox(v) }
-
else
-
value
-
end
-
end
-
-
2
def wrap_error(e)
-
return e unless e.is_a?(::Rhino::JSError)
-
-
error_class = e.message == "syntax error" ? RuntimeError : ProgramError
-
-
stack = e.backtrace
-
stack = stack.map { |line| line.sub(" at ", "").sub("<eval>", "(execjs)").strip }
-
stack.unshift("(execjs):1") if e.javascript_backtrace.empty?
-
-
error = error_class.new(e.value.to_s)
-
error.set_backtrace(stack)
-
error
-
end
-
-
2
private
-
# Disables bytecode compiling which limits you to 64K scripts
-
2
def fix_memory_limit!(context)
-
if context.respond_to?(:optimization_level=)
-
context.optimization_level = -1
-
else
-
context.instance_eval { @native.setOptimizationLevel(-1) }
-
end
-
end
-
end
-
-
2
def name
-
"therubyrhino (Rhino)"
-
end
-
-
2
def available?
-
2
require "rhino"
-
true
-
rescue LoadError
-
2
false
-
end
-
end
-
end
-
2
require "execjs/encoding"
-
-
2
module ExecJS
-
# Abstract base class for runtimes
-
2
class Runtime
-
2
class Context
-
2
include Encoding
-
-
2
def initialize(runtime, source = "")
-
end
-
-
2
def exec(source, options = {})
-
raise NotImplementedError
-
end
-
-
2
def eval(source, options = {})
-
raise NotImplementedError
-
end
-
-
2
def call(properties, *args)
-
raise NotImplementedError
-
end
-
end
-
-
2
def name
-
raise NotImplementedError
-
end
-
-
2
def context_class
-
self.class::Context
-
end
-
-
2
def exec(source)
-
context = context_class.new(self)
-
context.exec(source)
-
end
-
-
2
def eval(source)
-
context = context_class.new(self)
-
context.eval(source)
-
end
-
-
2
def compile(source)
-
context_class.new(self, source)
-
end
-
-
2
def deprecated?
-
6
false
-
end
-
-
2
def available?
-
raise NotImplementedError
-
end
-
end
-
end
-
2
require "execjs/module"
-
2
require "execjs/disabled_runtime"
-
2
require "execjs/duktape_runtime"
-
2
require "execjs/external_runtime"
-
2
require "execjs/ruby_racer_runtime"
-
2
require "execjs/ruby_rhino_runtime"
-
-
2
module ExecJS
-
2
module Runtimes
-
2
Disabled = DisabledRuntime.new
-
-
2
Duktape = DuktapeRuntime.new
-
-
2
RubyRacer = RubyRacerRuntime.new
-
-
2
RubyRhino = RubyRhinoRuntime.new
-
-
2
Node = ExternalRuntime.new(
-
name: "Node.js (V8)",
-
command: ["nodejs", "node"],
-
runner_path: ExecJS.root + "/support/node_runner.js",
-
encoding: 'UTF-8'
-
)
-
-
2
JavaScriptCore = ExternalRuntime.new(
-
name: "JavaScriptCore",
-
command: "/System/Library/Frameworks/JavaScriptCore.framework/Versions/A/Resources/jsc",
-
runner_path: ExecJS.root + "/support/jsc_runner.js"
-
)
-
-
2
SpiderMonkey = Spidermonkey = ExternalRuntime.new(
-
name: "SpiderMonkey",
-
command: "js",
-
runner_path: ExecJS.root + "/support/spidermonkey_runner.js",
-
deprecated: true
-
)
-
-
2
JScript = ExternalRuntime.new(
-
name: "JScript",
-
command: "cscript //E:jscript //Nologo //U",
-
runner_path: ExecJS.root + "/support/jscript_runner.js",
-
encoding: 'UTF-16LE' # CScript with //U returns UTF-16LE
-
)
-
-
-
2
def self.autodetect
-
2
from_environment || best_available ||
-
raise(RuntimeUnavailable, "Could not find a JavaScript runtime. " +
-
"See https://github.com/rails/execjs for a list of available runtimes.")
-
end
-
-
2
def self.best_available
-
2
runtimes.reject(&:deprecated?).find(&:available?)
-
end
-
-
2
def self.from_environment
-
2
if name = ENV["EXECJS_RUNTIME"]
-
raise RuntimeUnavailable, "#{name} runtime is not defined" unless const_defined?(name)
-
runtime = const_get(name)
-
-
raise RuntimeUnavailable, "#{runtime.name} runtime is not available on this system" unless runtime.available?
-
runtime
-
end
-
end
-
-
2
def self.names
-
@names ||= constants.inject({}) { |h, name| h.merge(const_get(name) => name) }.values
-
end
-
-
2
def self.runtimes
-
@runtimes ||= [
-
RubyRacer,
-
RubyRhino,
-
Duktape,
-
Node,
-
JavaScriptCore,
-
SpiderMonkey,
-
JScript
-
2
]
-
end
-
end
-
-
2
def self.runtimes
-
Runtimes.runtimes
-
end
-
end
-
2
module ExecJS
-
2
VERSION = "2.6.0"
-
end
-
2
require "geocoder/configuration"
-
2
require "geocoder/logger"
-
2
require "geocoder/kernel_logger"
-
2
require "geocoder/query"
-
2
require "geocoder/calculations"
-
2
require "geocoder/exceptions"
-
2
require "geocoder/cache"
-
2
require "geocoder/request"
-
2
require "geocoder/lookup"
-
2
require "geocoder/ip_address"
-
2
require "geocoder/models/active_record" if defined?(::ActiveRecord)
-
2
require "geocoder/models/mongoid" if defined?(::Mongoid)
-
2
require "geocoder/models/mongo_mapper" if defined?(::MongoMapper)
-
-
2
module Geocoder
-
-
##
-
# Search for information about an address or a set of coordinates.
-
#
-
2
def self.search(query, options = {})
-
query = Geocoder::Query.new(query, options) unless query.is_a?(Geocoder::Query)
-
query.blank? ? [] : query.execute
-
end
-
-
##
-
# Look up the coordinates of the given street or IP address.
-
#
-
2
def self.coordinates(address, options = {})
-
if (results = search(address, options)).size > 0
-
results.first.coordinates
-
end
-
end
-
-
##
-
# Look up the address of the given coordinates ([lat,lon])
-
# or IP address (string).
-
#
-
2
def self.address(query, options = {})
-
if (results = search(query, options)).size > 0
-
results.first.address
-
end
-
end
-
end
-
-
# load Railtie if Rails exists
-
2
if defined?(Rails)
-
2
require "geocoder/railtie"
-
end
-
2
module Geocoder
-
2
class Cache
-
-
2
def initialize(store, prefix)
-
@store = store
-
@prefix = prefix
-
end
-
-
##
-
# Read from the Cache.
-
#
-
2
def [](url)
-
interpret case
-
when store.respond_to?(:[])
-
store[key_for(url)]
-
when store.respond_to?(:get)
-
store.get key_for(url)
-
when store.respond_to?(:read)
-
store.read key_for(url)
-
end
-
end
-
-
##
-
# Write to the Cache.
-
#
-
2
def []=(url, value)
-
case
-
when store.respond_to?(:[]=)
-
store[key_for(url)] = value
-
when store.respond_to?(:set)
-
store.set key_for(url), value
-
when store.respond_to?(:write)
-
store.write key_for(url), value
-
end
-
end
-
-
##
-
# Delete cache entry for given URL,
-
# or pass <tt>:all</tt> to clear all URLs.
-
#
-
2
def expire(url)
-
if url == :all
-
urls.each{ |u| expire(u) }
-
else
-
expire_single_url(url)
-
end
-
end
-
-
-
2
private # ----------------------------------------------------------------
-
-
2
def prefix; @prefix; end
-
2
def store; @store; end
-
-
##
-
# Cache key for a given URL.
-
#
-
2
def key_for(url)
-
[prefix, url].join
-
end
-
-
##
-
# Array of keys with the currently configured prefix
-
# that have non-nil values.
-
#
-
2
def keys
-
store.keys.select{ |k| k.match(/^#{prefix}/) and interpret(store[k]) }
-
end
-
-
##
-
# Array of cached URLs.
-
#
-
2
def urls
-
keys.map{ |k| k[/^#{prefix}(.*)/, 1] }
-
end
-
-
##
-
# Clean up value before returning. Namely, convert empty string to nil.
-
# (Some key/value stores return empty string instead of nil.)
-
#
-
2
def interpret(value)
-
value == "" ? nil : value
-
end
-
-
2
def expire_single_url(url)
-
key = key_for(url)
-
store.respond_to?(:del) ? store.del(key) : store.delete(key)
-
end
-
end
-
end
-
2
module Geocoder
-
2
module Calculations
-
2
extend self
-
-
##
-
# Compass point names, listed clockwise starting at North.
-
#
-
# If you want bearings named using more, fewer, or different points
-
# override Geocoder::Calculations.COMPASS_POINTS with your own array.
-
#
-
2
COMPASS_POINTS = %w[N NE E SE S SW W NW]
-
-
##
-
# Radius of the Earth, in kilometers.
-
# Value taken from: http://en.wikipedia.org/wiki/Earth_radius
-
#
-
2
EARTH_RADIUS = 6371.0
-
-
##
-
# Conversion factor: multiply by kilometers to get miles.
-
#
-
2
KM_IN_MI = 0.621371192
-
-
##
-
# Conversion factor: multiply by nautical miles to get miles.
-
#
-
2
KM_IN_NM = 0.539957
-
-
##
-
# Conversion factor: multiply by radians to get degrees.
-
#
-
2
DEGREES_PER_RADIAN = 57.2957795
-
-
# Not a number constant
-
2
NAN = defined?(::Float::NAN) ? ::Float::NAN : 0 / 0.0
-
-
##
-
# Returns true if all given arguments are valid latitude/longitude values.
-
#
-
2
def coordinates_present?(*args)
-
args.each do |a|
-
# note that Float::NAN != Float::NAN
-
# still, this could probably be improved:
-
return false if (!a.is_a?(Numeric) or a.to_s == "NaN")
-
end
-
true
-
end
-
-
##
-
# Distance spanned by one degree of latitude in the given units.
-
#
-
2
def latitude_degree_distance(units = nil)
-
units ||= Geocoder.config.units
-
2 * Math::PI * earth_radius(units) / 360
-
end
-
-
##
-
# Distance spanned by one degree of longitude at the given latitude.
-
# This ranges from around 69 miles at the equator to zero at the poles.
-
#
-
2
def longitude_degree_distance(latitude, units = nil)
-
units ||= Geocoder.config.units
-
latitude_degree_distance(units) * Math.cos(to_radians(latitude))
-
end
-
-
##
-
# Distance between two points on Earth (Haversine formula).
-
# Takes two points and an options hash.
-
# The points are given in the same way that points are given to all
-
# Geocoder methods that accept points as arguments. They can be:
-
#
-
# * an array of coordinates ([lat,lon])
-
# * a geocodable address (string)
-
# * a geocoded object (one which implements a +to_coordinates+ method
-
# which returns a [lat,lon] array
-
#
-
# The options hash supports:
-
#
-
# * <tt>:units</tt> - <tt>:mi</tt> or <tt>:km</tt>
-
# Use Geocoder.configure(:units => ...) to configure default units.
-
#
-
2
def distance_between(point1, point2, options = {})
-
-
# set default options
-
options[:units] ||= Geocoder.config.units
-
-
# convert to coordinate arrays
-
point1 = extract_coordinates(point1)
-
point2 = extract_coordinates(point2)
-
-
# convert degrees to radians
-
point1 = to_radians(point1)
-
point2 = to_radians(point2)
-
-
# compute deltas
-
dlat = point2[0] - point1[0]
-
dlon = point2[1] - point1[1]
-
-
a = (Math.sin(dlat / 2))**2 + Math.cos(point1[0]) *
-
(Math.sin(dlon / 2))**2 * Math.cos(point2[0])
-
c = 2 * Math.atan2( Math.sqrt(a), Math.sqrt(1-a))
-
c * earth_radius(options[:units])
-
end
-
-
##
-
# Bearing between two points on Earth.
-
# Returns a number of degrees from due north (clockwise).
-
#
-
# See Geocoder::Calculations.distance_between for
-
# ways of specifying the points. Also accepts an options hash:
-
#
-
# * <tt>:method</tt> - <tt>:linear</tt> or <tt>:spherical</tt>;
-
# the spherical method is "correct" in that it returns the shortest path
-
# (one along a great circle) but the linear method is less confusing
-
# (returns due east or west when given two points with the same latitude).
-
# Use Geocoder.configure(:distances => ...) to configure calculation method.
-
#
-
# Based on: http://www.movable-type.co.uk/scripts/latlong.html
-
#
-
2
def bearing_between(point1, point2, options = {})
-
-
# set default options
-
options[:method] ||= Geocoder.config.distances
-
options[:method] = :linear unless options[:method] == :spherical
-
-
# convert to coordinate arrays
-
point1 = extract_coordinates(point1)
-
point2 = extract_coordinates(point2)
-
-
# convert degrees to radians
-
point1 = to_radians(point1)
-
point2 = to_radians(point2)
-
-
# compute deltas
-
dlat = point2[0] - point1[0]
-
dlon = point2[1] - point1[1]
-
-
case options[:method]
-
when :linear
-
y = dlon
-
x = dlat
-
-
when :spherical
-
y = Math.sin(dlon) * Math.cos(point2[0])
-
x = Math.cos(point1[0]) * Math.sin(point2[0]) -
-
Math.sin(point1[0]) * Math.cos(point2[0]) * Math.cos(dlon)
-
end
-
-
bearing = Math.atan2(x,y)
-
# Answer is in radians counterclockwise from due east.
-
# Convert to degrees clockwise from due north:
-
(90 - to_degrees(bearing) + 360) % 360
-
end
-
-
##
-
# Translate a bearing (float) into a compass direction (string, eg "North").
-
#
-
2
def compass_point(bearing, points = COMPASS_POINTS)
-
seg_size = 360 / points.size
-
points[((bearing + (seg_size / 2)) % 360) / seg_size]
-
end
-
-
##
-
# Compute the geographic center (aka geographic midpoint, center of
-
# gravity) for an array of geocoded objects and/or [lat,lon] arrays
-
# (can be mixed). Any objects missing coordinates are ignored. Follows
-
# the procedure documented at http://www.geomidpoint.com/calculation.html.
-
#
-
2
def geographic_center(points)
-
-
# convert objects to [lat,lon] arrays and convert degrees to radians
-
coords = points.map{ |p| to_radians(extract_coordinates(p)) }
-
-
# convert to Cartesian coordinates
-
x = []; y = []; z = []
-
coords.each do |p|
-
x << Math.cos(p[0]) * Math.cos(p[1])
-
y << Math.cos(p[0]) * Math.sin(p[1])
-
z << Math.sin(p[0])
-
end
-
-
# compute average coordinate values
-
xa, ya, za = [x,y,z].map do |c|
-
c.inject(0){ |tot,i| tot += i } / c.size.to_f
-
end
-
-
# convert back to latitude/longitude
-
lon = Math.atan2(ya, xa)
-
hyp = Math.sqrt(xa**2 + ya**2)
-
lat = Math.atan2(za, hyp)
-
-
# return answer in degrees
-
to_degrees [lat, lon]
-
end
-
-
##
-
# Returns coordinates of the southwest and northeast corners of a box
-
# with the given point at its center. The radius is the shortest distance
-
# from the center point to any side of the box (the length of each side
-
# is twice the radius).
-
#
-
# This is useful for finding corner points of a map viewport, or for
-
# roughly limiting the possible solutions in a geo-spatial search
-
# (ActiveRecord queries use it thusly).
-
#
-
# See Geocoder::Calculations.distance_between for
-
# ways of specifying the point. Also accepts an options hash:
-
#
-
# * <tt>:units</tt> - <tt>:mi</tt> or <tt>:km</tt>.
-
# Use Geocoder.configure(:units => ...) to configure default units.
-
#
-
2
def bounding_box(point, radius, options = {})
-
lat,lon = extract_coordinates(point)
-
radius = radius.to_f
-
units = options[:units] || Geocoder.config.units
-
[
-
lat - (radius / latitude_degree_distance(units)),
-
lon - (radius / longitude_degree_distance(lat, units)),
-
lat + (radius / latitude_degree_distance(units)),
-
lon + (radius / longitude_degree_distance(lat, units))
-
]
-
end
-
-
##
-
# Random point within a circle of provided radius centered
-
# around the provided point
-
# Takes one point, one radius, and an options hash.
-
# The points are given in the same way that points are given to all
-
# Geocoder methods that accept points as arguments. They can be:
-
#
-
# * an array of coordinates ([lat,lon])
-
# * a geocodable address (string)
-
# * a geocoded object (one which implements a +to_coordinates+ method
-
# which returns a [lat,lon] array
-
#
-
# The options hash supports:
-
#
-
# * <tt>:units</tt> - <tt>:mi</tt> or <tt>:km</tt>
-
# Use Geocoder.configure(:units => ...) to configure default units.
-
# * <tt>:seed</tt> - The seed for the random number generator
-
2
def random_point_near(center, radius, options = {})
-
-
# set default options
-
options[:units] ||= Geocoder.config.units
-
-
random = Random.new(options[:seed] || Random.new_seed)
-
-
# convert to coordinate arrays
-
center = extract_coordinates(center)
-
-
earth_circumference = 2 * Math::PI * earth_radius(options[:units])
-
max_degree_delta = 360.0 * (radius / earth_circumference)
-
-
# random bearing in radians
-
theta = 2 * Math::PI * random.rand
-
-
# random radius, use the square root to ensure a uniform
-
# distribution of points over the circle
-
r = Math.sqrt(random.rand) * max_degree_delta
-
-
delta_lat, delta_long = [r * Math.cos(theta), r * Math.sin(theta)]
-
[center[0] + delta_lat, center[1] + delta_long]
-
end
-
-
##
-
# Given a start point, heading (in degrees), and distance, provides
-
# an endpoint.
-
# The starting point is given in the same way that points are given to all
-
# Geocoder methods that accept points as arguments. It can be:
-
#
-
# * an array of coordinates ([lat,lon])
-
# * a geocodable address (string)
-
# * a geocoded object (one which implements a +to_coordinates+ method
-
# which returns a [lat,lon] array
-
#
-
2
def endpoint(start, heading, distance, options = {})
-
options[:units] ||= Geocoder.config.units
-
radius = earth_radius(options[:units])
-
-
start = extract_coordinates(start)
-
-
# convert degrees to radians
-
start = to_radians(start)
-
-
lat = start[0]
-
lon = start[1]
-
heading = to_radians(heading)
-
distance = distance.to_f
-
-
end_lat = Math.asin(Math.sin(lat)*Math.cos(distance/radius) +
-
Math.cos(lat)*Math.sin(distance/radius)*Math.cos(heading))
-
-
end_lon = lon+Math.atan2(Math.sin(heading)*Math.sin(distance/radius)*Math.cos(lat),
-
Math.cos(distance/radius)-Math.sin(lat)*Math.sin(end_lat))
-
-
to_degrees [end_lat, end_lon]
-
end
-
-
##
-
# Convert degrees to radians.
-
# If an array (or multiple arguments) is passed,
-
# converts each value and returns array.
-
#
-
2
def to_radians(*args)
-
args = args.first if args.first.is_a?(Array)
-
if args.size == 1
-
args.first * (Math::PI / 180)
-
else
-
args.map{ |i| to_radians(i) }
-
end
-
end
-
-
##
-
# Convert radians to degrees.
-
# If an array (or multiple arguments) is passed,
-
# converts each value and returns array.
-
#
-
2
def to_degrees(*args)
-
args = args.first if args.first.is_a?(Array)
-
if args.size == 1
-
(args.first * 180.0) / Math::PI
-
else
-
args.map{ |i| to_degrees(i) }
-
end
-
end
-
-
2
def distance_to_radians(distance, units = nil)
-
units ||= Geocoder.config.units
-
distance.to_f / earth_radius(units)
-
end
-
-
2
def radians_to_distance(radians, units = nil)
-
units ||= Geocoder.config.units
-
radians * earth_radius(units)
-
end
-
-
##
-
# Convert miles to kilometers.
-
#
-
2
def to_kilometers(mi)
-
mi * mi_in_km
-
end
-
-
##
-
# Convert kilometers to miles.
-
#
-
2
def to_miles(km)
-
km * km_in_mi
-
end
-
-
##
-
# Convert kilometers to nautical miles.
-
#
-
2
def to_nautical_miles(km)
-
km * km_in_nm
-
end
-
-
##
-
# Radius of the Earth in the given units (:mi or :km).
-
# Use Geocoder.configure(:units => ...) to configure default units.
-
#
-
2
def earth_radius(units = nil)
-
units ||= Geocoder.config.units
-
case units
-
when :km; EARTH_RADIUS
-
when :mi; to_miles(EARTH_RADIUS)
-
when :nm; to_nautical_miles(EARTH_RADIUS)
-
end
-
end
-
-
##
-
# Conversion factor: km to mi.
-
#
-
2
def km_in_mi
-
KM_IN_MI
-
end
-
-
##
-
# Conversion factor: km to nm.
-
#
-
2
def km_in_nm
-
KM_IN_NM
-
end
-
-
-
-
##
-
# Conversion factor: mi to km.
-
#
-
2
def mi_in_km
-
1.0 / KM_IN_MI
-
end
-
-
##
-
# Conversion factor: nm to km.
-
#
-
2
def nm_in_km
-
1.0 / KM_IN_NM
-
end
-
-
##
-
# Takes an object which is a [lat,lon] array, a geocodable string,
-
# or an object that implements +to_coordinates+ and returns a
-
# [lat,lon] array. Note that if a string is passed this may be a slow-
-
# running method and may return nil.
-
#
-
2
def extract_coordinates(point)
-
case point
-
when Array
-
if point.size == 2
-
lat, lon = point
-
if !lat.nil? && lat.respond_to?(:to_f) and
-
!lon.nil? && lon.respond_to?(:to_f)
-
then
-
return [ lat.to_f, lon.to_f ]
-
end
-
end
-
when String
-
point = Geocoder.coordinates(point) and return point
-
else
-
if point.respond_to?(:to_coordinates)
-
if Array === array = point.to_coordinates
-
return extract_coordinates(array)
-
end
-
end
-
end
-
[ NAN, NAN ]
-
end
-
end
-
end
-
-
2
require 'singleton'
-
2
require 'geocoder/configuration_hash'
-
-
2
module Geocoder
-
-
##
-
# Configuration options should be set by passing a hash:
-
#
-
# Geocoder.configure(
-
# :timeout => 5,
-
# :lookup => :yandex,
-
# :api_key => "2a9fsa983jaslfj982fjasd",
-
# :units => :km
-
# )
-
#
-
2
def self.configure(options = nil, &block)
-
if !options.nil?
-
Configuration.instance.configure(options)
-
end
-
end
-
-
##
-
# Read-only access to the singleton's config data.
-
#
-
2
def self.config
-
Configuration.instance.data
-
end
-
-
##
-
# Read-only access to lookup-specific config data.
-
#
-
2
def self.config_for_lookup(lookup_name)
-
data = config.clone
-
data.reject!{ |key,value| !Configuration::OPTIONS.include?(key) }
-
if config.has_key?(lookup_name)
-
data.merge!(config[lookup_name])
-
end
-
data
-
end
-
-
2
class Configuration
-
2
include Singleton
-
-
2
OPTIONS = [
-
:timeout,
-
:lookup,
-
:ip_lookup,
-
:language,
-
:http_headers,
-
:use_https,
-
:http_proxy,
-
:https_proxy,
-
:api_key,
-
:cache,
-
:cache_prefix,
-
:always_raise,
-
:units,
-
:distances,
-
:basic_auth,
-
:logger,
-
:kernel_logger_level
-
]
-
-
2
attr_accessor :data
-
-
2
def self.set_defaults
-
instance.set_defaults
-
end
-
-
2
OPTIONS.each do |o|
-
34
define_method o do
-
@data[o]
-
end
-
34
define_method "#{o}=" do |value|
-
@data[o] = value
-
end
-
end
-
-
2
def configure(options)
-
@data.rmerge!(options)
-
end
-
-
2
def initialize # :nodoc
-
@data = Geocoder::ConfigurationHash.new
-
set_defaults
-
end
-
-
2
def set_defaults
-
-
# geocoding options
-
@data[:timeout] = 3 # geocoding service timeout (secs)
-
@data[:lookup] = :google # name of street address geocoding service (symbol)
-
@data[:ip_lookup] = :freegeoip # name of IP address geocoding service (symbol)
-
@data[:language] = :en # ISO-639 language code
-
@data[:http_headers] = {} # HTTP headers for lookup
-
@data[:use_https] = false # use HTTPS for lookup requests? (if supported)
-
@data[:http_proxy] = nil # HTTP proxy server (user:pass@host:port)
-
@data[:https_proxy] = nil # HTTPS proxy server (user:pass@host:port)
-
@data[:api_key] = nil # API key for geocoding service
-
@data[:cache] = nil # cache object (must respond to #[], #[]=, and #keys)
-
@data[:cache_prefix] = "geocoder:" # prefix (string) to use for all cache keys
-
@data[:basic_auth] = {} # user and password for basic auth ({:user => "user", :password => "password"})
-
@data[:logger] = :kernel # :kernel or Logger instance
-
@data[:kernel_logger_level] = ::Logger::WARN # log level, if kernel logger is used
-
-
# exceptions that should not be rescued by default
-
# (if you want to implement custom error handling);
-
# supports SocketError and Timeout::Error
-
@data[:always_raise] = []
-
-
# calculation options
-
@data[:units] = :mi # :mi or :km
-
@data[:distances] = :linear # :linear or :spherical
-
end
-
-
2
instance_eval(OPTIONS.map do |option|
-
34
o = option.to_s
-
<<-EOS
-
34
def #{o}
-
instance.data[:#{o}]
-
end
-
-
def #{o}=(value)
-
instance.data[:#{o}] = value
-
end
-
EOS
-
end.join("\n\n"))
-
end
-
end
-
2
require 'hash_recursive_merge'
-
-
2
module Geocoder
-
2
class ConfigurationHash < Hash
-
2
include HashRecursiveMerge
-
-
2
def method_missing(meth, *args, &block)
-
has_key?(meth) ? self[meth] : super
-
end
-
end
-
end
-
2
require 'timeout' # required for Ruby 1.9.3
-
-
2
module Geocoder
-
-
2
class Error < StandardError
-
end
-
-
2
class ConfigurationError < Error
-
end
-
-
2
class OverQueryLimitError < Error
-
end
-
-
2
class ResponseParseError < Error
-
2
attr_reader :response
-
-
2
def initialize(response)
-
@response = response
-
end
-
end
-
-
2
class RequestDenied < Error
-
end
-
-
2
class InvalidRequest < Error
-
end
-
-
2
class InvalidApiKey < Error
-
end
-
-
2
class ServiceUnavailable < Error
-
end
-
-
2
class LookupTimeout < ::Timeout::Error
-
end
-
-
end
-
2
require 'resolv'
-
2
module Geocoder
-
2
class IpAddress < String
-
-
2
def loopback?
-
valid? and (self == "0.0.0.0" or self.match(/\A127\./) or self == "::1")
-
end
-
-
2
def valid?
-
!!((self =~ Resolv::IPv4::Regex) || (self =~ Resolv::IPv6::Regex))
-
end
-
end
-
end
-
2
module Geocoder
-
2
class KernelLogger
-
2
include Singleton
-
-
2
def add(level, message)
-
return unless log_message_at_level?(level)
-
case level
-
when ::Logger::DEBUG, ::Logger::INFO
-
puts message
-
when ::Logger::WARN
-
warn message
-
when ::Logger::ERROR
-
raise message
-
when ::Logger::FATAL
-
fail message
-
end
-
end
-
-
2
private # ----------------------------------------------------------------
-
-
2
def log_message_at_level?(level)
-
level >= Geocoder.config.kernel_logger_level
-
end
-
end
-
end
-
2
require 'logger'
-
-
2
module Geocoder
-
-
2
def self.log(level, message)
-
Logger.instance.log(level, message)
-
end
-
-
2
class Logger
-
2
include Singleton
-
-
2
SEVERITY = {
-
debug: ::Logger::DEBUG,
-
info: ::Logger::INFO,
-
warn: ::Logger::WARN,
-
error: ::Logger::ERROR,
-
fatal: ::Logger::FATAL
-
}
-
-
2
def log(level, message)
-
unless valid_level?(level)
-
raise StandardError, "Geocoder tried to log a message with an invalid log level."
-
end
-
if current_logger.respond_to? :add
-
current_logger.add(SEVERITY[level], message)
-
else
-
raise Geocoder::ConfigurationError, "Please specify valid logger for Geocoder. " +
-
"Logger specified must be :kernel or must respond to `add(level, message)`."
-
end
-
nil
-
end
-
-
2
private # ----------------------------------------------------------------
-
-
2
def current_logger
-
logger = Geocoder.config[:logger]
-
if logger == :kernel
-
logger = Geocoder::KernelLogger.instance
-
end
-
logger
-
end
-
-
2
def valid_level?(level)
-
SEVERITY.keys.include?(level)
-
end
-
end
-
end
-
2
require "geocoder/lookups/test"
-
-
2
module Geocoder
-
2
module Lookup
-
2
extend self
-
-
##
-
# Array of valid Lookup service names.
-
#
-
2
def all_services
-
street_services + ip_services
-
end
-
-
##
-
# Array of valid Lookup service names, excluding :test.
-
#
-
2
def all_services_except_test
-
all_services - [:test]
-
end
-
-
##
-
# All street address lookup services, default first.
-
#
-
2
def street_services
-
@street_services ||= [
-
:dstk,
-
:esri,
-
:google,
-
:google_premier,
-
:google_places_details,
-
:bing,
-
:geocoder_ca,
-
:geocoder_us,
-
:yandex,
-
:nominatim,
-
:mapbox,
-
:mapquest,
-
:mapzen,
-
:opencagedata,
-
:ovi,
-
:pelias,
-
:here,
-
:baidu,
-
:geocodio,
-
:smarty_streets,
-
:okf,
-
:postcode_anywhere_uk,
-
:geoportail_lu,
-
:test,
-
:latlon
-
]
-
end
-
-
##
-
# All IP address lookup services, default first.
-
#
-
2
def ip_services
-
@ip_services ||= [
-
:baidu_ip,
-
:freegeoip,
-
:geoip2,
-
:maxmind,
-
:maxmind_local,
-
:telize,
-
:pointpin,
-
:maxmind_geoip2,
-
:ipinfo_io,
-
:ipapi_com
-
]
-
end
-
-
2
attr_writer :street_services, :ip_services
-
-
##
-
# Retrieve a Lookup object from the store.
-
# Use this instead of Geocoder::Lookup::X.new to get an
-
# already-configured Lookup object.
-
#
-
2
def get(name)
-
@services = {} unless defined?(@services)
-
@services[name] = spawn(name) unless @services.include?(name)
-
@services[name]
-
end
-
-
-
2
private # -----------------------------------------------------------------
-
-
##
-
# Spawn a Lookup of the given name.
-
#
-
2
def spawn(name)
-
if all_services.include?(name)
-
name = name.to_s
-
require "geocoder/lookups/#{name}"
-
Geocoder::Lookup.const_get(classify_name(name)).new
-
else
-
valids = all_services.map(&:inspect).join(", ")
-
raise ConfigurationError, "Please specify a valid lookup for Geocoder " +
-
"(#{name.inspect} is not one of: #{valids})."
-
end
-
end
-
-
##
-
# Convert an "underscore" version of a name into a "class" version.
-
#
-
2
def classify_name(filename)
-
filename.to_s.split("_").map{ |i| i[0...1].upcase + i[1..-1] }.join
-
end
-
end
-
end
-
2
require 'net/http'
-
2
require 'net/https'
-
2
require 'uri'
-
-
2
unless defined?(ActiveSupport::JSON)
-
begin
-
require 'rubygems' # for Ruby 1.8
-
require 'json'
-
rescue LoadError
-
raise LoadError, "Please install the 'json' or 'json_pure' gem to parse geocoder results."
-
end
-
end
-
-
2
module Geocoder
-
2
module Lookup
-
-
2
class Base
-
2
def initialize
-
@cache = nil
-
end
-
-
##
-
# Human-readable name of the geocoding API.
-
#
-
2
def name
-
fail
-
end
-
-
##
-
# Symbol which is used in configuration to refer to this Lookup.
-
#
-
2
def handle
-
str = self.class.to_s
-
str[str.rindex(':')+1..-1].gsub(/([a-z\d]+)([A-Z])/,'\1_\2').downcase.to_sym
-
end
-
-
##
-
# Query the geocoding API and return a Geocoder::Result object.
-
# Returns +nil+ on timeout or error.
-
#
-
# Takes a search string (eg: "Mississippi Coast Coliseumf, Biloxi, MS",
-
# "205.128.54.202") for geocoding, or coordinates (latitude, longitude)
-
# for reverse geocoding. Returns an array of <tt>Geocoder::Result</tt>s.
-
#
-
2
def search(query, options = {})
-
query = Geocoder::Query.new(query, options) unless query.is_a?(Geocoder::Query)
-
results(query).map{ |r|
-
result = result_class.new(r)
-
result.cache_hit = @cache_hit if cache
-
result
-
}
-
end
-
-
##
-
# Return the URL for a map of the given coordinates.
-
#
-
# Not necessarily implemented by all subclasses as only some lookups
-
# also provide maps.
-
#
-
2
def map_link_url(coordinates)
-
nil
-
end
-
-
##
-
# Array containing string descriptions of keys required by the API.
-
# Empty array if keys are optional or not required.
-
#
-
2
def required_api_key_parts
-
[]
-
end
-
-
##
-
# URL to use for querying the geocoding engine.
-
#
-
2
def query_url(query)
-
fail
-
end
-
-
##
-
# The working Cache object.
-
#
-
2
def cache
-
if @cache.nil? and store = configuration.cache
-
@cache = Cache.new(store, configuration.cache_prefix)
-
end
-
@cache
-
end
-
-
##
-
# Array containing the protocols supported by the api.
-
# Should be set to [:http] if only HTTP is supported
-
# or [:https] if only HTTPS is supported.
-
#
-
2
def supported_protocols
-
[:http, :https]
-
end
-
-
2
private # -------------------------------------------------------------
-
-
##
-
# An object with configuration data for this particular lookup.
-
#
-
2
def configuration
-
Geocoder.config_for_lookup(handle)
-
end
-
-
##
-
# Object used to make HTTP requests.
-
#
-
2
def http_client
-
proxy_name = "#{protocol}_proxy"
-
if proxy = configuration.send(proxy_name)
-
proxy_url = !!(proxy =~ /^#{protocol}/) ? proxy : protocol + '://' + proxy
-
begin
-
uri = URI.parse(proxy_url)
-
rescue URI::InvalidURIError
-
raise ConfigurationError,
-
"Error parsing #{protocol.upcase} proxy URL: '#{proxy_url}'"
-
end
-
Net::HTTP::Proxy(uri.host, uri.port, uri.user, uri.password)
-
else
-
Net::HTTP
-
end
-
end
-
-
##
-
# Geocoder::Result object or nil on timeout or other error.
-
#
-
2
def results(query)
-
fail
-
end
-
-
2
def query_url_params(query)
-
query.options[:params] || {}
-
end
-
-
2
def url_query_string(query)
-
hash_to_query(
-
query_url_params(query).reject{ |key,value| value.nil? }
-
)
-
end
-
-
##
-
# Key to use for caching a geocoding result. Usually this will be the
-
# request URL, but in cases where OAuth is used and the nonce,
-
# timestamp, etc varies from one request to another, we need to use
-
# something else (like the URL before OAuth encoding).
-
#
-
2
def cache_key(query)
-
query_url(query)
-
end
-
-
##
-
# Class of the result objects
-
#
-
2
def result_class
-
Geocoder::Result.const_get(self.class.to_s.split(":").last)
-
end
-
-
##
-
# Raise exception if configuration specifies it should be raised.
-
# Return false if exception not raised.
-
#
-
2
def raise_error(error, message = nil)
-
exceptions = configuration.always_raise
-
if exceptions == :all or exceptions.include?( error.is_a?(Class) ? error : error.class )
-
raise error, message
-
else
-
false
-
end
-
end
-
-
##
-
# Returns a parsed search result (Ruby hash).
-
#
-
2
def fetch_data(query)
-
parse_raw_data fetch_raw_data(query)
-
rescue SocketError => err
-
raise_error(err) or Geocoder.log(:warn, "Geocoding API connection cannot be established.")
-
rescue Errno::ECONNREFUSED => err
-
raise_error(err) or Geocoder.log(:warn, "Geocoding API connection refused.")
-
rescue Timeout::Error => err
-
raise_error(err) or Geocoder.log(:warn, "Geocoding API not responding fast enough " +
-
"(use Geocoder.configure(:timeout => ...) to set limit).")
-
end
-
-
2
def parse_json(data)
-
if defined?(ActiveSupport::JSON)
-
ActiveSupport::JSON.decode(data)
-
else
-
JSON.parse(data)
-
end
-
rescue
-
raise_error(ResponseParseError.new(data)) or Geocoder.log(:warn, "Geocoding API's response was not valid JSON: #{data}")
-
end
-
-
##
-
# Parses a raw search result (returns hash or array).
-
#
-
2
def parse_raw_data(raw_data)
-
parse_json(raw_data)
-
end
-
-
##
-
# Protocol to use for communication with geocoding services.
-
# Set in configuration but not available for every service.
-
#
-
2
def protocol
-
"http" + (use_ssl? ? "s" : "")
-
end
-
-
2
def valid_response?(response)
-
(200..399).include?(response.code.to_i)
-
end
-
-
##
-
# Fetch a raw geocoding result (JSON string).
-
# The result might or might not be cached.
-
#
-
2
def fetch_raw_data(query)
-
key = cache_key(query)
-
if cache and body = cache[key]
-
@cache_hit = true
-
else
-
check_api_key_configuration!(query)
-
response = make_api_request(query)
-
check_response_for_errors!(response)
-
body = response.body
-
-
# apply the charset from the Content-Type header, if possible
-
ct = response['content-type']
-
-
if ct && ct['charset']
-
charset = ct.split(';').select do |s|
-
s['charset']
-
end.first.to_s.split('=')
-
if charset.length == 2
-
body.force_encoding(charset.last) rescue ArgumentError
-
end
-
end
-
-
if cache and valid_response?(response)
-
cache[key] = body
-
end
-
@cache_hit = false
-
end
-
body
-
end
-
-
2
def check_response_for_errors!(response)
-
if response.code.to_i == 400
-
raise_error(Geocoder::InvalidRequest) ||
-
Geocoder.log(:warn, "Geocoding API error: 400 Bad Request")
-
elsif response.code.to_i == 401
-
raise_error(Geocoder::RequestDenied) ||
-
Geocoder.log(:warn, "Geocoding API error: 401 Unauthorized")
-
elsif response.code.to_i == 402
-
raise_error(Geocoder::OverQueryLimitError) ||
-
Geocoder.log(:warn, "Geocoding API error: 402 Payment Required")
-
elsif response.code.to_i == 429
-
raise_error(Geocoder::OverQueryLimitError) ||
-
Geocoder.log(:warn, "Geocoding API error: 429 Too Many Requests")
-
elsif response.code.to_i == 503
-
raise_error(Geocoder::ServiceUnavailable) ||
-
Geocoder.log(:warn, "Geocoding API error: 503 Service Unavailable")
-
end
-
end
-
-
##
-
# Make an HTTP(S) request to a geocoding API and
-
# return the response object.
-
#
-
2
def make_api_request(query)
-
uri = URI.parse(query_url(query))
-
Geocoder.log(:debug, "Geocoder: HTTP request being made for #{uri.to_s}")
-
http_client.start(uri.host, uri.port, use_ssl: use_ssl?, open_timeout: configuration.timeout, read_timeout: configuration.timeout) do |client|
-
req = Net::HTTP::Get.new(uri.request_uri, configuration.http_headers)
-
if configuration.basic_auth[:user] and configuration.basic_auth[:password]
-
req.basic_auth(
-
configuration.basic_auth[:user],
-
configuration.basic_auth[:password]
-
)
-
end
-
client.request(req)
-
end
-
rescue Timeout::Error
-
raise Geocoder::LookupTimeout
-
end
-
-
2
def use_ssl?
-
if supported_protocols == [:https]
-
true
-
elsif supported_protocols == [:http]
-
false
-
else
-
configuration.use_https
-
end
-
end
-
-
2
def check_api_key_configuration!(query)
-
key_parts = query.lookup.required_api_key_parts
-
if key_parts.size > Array(configuration.api_key).size
-
parts_string = key_parts.size == 1 ? key_parts.first : key_parts
-
raise Geocoder::ConfigurationError,
-
"The #{query.lookup.name} API requires a key to be configured: " +
-
parts_string.inspect
-
end
-
end
-
-
##
-
# Simulate ActiveSupport's Object#to_query.
-
# Removes any keys with nil value.
-
#
-
2
def hash_to_query(hash)
-
require 'cgi' unless defined?(CGI) && defined?(CGI.escape)
-
hash.collect{ |p|
-
p[1].nil? ? nil : p.map{ |i| CGI.escape i.to_s } * '='
-
}.compact.sort * '&'
-
end
-
end
-
end
-
end
-
2
require 'geocoder/lookups/base'
-
2
require 'geocoder/results/test'
-
-
2
module Geocoder
-
2
module Lookup
-
2
class Test < Base
-
-
2
def name
-
"Test"
-
end
-
-
2
def self.add_stub(query_text, results)
-
stubs[query_text] = results
-
end
-
-
2
def self.set_default_stub(results)
-
@default_stub = results
-
end
-
-
2
def self.read_stub(query_text)
-
stubs.fetch(query_text) {
-
return @default_stub unless @default_stub.nil?
-
raise ArgumentError, "unknown stub request #{query_text}"
-
}
-
end
-
-
2
def self.stubs
-
@stubs ||= {}
-
end
-
-
2
def self.reset
-
@stubs = {}
-
@default_stub = nil
-
end
-
-
2
private
-
-
2
def results(query)
-
Geocoder::Lookup::Test.read_stub(query.text)
-
end
-
-
end
-
end
-
end
-
2
require 'geocoder/models/base'
-
-
2
module Geocoder
-
2
module Model
-
2
module ActiveRecord
-
2
include Base
-
-
##
-
# Set attribute names and include the Geocoder module.
-
#
-
2
def geocoded_by(address_attr, options = {}, &block)
-
geocoder_init(
-
:geocode => true,
-
:user_address => address_attr,
-
:latitude => options[:latitude] || :latitude,
-
:longitude => options[:longitude] || :longitude,
-
:geocode_block => block,
-
:units => options[:units],
-
:method => options[:method],
-
:lookup => options[:lookup],
-
:language => options[:language]
-
)
-
end
-
-
##
-
# Set attribute names and include the Geocoder module.
-
#
-
2
def reverse_geocoded_by(latitude_attr, longitude_attr, options = {}, &block)
-
geocoder_init(
-
:reverse_geocode => true,
-
:fetched_address => options[:address] || :address,
-
:latitude => latitude_attr,
-
:longitude => longitude_attr,
-
:reverse_block => block,
-
:units => options[:units],
-
:method => options[:method],
-
:lookup => options[:lookup],
-
:language => options[:language]
-
)
-
end
-
-
-
2
private # --------------------------------------------------------------
-
-
2
def geocoder_file_name; "active_record"; end
-
2
def geocoder_module_name; "ActiveRecord"; end
-
end
-
end
-
end
-
-
2
module Geocoder
-
-
##
-
# Methods for invoking Geocoder in a model.
-
#
-
2
module Model
-
2
module Base
-
-
2
def geocoder_options
-
if defined?(@geocoder_options)
-
@geocoder_options
-
elsif superclass.respond_to?(:geocoder_options)
-
superclass.geocoder_options || { }
-
else
-
{ }
-
end
-
end
-
-
2
def geocoded_by
-
fail
-
end
-
-
2
def reverse_geocoded_by
-
fail
-
end
-
-
2
private # ----------------------------------------------------------------
-
-
2
def geocoder_init(options)
-
unless defined?(@geocoder_options)
-
@geocoder_options = {}
-
require "geocoder/stores/#{geocoder_file_name}"
-
include Geocoder::Store.const_get(geocoder_module_name)
-
end
-
@geocoder_options.merge! options
-
end
-
end
-
end
-
end
-
2
module Geocoder
-
2
class Query
-
2
attr_accessor :text, :options
-
-
2
def initialize(text, options = {})
-
self.text = text
-
self.options = options
-
end
-
-
2
def execute
-
lookup.search(text, options)
-
end
-
-
2
def to_s
-
text
-
end
-
-
2
def sanitized_text
-
if coordinates?
-
if text.is_a?(Array)
-
text.join(',')
-
else
-
text.split(/\s*,\s*/).join(',')
-
end
-
else
-
text
-
end
-
end
-
-
##
-
# Get a Lookup object (which communicates with the remote geocoding API)
-
# appropriate to the Query text.
-
#
-
2
def lookup
-
if !options[:street_address] and (options[:ip_address] or ip_address?)
-
name = options[:ip_lookup] || Configuration.ip_lookup || Geocoder::Lookup.ip_services.first
-
else
-
name = options[:lookup] || Configuration.lookup || Geocoder::Lookup.street_services.first
-
end
-
Lookup.get(name)
-
end
-
-
2
def url
-
lookup.query_url(self)
-
end
-
-
##
-
# Is the Query blank? (ie, should we not bother searching?)
-
# A query is considered blank if its text is nil or empty string AND
-
# no URL parameters are specified.
-
#
-
2
def blank?
-
!params_given? and (
-
(text.is_a?(Array) and text.compact.size < 2) or
-
text.to_s.match(/\A\s*\z/)
-
)
-
end
-
-
##
-
# Does the Query text look like an IP address?
-
#
-
# Does not check for actual validity, just the appearance of four
-
# dot-delimited numbers.
-
#
-
2
def ip_address?
-
IpAddress.new(text).valid? rescue false
-
end
-
-
##
-
# Is the Query text a loopback IP address?
-
#
-
2
def loopback_ip_address?
-
ip_address? && IpAddress.new(text).loopback?
-
end
-
-
##
-
# Does the given string look like latitude/longitude coordinates?
-
#
-
2
def coordinates?
-
text.is_a?(Array) or (
-
text.is_a?(String) and
-
!!text.to_s.match(/\A-?[0-9\.]+, *-?[0-9\.]+\z/)
-
)
-
end
-
-
##
-
# Return the latitude/longitude coordinates specified in the query,
-
# or nil if none.
-
#
-
2
def coordinates
-
sanitized_text.split(',') if coordinates?
-
end
-
-
##
-
# Should reverse geocoding be performed for this query?
-
#
-
2
def reverse_geocode?
-
coordinates?
-
end
-
-
2
def language
-
options[:language]
-
end
-
-
2
private # ----------------------------------------------------------------
-
-
2
def params_given?
-
!!(options[:params].is_a?(Hash) and options[:params].keys.size > 0)
-
end
-
end
-
end
-
2
require 'geocoder/models/active_record'
-
-
2
module Geocoder
-
2
if defined? Rails::Railtie
-
2
require 'rails'
-
2
class Railtie < Rails::Railtie
-
2
initializer 'geocoder.insert_into_active_record' do
-
2
ActiveSupport.on_load :active_record do
-
2
Geocoder::Railtie.insert
-
end
-
end
-
2
rake_tasks do
-
load "tasks/geocoder.rake"
-
load "tasks/maxmind.rake"
-
end
-
end
-
end
-
-
2
class Railtie
-
2
def self.insert
-
2
if defined?(::ActiveRecord)
-
2
::ActiveRecord::Base.extend(Model::ActiveRecord)
-
end
-
end
-
end
-
end
-
2
module Geocoder
-
2
module Request
-
-
# The location() method is vulnerable to trivial IP spoofing.
-
# Don't use it in authorization/authentication code, or any
-
# other security-sensitive application. Use safe_location
-
# instead.
-
2
def location
-
@location ||= Geocoder.search(geocoder_spoofable_ip, ip_address: true).first
-
end
-
-
# This safe_location() protects you from trivial IP spoofing.
-
# For requests that go through a proxy that you haven't
-
# whitelisted as trusted in your Rack config, you will get the
-
# location for the IP of the last untrusted proxy in the chain,
-
# not the original client IP. You WILL NOT get the location
-
# corresponding to the original client IP for any request sent
-
# through a non-whitelisted proxy.
-
2
def safe_location
-
@safe_location ||= Geocoder.search(ip, ip_address: true).first
-
end
-
-
# There's a whole zoo of nonstandard headers added by various
-
# proxy softwares to indicate original client IP.
-
# ANY of these can be trivially spoofed!
-
# (except REMOTE_ADDR, which should by set by your server,
-
# and is included at the end as a fallback.
-
# Order does matter: we're following the convention established in
-
# ActionDispatch::RemoteIp::GetIp::calculate_ip()
-
# https://github.com/rails/rails/blob/master/actionpack/lib/action_dispatch/middleware/remote_ip.rb
-
# where the forwarded_for headers, possibly containing lists,
-
# are arbitrarily preferred over headers expected to contain a
-
# single address.
-
2
GEOCODER_CANDIDATE_HEADERS = ['HTTP_X_FORWARDED_FOR',
-
'HTTP_X_FORWARDED',
-
'HTTP_FORWARDED_FOR',
-
'HTTP_FORWARDED',
-
'HTTP_X_CLIENT_IP',
-
'HTTP_CLIENT_IP',
-
'HTTP_X_REAL_IP',
-
'HTTP_X_CLUSTER_CLIENT_IP',
-
'REMOTE_ADDR']
-
-
2
def geocoder_spoofable_ip
-
-
# We could use a more sophisticated IP-guessing algorithm here,
-
# in which we'd try to resolve the use of different headers by
-
# different proxies. The idea is that by comparing IPs repeated
-
# in different headers, you can sometimes decide which header
-
# was used by a proxy further along in the chain, and thus
-
# prefer the headers used earlier. However, the gains might not
-
# be worth the performance tradeoff, since this method is likely
-
# to be called on every request in a lot of applications.
-
GEOCODER_CANDIDATE_HEADERS.each do |header|
-
if @env.has_key? header
-
addrs = geocoder_split_ip_addresses(@env[header])
-
addrs = geocoder_reject_trusted_ip_addresses(addrs)
-
return addrs.first if addrs.any?
-
end
-
end
-
-
@env['REMOTE_ADDR']
-
end
-
-
2
private
-
-
2
def geocoder_split_ip_addresses(ip_addresses)
-
ip_addresses ? ip_addresses.strip.split(/[,\s]+/) : []
-
end
-
-
# use Rack's trusted_proxy?() method to filter out IPs that have
-
# been configured as trusted; includes private ranges by
-
# default. (we don't want every lookup to return the location
-
# of our own proxy/load balancer)
-
2
def geocoder_reject_trusted_ip_addresses(ip_addresses)
-
ip_addresses.reject { |ip| trusted_proxy?(ip) }
-
end
-
end
-
end
-
-
2
if defined?(Rack) and defined?(Rack::Request)
-
2
Rack::Request.send :include, Geocoder::Request
-
end
-
2
module Geocoder
-
2
module Result
-
2
class Base
-
-
# data (hash) fetched from geocoding service
-
2
attr_accessor :data
-
-
# true if result came from cache, false if from request to geocoding
-
# service; nil if cache is not configured
-
2
attr_accessor :cache_hit
-
-
##
-
# Takes a hash of data from a parsed geocoding service response.
-
#
-
2
def initialize(data)
-
@data = data
-
@cache_hit = nil
-
end
-
-
##
-
# A string in the given format.
-
#
-
2
def address(format = :full)
-
fail
-
end
-
-
##
-
# A two-element array: [lat, lon].
-
#
-
2
def coordinates
-
[@data['latitude'].to_f, @data['longitude'].to_f]
-
end
-
-
2
def latitude
-
coordinates[0]
-
end
-
-
2
def longitude
-
coordinates[1]
-
end
-
-
2
def state
-
fail
-
end
-
-
2
def province
-
state
-
end
-
-
2
def state_code
-
fail
-
end
-
-
2
def province_code
-
state_code
-
end
-
-
2
def country
-
fail
-
end
-
-
2
def country_code
-
fail
-
end
-
end
-
end
-
end
-
2
require 'geocoder/results/base'
-
-
2
module Geocoder
-
2
module Result
-
2
class Test < Base
-
-
2
def self.add_result_attribute(attr)
-
36
begin
-
36
remove_method(attr) if method_defined?(attr)
-
rescue NameError # method defined on superclass
-
end
-
-
36
define_method(attr) do
-
@data[attr.to_s] || @data[attr.to_sym]
-
end
-
end
-
-
%w[latitude longitude neighborhood city state state_code sub_state
-
sub_state_code province province_code postal_code country
-
2
country_code address street_address street_number route geometry].each do |attr|
-
36
add_result_attribute(attr)
-
end
-
-
2
def initialize(data)
-
data.each_key do |attr|
-
Test.add_result_attribute(attr)
-
end
-
-
super
-
end
-
end
-
end
-
end
-
#
-
# = Hash Recursive Merge
-
#
-
# Merges a Ruby Hash recursively, Also known as deep merge.
-
# Recursive version of Hash#merge and Hash#merge!.
-
#
-
# Category:: Ruby
-
# Package:: Hash
-
# Author:: Simone Carletti <weppos@weppos.net>
-
# Copyright:: 2007-2008 The Authors
-
# License:: MIT License
-
# Link:: http://www.simonecarletti.com/
-
# Source:: http://gist.github.com/gists/6391/
-
#
-
2
module HashRecursiveMerge
-
-
#
-
# Recursive version of Hash#merge!
-
#
-
# Adds the contents of +other_hash+ to +hsh+,
-
# merging entries in +hsh+ with duplicate keys with those from +other_hash+.
-
#
-
# Compared with Hash#merge!, this method supports nested hashes.
-
# When both +hsh+ and +other_hash+ contains an entry with the same key,
-
# it merges and returns the values from both arrays.
-
#
-
# h1 = {"a" => 100, "b" => 200, "c" => {"c1" => 12, "c2" => 14}}
-
# h2 = {"b" => 254, "c" => {"c1" => 16, "c3" => 94}}
-
# h1.rmerge!(h2) #=> {"a" => 100, "b" => 254, "c" => {"c1" => 16, "c2" => 14, "c3" => 94}}
-
#
-
# Simply using Hash#merge! would return
-
#
-
# h1.merge!(h2) #=> {"a" => 100, "b" = >254, "c" => {"c1" => 16, "c3" => 94}}
-
#
-
2
def rmerge!(other_hash)
-
merge!(other_hash) do |key, oldval, newval|
-
oldval.class == self.class ? oldval.rmerge!(newval) : newval
-
end
-
end
-
-
#
-
# Recursive version of Hash#merge
-
#
-
# Compared with Hash#merge!, this method supports nested hashes.
-
# When both +hsh+ and +other_hash+ contains an entry with the same key,
-
# it merges and returns the values from both arrays.
-
#
-
# Compared with Hash#merge, this method provides a different approch
-
# for merging nasted hashes.
-
# If the value of a given key is an Hash and both +other_hash+ abd +hsh
-
# includes the same key, the value is merged instead replaced with
-
# +other_hash+ value.
-
#
-
# h1 = {"a" => 100, "b" => 200, "c" => {"c1" => 12, "c2" => 14}}
-
# h2 = {"b" => 254, "c" => {"c1" => 16, "c3" => 94}}
-
# h1.rmerge(h2) #=> {"a" => 100, "b" => 254, "c" => {"c1" => 16, "c2" => 14, "c3" => 94}}
-
#
-
# Simply using Hash#merge would return
-
#
-
# h1.merge(h2) #=> {"a" => 100, "b" = >254, "c" => {"c1" => 16, "c3" => 94}}
-
#
-
2
def rmerge(other_hash)
-
r = {}
-
merge(other_hash) do |key, oldval, newval|
-
r[key] = oldval.class == self.class ? oldval.rmerge(newval) : newval
-
end
-
end
-
-
end
-
-
-
2
class Hash
-
2
include HashRecursiveMerge
-
end
-
2
if defined?(::Rails)
-
2
require 'gmaps4rails/rails/engine' if ::Rails.version >= '3.1'
-
2
require 'gmaps4rails/rails/railtie'
-
end
-
2
require 'gmaps4rails/version'
-
-
2
module Gmaps4rails
-
2
autoload :MarkersBuilder, 'gmaps4rails/markers_builder'
-
-
2
module Rails
-
end
-
-
2
def Gmaps4rails.build_markers(collection, &block)
-
::Gmaps4rails::MarkersBuilder.new(collection).call(&block)
-
end
-
end
-
2
module Gmaps4rails
-
2
module Rails
-
2
class Engine < ::Rails::Engine
-
end
-
end
-
end
-
2
module Gmaps4rails
-
2
module Rails
-
2
class Railtie < ::Rails::Railtie
-
end
-
end
-
end
-
2
module Gmaps4rails
-
2
VERSION = "2.1.2"
-
end
-
2
require "thread"
-
2
require "listen"
-
-
2
require "guard/config"
-
2
require "guard/deprecated/guard" unless Guard::Config.new.strict?
-
2
require "guard/internals/helpers"
-
-
2
require "guard/internals/debugging"
-
2
require "guard/internals/traps"
-
2
require "guard/internals/queue"
-
-
# TODO: remove this class altogether
-
2
require "guard/interactor"
-
-
# Guard is the main module for all Guard related modules and classes.
-
# Also Guard plugins should use this namespace.
-
2
module Guard
-
2
Deprecated::Guard.add_deprecated(self) unless Config.new.strict?
-
-
2
class << self
-
2
attr_reader :state
-
2
attr_reader :queue
-
2
attr_reader :listener
-
2
attr_reader :interactor
-
-
# @private api
-
-
2
include Internals::Helpers
-
-
# Initializes the Guard singleton:
-
#
-
# * Initialize the internal Guard state;
-
# * Create the interactor
-
# * Select and initialize the file change listener.
-
#
-
# @option options [Boolean] clear if auto clear the UI should be done
-
# @option options [Boolean] notify if system notifications should be shown
-
# @option options [Boolean] debug if debug output should be shown
-
# @option options [Array<String>] group the list of groups to start
-
# @option options [Array<String>] watchdir the directories to watch
-
# @option options [String] guardfile the path to the Guardfile
-
#
-
# @return [Guard] the Guard singleton
-
2
def setup(cmdline_options = {})
-
init(cmdline_options)
-
-
@queue = Internals::Queue.new(Guard)
-
-
_evaluate(state.session.evaluator_options)
-
-
# NOTE: this should be *after* evaluate so :directories can work
-
# TODO: move listener setup to session?
-
@listener = Listen.send(*state.session.listener_args, &_listener_callback)
-
-
ignores = state.session.guardfile_ignore
-
@listener.ignore(ignores) unless ignores.empty?
-
-
ignores = state.session.guardfile_ignore_bang
-
@listener.ignore!(ignores) unless ignores.empty?
-
-
Notifier.connect(state.session.notify_options)
-
-
traps = Internals::Traps
-
traps.handle("USR1") { async_queue_add([:guard_pause, :paused]) }
-
traps.handle("USR2") { async_queue_add([:guard_pause, :unpaused]) }
-
-
@interactor = Interactor.new(state.session.interactor_name == :sleep)
-
traps.handle("INT") { @interactor.handle_interrupt }
-
-
self
-
end
-
-
2
def init(cmdline_options)
-
@state = Internals::State.new(cmdline_options)
-
end
-
-
# Asynchronously trigger changes
-
#
-
# Currently supported args:
-
#
-
# @example Old style hash:
-
# async_queue_add(modified: ['foo'], added: ['bar'], removed: [])
-
#
-
# @example New style signals with args:
-
# async_queue_add([:guard_pause, :unpaused ])
-
#
-
2
def async_queue_add(changes)
-
@queue << changes
-
-
# Putting interactor in background puts guard into foreground
-
# so it can handle change notifications
-
Thread.new { interactor.background }
-
end
-
-
2
private
-
-
# Check if any of the changes are actually watched for
-
# TODO: why iterate twice? reuse this info when running tasks
-
2
def _relevant_changes?(changes)
-
# TODO: no coverage!
-
files = changes.values.flatten(1)
-
scope = Guard.state.scope
-
watchers = scope.grouped_plugins.map do |_group, plugins|
-
plugins.map(&:watchers).flatten
-
end.flatten
-
watchers.any? { |watcher| files.any? { |file| watcher.match(file) } }
-
end
-
-
2
def _relative_pathnames(paths)
-
paths.map { |path| _relative_pathname(path) }
-
end
-
-
2
def _listener_callback
-
lambda do |modified, added, removed|
-
relative_paths = {
-
modified: _relative_pathnames(modified),
-
added: _relative_pathnames(added),
-
removed: _relative_pathnames(removed)
-
}
-
-
_guardfile_deprecated_check(relative_paths[:modified])
-
-
async_queue_add(relative_paths) if _relevant_changes?(relative_paths)
-
end
-
end
-
-
# TODO: obsoleted? (move to Dsl?)
-
2
def _pluginless_guardfile?
-
state.session.plugins.all.empty?
-
end
-
-
2
def _evaluate(options)
-
evaluator = Guardfile::Evaluator.new(options)
-
evaluator.evaluate
-
-
UI.reset_and_clear
-
-
msg = "No plugins found in Guardfile, please add at least one."
-
UI.error msg if _pluginless_guardfile?
-
-
if evaluator.inline?
-
UI.info("Using inline Guardfile.")
-
elsif evaluator.custom?
-
UI.info("Using Guardfile at #{ evaluator.path }.")
-
end
-
rescue Guardfile::Evaluator::NoPluginsError => e
-
UI.error(e.message)
-
end
-
-
# TODO: remove at some point
-
# TODO: not tested because collides with ongoing refactoring
-
2
def _guardfile_deprecated_check(modified)
-
modified.map!(&:to_s)
-
guardfiles = modified.select { |path| /^(?:.+\/)?Guardfile$/.match(path) }
-
return if guardfiles.empty?
-
-
guardfile = Pathname("Guardfile").realpath
-
real_guardfiles = guardfiles.detect do |path|
-
/^Guardfile$/.match(path) || Pathname(path).expand_path == guardfile
-
end
-
-
if real_guardfiles
-
UI.warning "Guardfile changed -- _guard-core will exit.\n"
-
exit 2 # nonzero to break any while loop
-
else # e.g. templates/Guardfile
-
msg = "Config changed: %s - Guard will exit so it can be restarted."
-
UI.info format(msg, guardfiles.inspect)
-
exit 0 # 0 so any shell while loop can continue
-
end
-
end
-
end
-
end
-
2
require "nenv"
-
-
2
module Guard
-
2
config_class = Nenv::Builder.build do
-
2
create_method(:strict?)
-
2
create_method(:gem_silence_deprecations?)
-
end
-
-
2
class Config < config_class
-
2
def initialize
-
24
super "guard"
-
end
-
-
2
def silence_deprecations?
-
gem_silence_deprecations?
-
end
-
end
-
end
-
2
require "guard/config"
-
2
fail "Deprecations disabled (strict mode)" if Guard::Config.new.strict?
-
-
2
module Guard
-
2
module Deprecated
-
2
module Dsl
-
2
def self.add_deprecated(dsl_klass)
-
2
dsl_klass.send(:extend, ClassMethods)
-
end
-
-
2
MORE_INFO_ON_UPGRADING_TO_GUARD_2 = <<-EOS.gsub(/^\s*/, "")
-
For more information on how to upgrade for Guard 2.0, please head over
-
to: https://github.com/guard/guard/wiki/Upgrading-to-Guard-2.0%s
-
EOS
-
-
2
module ClassMethods
-
# @deprecated Use
-
# `Guard::Guardfile::Evaluator.new(options).evaluate_guardfile`
-
# instead.
-
#
-
# @see https://github.com/guard/guard/wiki/Upgrading-to-Guard-2.0 How
-
# to upgrade for Guard 2.0
-
#
-
2
EVALUATE_GUARDFILE = <<-EOS.gsub(/^\s*/, "")
-
Starting with Guard 2.0 'Guard::Dsl.evaluate_guardfile(options)' is
-
deprecated.
-
-
Please use
-
'Guard::Guardfile::Evaluator.new(options).evaluate_guardfile'
-
instead.
-
-
#{MORE_INFO_ON_UPGRADING_TO_GUARD_2 % '#deprecated-methods-1'}
-
EOS
-
-
2
def evaluate_guardfile(options = {})
-
require "guard/guardfile/evaluator"
-
require "guard/ui"
-
-
UI.deprecation(EVALUATE_GUARDFILE)
-
::Guard::Guardfile::Evaluator.new(options).evaluate_guardfile
-
end
-
end
-
end
-
end
-
end
-
2
require "guard/config"
-
2
fail "Deprecations disabled (strict mode)" if Guard::Config.new.strict?
-
-
2
require "guard/ui"
-
-
2
module Guard
-
2
module Deprecated
-
2
module Evaluator
-
2
def self.add_deprecated(klass)
-
2
klass.send(:include, self)
-
end
-
-
2
EVALUATE_GUARDFILE = <<-EOS.gsub(/^\s*/, "")
-
Starting with Guard 2.8.3 'Guard::Evaluator#evaluate_guardfile' is
-
deprecated in favor of '#evaluate'.
-
EOS
-
-
2
REEVALUATE_GUARDFILE = <<-EOS.gsub(/^\s*/, "")
-
Starting with Guard 2.8.3 'Guard::Evaluator#reevaluate_guardfile' is
-
deprecated in favor of '#reevaluate'.
-
-
NOTE: this method no longer does anything since it could not be
-
implemented reliably.
-
EOS
-
-
2
def evaluate_guardfile
-
UI.deprecation(EVALUATE_GUARDFILE)
-
evaluate
-
end
-
-
2
def reevaluate_guardfile
-
# require guard only when needed, becuase
-
# guard's deprecations require us
-
require "guard"
-
UI.deprecation(REEVALUATE_GUARDFILE)
-
end
-
end
-
end
-
end
-
2
require "guard/config"
-
2
fail "Deprecations disabled (strict mode)" if Guard::Config.new.strict?
-
-
2
require "guard/ui"
-
2
require "guard/internals/session"
-
2
require "guard/internals/state"
-
2
require "guard/guardfile/evaluator"
-
-
2
module Guard
-
# @deprecated Every method in this module is deprecated
-
2
module Deprecated
-
2
module Guard
-
2
def self.add_deprecated(klass)
-
2
klass.send(:extend, ClassMethods)
-
end
-
-
2
module ClassMethods
-
2
MORE_INFO_ON_UPGRADING_TO_GUARD_2 = <<-EOS.gsub(/^\s*/, "")
-
For more information on how to upgrade for Guard 2.0, please head
-
over to: https://github.com/guard/guard/wiki/Upgrading-to-Guard-2.0%s
-
EOS
-
-
# @deprecated Use `Guard.plugins(filter)` instead.
-
#
-
# @see https://github.com/guard/guard/wiki/Upgrading-to-Guard-2.0 How to
-
# upgrade for Guard 2.0
-
#
-
2
GUARDS = <<-EOS.gsub(/^\s*/, "")
-
Starting with Guard 2.0 'Guard.guards(filter)' is deprecated.
-
-
Please use 'Guard.plugins(filter)' instead.
-
-
#{MORE_INFO_ON_UPGRADING_TO_GUARD_2 % '#deprecated-methods'}
-
EOS
-
-
2
def guards(filter = nil)
-
::Guard::UI.deprecation(GUARDS)
-
::Guard.state.session.plugins.all(filter)
-
end
-
-
# @deprecated Use `Guard.add_plugin(name, options = {})` instead.
-
#
-
# @see https://github.com/guard/guard/wiki/Upgrading-to-Guard-2.0 How to
-
# upgrade for Guard 2.0
-
#
-
2
ADD_GUARD = <<-EOS.gsub(/^\s*/, "")
-
Starting with Guard 2.0 'Guard.add_guard(name, options = {})' is
-
deprecated.
-
-
Please use 'Guard.add_plugin(name, options = {})' instead.
-
-
#{MORE_INFO_ON_UPGRADING_TO_GUARD_2 % '#deprecated-methods'}
-
EOS
-
-
2
def add_guard(*args)
-
::Guard::UI.deprecation(ADD_GUARD)
-
add_plugin(*args)
-
end
-
-
# @deprecated Use
-
# `Guard::PluginUtil.new(name).plugin_class(fail_gracefully:
-
# fail_gracefully)` instead.
-
#
-
# @see https://github.com/guard/guard/wiki/Upgrading-to-Guard-2.0 How to
-
# upgrade for Guard 2.0
-
#
-
2
GET_GUARD_CLASS = <<-EOS.gsub(/^\s*/, "")
-
Starting with Guard 2.0 'Guard.get_guard_class(name, fail_gracefully
-
= false)' is deprecated and is now always on.
-
-
Please use 'Guard::PluginUtil.new(name).plugin_class(fail_gracefully:
-
fail_gracefully)' instead.
-
-
#{MORE_INFO_ON_UPGRADING_TO_GUARD_2 % '#deprecated-methods'}
-
EOS
-
-
2
def get_guard_class(name, fail_gracefully = false)
-
UI.deprecation(GET_GUARD_CLASS)
-
PluginUtil.new(name).plugin_class(fail_gracefully: fail_gracefully)
-
end
-
-
# @deprecated Use `Guard::PluginUtil.new(name).plugin_location` instead.
-
#
-
# @see https://github.com/guard/guard/wiki/Upgrading-to-Guard-2.0 How to
-
# upgrade for Guard 2.0
-
#
-
2
LOCATE_GUARD = <<-EOS.gsub(/^\s*/, "")
-
Starting with Guard 2.0 'Guard.locate_guard(name)' is deprecated.
-
-
Please use 'Guard::PluginUtil.new(name).plugin_location' instead.
-
-
#{MORE_INFO_ON_UPGRADING_TO_GUARD_2 % '#deprecated-methods'}
-
EOS
-
-
2
def locate_guard(name)
-
UI.deprecation(LOCATE_GUARD)
-
PluginUtil.new(name).plugin_location
-
end
-
-
# @deprecated Use `Guard::PluginUtil.plugin_names` instead.
-
#
-
# @see https://github.com/guard/guard/wiki/Upgrading-to-Guard-2.0 How to
-
# upgrade for Guard 2.0
-
#
-
# Deprecator message for the `Guard.guard_gem_names` method
-
2
GUARD_GEM_NAMES = <<-EOS.gsub(/^\s*/, "")
-
Starting with Guard 2.0 'Guard.guard_gem_names' is deprecated.
-
-
Please use 'Guard::PluginUtil.plugin_names' instead.
-
-
#{MORE_INFO_ON_UPGRADING_TO_GUARD_2 % '#deprecated-methods'}
-
EOS
-
-
2
def guard_gem_names
-
UI.deprecation(GUARD_GEM_NAMES)
-
PluginUtil.plugin_names
-
end
-
-
2
RUNNING = <<-EOS.gsub(/^\s*/, "")
-
Starting with Guard 2.7.1 it was discovered that Guard.running was
-
never initialized or used internally.
-
EOS
-
-
2
def running
-
UI.deprecation(RUNNING)
-
nil
-
end
-
-
2
LOCK = <<-EOS.gsub(/^\s*/, "")
-
Starting with Guard 2.7.1 it was discovered that this accessor was
-
never initialized or used internally.
-
EOS
-
2
def lock
-
UI.deprecation(LOCK)
-
end
-
-
2
LISTENER_ASSIGN = <<-EOS.gsub(/^\s*/, "")
-
listener= should not be used
-
EOS
-
-
2
def listener=(_)
-
UI.deprecation(LISTENER_ASSIGN)
-
::Guard.listener
-
end
-
-
2
EVALUATOR = <<-EOS.gsub(/^\s*/, "")
-
Starting with Guard 2.8.2 this method shouldn't be used
-
EOS
-
-
2
def evaluator
-
UI.deprecation(EVALUATOR)
-
options = ::Guard.state.session.evaluator_options
-
::Guard::Guardfile::Evaluator.new(options)
-
end
-
-
2
RESET_EVALUATOR = <<-EOS.gsub(/^\s*/, "")
-
Starting with Guard 2.8.2 this method shouldn't be used
-
EOS
-
-
2
def reset_evaluator(_options)
-
UI.deprecation(RESET_EVALUATOR)
-
end
-
-
2
RUNNER = <<-EOS.gsub(/^\s*/, "")
-
Starting with Guard 2.8.2 this method shouldn't be used
-
EOS
-
-
2
def runner
-
UI.deprecation(RUNNER)
-
::Guard::Runner.new
-
end
-
-
2
EVALUATE_GUARDFILE = <<-EOS.gsub(/^\s*/, "")
-
Starting with Guard 2.8.2 this method shouldn't be used
-
EOS
-
-
2
def evaluate_guardfile
-
UI.deprecation(EVALUATE_GUARDFILE)
-
options = ::Guard.state.session.evaluator_options
-
evaluator = ::Guard::Guardfile::Evaluator.new(options)
-
evaluator.evaluate
-
msg = "No plugins found in Guardfile, please add at least one."
-
::Guard::UI.error msg if _pluginless_guardfile?
-
end
-
-
2
OPTIONS = <<-EOS.gsub(/^\s*/, "")
-
Starting with Guard 2.9.0 Guard.options is deprecated and ideally you
-
should be able to set specific options through an API or a DSL
-
method. Feel free to add feature requests if there's something
-
missing.
-
EOS
-
-
2
def options
-
UI.deprecation(OPTIONS)
-
-
Class.new(Hash) do
-
def initialize
-
super(to_hash)
-
end
-
-
def to_hash
-
session = ::Guard.state.session
-
{
-
clear: session.clearing?,
-
debug: session.debug?,
-
watchdir: Array(session.watchdirs).map(&:to_s),
-
notify: session.notify_options[:notify],
-
no_interactions: (session.interactor_name == :sleep)
-
}
-
end
-
-
def to_a
-
to_hash.to_a
-
end
-
-
def fetch(key, *args)
-
hash = to_hash
-
verify_key!(hash, key)
-
hash.fetch(key, *args)
-
end
-
-
def []=(key, value)
-
case key
-
when :clear
-
::Guard.state.session.clearing(value)
-
else
-
msg = "Oops! Guard.option[%s]= is unhandled or unsupported." \
-
"Please file an issue if you rely on this option working."
-
fail NotImplementedError, format(msg, key)
-
end
-
end
-
-
def keys
-
to_hash.keys
-
end
-
-
def include?(value)
-
keys.include? value
-
end
-
-
private
-
-
def verify_key!(hash, key)
-
return if hash.key?(key)
-
msg = "Oops! Guard.option[%s] is unhandled or unsupported." \
-
"Please file an issue if you rely on this option working."
-
fail NotImplementedError, format(msg, key)
-
end
-
end.new
-
end
-
-
2
ADD_GROUP = <<-EOS.gsub(/^\s*/, "")
-
add_group is deprecated since 2.10.0 in favor of
-
Guard.state.session.groups.add
-
EOS
-
-
2
def add_group(name, options = {})
-
UI.deprecation(ADD_GROUP)
-
::Guard.state.session.groups.add(name, options)
-
end
-
-
2
ADD_PLUGIN = <<-EOS.gsub(/^\s*/, "")
-
add_plugin is deprecated since 2.10.0 in favor of
-
Guard.state.session.plugins.add
-
EOS
-
-
2
def add_plugin(name, options = {})
-
UI.deprecation(ADD_PLUGIN)
-
::Guard.state.session.plugins.add(name, options)
-
end
-
-
2
GROUP = <<-EOS.gsub(/^\s*/, "")
-
group is deprecated since 2.10.0 in favor of
-
Guard.state.session.group.add(filter).first
-
EOS
-
-
2
def group(filter)
-
UI.deprecation(GROUP)
-
::Guard.state.session.groups.all(filter).first
-
end
-
-
2
PLUGIN = <<-EOS.gsub(/^\s*/, "")
-
plugin is deprecated since 2.10.0 in favor of
-
Guard.state.session.group.add(filter).first
-
EOS
-
-
2
def plugin(filter)
-
UI.deprecation(PLUGIN)
-
::Guard.state.session.plugins.all(filter).first
-
end
-
-
2
GROUPS = <<-EOS.gsub(/^\s*/, "")
-
group is deprecated since 2.10.0 in favor of
-
Guard.state.session.groups.all(filter)
-
EOS
-
-
2
def groups(filter)
-
UI.deprecation(GROUPS)
-
::Guard.state.session.groups.all(filter)
-
end
-
-
2
PLUGINS = <<-EOS.gsub(/^\s*/, "")
-
plugins is deprecated since 2.10.0 in favor of
-
Guard.state.session.plugins.all(filter)
-
EOS
-
-
2
def plugins(filter)
-
UI.deprecation(PLUGINS)
-
::Guard.state.session.plugins.all(filter)
-
end
-
-
2
SCOPE = <<-EOS.gsub(/^\s*/, "")
-
scope is deprecated since 2.10.0 in favor of
-
Guard.state.scope.to_hash
-
EOS
-
-
2
def scope
-
UI.deprecation(SCOPE)
-
::Guard.state.scope.to_hash
-
end
-
-
2
SCOPE_ASSIGN = <<-EOS.gsub(/^\s*/, "")
-
scope= is deprecated since 2.10.0 in favor of
-
Guard.state.scope.to_hash
-
EOS
-
-
2
def scope=(scope)
-
UI.deprecation(SCOPE_ASSIGN)
-
::Guard.state.scope.from_interactor(scope)
-
end
-
end
-
end
-
end
-
end
-
2
require "guard/config"
-
2
fail "Deprecations disabled (strict mode)" if Guard::Config.new.strict?
-
-
2
module Guard
-
2
module Deprecated
-
2
module Watcher
-
2
def self.add_deprecated(dsl_klass)
-
2
dsl_klass.send(:extend, ClassMethods)
-
end
-
-
2
module ClassMethods
-
2
MATCH_GUARDFILE = <<-EOS.gsub(/^\s*/, "")
-
Starting with Guard 2.8.3 this method is deprecated.
-
EOS
-
-
2
def match_guardfile?(files)
-
require "guard/guardfile/evaluator"
-
UI.deprecation(MATCH_GUARDFILE)
-
options = ::Guard.state.session.evaluator_options
-
evaluator = ::Guard::Guardfile::Evaluator.new(options)
-
path = evaluator.guardfile_path
-
files.any? { |file| File.expand_path(file) == path }
-
end
-
end
-
end
-
end
-
end
-
2
require "guard/guardfile/evaluator"
-
2
require "guard/interactor"
-
2
require "guard/notifier"
-
2
require "guard/ui"
-
2
require "guard/watcher"
-
-
2
require "guard/deprecated/dsl" unless Guard::Config.new.strict?
-
2
require "guard"
-
-
2
module Guard
-
# The Dsl class provides the methods that are used in each `Guardfile` to
-
# describe the behaviour of Guard.
-
#
-
# The main keywords of the DSL are {#guard} and {#watch}. These are necessary
-
# to define the used Guard plugins and the file changes they are watching.
-
#
-
# You can optionally group the Guard plugins with the {#group} keyword and
-
# ignore and filter certain paths with the {#ignore} and {#filter} keywords.
-
#
-
# You can set your preferred system notification library with {#notification}
-
# and pass some optional configuration options for the library. If you don't
-
# configure a library, Guard will automatically pick one with default options
-
# (if you don't want notifications, specify `:off` as library). Please see
-
# {Notifier} for more information about the supported libraries.
-
#
-
# A more advanced DSL use is the {#callback} keyword that allows you to
-
# execute arbitrary code before or after any of the {Plugin#start},
-
# {Plugin#stop}, {Plugin#reload}, {Plugin#run_all},
-
# {Plugin#run_on_changes}, {Plugin#run_on_additions},
-
# {Plugin#run_on_modifications} and {Plugin#run_on_removals}
-
# Guard plugins method.
-
# You can even insert more hooks inside these methods. Please [checkout the
-
# Wiki page](https://github.com/guard/guard/wiki/Hooks-and-callbacks) for
-
# more details.
-
#
-
# The DSL will also evaluate normal Ruby code.
-
#
-
# There are two possible locations for the `Guardfile`:
-
#
-
# * The `Guardfile` in the current directory where Guard has been started
-
# * The `.Guardfile` in your home directory.
-
#
-
# In addition, if a user configuration `.guard.rb` in your home directory is
-
# found, it will be appended to the current project `Guardfile`.
-
#
-
# @see https://github.com/guard/guard/wiki/Guardfile-examples
-
#
-
2
class Dsl
-
2
Deprecated::Dsl.add_deprecated(self) unless Config.new.strict?
-
-
# Wrap exceptions during parsing Guardfile
-
2
class Error < RuntimeError
-
end
-
-
2
WARN_INVALID_LOG_LEVEL = "Invalid log level `%s` ignored. "\
-
"Please use either :debug, :info, :warn or :error."
-
-
2
WARN_INVALID_LOG_OPTIONS = "You cannot specify the logger options"\
-
" :only and :except at the same time."
-
-
# Set notification options for the system notifications.
-
# You can set multiple notifications, which allows you to show local
-
# system notifications and remote notifications with separate libraries.
-
# You can also pass `:off` as library to turn off notifications.
-
#
-
# @example Define multiple notifications
-
# notification :ruby_gntp
-
# notification :ruby_gntp, host: '192.168.1.5'
-
#
-
# @param [Symbol, String] notifier the name of the notifier to use
-
# @param [Hash] options the notification library options
-
#
-
# @see Guard::Notifier for available notifier and its options.
-
#
-
2
def notification(notifier, opts = {})
-
Guard.state.session.guardfile_notification = { notifier.to_sym => opts }
-
end
-
-
# Sets the interactor options or disable the interactor.
-
#
-
# @example Pass options to the interactor
-
# interactor option1: 'value1', option2: 'value2'
-
#
-
# @example Turn off interactions
-
# interactor :off
-
#
-
# @param [Symbol, Hash] options either `:off` or a Hash with interactor
-
# options
-
#
-
2
def interactor(options)
-
# TODO: remove dependency on Interactor (let session handle this)
-
case options
-
when :off
-
Interactor.enabled = false
-
when Hash
-
Interactor.options = options
-
end
-
end
-
-
# Declares a group of Guard plugins to be run with `guard start --group
-
# group_name`.
-
#
-
# @example Declare two groups of Guard plugins
-
# group :backend do
-
# guard :spork
-
# guard :rspec
-
# end
-
#
-
# group :frontend do
-
# guard :passenger
-
# guard :livereload
-
# end
-
#
-
# @param [Symbol, String, Array<Symbol, String>] name the group name called
-
# from the CLI
-
# @param [Hash] options the options accepted by the group
-
# @yield a block where you can declare several Guard plugins
-
#
-
# @see Group
-
# @see Guard.add_group
-
# @see #guard
-
#
-
2
def group(*args)
-
options = args.last.is_a?(Hash) ? args.pop : {}
-
groups = args
-
-
groups.each do |group|
-
next unless group.to_sym == :all
-
fail ArgumentError, "'all' is not an allowed group name!"
-
end
-
-
if block_given?
-
groups.each do |group|
-
# TODO: let groups be added *after* evaluation
-
Guard.state.session.groups.add(group, options)
-
end
-
-
@current_groups ||= []
-
@current_groups.push(groups)
-
-
yield
-
-
@current_groups.pop
-
else
-
UI.error \
-
"No Guard plugins found in the group '#{ groups.join(', ') }',"\
-
" please add at least one."
-
end
-
end
-
-
# Declares a Guard plugin to be used when running `guard start`.
-
#
-
# The name parameter is usually the name of the gem without
-
# the 'guard-' prefix.
-
#
-
# The available options are different for each Guard implementation.
-
#
-
# @example Declare a Guard without `watch` patterns
-
# guard :rspec
-
#
-
# @example Declare a Guard with a `watch` pattern
-
# guard :rspec do
-
# watch %r{.*_spec.rb}
-
# end
-
#
-
# @param [String] name the Guard plugin name
-
# @param [Hash] options the options accepted by the Guard plugin
-
# @yield a block where you can declare several watch patterns and actions
-
#
-
# @see Plugin
-
# @see Guard.add_plugin
-
# @see #watch
-
# @see #group
-
#
-
2
def guard(name, options = {})
-
@plugin_options = options.merge(watchers: [], callbacks: [])
-
-
yield if block_given?
-
-
@current_groups ||= []
-
groups = @current_groups && @current_groups.last || [:default]
-
groups.each do |group|
-
opts = @plugin_options.merge(group: group)
-
# TODO: let plugins be added *after* evaluation
-
Guard.state.session.plugins.add(name, opts)
-
end
-
-
@plugin_options = nil
-
end
-
-
# Defines a pattern to be watched in order to run actions on file
-
# modification.
-
#
-
# @example Declare watchers for a Guard
-
# guard :rspec do
-
# watch('spec/spec_helper.rb')
-
# watch(%r{^.+_spec.rb})
-
# watch(%r{^app/controllers/(.+).rb}) do |m|
-
# 'spec/acceptance/#{m[1]}s_spec.rb'
-
# end
-
# end
-
#
-
# @example Declare global watchers outside of a Guard
-
# watch(%r{^(.+)$}) { |m| puts "#{m[1]} changed." }
-
#
-
# @param [String, Regexp] pattern the pattern that Guard must watch for
-
# modification
-
#
-
# @yield a block to be run when the pattern is matched
-
# @yieldparam [MatchData] m matches of the pattern
-
# @yieldreturn a directory, a filename, an array of
-
# directories / filenames, or nothing (can be an arbitrary command)
-
#
-
# @see Guard::Watcher
-
# @see #guard
-
#
-
2
def watch(pattern, &action)
-
# Allow watches in the global scope (to execute arbitrary commands) by
-
# building a generic Guard::Plugin.
-
@plugin_options ||= nil
-
return guard(:plugin) { watch(pattern, &action) } unless @plugin_options
-
-
@plugin_options[:watchers] << Watcher.new(pattern, action)
-
end
-
-
# Defines a callback to execute arbitrary code before or after any of
-
# the `start`, `stop`, `reload`, `run_all`, `run_on_changes`,
-
# `run_on_additions`, `run_on_modifications` and `run_on_removals` plugin
-
# method.
-
#
-
# @example Add callback before the `reload` action.
-
# callback(:reload_begin) { puts "Let's reload!" }
-
#
-
# @example Add callback before the `start` and `stop` actions.
-
#
-
# my_lambda = lambda do |plugin, event, *args|
-
# puts "Let's #{event} #{plugin} with #{args}!"
-
# end
-
#
-
# callback(my_lambda, [:start_begin, :start_end])
-
#
-
# @param [Array] args the callback arguments
-
# @yield a callback block
-
#
-
2
def callback(*args, &block)
-
@plugin_options ||= nil
-
fail "callback must be called within a guard block" unless @plugin_options
-
-
block, events = if args.size > 1
-
# block must be the first argument in that case, the
-
# yielded block is ignored
-
args
-
else
-
[block, args[0]]
-
end
-
@plugin_options[:callbacks] << { events: events, listener: block }
-
end
-
-
# Ignores certain paths globally.
-
#
-
# @example Ignore some paths
-
# ignore %r{^ignored/path/}, /man/
-
#
-
# @param [Regexp] regexps a pattern (or list of patterns) for ignoring paths
-
#
-
2
def ignore(*regexps)
-
# TODO: use guardfile results class
-
Guard.state.session.guardfile_ignore = regexps
-
end
-
-
# TODO: deprecate
-
2
alias filter ignore
-
-
# Replaces ignored paths globally
-
#
-
# @example Ignore only these paths
-
# ignore! %r{^ignored/path/}, /man/
-
#
-
# @param [Regexp] regexps a pattern (or list of patterns) for ignoring paths
-
#
-
2
def ignore!(*regexps)
-
@ignore_regexps ||= []
-
@ignore_regexps << regexps
-
# TODO: use guardfile results class
-
Guard.state.session.guardfile_ignore_bang = @ignore_regexps
-
end
-
-
# TODO: deprecate
-
2
alias filter! ignore!
-
-
# Configures the Guard logger.
-
#
-
# * Log level must be either `:debug`, `:info`, `:warn` or `:error`.
-
# * Template supports the following placeholders: `:time`, `:severity`,
-
# `:progname`, `:pid`, `:unit_of_work_id` and `:message`.
-
# * Time format directives are the same as `Time#strftime` or
-
# `:milliseconds`.
-
# * The `:only` and `:except` options must be a `RegExp`.
-
#
-
# @example Set the log level
-
# logger level: :warn
-
#
-
# @example Set a custom log template
-
# logger template: '[Guard - :severity - :progname - :time] :message'
-
#
-
# @example Set a custom time format
-
# logger time_format: '%h'
-
#
-
# @example Limit logging to a Guard plugin
-
# logger only: :jasmine
-
#
-
# @example Log all but not the messages from a specific Guard plugin
-
# logger except: :jasmine
-
#
-
# @param [Hash] options the log options
-
# @option options [String, Symbol] level the log level
-
# @option options [String] template the logger template
-
# @option options [String, Symbol] time_format the time format
-
# @option options [Regexp] only show only messages from the matching Guard
-
# plugin
-
# @option options [Regexp] except does not show messages from the matching
-
# Guard plugin
-
#
-
2
def logger(options)
-
if options[:level]
-
options[:level] = options[:level].to_sym
-
-
unless [:debug, :info, :warn, :error].include? options[:level]
-
UI.warning WARN_INVALID_LOG_LEVEL % [options[:level]]
-
options.delete :level
-
end
-
end
-
-
if options[:only] && options[:except]
-
UI.warning WARN_INVALID_LOG_OPTIONS
-
-
options.delete :only
-
options.delete :except
-
end
-
-
# Convert the :only and :except options to a regular expression
-
[:only, :except].each do |name|
-
next unless options[name]
-
-
list = [].push(options[name]).flatten.map do |plugin|
-
Regexp.escape(plugin.to_s)
-
end
-
-
options[name] = Regexp.new(list.join("|"), Regexp::IGNORECASE)
-
end
-
-
UI.options.merge!(options)
-
end
-
-
# Sets the default scope on startup
-
#
-
# @example Scope Guard to a single group
-
# scope group: :frontend
-
#
-
# @example Scope Guard to multiple groups
-
# scope groups: [:specs, :docs]
-
#
-
# @example Scope Guard to a single plugin
-
# scope plugin: :test
-
#
-
# @example Scope Guard to multiple plugins
-
# scope plugins: [:jasmine, :rspec]
-
#
-
# @param [Hash] scopes the scope for the groups and plugins
-
#
-
2
def scope(scope = {})
-
# TODO: use a Guardfile::Results class
-
Guard.state.session.guardfile_scope(scope)
-
end
-
-
2
def evaluate(contents, filename, lineno) # :nodoc
-
instance_eval(contents, filename.to_s, lineno)
-
rescue StandardError, ScriptError => e
-
prefix = "\n\t(dsl)> "
-
cleaned_backtrace = _cleanup_backtrace(e.backtrace)
-
backtrace = "#{prefix}#{cleaned_backtrace.join(prefix)}"
-
msg = "Invalid Guardfile, original error is: \n\n%s, \nbacktrace: %s"
-
raise Error, format(msg, e, backtrace)
-
end
-
-
# Sets the directories to pass to Listen
-
#
-
# @example watch only given directories
-
# directories %w(lib specs)
-
#
-
# @param [Array] directories directories for Listen to watch
-
#
-
2
def directories(directories)
-
directories.each do |dir|
-
fail "Directory #{dir.inspect} does not exist!" unless Dir.exist?(dir)
-
end
-
Guard.state.session.watchdirs = directories
-
end
-
-
# Sets Guard to clear the screen before every task is run
-
#
-
# @example switching clearing the screen on
-
# clearing(:on)
-
#
-
# @param [Symbol] on ':on' to turn on, ':off' (default) to turn off
-
#
-
2
def clearing(on)
-
Guard.state.session.clearing(on == :on)
-
end
-
-
2
private
-
-
2
def _cleanup_backtrace(backtrace)
-
dirs = { File.realpath(Dir.pwd) => ".", }
-
-
gem_env = ENV["GEM_HOME"] || ""
-
dirs[gem_env] = "$GEM_HOME" unless gem_env.empty?
-
-
gem_paths = (ENV["GEM_PATH"] || "").split(File::PATH_SEPARATOR)
-
gem_paths.each_with_index do |path, index|
-
dirs[path] = "$GEM_PATH[#{index}]"
-
end
-
-
backtrace.dup.map do |raw_line|
-
path = nil
-
symlinked_path = raw_line.split(":").first
-
begin
-
path = raw_line.sub(symlinked_path, File.realpath(symlinked_path))
-
dirs.detect { |dir, name| path.sub!(File.realpath(dir), name) }
-
path
-
rescue Errno::ENOENT
-
path || symlinked_path
-
end
-
end
-
end
-
end
-
end
-
2
require "guard/dsl"
-
-
2
module Guard
-
# TODO: this should probably be a base class for Dsl instead (in Guard 3.x)
-
2
class DslReader < Dsl
-
2
attr_reader :plugin_names
-
-
2
def initialize
-
super
-
@plugin_names = []
-
end
-
-
2
def guard(name, _options = {})
-
@plugin_names << name.to_s
-
end
-
-
# Stub everything else
-
2
def notification(_notifier, _opts = {})
-
end
-
-
2
def interactor(_options)
-
end
-
-
2
def group(*_args)
-
end
-
-
2
def watch(_pattern, &_action)
-
end
-
-
2
def callback(*_args, &_block)
-
end
-
-
2
def ignore(*_regexps)
-
end
-
-
2
def ignore!(*_regexps)
-
end
-
-
2
def logger(_options)
-
end
-
-
2
def scope(_scope = {})
-
end
-
-
2
def directories(_directories)
-
end
-
-
2
def clearing(_on)
-
end
-
end
-
end
-
2
module Guard
-
# A group of Guard plugins. There are two reasons why you want to group your
-
# Guard plugins:
-
#
-
# * You can start only certain groups from the command line by passing the
-
# `--group` option to `guard start`.
-
# * Abort task execution chain on failure within a group with the
-
# `:halt_on_fail` option.
-
#
-
# @example Group that aborts on failure
-
#
-
# group :frontend, halt_on_fail: true do
-
# guard 'coffeescript', input: 'spec/coffeescripts',
-
# output: 'spec/javascripts'
-
# guard 'jasmine-headless-webkit' do
-
# watch(%r{^spec/javascripts/(.*)\..*}) do |m|
-
# newest_js_file("spec/javascripts/#{m[1]}_spec")
-
# end
-
# end
-
# end
-
#
-
# @see Guard::CLI
-
#
-
2
class Group
-
2
attr_accessor :name, :options
-
-
# Initializes a Group.
-
#
-
# @param [String] name the name of the group
-
# @param [Hash] options the group options
-
# @option options [Boolean] halt_on_fail if a task execution
-
# should be halted for all Guard plugins in this group if a Guard plugin
-
# throws `:task_has_failed`
-
#
-
2
def initialize(name, options = {})
-
@name = name.to_sym
-
@options = options
-
end
-
-
# Returns the group title.
-
#
-
# @example Title for a group named 'backend'
-
# > Guard::Group.new('backend').title
-
# => "Backend"
-
#
-
# @return [String]
-
#
-
2
def title
-
@title ||= name.to_s.capitalize
-
end
-
-
# String representation of the group.
-
#
-
# @example String representation of a group named 'backend'
-
# > Guard::Group.new('backend').to_s
-
# => "#<Guard::Group @name=backend @options={}>"
-
#
-
# @return [String] the string representation
-
#
-
2
def to_s
-
"#<#{self.class} @name=#{name} @options=#{options}>"
-
end
-
end
-
end
-
2
require "guard/config"
-
2
require "guard/deprecated/evaluator" unless Guard::Config.new.strict?
-
-
2
require "guard/options"
-
2
require "guard/plugin"
-
-
2
require "guard/dsl"
-
2
require "guard/dsl_reader"
-
-
2
module Guard
-
2
module Guardfile
-
# This class is responsible for evaluating the Guardfile. It delegates to
-
# Guard::Dsl for the actual objects generation from the Guardfile content.
-
#
-
# @see Guard::Dsl
-
#
-
# TODO: rename this to a Locator or Loader or something
-
2
class Evaluator
-
2
Deprecated::Evaluator.add_deprecated(self) unless Config.new.strict?
-
-
2
ERROR_NO_GUARDFILE = "No Guardfile found,"\
-
" please create one with `guard init`."
-
-
2
attr_reader :options, :guardfile_path
-
-
2
ERROR_NO_PLUGINS = "No Guard plugins found in Guardfile,"\
-
" please add at least one."
-
-
2
class Error < RuntimeError
-
end
-
-
2
class NoGuardfileError < Error
-
end
-
-
2
class NoCustomGuardfile < Error
-
end
-
-
2
class NoPluginsError < Error
-
end
-
-
2
def guardfile_source
-
@source
-
end
-
-
# Initializes a new Guard::Guardfile::Evaluator object.
-
#
-
# @option opts [String] guardfile the path to a valid Guardfile
-
# @option opts [String] contents a string representing the
-
# content of a valid Guardfile
-
#
-
2
def initialize(opts = {})
-
@type = nil
-
@path = nil
-
@user_config = nil
-
-
opts = _from_deprecated(opts)
-
-
if opts[:contents]
-
@type = :inline
-
@contents = opts[:contents]
-
else
-
if opts[:guardfile]
-
@type = :custom
-
@path = Pathname(opts[:guardfile]) # may be updated by _read
-
end
-
end
-
end
-
-
# Evaluates the DSL methods in the `Guardfile`.
-
#
-
# @example Programmatically evaluate a Guardfile
-
# Guard::Guardfile::Evaluator.new.evaluate
-
#
-
# @example Programmatically evaluate a Guardfile with a custom Guardfile
-
# path
-
#
-
# options = { guardfile: '/Users/guardfile/MyAwesomeGuardfile' }
-
# Guard::Guardfile::Evaluator.new(options).evaluate
-
#
-
# @example Programmatically evaluate a Guardfile with an inline Guardfile
-
#
-
# options = { contents: 'guard :rspec' }
-
# Guard::Guardfile::Evaluator.new(options).evaluate
-
#
-
2
def evaluate
-
inline? || _use_provided || _use_default!
-
-
contents = _guardfile_contents
-
fail NoPluginsError, ERROR_NO_PLUGINS unless /guard/m =~ contents
-
-
Dsl.new.evaluate(contents, @path || "", 1)
-
end
-
-
# Tests if the current `Guardfile` contains a specific Guard plugin.
-
#
-
# @example Programmatically test if a Guardfile contains a specific Guard
-
# plugin
-
#
-
# File.read('Guardfile')
-
# => "guard :rspec"
-
#
-
# Guard::Guardfile::Evaluator.new.guardfile_include?('rspec)
-
# => true
-
#
-
# @param [String] plugin_name the name of the Guard
-
# @return [Boolean] whether the Guard plugin has been declared
-
#
-
# TODO: rename this method to it matches RSpec examples better
-
2
def guardfile_include?(plugin_name)
-
reader = DslReader.new
-
reader.evaluate(@contents, @path || "", 1)
-
reader.plugin_names.include?(plugin_name)
-
end
-
-
2
attr_reader :path
-
-
2
def custom?
-
@type == :custom
-
end
-
-
# Gets the content of the `Guardfile` concatenated with the global
-
# user configuration file.
-
#
-
# @example Programmatically get the content of the current Guardfile
-
# Guard::Guardfile::Evaluator.new.guardfile_contents
-
# => "guard :rspec"
-
#
-
# @return [String] the Guardfile content
-
#
-
2
def guardfile_contents
-
config = File.read(_user_config_path) if File.exist?(_user_config_path)
-
[_guardfile_contents_without_user_config, config].compact.join("\n")
-
end
-
-
2
def inline?
-
@type == :inline
-
end
-
-
2
private
-
-
2
def _guardfile_contents_without_user_config
-
@guardfile_contents || ""
-
end
-
-
2
def _instance_eval_guardfile(contents)
-
Dsl.new.evaluate(contents, @guardfile_path || "", 1)
-
rescue => ex
-
UI.error "Invalid Guardfile, original error is:\n#{ $! }"
-
raise ex
-
end
-
-
2
def _fetch_guardfile_contents
-
_use_inline || _use_provided || _use_default
-
@evaluated = true
-
-
return if _guardfile_contents_usable?
-
UI.error "No Guard plugins found in Guardfile,"\
-
" please add at least one."
-
end
-
-
2
def _use_inline
-
source_from_option = @source.nil? && options[:guardfile_contents]
-
inline = @source == :inline
-
-
return false unless (source_from_option) || inline
-
-
@source = :inline
-
@guardfile_contents = options[:guardfile_contents]
-
-
UI.info "Using inline Guardfile."
-
true
-
end
-
-
2
def _use_provided
-
return unless custom?
-
@path, @contents = _read(@path)
-
true
-
rescue Errno::ENOENT
-
fail NoCustomGuardfile, "No Guardfile exists at #{ @path }."
-
end
-
-
2
def _use_default!
-
@path, @contents = _read("Guardfile")
-
@type = :default
-
rescue Errno::ENOENT
-
begin
-
@path, @contents = _read("~/.Guardfile")
-
@type = :default
-
rescue Errno::ENOENT
-
fail NoGuardfileError, ERROR_NO_GUARDFILE
-
end
-
end
-
-
2
def _read(path)
-
full_path = Pathname(path).expand_path
-
[full_path, full_path.read]
-
rescue Errno::ENOENT
-
fail
-
rescue SystemCallError => e
-
UI.error "Error reading file #{full_path}:"
-
UI.error e.inspect
-
UI.error e.backtrace
-
abort
-
end
-
-
2
def _guardfile_contents
-
@user_config ||= Pathname("~/.guard.rb").expand_path.read
-
[@contents, @user_config].compact.join("\n")
-
rescue Errno::ENOENT
-
@contents || ""
-
end
-
-
2
def _guardfile_contents_usable?
-
guardfile_contents && guardfile_contents =~ /guard/m
-
end
-
-
2
def _from_deprecated(opts)
-
res = opts.dup
-
if opts.key?(:guardfile_contents)
-
res[:contents] = opts[:guardfile_contents]
-
end
-
res
-
end
-
end
-
end
-
end
-
2
module Guard
-
2
class Interactor
-
# Initializes the interactor. This configures
-
# Pry and creates some custom commands and aliases
-
# for Guard.
-
#
-
2
def initialize(no_interaction = false)
-
@interactive = !no_interaction && self.class.enabled?
-
-
# TODO: only require the one used
-
require "guard/jobs/sleep"
-
require "guard/jobs/pry_wrapper"
-
-
job_klass = interactive? ? Jobs::PryWrapper : Jobs::Sleep
-
@idle_job = job_klass.new(self.class.options)
-
end
-
-
2
def interactive?
-
@interactive
-
end
-
-
# Run in foreground and wait until interrupted or closed
-
2
def foreground
-
idle_job.foreground
-
end
-
-
# Remove interactor so other tasks can run in foreground
-
2
def background
-
idle_job.background
-
end
-
-
2
def handle_interrupt
-
idle_job.handle_interrupt
-
end
-
-
# TODO: everything below is just so the DSL can set options
-
# before setup() is called, which makes it useless for when
-
# Guardfile is reevaluated
-
2
class << self
-
2
def options
-
@options ||= {}
-
end
-
-
# Pass options to interactor's job when it's created
-
2
attr_writer :options
-
-
# TODO: allow custom user idle jobs, e.g. [:pry, :sleep, :exit, ...]
-
2
def enabled?
-
@enabled || @enabled.nil?
-
end
-
-
2
alias_method :enabled, :enabled?
-
-
# TODO: handle switching interactors during runtime?
-
2
attr_writer :enabled
-
end
-
-
2
private
-
-
2
attr_reader :idle_job
-
end
-
end
-
# Because it's used by Sheller
-
2
require "open3"
-
2
require "logger"
-
-
2
require "guard/ui"
-
-
2
require "guard/internals/tracing"
-
-
2
module Guard
-
# @private api
-
2
module Internals
-
2
class Debugging
-
2
class << self
-
2
TRACES = [
-
[Kernel, :system],
-
[Kernel, :`],
-
[Open3, :popen3]
-
]
-
-
# Sets up debugging:
-
#
-
# * aborts on thread exceptions
-
# * Set the logging level to `:debug`
-
# * traces execution of Kernel.system and backtick calls
-
2
def start
-
return if @started ||= false
-
@started = true
-
-
Thread.abort_on_exception = true
-
-
UI.level = Logger::DEBUG
-
-
TRACES.each { |mod, meth| _trace(mod, meth, &method(:_notify)) }
-
@traced = true
-
end
-
-
2
def stop
-
return unless @started ||= false
-
UI.level = Logger::INFO
-
_reset
-
end
-
-
2
private
-
-
2
def _notify(*args)
-
UI.debug "Command execution: #{args.join(' ')}"
-
end
-
-
# reset singleton - called by tests
-
2
def _reset
-
@started = false
-
return unless @traced
-
TRACES.each { |mod, meth| _untrace(mod, meth) }
-
@traced = false
-
end
-
-
2
def _trace(mod, meth, &block)
-
Tracing.trace(mod, meth, &block)
-
end
-
-
2
def _untrace(mod, meth)
-
Tracing.untrace(mod, meth)
-
end
-
end
-
end
-
end
-
end
-
2
require "guard/group"
-
-
2
module Guard
-
# @private api
-
2
module Internals
-
2
class Groups
-
2
DEFAULT_GROUPS = [:common, :default]
-
-
2
def initialize
-
@groups = DEFAULT_GROUPS.map { |name| Group.new(name) }
-
end
-
-
2
def all(filter = nil)
-
return @groups if filter.nil?
-
matcher = matcher_for(filter)
-
@groups.select { |group| matcher.call(group) }
-
end
-
-
2
def add(name, options = {})
-
all(name).first || Group.new(name, options).tap do |group|
-
fail if name == :specs && options.empty?
-
@groups << group
-
end
-
end
-
-
2
private
-
-
2
def matcher_for(filter)
-
case filter
-
when String, Symbol
-
lambda { |group| group.name == filter.to_sym }
-
when Regexp
-
lambda { |group| group.name.to_s =~ filter }
-
else
-
fail "Invalid filter: #{filter.inspect}"
-
end
-
end
-
end
-
end
-
end
-
2
module Guard
-
# @private api
-
2
module Internals
-
2
module Helpers
-
2
def _relative_pathname(path)
-
full_path = Pathname(path)
-
full_path.relative_path_from(Pathname.pwd)
-
rescue ArgumentError
-
full_path
-
end
-
end
-
end
-
end
-
2
require "guard/plugin_util"
-
2
require "guard/group"
-
2
require "guard/plugin"
-
-
2
module Guard
-
# @private api
-
2
module Internals
-
2
class Plugins
-
2
def initialize
-
@plugins = []
-
end
-
-
2
def all(filter = nil)
-
return @plugins if filter.nil?
-
matcher = matcher_for(filter)
-
@plugins.select { |plugin| matcher.call(plugin) }
-
end
-
-
2
def remove(plugin)
-
@plugins.delete(plugin)
-
end
-
-
# TODO: should it allow duplicates? (probably yes because of different
-
# configs or groups)
-
2
def add(name, options)
-
@plugins << PluginUtil.new(name).initialize_plugin(options)
-
end
-
-
2
private
-
-
2
def matcher_for(filter)
-
case filter
-
when String, Symbol
-
shortname = filter.to_s.downcase.gsub("-", "")
-
lambda { |plugin| plugin.name == shortname }
-
when Regexp
-
lambda { |plugin| plugin.name =~ filter }
-
when Hash
-
lambda do |plugin|
-
filter.all? do |k, v|
-
case k
-
when :name
-
plugin.name == v.to_s.downcase.gsub("-", "")
-
when :group
-
plugin.group.name == v.to_sym
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
2
module Guard
-
2
module Internals
-
2
class Queue
-
2
def initialize(commander)
-
@commander = commander
-
@queue = ::Queue.new
-
end
-
-
# Process the change queue, running tasks within the main Guard thread
-
2
def process
-
actions, changes = [], { modified: [], added: [], removed: [] }
-
-
while pending?
-
if (item = @queue.pop).first.is_a?(Symbol)
-
actions << item
-
else
-
item.each { |key, value| changes[key] += value }
-
end
-
end
-
-
_run_actions(actions)
-
return if changes.values.all?(&:empty?)
-
Runner.new.run_on_changes(*changes.values)
-
end
-
-
2
def pending?
-
! @queue.empty?
-
end
-
-
2
def <<(changes)
-
@queue << changes
-
end
-
-
2
private
-
-
2
def _run_actions(actions)
-
actions.each do |action_args|
-
args = action_args.dup
-
namespaced_action = args.shift
-
action = namespaced_action.to_s.sub(/^guard_/, "")
-
if @commander.respond_to?(action)
-
@commander.send(action, *args)
-
else
-
fail "Unknown action: #{action.inspect}"
-
end
-
end
-
end
-
end
-
end
-
end
-
2
require "guard"
-
-
2
module Guard
-
# @private api
-
2
module Internals
-
2
class Scope
-
2
def initialize
-
@interactor_plugin_scope = []
-
@interactor_group_scope = []
-
end
-
-
2
def to_hash
-
{
-
plugins: _hashify_scope(:plugin),
-
groups: _hashify_scope(:group)
-
}.dup.freeze
-
end
-
-
# TODO: refactor
-
2
def grouped_plugins(scope = { plugins: [], groups: [] })
-
items = nil
-
plugins = _find_non_empty_scope(:plugins, scope)
-
if plugins
-
items = Array(plugins).map { |plugin| _instantiate(:plugin, plugin) }
-
end
-
-
unless items
-
# TODO: no coverage here!!
-
found = _find_non_empty_scope(:groups, scope)
-
found ||= Guard.state.session.groups.all
-
groups = Array(found).map { |group| _instantiate(:group, group) }
-
if groups.any? { |g| g.name == :common }
-
items = groups
-
else
-
items = ([_instantiate(:group, :common)] + Array(found)).compact
-
end
-
end
-
-
items.map do |plugin_or_group|
-
group = nil
-
plugins = [plugin_or_group]
-
if plugin_or_group.is_a?(Group)
-
# TODO: no coverage here!
-
group = plugin_or_group
-
plugins = Guard.state.session.plugins.all(group: group.name)
-
end
-
[group, plugins]
-
end
-
end
-
-
2
def from_interactor(scope)
-
@interactor_plugin_scope = Array(scope[:plugins])
-
@interactor_group_scope = Array(scope[:groups])
-
end
-
-
2
def titles(scope = nil)
-
hash = scope || to_hash
-
plugins = hash[:plugins]
-
groups = hash[:groups]
-
return plugins.map(&:title) unless plugins.nil? || plugins.empty?
-
return hash[:groups].map(&:title) unless groups.nil? || groups.empty?
-
["all"]
-
end
-
-
2
private
-
-
# TODO: move to session
-
2
def _scope_names(new_scope, name)
-
items = Array(new_scope[:"#{name}s"] || new_scope[name]) if items.empty?
-
-
# Convert objects to names
-
items.map { |p| p.respond_to?(:name) ? p.name : p }
-
end
-
-
# TODO: let the Plugins and Groups classes handle this?
-
# TODO: why even instantiate?? just to check if it exists?
-
2
def _hashify_scope(type)
-
# TODO: get cmdline passed to initialize above?
-
cmdline = Array(Guard.state.session.send("cmdline_#{type}s"))
-
guardfile = Guard.state.session.send(:"guardfile_#{type}_scope")
-
interactor = instance_variable_get(:"@interactor_#{type}_scope")
-
-
# TODO: session should decide whether to use cmdline or guardfile -
-
# since it has access to both variables
-
items = [interactor, cmdline, guardfile].detect do |source|
-
!source.empty?
-
end
-
-
# TODO: not tested when groups/plugins given don't exist
-
-
# TODO: should already be instantiated
-
Array(items).map do |obj|
-
if obj.respond_to?(:name)
-
obj
-
else
-
name = obj
-
(type == :group ? _groups : _plugins).all(name).first
-
end
-
end.compact
-
end
-
-
2
def _instantiate(meth, obj)
-
# TODO: no coverage
-
return obj unless obj.is_a?(Symbol) || obj.is_a?(String)
-
Guard.state.session.send("#{meth}s".to_sym).all(obj).first
-
end
-
-
2
def _find_non_empty_scope(type, local_scope)
-
[Array(local_scope[type]), to_hash[type]].map(&:compact).detect(&:any?)
-
end
-
-
2
def _groups
-
Guard.state.session.groups
-
end
-
-
2
def _plugins
-
Guard.state.session.plugins
-
end
-
end
-
end
-
end
-
2
require "guard/internals/plugins"
-
2
require "guard/internals/groups"
-
-
2
require "guard/options"
-
-
2
module Guard
-
# @private api
-
2
module Internals
-
# TODO: split into a commandline class and session (plugins, groups)
-
# TODO: swap session and metadata
-
2
class Session
-
2
attr_reader :plugins
-
2
attr_reader :groups
-
-
2
DEFAULT_OPTIONS = {
-
clear: false,
-
debug: false,
-
no_bundler_warning: false,
-
-
# User defined scopes
-
group: [],
-
plugin: [],
-
-
# Notifier
-
notify: true,
-
-
# Interactor
-
no_interactions: false,
-
-
# Guardfile options:
-
# guardfile_contents
-
guardfile: nil,
-
-
# Listener options
-
# TODO: rename to watchdirs?
-
watchdir: Dir.pwd,
-
latency: nil,
-
force_polling: false,
-
wait_for_delay: nil,
-
listen_on: nil
-
}
-
-
2
def cmdline_groups
-
@cmdline_groups.dup.freeze
-
end
-
-
2
def cmdline_plugins
-
@cmdline_plugins.dup.freeze
-
end
-
-
2
def initialize(new_options)
-
@options = Options.new(new_options, DEFAULT_OPTIONS)
-
-
@plugins = Plugins.new
-
@groups = Groups.new
-
-
@cmdline_groups = @options[:group]
-
@cmdline_plugins = @options[:plugin]
-
-
@clear = @options[:clear]
-
@debug = @options[:debug]
-
@watchdirs = Array(@options[:watchdir])
-
@notify = @options[:notify]
-
@interactor_name = @options[:no_interactions] ? :sleep : :pry_wrapper
-
-
@guardfile_plugin_scope = []
-
@guardfile_group_scope = []
-
@guardfile_ignore = []
-
@guardfile_ignore_bang = []
-
-
@guardfile_notifier_options = {}
-
end
-
-
2
def guardfile_scope(scope)
-
opts = scope.dup
-
-
groups = Array(opts.delete(:groups))
-
group = Array(opts.delete(:group))
-
@guardfile_group_scope = Array(groups) + Array(group)
-
-
plugins = Array(opts.delete(:plugins))
-
plugin = Array(opts.delete(:plugin))
-
@guardfile_plugin_scope = Array(plugins) + Array(plugin)
-
-
fail "Unknown options: #{opts.inspect}" unless opts.empty?
-
end
-
-
# TODO: create a EvaluatorResult class?
-
2
attr_reader :guardfile_group_scope
-
2
attr_reader :guardfile_plugin_scope
-
2
attr_accessor :guardfile_ignore_bang
-
-
2
attr_reader :guardfile_ignore
-
2
def guardfile_ignore=(ignores)
-
@guardfile_ignore += Array(ignores).flatten
-
end
-
-
2
def clearing(on)
-
@clear = on
-
end
-
-
2
def clearing?
-
@clear
-
end
-
-
2
alias :clear? :clearing?
-
-
2
def debug?
-
@debug
-
end
-
-
2
def watchdirs
-
@watchdirs_from_guardfile ||= nil
-
@watchdirs_from_guardfile || @watchdirs
-
end
-
-
# set by Dsl with :directories() command
-
2
def watchdirs=(dirs)
-
dirs = [Dir.pwd] if dirs.empty?
-
@watchdirs_from_guardfile = dirs.map { |dir| File.expand_path dir }
-
end
-
-
2
def listener_args
-
if @options[:listen_on]
-
[:on, @options[:listen_on]]
-
else
-
listener_options = {}
-
[:latency, :force_polling, :wait_for_delay].each do |option|
-
listener_options[option] = @options[option] if @options[option]
-
end
-
expanded_watchdirs = watchdirs.map { |dir| File.expand_path dir }
-
[:to, *expanded_watchdirs, listener_options]
-
end
-
end
-
-
2
def evaluator_options
-
opts = { guardfile: @options[:guardfile] }
-
# TODO: deprecate :guardfile_contents
-
if @options[:guardfile_contents]
-
opts[:contents] = @options[:guardfile_contents]
-
end
-
opts
-
end
-
-
2
def notify_options
-
names = @guardfile_notifier_options.keys
-
return { notify: false } if names.include?(:off)
-
-
{
-
notify: @options[:notify],
-
notifiers: @guardfile_notifier_options
-
}
-
end
-
-
2
def guardfile_notification=(config)
-
@guardfile_notifier_options.merge!(config)
-
end
-
-
2
def interactor_name
-
@interactor_name
-
end
-
-
# TODO: call this from within action, not within interactor command
-
2
def convert_scope(entries)
-
scopes = { plugins: [], groups: [] }
-
unknown = []
-
-
entries.each do |entry|
-
if plugin = plugins.all(entry).first
-
scopes[:plugins] << plugin
-
elsif group = groups.all(entry).first
-
scopes[:groups] << group
-
else
-
unknown << entry
-
end
-
end
-
-
[scopes, unknown]
-
end
-
end
-
end
-
end
-
2
require "guard/group"
-
-
2
require "guard/plugin_util"
-
2
require "guard/internals/session"
-
2
require "guard/internals/scope"
-
2
require "guard/runner"
-
-
2
module Guard
-
2
module Internals
-
2
class State
-
# Minimal setup for non-interactive commands (list, init, show, etc.)
-
2
def initialize(cmdline_opts)
-
@session = Session.new(cmdline_opts)
-
-
@scope = Scope.new
-
-
# NOTE: must be set before anything calls Guard::UI.debug
-
Debugging.start if session.debug?
-
end
-
-
2
attr_reader :scope
-
2
attr_reader :session
-
end
-
end
-
end
-
2
module Guard
-
2
module Internals
-
2
module Tracing
-
2
def self.trace(mod, meth)
-
meta = (class << mod; self; end)
-
original_meth = "original_#{meth}".to_sym
-
-
if mod.respond_to?(original_meth)
-
fail "ALREADY TRACED: #{mod}.#{meth}"
-
end
-
-
meta.send(:alias_method, original_meth, meth)
-
meta.send(:define_method, meth) do |*args, &block|
-
yield(*args) if block_given?
-
mod.send original_meth, *args, &block
-
end
-
end
-
-
2
def self.untrace(mod, meth)
-
meta = (class << mod; self; end)
-
original_meth = "original_#{meth}".to_sym
-
-
unless mod.respond_to?(original_meth)
-
fail "NOT TRACED: #{mod}.#{meth} (no method: #{original_meth})"
-
end
-
-
meta.send(:remove_method, meth)
-
meta.send(:alias_method, meth, original_meth)
-
meta.send(:undef_method, original_meth)
-
end
-
end
-
end
-
end
-
2
module Guard
-
2
module Internals
-
2
module Traps
-
2
def self.handle(signal, &block)
-
return unless Signal.list.key?(signal)
-
Signal.trap(signal, &block)
-
end
-
end
-
end
-
end
-
2
require "notiffany/notifier"
-
2
require "guard/ui"
-
-
2
module Guard
-
2
class Notifier
-
2
def self.connect(options = {})
-
@notifier ||= nil
-
fail "Already connected!" if @notifier
-
begin
-
opts = options.merge(namespace: "guard", logger: UI)
-
@notifier = Notiffany.connect(opts)
-
rescue Notiffany::Notifier::Detected::UnknownNotifier => e
-
UI.error "Failed to setup notification: #{e.message}"
-
fail
-
end
-
end
-
-
2
def self.disconnect
-
@notifier.disconnect
-
@notifier = nil
-
end
-
-
2
DEPRECATED_IMPLICIT_CONNECT = "Calling Notiffany::Notifier.notify()"\
-
" without a prior Notifier.connect() is"\
-
" deprecated"
-
-
2
def self.notify(message, options = {})
-
unless @notifier
-
# TODO: reenable again?
-
# UI.deprecation(DEPRECTED_IMPLICIT_CONNECT)
-
connect(notify: true)
-
end
-
-
@notifier.notify(message, options)
-
rescue RuntimeError => e
-
UI.error "Notification failed for #{@notifier.class.name}: #{e.message}"
-
UI.debug e.backtrace.join("\n")
-
end
-
-
2
def self.turn_on
-
@notifier.turn_on
-
end
-
-
2
def self.toggle
-
unless @notifier.enabled?
-
UI.error NOTIFICATIONS_DISABLED
-
return
-
end
-
-
if @notifier.active?
-
UI.info "Turn off notifications"
-
@notifier.turn_off
-
return
-
end
-
-
@notifier.turn_on
-
end
-
-
# Used by dsl describer
-
2
def self.supported
-
Notiffany::Notifier::SUPPORTED.inject(:merge)
-
end
-
-
# Used by dsl describer
-
2
def self.detected
-
@notifier.available.map do |mod|
-
{ name: mod.name.to_sym, options: mod.options }
-
end
-
end
-
end
-
end
-
2
require "thor/core_ext/hash_with_indifferent_access"
-
-
2
module Guard
-
# A class that holds options. Can be instantiated with default options.
-
#
-
2
class Options < Thor::CoreExt::HashWithIndifferentAccess
-
# Initializes an Guard::Options object. `default_opts` is merged into
-
# `opts`.
-
#
-
# @param [Hash] opts the options
-
# @param [Hash] default_opts the default options
-
#
-
2
def initialize(opts = {}, default_opts = {})
-
super(default_opts.merge(opts || {}))
-
end
-
end
-
end
-
2
require "guard"
-
2
require "guard/internals/groups"
-
-
2
module Guard
-
# Base class from which every Guard plugin implementation must inherit.
-
#
-
# Guard will trigger the {#start}, {#stop}, {#reload}, {#run_all} and
-
# {#run_on_changes} ({#run_on_additions}, {#run_on_modifications} and
-
# {#run_on_removals}) task methods depending on user interaction and file
-
# modification.
-
#
-
# {#run_on_changes} could be implemented to handle all the changes task case
-
# (additions, modifications, removals) in once, or each task can be
-
# implemented separately with a specific behavior.
-
#
-
# In each of these Guard task methods you have to implement some work when
-
# you want to support this kind of task. The return value of each Guard task
-
# method is not evaluated by Guard, but it'll be passed to the "_end" hook
-
# for further evaluation. You can throw `:task_has_failed` to indicate that
-
# your Guard plugin method was not successful, and successive Guard plugin
-
# tasks will be aborted when the group has set the `:halt_on_fail` option.
-
#
-
# @see Guard::Group
-
#
-
# @example Throw :task_has_failed
-
#
-
# def run_all
-
# if !runner.run(['all'])
-
# throw :task_has_failed
-
# end
-
# end
-
#
-
# Each Guard plugin should provide a template Guardfile located within the Gem
-
# at `lib/guard/guard-name/templates/Guardfile`.
-
#
-
# Watchers for a Guard plugin should return a file path or an array of files
-
# paths to Guard, but if your Guard plugin wants to allow any return value
-
# from a watcher, you can set the `any_return` option to true.
-
#
-
# If one of those methods raises an exception other than `:task_has_failed`,
-
# the `Guard::GuardName` instance will be removed from the active Guard
-
# plugins.
-
#
-
2
class Plugin
-
2
TEMPLATE_FORMAT = "%s/lib/guard/%s/templates/Guardfile"
-
-
2
require "guard/ui"
-
-
# Get all callbacks registered for all Guard plugins present in the
-
# Guardfile.
-
#
-
2
def self.callbacks
-
@callbacks ||= Hash.new { |hash, key| hash[key] = [] }
-
end
-
-
# Add a callback.
-
#
-
# @param [Block] listener the listener to notify
-
# @param [Guard::Plugin] guard_plugin the Guard plugin to add the callback
-
# @param [Array<Symbol>] events the events to register
-
#
-
2
def self.add_callback(listener, guard_plugin, events)
-
Array(events).each do |event|
-
callbacks[[guard_plugin, event]] << listener
-
end
-
end
-
-
# Notify a callback.
-
#
-
# @param [Guard::Plugin] guard_plugin the Guard plugin to add the callback
-
# @param [Symbol] event the event to trigger
-
# @param [Array] args the arguments for the listener
-
#
-
2
def self.notify(guard_plugin, event, *args)
-
callbacks[[guard_plugin, event]].each do |listener|
-
listener.call(guard_plugin, event, *args)
-
end
-
end
-
-
# Reset all callbacks.
-
#
-
# TODO: remove (not used anywhere)
-
2
def self.reset_callbacks!
-
@callbacks = nil
-
end
-
-
# When event is a Symbol, {#hook} will generate a hook name
-
# by concatenating the method name from where {#hook} is called
-
# with the given Symbol.
-
#
-
# @example Add a hook with a Symbol
-
#
-
# def run_all
-
# hook :foo
-
# end
-
#
-
# Here, when {Guard::Plugin#run_all} is called, {#hook} will notify
-
# callbacks registered for the "run_all_foo" event.
-
#
-
# When event is a String, {#hook} will directly turn the String
-
# into a Symbol.
-
#
-
# @example Add a hook with a String
-
#
-
# def run_all
-
# hook "foo_bar"
-
# end
-
#
-
# When {Guard::Plugin::run_all} is called, {#hook} will notify
-
# callbacks registered for the "foo_bar" event.
-
#
-
# @param [Symbol, String] event the name of the Guard event
-
# @param [Array] args the parameters are passed as is to the callbacks
-
# registered for the given event.
-
#
-
2
def hook(event, *args)
-
hook_name = if event.is_a? Symbol
-
calling_method = caller[0][/`([^']*)'/, 1]
-
"#{ calling_method }_#{ event }"
-
else
-
event
-
end
-
-
UI.debug "Hook :#{ hook_name } executed for #{ self.class }"
-
-
self.class.notify(self, hook_name.to_sym, *args)
-
end
-
-
2
attr_accessor :group, :watchers, :callbacks, :options
-
-
# Returns the non-namespaced class name of the plugin
-
#
-
#
-
# @example Non-namespaced class name for Guard::RSpec
-
# Guard::RSpec.non_namespaced_classname
-
# #=> "RSpec"
-
#
-
# @return [String]
-
#
-
2
def self.non_namespaced_classname
-
to_s.sub("Guard::", "")
-
end
-
-
# Returns the non-namespaced name of the plugin
-
#
-
#
-
# @example Non-namespaced name for Guard::RSpec
-
# Guard::RSpec.non_namespaced_name
-
# #=> "rspec"
-
#
-
# @return [String]
-
#
-
2
def self.non_namespaced_name
-
non_namespaced_classname.downcase
-
end
-
-
# Specify the source for the Guardfile template.
-
# Each Guard plugin can redefine this method to add its own logic.
-
#
-
# @param [String] plugin_location the plugin location
-
#
-
2
def self.template(plugin_location)
-
File.read TEMPLATE_FORMAT % [plugin_location, non_namespaced_name]
-
end
-
-
# Called once when Guard starts. Please override initialize method to
-
# init stuff.
-
#
-
# @raise [:task_has_failed] when start has failed
-
# @return [Object] the task result
-
#
-
# @!method start
-
-
# Called when `stop|quit|exit|s|q|e + enter` is pressed (when Guard
-
# quits).
-
#
-
# @raise [:task_has_failed] when stop has failed
-
# @return [Object] the task result
-
#
-
# @!method stop
-
-
# Called when `reload|r|z + enter` is pressed.
-
# This method should be mainly used for "reload" (really!) actions like
-
# reloading passenger/spork/bundler/...
-
#
-
# @raise [:task_has_failed] when reload has failed
-
# @return [Object] the task result
-
#
-
# @!method reload
-
-
# Called when just `enter` is pressed
-
# This method should be principally used for long action like running all
-
# specs/tests/...
-
#
-
# @raise [:task_has_failed] when run_all has failed
-
# @return [Object] the task result
-
#
-
# @!method run_all
-
-
# Default behaviour on file(s) changes that the Guard plugin watches.
-
#
-
# @param [Array<String>] paths the changes files or paths
-
# @raise [:task_has_failed] when run_on_changes has failed
-
# @return [Object] the task result
-
#
-
# @!method run_on_changes(paths)
-
-
# Called on file(s) additions that the Guard plugin watches.
-
#
-
# @param [Array<String>] paths the changes files or paths
-
# @raise [:task_has_failed] when run_on_additions has failed
-
# @return [Object] the task result
-
#
-
# @!method run_on_additions(paths)
-
-
# Called on file(s) modifications that the Guard plugin watches.
-
#
-
# @param [Array<String>] paths the changes files or paths
-
# @raise [:task_has_failed] when run_on_modifications has failed
-
# @return [Object] the task result
-
#
-
# @!method run_on_modifications(paths)
-
-
# Called on file(s) removals that the Guard plugin watches.
-
#
-
# @param [Array<String>] paths the changes files or paths
-
# @raise [:task_has_failed] when run_on_removals has failed
-
# @return [Object] the task result
-
#
-
# @!method run_on_removals(paths)
-
-
# Returns the plugin's name (without "guard-").
-
#
-
# @example Name for Guard::RSpec
-
# Guard::RSpec.new.name
-
# #=> "rspec"
-
#
-
# @return [String]
-
#
-
2
def name
-
@name ||= self.class.non_namespaced_name
-
end
-
-
# Returns the plugin's class name without the Guard:: namespace.
-
#
-
# @example Title for Guard::RSpec
-
# Guard::RSpec.new.title
-
# #=> "RSpec"
-
#
-
# @return [String]
-
#
-
2
def title
-
@title ||= self.class.non_namespaced_classname
-
end
-
-
# String representation of the plugin.
-
#
-
# @example String representation of an instance of the Guard::RSpec plugin
-
#
-
# Guard::RSpec.new.title
-
# #=> "#<Guard::RSpec @name=rspec @group=#<Guard::Group @name=default
-
# @options={}> @watchers=[] @callbacks=[] @options={all_after_pass:
-
# true}>"
-
#
-
# @return [String] the string representation
-
#
-
2
def to_s
-
"#<#{self.class} @name=#{name} @group=#{group} @watchers=#{watchers}"\
-
" @callbacks=#{callbacks} @options=#{options}>"
-
end
-
-
2
private
-
-
# Initializes a Guard plugin.
-
# Don't do any work here, especially as Guard plugins get initialized even
-
# if they are not in an active group!
-
#
-
# @param [Hash] options the Guard plugin options
-
# @option options [Array<Guard::Watcher>] watchers the Guard plugin file
-
# watchers
-
# @option options [Symbol] group the group this Guard plugin belongs to
-
# @option options [Boolean] any_return allow any object to be returned from
-
# a watcher
-
#
-
2
def initialize(options = {})
-
group_name = options.delete(:group) { :default }
-
@group = Guard.state.session.groups.add(group_name)
-
@watchers = options.delete(:watchers) { [] }
-
@callbacks = options.delete(:callbacks) { [] }
-
@options = options
-
_register_callbacks
-
end
-
-
# Add all the Guard::Plugin's callbacks to the global @callbacks array
-
# that's used by Guard to know which callbacks to notify.
-
#
-
2
def _register_callbacks
-
callbacks.each do |callback|
-
self.class.add_callback(callback[:listener], self, callback[:events])
-
end
-
end
-
end
-
end
-
2
require "guard/ui"
-
-
2
module Guard
-
# This class contains useful methods to:
-
#
-
# * Fetch all the Guard plugins names;
-
# * Initialize a plugin, get its location;
-
# * Return its class name;
-
# * Add its template to the Guardfile.
-
#
-
2
class PluginUtil
-
2
ERROR_NO_GUARD_OR_CLASS = "Could not load 'guard/%s' or" \
-
" find class Guard::%s"
-
-
2
INFO_ADDED_GUARD_TO_GUARDFILE = "%s guard added to Guardfile,"\
-
" feel free to edit it"
-
-
2
attr_accessor :name
-
-
# Returns a list of Guard plugin Gem names installed locally.
-
#
-
# @return [Array<String>] a list of Guard plugin gem names
-
#
-
2
def self.plugin_names
-
valid = Gem::Specification.find_all.select do |gem|
-
_gem_valid?(gem)
-
end
-
-
valid.map { |x| x.name.sub(/^guard-/, "") }.uniq
-
end
-
-
# Initializes a new `Guard::PluginUtil` object.
-
#
-
# @param [String] name the name of the Guard plugin
-
#
-
2
def initialize(name)
-
@name = name.to_s.sub(/^guard-/, "")
-
end
-
-
# Initializes a new `Guard::Plugin` with the given `options` hash. This
-
# methods handles plugins that inherit from the deprecated `Guard::Guard`
-
# class as well as plugins that inherit from `Guard::Plugin`.
-
#
-
# @see Guard::Plugin
-
# @see https://github.com/guard/guard/wiki/Upgrading-to-Guard-2.0 How to
-
# upgrade for Guard 2.0
-
#
-
# @return [Guard::Plugin] the initialized plugin
-
# @return [Guard::Guard] the initialized plugin. This return type is
-
# deprecated and the plugin's maintainer should update it to be
-
# compatible with Guard 2.0. For more information on how to upgrade for
-
# Guard 2.0, please head over to:
-
# https://github.com/guard/guard/wiki/Upgrading-to-Guard-2.0
-
#
-
2
def initialize_plugin(options)
-
klass = plugin_class
-
fail "Could not load class: #{_constant_name.inspect}" unless klass
-
if klass.superclass.to_s == "Guard::Guard"
-
klass.new(options.delete(:watchers), options)
-
else
-
begin
-
klass.new(options)
-
rescue ArgumentError => e
-
fail "Failed to call #{klass}.new(options): #{e}"
-
end
-
end
-
end
-
-
# Locates a path to a Guard plugin gem.
-
#
-
# @return [String] the full path to the plugin gem
-
#
-
2
def plugin_location
-
@plugin_location ||= _full_gem_path("guard-#{name}")
-
rescue Gem::LoadError
-
UI.error "Could not find 'guard-#{ name }' gem path."
-
end
-
-
# Tries to load the Guard plugin main class. This transforms the supplied
-
# plugin name into a class name:
-
#
-
# * `guardname` will become `Guard::Guardname`
-
# * `dashed-guard-name` will become `Guard::DashedGuardName`
-
# * `underscore_guard_name` will become `Guard::UnderscoreGuardName`
-
#
-
# When no class is found with the strict case sensitive rules, another
-
# try is made to locate the class without matching case:
-
#
-
# * `rspec` will find a class `Guard::RSpec`
-
#
-
# @option options [Boolean] fail_gracefully whether error messages should
-
# not be printed
-
#
-
# @return [Class, nil] the loaded class
-
#
-
2
def plugin_class(options = {})
-
options = { fail_gracefully: false }.merge(options)
-
-
const = _plugin_constant
-
fail TypeError, "no constant: #{_constant_name}" unless const
-
@plugin_class ||= Guard.const_get(const)
-
-
rescue TypeError
-
begin
-
require "guard/#{ name.downcase }"
-
const = _plugin_constant
-
@plugin_class ||= Guard.const_get(const)
-
-
rescue TypeError => error
-
UI.error "Could not find class Guard::#{ _constant_name }"
-
UI.error error.backtrace.join("\n")
-
# TODO: return value or move exception higher
-
rescue LoadError => error
-
unless options[:fail_gracefully]
-
UI.error ERROR_NO_GUARD_OR_CLASS % [name.downcase, _constant_name]
-
UI.error "Error is: #{error}"
-
UI.error error.backtrace.join("\n")
-
# TODO: return value or move exception higher
-
end
-
end
-
end
-
-
# Adds a plugin's template to the Guardfile.
-
#
-
2
def add_to_guardfile
-
klass = plugin_class # call here to avoid failing later
-
-
require "guard/guardfile/evaluator"
-
# TODO: move this to Generator?
-
options = Guard.state.session.evaluator_options
-
evaluator = Guardfile::Evaluator.new(options)
-
begin
-
evaluator.evaluate
-
rescue Guard::Guardfile::Evaluator::NoPluginsError
-
end
-
-
if evaluator.guardfile_include?(name)
-
UI.info "Guardfile already includes #{ name } guard"
-
else
-
content = File.read("Guardfile")
-
File.open("Guardfile", "wb") do |f|
-
f.puts(content)
-
f.puts("")
-
f.puts(klass.template(plugin_location))
-
end
-
-
UI.info INFO_ADDED_GUARD_TO_GUARDFILE % name
-
end
-
end
-
-
2
private
-
-
# Returns the constant for the current plugin.
-
#
-
# @example Returns the constant for a plugin
-
# > Guard::PluginUtil.new('rspec').send(:_plugin_constant)
-
# => Guard::RSpec
-
#
-
2
def _plugin_constant
-
@_plugin_constant ||= Guard.constants.detect do |c|
-
c.to_s.downcase == _constant_name.downcase
-
end
-
end
-
-
# Guesses the most probable name for the current plugin based on its name.
-
#
-
# @example Returns the most probable name for a plugin
-
# > Guard::PluginUtil.new('rspec').send(:_constant_name)
-
# => "Rspec"
-
#
-
2
def _constant_name
-
@_constant_name ||= name.gsub(/\/(.?)/) { "::#{ $1.upcase }" }.
-
gsub(/(?:^|[_-])(.)/) { $1.upcase }
-
end
-
-
2
def self._gem_valid?(gem)
-
return false if gem.name == "guard-compat"
-
return true if gem.name =~ /^guard-/
-
full_path = gem.full_gem_path
-
file = File.join(full_path, "lib", "guard", "#{gem.name}.rb")
-
File.exist?(file)
-
end
-
-
2
def _full_gem_path(name)
-
Gem::Specification.find_by_name(name).full_gem_path
-
end
-
end
-
end
-
2
require "lumberjack"
-
-
2
require "guard/ui"
-
2
require "guard/watcher"
-
-
2
module Guard
-
# The runner is responsible for running all methods defined on each plugin.
-
#
-
2
class Runner
-
# Runs a Guard-task on all registered plugins.
-
#
-
# @param [Symbol] task the task to run
-
#
-
# @param [Hash] scopes either the Guard plugin or the group to run the task
-
# on
-
#
-
2
def run(task, scope_hash = {})
-
Lumberjack.unit_of_work do
-
items = Guard.state.scope.grouped_plugins(scope_hash || {})
-
items.each do |_group, plugins|
-
_run_group_plugins(plugins) do |plugin|
-
_supervise(plugin, task) if plugin.respond_to?(task)
-
end
-
end
-
end
-
end
-
-
2
PLUGIN_FAILED = "%s has failed, other group's plugins will be skipped."
-
-
2
MODIFICATION_TASKS = [
-
:run_on_modifications, :run_on_changes, :run_on_change
-
]
-
-
2
ADDITION_TASKS = [:run_on_additions, :run_on_changes, :run_on_change]
-
2
REMOVAL_TASKS = [:run_on_removals, :run_on_changes, :run_on_deletion]
-
-
# Runs the appropriate tasks on all registered plugins
-
# based on the passed changes.
-
#
-
# @param [Array<String>] modified the modified paths.
-
# @param [Array<String>] added the added paths.
-
# @param [Array<String>] removed the removed paths.
-
#
-
2
def run_on_changes(modified, added, removed)
-
types = {
-
MODIFICATION_TASKS => modified,
-
ADDITION_TASKS => added,
-
REMOVAL_TASKS => removed
-
}
-
-
UI.clearable
-
-
Guard.state.scope.grouped_plugins.each do |_group, plugins|
-
_run_group_plugins(plugins) do |plugin|
-
UI.clear
-
types.each do |tasks, unmatched_paths|
-
next if unmatched_paths.empty?
-
match_result = Watcher.match_files(plugin, unmatched_paths)
-
next if match_result.empty?
-
task = tasks.detect { |meth| plugin.respond_to?(meth) }
-
_supervise(plugin, task, match_result) if task
-
end
-
end
-
end
-
end
-
-
# Run a Guard plugin task, but remove the Guard plugin when his work leads
-
# to a system failure.
-
#
-
# When the Group has `:halt_on_fail` disabled, we've to catch
-
# `:task_has_failed` here in order to avoid an uncaught throw error.
-
#
-
# @param [Guard::Plugin] guard the Guard to execute
-
# @param [Symbol] task the task to run
-
# @param [Array] args the arguments for the task
-
# @raise [:task_has_failed] when task has failed
-
#
-
2
def _supervise(plugin, task, *args)
-
catch self.class.stopping_symbol_for(plugin) do
-
plugin.hook("#{ task }_begin", *args)
-
begin
-
result = plugin.send(task, *args)
-
rescue Interrupt
-
throw(:task_has_failed)
-
end
-
plugin.hook("#{ task }_end", result)
-
result
-
end
-
rescue ScriptError, StandardError, RuntimeError
-
UI.error("#{ plugin.class.name } failed to achieve its"\
-
" <#{ task }>, exception was:" \
-
"\n#{ $!.class }: #{ $!.message }" \
-
"\n#{ $!.backtrace.join("\n") }")
-
Guard.state.session.plugins.remove(plugin)
-
UI.info("\n#{ plugin.class.name } has just been fired")
-
$!
-
end
-
-
# Returns the symbol that has to be caught when running a supervised task.
-
#
-
# @note If a Guard group is being run and it has the `:halt_on_fail`
-
# option set, this method returns :no_catch as it will be caught at the
-
# group level.
-
#
-
# @param [Guard::Plugin] guard the Guard plugin to execute
-
# @return [Symbol] the symbol to catch
-
#
-
2
def self.stopping_symbol_for(guard)
-
guard.group.options[:halt_on_fail] ? :no_catch : :task_has_failed
-
end
-
-
2
private
-
-
2
def _run_group_plugins(plugins)
-
failed_plugin = nil
-
catch :task_has_failed do
-
plugins.each do |plugin|
-
failed_plugin = plugin
-
yield plugin
-
failed_plugin = nil
-
end
-
end
-
UI.info format(PLUGIN_FAILED, failed_plugin.class.name) if failed_plugin
-
end
-
end
-
end
-
2
require "shellany/sheller"
-
-
2
module Guard
-
2
class Terminal
-
2
class << self
-
2
def clear
-
cmd = Gem.win_platform? ? "cls" : "clear;"
-
exit_code, _, stderr = Shellany::Sheller.system(cmd)
-
fail Errno::ENOENT, stderr unless exit_code == 0
-
end
-
end
-
end
-
end
-
2
require "guard/ui/colors"
-
-
2
require "guard/terminal"
-
2
require "guard/options"
-
-
# TODO: rework this class from the bottom-up
-
# - remove dependency on Session and Scope
-
# - extract into a separate gem
-
-
2
module Guard
-
# The UI class helps to format messages for the user. Everything that is
-
# logged through this class is considered either as an error message or a
-
# diagnostic message and is written to standard error ($stderr).
-
#
-
# If your Guard plugin does some output that is piped into another process
-
# for further processing, please just write it to STDOUT with `puts`.
-
#
-
2
module UI
-
2
include Colors
-
-
2
class << self
-
# Get the Guard::UI logger instance
-
#
-
2
def logger
-
@logger ||= begin
-
require "lumberjack"
-
Lumberjack::Logger.new(
-
options.fetch(:device) { $stderr },
-
options)
-
end
-
end
-
-
# Since logger is global, for Aruba in-process to properly
-
# separate output between calls, we need to reset
-
#
-
# We don't use logger=() since it's expected to be a Lumberjack instance
-
2
def reset_logger
-
@logger = nil
-
end
-
-
# Get the logger options
-
#
-
# @return [Hash] the logger options
-
#
-
2
def options
-
@options ||= Options.new(
-
level: :info,
-
template: ":time - :severity - :message",
-
time_format: "%H:%M:%S")
-
end
-
-
# Set the logger options
-
#
-
# @param [Hash] options the logger options
-
# @option options [Symbol] level the log level
-
# @option options [String] template the logger template
-
# @option options [String] time_format the time format
-
#
-
# TODO: deprecate?
-
2
def options=(options)
-
@options = Options.new(options)
-
end
-
-
# Assigns a log level
-
2
def level=(new_level)
-
logger.level = new_level
-
end
-
-
# Show an info message.
-
#
-
# @param [String] message the message to show
-
# @option options [Boolean] reset whether to clean the output before
-
# @option options [String] plugin manually define the calling plugin
-
#
-
2
def info(message, options = {})
-
_filtered_logger_message(message, :info, nil, options)
-
end
-
-
# Show a yellow warning message that is prefixed with WARNING.
-
#
-
# @param [String] message the message to show
-
# @option options [Boolean] reset whether to clean the output before
-
# @option options [String] plugin manually define the calling plugin
-
#
-
2
def warning(message, options = {})
-
_filtered_logger_message(message, :warn, :yellow, options)
-
end
-
-
# Show a red error message that is prefixed with ERROR.
-
#
-
# @param [String] message the message to show
-
# @option options [Boolean] reset whether to clean the output before
-
# @option options [String] plugin manually define the calling plugin
-
#
-
2
def error(message, options = {})
-
_filtered_logger_message(message, :error, :red, options)
-
end
-
-
# Show a red deprecation message that is prefixed with DEPRECATION.
-
# It has a log level of `warn`.
-
#
-
# @param [String] message the message to show
-
# @option options [Boolean] reset whether to clean the output before
-
# @option options [String] plugin manually define the calling plugin
-
#
-
2
def deprecation(message, options = {})
-
unless ENV["GUARD_GEM_SILENCE_DEPRECATIONS"] == "1"
-
backtrace = Thread.current.backtrace[1..5].join("\n\t >")
-
msg = format("%s\nDeprecation backtrace: %s", message, backtrace)
-
warning(msg, options)
-
end
-
end
-
-
# Show a debug message that is prefixed with DEBUG and a timestamp.
-
#
-
# @param [String] message the message to show
-
# @option options [Boolean] reset whether to clean the output before
-
# @option options [String] plugin manually define the calling plugin
-
#
-
2
def debug(message, options = {})
-
_filtered_logger_message(message, :debug, :yellow, options)
-
end
-
-
# Reset a line.
-
#
-
2
def reset_line
-
$stderr.print(color_enabled? ? "\r\e[0m" : "\r\n")
-
end
-
-
# Clear the output if clearable.
-
#
-
2
def clear(opts = {})
-
return unless Guard.state.session.clear?
-
-
fail "UI not set up!" if @clearable.nil?
-
return unless @clearable || opts[:force]
-
-
@clearable = false
-
Terminal.clear
-
rescue Errno::ENOENT => e
-
warning("Failed to clear the screen: #{e.inspect}")
-
end
-
-
# TODO: arguments: UI uses Guard::options anyway
-
# @private api
-
2
def reset_and_clear
-
@clearable = false
-
clear(force: true)
-
end
-
-
# Allow the screen to be cleared again.
-
#
-
2
def clearable
-
@clearable = true
-
end
-
-
# Show a scoped action message.
-
#
-
# @param [String] action the action to show
-
# @param [Hash] scope hash with a guard or a group scope
-
#
-
2
def action_with_scopes(action, scope)
-
titles = Guard.state.scope.titles(scope)
-
info "#{action} #{titles.join(', ')}"
-
end
-
-
2
private
-
-
# Filters log messages depending on either the
-
# `:only`` or `:except` option.
-
#
-
# @param [String] plugin the calling plugin name
-
# @yield When the message should be logged
-
# @yieldparam [String] param the calling plugin name
-
#
-
2
def _filter(plugin)
-
only = options[:only]
-
except = options[:except]
-
plugin ||= calling_plugin_name
-
-
match = !(only || except)
-
match ||= (only && only.match(plugin))
-
match ||= (except && !except.match(plugin))
-
return unless match
-
yield plugin
-
end
-
-
# @private
-
2
def _filtered_logger_message(message, method, color_name, options = {})
-
message = color(message, color_name) if color_name
-
-
_filter(options[:plugin]) do |plugin|
-
reset_line if options[:reset]
-
logger.send(method, message, plugin)
-
end
-
end
-
-
# Tries to extract the calling Guard plugin name
-
# from the call stack.
-
#
-
# @param [Integer] depth the stack depth
-
# @return [String] the Guard plugin name
-
#
-
2
def calling_plugin_name(depth = 2)
-
name = /(guard\/[a-z_]*)(\/[a-z_]*)?.rb:/i.match(caller[depth])
-
return "Guard" unless name
-
name[1].split("/").map do |part|
-
part.split(/[^a-z0-9]/i).map(&:capitalize).join
-
end.join("::")
-
end
-
-
# Checks if color output can be enabled.
-
#
-
# @return [Boolean] whether color is enabled or not
-
#
-
2
def color_enabled?
-
@color_enabled_initialized ||= false
-
@color_enabled = nil unless @color_enabled_initialized
-
@color_enabled_initialized = true
-
if @color_enabled.nil?
-
if Gem.win_platform?
-
if ENV["ANSICON"]
-
@color_enabled = true
-
else
-
begin
-
require "rubygems" unless ENV["NO_RUBYGEMS"]
-
require "Win32/Console/ANSI"
-
@color_enabled = true
-
rescue LoadError
-
@color_enabled = false
-
info "Run 'gem install win32console' to use color on Windows"
-
end
-
end
-
else
-
@color_enabled = true
-
end
-
end
-
-
@color_enabled
-
end
-
-
# Colorizes a text message. See the constant in the UI class for possible
-
# color_options parameters. You can pass optionally :bright, a foreground
-
# color and a background color.
-
#
-
# @example
-
#
-
# color('Hello World', :red, :bright)
-
#
-
# @param [String] text the text to colorize
-
# @param [Array] color_options the color options
-
#
-
2
def color(text, *color_options)
-
color_code = ""
-
color_options.each do |color_option|
-
color_option = color_option.to_s
-
next if color_option == ""
-
-
unless color_option =~ /\d+/
-
color_option = const_get("ANSI_ESCAPE_#{ color_option.upcase }")
-
end
-
color_code += ";" + color_option
-
end
-
color_enabled? ? "\e[0#{ color_code }m#{ text }\e[0m" : text
-
end
-
end
-
end
-
end
-
2
module Guard
-
2
module UI
-
2
module Colors
-
# Brighten the color
-
2
ANSI_ESCAPE_BRIGHT = "1"
-
-
# Black foreground color
-
2
ANSI_ESCAPE_BLACK = "30"
-
-
# Red foreground color
-
2
ANSI_ESCAPE_RED = "31"
-
-
# Green foreground color
-
2
ANSI_ESCAPE_GREEN = "32"
-
-
# Yellow foreground color
-
2
ANSI_ESCAPE_YELLOW = "33"
-
-
# Blue foreground color
-
2
ANSI_ESCAPE_BLUE = "34"
-
-
# Magenta foreground color
-
2
ANSI_ESCAPE_MAGENTA = "35"
-
-
# Cyan foreground color
-
2
ANSI_ESCAPE_CYAN = "36"
-
-
# White foreground color
-
2
ANSI_ESCAPE_WHITE = "37"
-
-
# Black background color
-
2
ANSI_ESCAPE_BGBLACK = "40"
-
-
# Red background color
-
2
ANSI_ESCAPE_BGRED = "41"
-
-
# Green background color
-
2
ANSI_ESCAPE_BGGREEN = "42"
-
-
# Yellow background color
-
2
ANSI_ESCAPE_BGYELLOW = "43"
-
-
# Blue background color
-
2
ANSI_ESCAPE_BGBLUE = "44"
-
-
# Magenta background color
-
2
ANSI_ESCAPE_BGMAGENTA = "45"
-
-
# Cyan background color
-
2
ANSI_ESCAPE_BGCYAN = "46"
-
-
# White background color
-
2
ANSI_ESCAPE_BGWHITE = "47"
-
end
-
end
-
end
-
2
module Hike
-
2
VERSION = "1.2.0"
-
-
2
autoload :Extensions, "hike/extensions"
-
2
autoload :Index, "hike/index"
-
2
autoload :NormalizedArray, "hike/normalized_array"
-
2
autoload :Paths, "hike/paths"
-
2
autoload :Trail, "hike/trail"
-
end
-
2
require 'hike/normalized_array'
-
-
2
module Hike
-
# `Extensions` is an internal collection for tracking extension names.
-
2
class Extensions < NormalizedArray
-
# Extensions added to this array are normalized with a leading
-
# `.`.
-
#
-
# extensions << "js"
-
# extensions << ".css"
-
#
-
# extensions
-
# # => [".js", ".css"]
-
#
-
2
def normalize_element(extension)
-
22
if extension[/^\./]
-
22
extension
-
else
-
".#{extension}"
-
end
-
end
-
end
-
end
-
2
require 'pathname'
-
-
2
module Hike
-
# `Index` is an internal cached variant of `Trail`. It assumes the
-
# file system does not change between `find` calls. All `stat` and
-
# `entries` calls are cached for the lifetime of the `Index` object.
-
2
class Index
-
# `Index#paths` is an immutable `Paths` collection.
-
2
attr_reader :paths
-
-
# `Index#extensions` is an immutable `Extensions` collection.
-
2
attr_reader :extensions
-
-
# `Index#aliases` is an immutable `Hash` mapping an extension to
-
# an `Array` of aliases.
-
2
attr_reader :aliases
-
-
# `Index.new` is an internal method. Instead of constructing it
-
# directly, create a `Trail` and call `Trail#index`.
-
2
def initialize(root, paths, extensions, aliases)
-
2
@root = root
-
-
# Freeze is used here so an error is throw if a mutator method
-
# is called on the array. Mutating `@paths`, `@extensions`, or
-
# `@aliases` would have unpredictable results.
-
2
@paths = paths.dup.freeze
-
2
@extensions = extensions.dup.freeze
-
2
@aliases = aliases.inject({}) { |h, (k, a)|
-
10
h[k] = a.dup.freeze; h
-
}.freeze
-
62
@pathnames = paths.map { |path| Pathname.new(path) }
-
-
2
@stats = {}
-
2
@entries = {}
-
2
@patterns = {}
-
end
-
-
# `Index#root` returns root path as a `String`. This attribute is immutable.
-
2
def root
-
194
@root.to_s
-
end
-
-
# `Index#index` returns `self` to be compatable with the `Trail` interface.
-
2
def index
-
self
-
end
-
-
# The real implementation of `find`. `Trail#find` generates a one
-
# time index and delegates here.
-
#
-
# See `Trail#find` for usage.
-
2
def find(*logical_paths, &block)
-
16
if block_given?
-
16
options = extract_options!(logical_paths)
-
16
base_path = Pathname.new(options[:base_path] || @root)
-
-
16
logical_paths.each do |logical_path|
-
16
logical_path = Pathname.new(logical_path.sub(/^\//, ''))
-
-
16
if relative?(logical_path)
-
find_in_base_path(logical_path, base_path, &block)
-
else
-
16
find_in_paths(logical_path, &block)
-
end
-
end
-
-
nil
-
else
-
find(*logical_paths) do |path|
-
return path
-
end
-
end
-
end
-
-
# A cached version of `Dir.entries` that filters out `.` files and
-
# `~` swap files. Returns an empty `Array` if the directory does
-
# not exist.
-
2
def entries(path)
-
124
@entries[path.to_s] ||= begin
-
52
pathname = Pathname.new(path)
-
52
if pathname.directory?
-
179
pathname.entries.reject { |entry| entry.to_s =~ /^\.|~$|^\#.*\#$/ }.sort
-
else
-
28
[]
-
end
-
end
-
end
-
-
# A cached version of `File.stat`. Returns nil if the file does
-
# not exist.
-
2
def stat(path)
-
544
key = path.to_s
-
544
if @stats.key?(key)
-
431
@stats[key]
-
113
elsif File.exist?(path)
-
112
@stats[key] = File.stat(path)
-
else
-
1
@stats[key] = nil
-
end
-
end
-
-
2
protected
-
2
def extract_options!(arguments)
-
16
arguments.last.is_a?(Hash) ? arguments.pop.dup : {}
-
end
-
-
2
def relative?(logical_path)
-
16
logical_path.to_s =~ /^\.\.?\//
-
end
-
-
# Finds logical path across all `paths`
-
2
def find_in_paths(logical_path, &block)
-
16
dirname, basename = logical_path.split
-
16
@pathnames.each do |base_path|
-
120
match(base_path.join(dirname), basename, &block)
-
end
-
end
-
-
# Finds relative logical path, `../test/test_trail`. Requires a
-
# `base_path` for reference.
-
2
def find_in_base_path(logical_path, base_path, &block)
-
candidate = base_path.join(logical_path)
-
dirname, basename = candidate.split
-
match(dirname, basename, &block) if paths_contain?(dirname)
-
end
-
-
# Checks if the path is actually on the file system and performs
-
# any syscalls if necessary.
-
2
def match(dirname, basename)
-
# Potential `entries` syscall
-
120
matches = entries(dirname)
-
-
120
pattern = pattern_for(basename)
-
991
matches = matches.select { |m| m.to_s =~ pattern }
-
-
120
sort_matches(matches, basename).each do |path|
-
20
pathname = dirname.join(path)
-
-
# Potential `stat` syscall
-
20
stat = stat(pathname)
-
-
# Exclude directories
-
20
if stat && stat.file?
-
18
yield pathname.to_s
-
end
-
end
-
end
-
-
# Returns true if `dirname` is a subdirectory of any of the `paths`
-
2
def paths_contain?(dirname)
-
paths.any? { |path| dirname.to_s[0, path.length] == path }
-
end
-
-
# Cache results of `build_pattern_for`
-
2
def pattern_for(basename)
-
120
@patterns[basename] ||= build_pattern_for(basename)
-
end
-
-
# Returns a `Regexp` that matches the allowed extensions.
-
#
-
# pattern_for("index.html") #=> /^index(.html|.htm)(.builder|.erb)*$/
-
2
def build_pattern_for(basename)
-
15
extname = basename.extname
-
15
aliases = find_aliases_for(extname)
-
-
15
if aliases.any?
-
2
basename = basename.basename(extname)
-
2
aliases = [extname] + aliases
-
9
aliases_pattern = aliases.map { |e| Regexp.escape(e) }.join("|")
-
2
basename_re = Regexp.escape(basename.to_s) + "(?:#{aliases_pattern})"
-
else
-
13
basename_re = Regexp.escape(basename.to_s)
-
end
-
-
180
extension_pattern = extensions.map { |e| Regexp.escape(e) }.join("|")
-
15
/^#{basename_re}(?:#{extension_pattern})*$/
-
end
-
-
# Sorts candidate matches by their extension
-
# priority. Extensions in the front of the `extensions` carry
-
# more weight.
-
2
def sort_matches(matches, basename)
-
120
aliases = find_aliases_for(basename.extname)
-
-
120
matches.sort_by do |match|
-
21
extnames = match.sub(basename.to_s, '').to_s.scan(/\.[^.]+/)
-
21
extnames.inject(0) do |sum, ext|
-
20
if i = extensions.index(ext)
-
20
sum + i + 1
-
elsif i = aliases.index(ext)
-
sum + i + 11
-
else
-
sum
-
end
-
end
-
end
-
end
-
-
2
def find_aliases_for(extension)
-
135
@aliases.inject([]) do |aliases, (key, value)|
-
675
aliases.push(key) if value == extension
-
675
aliases
-
end
-
end
-
end
-
end
-
2
module Hike
-
# `NormalizedArray` is an internal abstract wrapper class that calls
-
# a callback `normalize_element` anytime an element is added to the
-
# Array.
-
#
-
# `Extensions` and `Paths` are subclasses of `NormalizedArray`.
-
2
class NormalizedArray < Array
-
2
def initialize
-
8
super()
-
end
-
-
2
def []=(*args)
-
value = args.pop
-
-
if value.respond_to?(:to_ary)
-
value = normalize_elements(value)
-
else
-
value = normalize_element(value)
-
end
-
-
super(*args.concat([value]))
-
end
-
-
2
def <<(element)
-
super normalize_element(element)
-
end
-
-
2
def collect!
-
super do |element|
-
result = yield element
-
normalize_element(result)
-
end
-
end
-
-
2
alias_method :map!, :collect!
-
-
2
def insert(index, *elements)
-
super index, *normalize_elements(elements)
-
end
-
-
2
def push(*elements)
-
82
super(*normalize_elements(elements))
-
end
-
-
2
def replace(elements)
-
super normalize_elements(elements)
-
end
-
-
2
def unshift(*elements)
-
super(*normalize_elements(elements))
-
end
-
-
2
def normalize_elements(elements)
-
82
elements.map do |element|
-
82
normalize_element(element)
-
end
-
end
-
end
-
end
-
2
require 'pathname'
-
2
require 'hike/normalized_array'
-
-
2
module Hike
-
# `Paths` is an internal collection for tracking path strings.
-
2
class Paths < NormalizedArray
-
2
def initialize(root = ".")
-
4
@root = Pathname.new(root)
-
4
super()
-
end
-
-
# Relative paths added to this array are expanded relative to `@root`.
-
#
-
# paths = Paths.new("/usr/local")
-
# paths << "tmp"
-
# paths << "/tmp"
-
#
-
# paths
-
# # => ["/usr/local/tmp", "/tmp"]
-
#
-
2
def normalize_element(path)
-
60
path = Pathname.new(path)
-
60
path = @root.join(path) if path.relative?
-
60
path.expand_path.to_s
-
end
-
end
-
end
-
2
require 'pathname'
-
2
require 'hike/extensions'
-
2
require 'hike/index'
-
2
require 'hike/paths'
-
-
2
module Hike
-
# `Trail` is the public container class for holding paths and extensions.
-
2
class Trail
-
# `Trail#paths` is a mutable `Paths` collection.
-
#
-
# trail = Hike::Trail.new
-
# trail.paths.push "~/Projects/hike/lib", "~/Projects/hike/test"
-
#
-
# The order of the paths is significant. Paths in the beginning of
-
# the collection will be checked first. In the example above,
-
# `~/Projects/hike/lib/hike.rb` would shadow the existent of
-
# `~/Projects/hike/test/hike.rb`.
-
2
attr_reader :paths
-
-
# `Trail#extensions` is a mutable `Extensions` collection.
-
#
-
# trail = Hike::Trail.new
-
# trail.paths.push "~/Projects/hike/lib"
-
# trail.extensions.push ".rb"
-
#
-
# Extensions allow you to find files by just their name omitting
-
# their extension. Is similar to Ruby's require mechanism that
-
# allows you to require files with specifiying `foo.rb`.
-
2
attr_reader :extensions
-
-
# `Index#aliases` is a mutable `Hash` mapping an extension to
-
# an `Array` of aliases.
-
#
-
# trail = Hike::Trail.new
-
# trail.paths.push "~/Projects/hike/site"
-
# trail.aliases['.htm'] = 'html'
-
# trail.aliases['.xhtml'] = 'html'
-
# trail.aliases['.php'] = 'html'
-
#
-
# Aliases provide a fallback when the primary extension is not
-
# matched. In the example above, a lookup for "foo.html" will
-
# check for the existence of "foo.htm", "foo.xhtml", or "foo.php".
-
2
attr_reader :aliases
-
-
# A Trail accepts an optional root path that defaults to your
-
# current working directory. Any relative paths added to
-
# `Trail#paths` will expanded relative to the root.
-
2
def initialize(root = ".")
-
4
@root = Pathname.new(root).expand_path
-
4
@paths = Paths.new(@root)
-
4
@extensions = Extensions.new
-
4
@aliases = Hash.new { |h, k| h[k] = Extensions.new }
-
end
-
-
# `Trail#root` returns root path as a `String`. This attribute is immutable.
-
2
def root
-
2
@root.to_s
-
end
-
-
# Prepend `path` to `Paths` collection
-
2
def prepend_paths(*paths)
-
self.paths.unshift(*paths)
-
end
-
2
alias_method :prepend_path, :prepend_paths
-
-
# Append `path` to `Paths` collection
-
2
def append_paths(*paths)
-
60
self.paths.push(*paths)
-
end
-
2
alias_method :append_path, :append_paths
-
-
# Remove `path` from `Paths` collection
-
2
def remove_path(path)
-
self.paths.delete(path)
-
end
-
-
# Prepend `extension` to `Extensions` collection
-
2
def prepend_extensions(*extensions)
-
self.extensions.unshift(*extensions)
-
end
-
2
alias_method :prepend_extension, :prepend_extensions
-
-
# Append `extension` to `Extensions` collection
-
2
def append_extensions(*extensions)
-
22
self.extensions.push(*extensions)
-
end
-
2
alias_method :append_extension, :append_extensions
-
-
# Remove `extension` from `Extensions` collection
-
2
def remove_extension(extension)
-
self.extensions.delete(extension)
-
end
-
-
# Alias `new_extension` to `old_extension`
-
2
def alias_extension(new_extension, old_extension)
-
10
aliases[normalize_extension(new_extension)] = normalize_extension(old_extension)
-
end
-
-
# Remove the alias for `extension`
-
2
def unalias_extension(extension)
-
aliases.delete(normalize_extension(extension))
-
end
-
-
# `Trail#find` returns a the expand path for a logical path in the
-
# path collection.
-
#
-
# trail = Hike::Trail.new "~/Projects/hike"
-
# trail.extensions.push ".rb"
-
# trail.paths.push "lib", "test"
-
#
-
# trail.find "hike/trail"
-
# # => "~/Projects/hike/lib/hike/trail.rb"
-
#
-
# trail.find "test_trail"
-
# # => "~/Projects/hike/test/test_trail.rb"
-
#
-
# `find` accepts multiple fallback logical paths that returns the
-
# first match.
-
#
-
# trail.find "hike", "hike/index"
-
#
-
# is equivalent to
-
#
-
# trail.find("hike") || trail.find("hike/index")
-
#
-
# Though `find` always returns the first match, it is possible
-
# to iterate over all shadowed matches and fallbacks by supplying
-
# a block.
-
#
-
# trail.find("hike", "hike/index") { |path| warn path }
-
#
-
# This allows you to filter your matches by any condition.
-
#
-
# trail.find("application") do |path|
-
# return path if mime_type_for(path) == "text/css"
-
# end
-
#
-
2
def find(*args, &block)
-
index.find(*args, &block)
-
end
-
-
# `Trail#index` returns an `Index` object that has the same
-
# interface as `Trail`. An `Index` is a cached `Trail` object that
-
# does not update when the file system changes. If you are
-
# confident that you are not making changes the paths you are
-
# searching, `index` will avoid excess system calls.
-
#
-
# index = trail.index
-
# index.find "hike/trail"
-
# index.find "test_trail"
-
#
-
2
def index
-
2
Index.new(root, paths, extensions, aliases)
-
end
-
-
# `Trail#entries` is equivalent to `Dir#entries`. It is not
-
# recommend to use this method for general purposes. It exists for
-
# parity with `Index#entries`.
-
2
def entries(path)
-
pathname = Pathname.new(path)
-
if pathname.directory?
-
pathname.entries.reject { |entry| entry.to_s =~ /^\.|~$|^\#.*\#$/ }.sort
-
else
-
[]
-
end
-
end
-
-
# `Trail#stat` is equivalent to `File#stat`. It is not
-
# recommend to use this method for general purposes. It exists for
-
# parity with `Index#stat`.
-
2
def stat(path)
-
if File.exist?(path)
-
File.stat(path.to_s)
-
else
-
nil
-
end
-
end
-
-
2
private
-
2
def normalize_extension(extension)
-
20
if extension[/^\./]
-
20
extension
-
else
-
".#{extension}"
-
end
-
end
-
end
-
end
-
2
require 'i18n/version'
-
2
require 'i18n/exceptions'
-
2
require 'i18n/interpolate/ruby'
-
-
2
module I18n
-
2
autoload :Backend, 'i18n/backend'
-
2
autoload :Config, 'i18n/config'
-
2
autoload :Gettext, 'i18n/gettext'
-
2
autoload :Locale, 'i18n/locale'
-
2
autoload :Tests, 'i18n/tests'
-
-
2
RESERVED_KEYS = [:scope, :default, :separator, :resolve, :object, :fallback, :format, :cascade, :throw, :raise]
-
2
RESERVED_KEYS_PATTERN = /%\{(#{RESERVED_KEYS.join("|")})\}/
-
-
2
extend(Module.new {
-
# Gets I18n configuration object.
-
2
def config
-
603
Thread.current[:i18n_config] ||= I18n::Config.new
-
end
-
-
# Sets I18n configuration object.
-
2
def config=(value)
-
48
Thread.current[:i18n_config] = value
-
end
-
-
# Write methods which delegates to the configuration object
-
%w(locale backend default_locale available_locales default_separator
-
2
exception_handler load_path enforce_available_locales).each do |method|
-
16
module_eval <<-DELEGATORS, __FILE__, __LINE__ + 1
-
def #{method}
-
config.#{method}
-
end
-
-
def #{method}=(value)
-
config.#{method} = (value)
-
end
-
DELEGATORS
-
end
-
-
# Tells the backend to reload translations. Used in situations like the
-
# Rails development environment. Backends can implement whatever strategy
-
# is useful.
-
2
def reload!
-
2
config.clear_available_locales_set
-
2
config.backend.reload!
-
end
-
-
# Translates, pluralizes and interpolates a given key using a given locale,
-
# scope, and default, as well as interpolation values.
-
#
-
# *LOOKUP*
-
#
-
# Translation data is organized as a nested hash using the upper-level keys
-
# as namespaces. <em>E.g.</em>, ActionView ships with the translation:
-
# <tt>:date => {:formats => {:short => "%b %d"}}</tt>.
-
#
-
# Translations can be looked up at any level of this hash using the key argument
-
# and the scope option. <em>E.g.</em>, in this example <tt>I18n.t :date</tt>
-
# returns the whole translations hash <tt>{:formats => {:short => "%b %d"}}</tt>.
-
#
-
# Key can be either a single key or a dot-separated key (both Strings and Symbols
-
# work). <em>E.g.</em>, the short format can be looked up using both:
-
# I18n.t 'date.formats.short'
-
# I18n.t :'date.formats.short'
-
#
-
# Scope can be either a single key, a dot-separated key or an array of keys
-
# or dot-separated keys. Keys and scopes can be combined freely. So these
-
# examples will all look up the same short date format:
-
# I18n.t 'date.formats.short'
-
# I18n.t 'formats.short', :scope => 'date'
-
# I18n.t 'short', :scope => 'date.formats'
-
# I18n.t 'short', :scope => %w(date formats)
-
#
-
# *INTERPOLATION*
-
#
-
# Translations can contain interpolation variables which will be replaced by
-
# values passed to #translate as part of the options hash, with the keys matching
-
# the interpolation variable names.
-
#
-
# <em>E.g.</em>, with a translation <tt>:foo => "foo %{bar}"</tt> the option
-
# value for the key +bar+ will be interpolated into the translation:
-
# I18n.t :foo, :bar => 'baz' # => 'foo baz'
-
#
-
# *PLURALIZATION*
-
#
-
# Translation data can contain pluralized translations. Pluralized translations
-
# are arrays of singluar/plural versions of translations like <tt>['Foo', 'Foos']</tt>.
-
#
-
# Note that <tt>I18n::Backend::Simple</tt> only supports an algorithm for English
-
# pluralization rules. Other algorithms can be supported by custom backends.
-
#
-
# This returns the singular version of a pluralized translation:
-
# I18n.t :foo, :count => 1 # => 'Foo'
-
#
-
# These both return the plural version of a pluralized translation:
-
# I18n.t :foo, :count => 0 # => 'Foos'
-
# I18n.t :foo, :count => 2 # => 'Foos'
-
#
-
# The <tt>:count</tt> option can be used both for pluralization and interpolation.
-
# <em>E.g.</em>, with the translation
-
# <tt>:foo => ['%{count} foo', '%{count} foos']</tt>, count will
-
# be interpolated to the pluralized translation:
-
# I18n.t :foo, :count => 1 # => '1 foo'
-
#
-
# *DEFAULTS*
-
#
-
# This returns the translation for <tt>:foo</tt> or <tt>default</tt> if no translation was found:
-
# I18n.t :foo, :default => 'default'
-
#
-
# This returns the translation for <tt>:foo</tt> or the translation for <tt>:bar</tt> if no
-
# translation for <tt>:foo</tt> was found:
-
# I18n.t :foo, :default => :bar
-
#
-
# Returns the translation for <tt>:foo</tt> or the translation for <tt>:bar</tt>
-
# or <tt>default</tt> if no translations for <tt>:foo</tt> and <tt>:bar</tt> were found.
-
# I18n.t :foo, :default => [:bar, 'default']
-
#
-
# *BULK LOOKUP*
-
#
-
# This returns an array with the translations for <tt>:foo</tt> and <tt>:bar</tt>.
-
# I18n.t [:foo, :bar]
-
#
-
# Can be used with dot-separated nested keys:
-
# I18n.t [:'baz.foo', :'baz.bar']
-
#
-
# Which is the same as using a scope option:
-
# I18n.t [:foo, :bar], :scope => :baz
-
#
-
# *LAMBDAS*
-
#
-
# Both translations and defaults can be given as Ruby lambdas. Lambdas will be
-
# called and passed the key and options.
-
#
-
# E.g. assuming the key <tt>:salutation</tt> resolves to:
-
# lambda { |key, options| options[:gender] == 'm' ? "Mr. %{options[:name]}" : "Mrs. %{options[:name]}" }
-
#
-
# Then <tt>I18n.t(:salutation, :gender => 'w', :name => 'Smith') will result in "Mrs. Smith".
-
#
-
# It is recommended to use/implement lambdas in an "idempotent" way. E.g. when
-
# a cache layer is put in front of I18n.translate it will generate a cache key
-
# from the argument values passed to #translate. Therefor your lambdas should
-
# always return the same translations/values per unique combination of argument
-
# values.
-
2
def translate(*args)
-
106
options = args.last.is_a?(Hash) ? args.pop.dup : {}
-
106
key = args.shift
-
106
backend = config.backend
-
106
locale = options.delete(:locale) || config.locale
-
106
handling = options.delete(:throw) && :throw || options.delete(:raise) && :raise # TODO deprecate :raise
-
-
106
enforce_available_locales!(locale)
-
106
raise I18n::ArgumentError if key.is_a?(String) && key.empty?
-
-
106
result = catch(:exception) do
-
106
if key.is_a?(Array)
-
key.map { |k| backend.translate(locale, k, options) }
-
else
-
106
backend.translate(locale, key, options)
-
end
-
end
-
106
result.is_a?(MissingTranslation) ? handle_exception(handling, result, locale, key, options) : result
-
end
-
2
alias :t :translate
-
-
# Wrapper for <tt>translate</tt> that adds <tt>:raise => true</tt>. With
-
# this option, if no translation is found, it will raise <tt>I18n::MissingTranslationData</tt>
-
2
def translate!(key, options={})
-
translate(key, options.merge(:raise => true))
-
end
-
2
alias :t! :translate!
-
-
# Returns true if a translation exists for a given key, otherwise returns false.
-
2
def exists?(key, locale = config.locale)
-
raise I18n::ArgumentError if key.is_a?(String) && key.empty?
-
config.backend.exists?(locale, key)
-
end
-
-
# Transliterates UTF-8 characters to ASCII. By default this method will
-
# transliterate only Latin strings to an ASCII approximation:
-
#
-
# I18n.transliterate("Ærøskøbing")
-
# # => "AEroskobing"
-
#
-
# I18n.transliterate("日本語")
-
# # => "???"
-
#
-
# It's also possible to add support for per-locale transliterations. I18n
-
# expects transliteration rules to be stored at
-
# <tt>i18n.transliterate.rule</tt>.
-
#
-
# Transliteration rules can either be a Hash or a Proc. Procs must accept a
-
# single string argument. Hash rules inherit the default transliteration
-
# rules, while Procs do not.
-
#
-
# *Examples*
-
#
-
# Setting a Hash in <locale>.yml:
-
#
-
# i18n:
-
# transliterate:
-
# rule:
-
# ü: "ue"
-
# ö: "oe"
-
#
-
# Setting a Hash using Ruby:
-
#
-
# store_translations(:de, :i18n => {
-
# :transliterate => {
-
# :rule => {
-
# "ü" => "ue",
-
# "ö" => "oe"
-
# }
-
# }
-
# )
-
#
-
# Setting a Proc:
-
#
-
# translit = lambda {|string| MyTransliterator.transliterate(string) }
-
# store_translations(:xx, :i18n => {:transliterate => {:rule => translit})
-
#
-
# Transliterating strings:
-
#
-
# I18n.locale = :en
-
# I18n.transliterate("Jürgen") # => "Jurgen"
-
# I18n.locale = :de
-
# I18n.transliterate("Jürgen") # => "Juergen"
-
# I18n.transliterate("Jürgen", :locale => :en) # => "Jurgen"
-
# I18n.transliterate("Jürgen", :locale => :de) # => "Juergen"
-
2
def transliterate(*args)
-
options = args.pop.dup if args.last.is_a?(Hash)
-
key = args.shift
-
locale = options && options.delete(:locale) || config.locale
-
handling = options && (options.delete(:throw) && :throw || options.delete(:raise) && :raise)
-
replacement = options && options.delete(:replacement)
-
enforce_available_locales!(locale)
-
config.backend.transliterate(locale, key, replacement)
-
rescue I18n::ArgumentError => exception
-
handle_exception(handling, exception, locale, key, options || {})
-
end
-
-
# Localizes certain objects, such as dates and numbers to local formatting.
-
2
def localize(object, options = nil)
-
options = options ? options.dup : {}
-
locale = options.delete(:locale) || config.locale
-
format = options.delete(:format) || :default
-
enforce_available_locales!(locale)
-
config.backend.localize(locale, object, format, options)
-
end
-
2
alias :l :localize
-
-
# Executes block with given I18n.locale set.
-
2
def with_locale(tmp_locale = nil)
-
if tmp_locale
-
current_locale = self.locale
-
self.locale = tmp_locale
-
end
-
yield
-
ensure
-
self.locale = current_locale if tmp_locale
-
end
-
-
# Merges the given locale, key and scope into a single array of keys.
-
# Splits keys that contain dots into multiple keys. Makes sure all
-
# keys are Symbols.
-
2
def normalize_keys(locale, key, scope, separator = nil)
-
106
separator ||= I18n.default_separator
-
-
106
keys = []
-
106
keys.concat normalize_key(locale, separator)
-
106
keys.concat normalize_key(scope, separator)
-
106
keys.concat normalize_key(key, separator)
-
106
keys
-
end
-
-
# Returns true when the passed locale, which can be either a String or a
-
# Symbol, is in the list of available locales. Returns false otherwise.
-
2
def locale_available?(locale)
-
106
I18n.config.available_locales_set.include?(locale)
-
end
-
-
# Raises an InvalidLocale exception when the passed locale is not available.
-
2
def enforce_available_locales!(locale)
-
106
if config.enforce_available_locales
-
106
raise I18n::InvalidLocale.new(locale) if !locale_available?(locale)
-
end
-
end
-
-
2
private
-
-
# Any exceptions thrown in translate will be sent to the @@exception_handler
-
# which can be a Symbol, a Proc or any other Object unless they're forced to
-
# be raised or thrown (MissingTranslation).
-
#
-
# If exception_handler is a Symbol then it will simply be sent to I18n as
-
# a method call. A Proc will simply be called. In any other case the
-
# method #call will be called on the exception_handler object.
-
#
-
# Examples:
-
#
-
# I18n.exception_handler = :custom_exception_handler # this is the default
-
# I18n.custom_exception_handler(exception, locale, key, options) # will be called like this
-
#
-
# I18n.exception_handler = lambda { |*args| ... } # a lambda
-
# I18n.exception_handler.call(exception, locale, key, options) # will be called like this
-
#
-
# I18n.exception_handler = I18nExceptionHandler.new # an object
-
# I18n.exception_handler.call(exception, locale, key, options) # will be called like this
-
2
def handle_exception(handling, exception, locale, key, options)
-
48
case handling
-
when :raise
-
raise exception.respond_to?(:to_exception) ? exception.to_exception : exception
-
when :throw
-
48
throw :exception, exception
-
else
-
case handler = options[:exception_handler] || config.exception_handler
-
when Symbol
-
send(handler, exception, locale, key, options)
-
else
-
handler.call(exception, locale, key, options)
-
end
-
end
-
end
-
-
2
def normalize_key(key, separator)
-
320
normalized_key_cache[separator][key] ||=
-
case key
-
when Array
-
3
key.map { |k| normalize_key(k, separator) }.flatten
-
else
-
45
keys = key.to_s.split(separator)
-
45
keys.delete('')
-
227
keys.map! { |k| k.to_sym }
-
45
keys
-
end
-
end
-
-
2
def normalized_key_cache
-
321
@normalized_key_cache ||= Hash.new { |h,k| h[k] = {} }
-
end
-
})
-
end
-
2
module I18n
-
2
module Backend
-
2
autoload :Base, 'i18n/backend/base'
-
2
autoload :InterpolationCompiler, 'i18n/backend/interpolation_compiler'
-
2
autoload :Cache, 'i18n/backend/cache'
-
2
autoload :Cascade, 'i18n/backend/cascade'
-
2
autoload :Chain, 'i18n/backend/chain'
-
2
autoload :Fallbacks, 'i18n/backend/fallbacks'
-
2
autoload :Flatten, 'i18n/backend/flatten'
-
2
autoload :Gettext, 'i18n/backend/gettext'
-
2
autoload :KeyValue, 'i18n/backend/key_value'
-
2
autoload :Memoize, 'i18n/backend/memoize'
-
2
autoload :Metadata, 'i18n/backend/metadata'
-
2
autoload :Pluralization, 'i18n/backend/pluralization'
-
2
autoload :Simple, 'i18n/backend/simple'
-
2
autoload :Transliterator, 'i18n/backend/transliterator'
-
end
-
end
-
2
require 'yaml'
-
2
require 'i18n/core_ext/hash'
-
2
require 'i18n/core_ext/kernel/suppress_warnings'
-
-
2
module I18n
-
2
module Backend
-
2
module Base
-
2
include I18n::Backend::Transliterator
-
-
# Accepts a list of paths to translation files. Loads translations from
-
# plain Ruby (*.rb) or YAML files (*.yml). See #load_rb and #load_yml
-
# for details.
-
2
def load_translations(*filenames)
-
1
filenames = I18n.load_path if filenames.empty?
-
20
filenames.flatten.each { |filename| load_file(filename) }
-
end
-
-
# This method receives a locale, a data hash and options for storing translations.
-
# Should be implemented
-
2
def store_translations(locale, data, options = {})
-
raise NotImplementedError
-
end
-
-
2
def translate(locale, key, options = {})
-
106
raise InvalidLocale.new(locale) unless locale
-
106
entry = key && lookup(locale, key, options[:scope], options)
-
-
106
if options.empty?
-
entry = resolve(locale, key, entry, options)
-
else
-
106
count, default = options.values_at(:count, :default)
-
106
values = options.except(*RESERVED_KEYS)
-
106
entry = entry.nil? && default ?
-
default(locale, key, default, options) : resolve(locale, key, entry, options)
-
end
-
-
106
throw(:exception, I18n::MissingTranslation.new(locale, key, options)) if entry.nil?
-
58
entry = entry.dup if entry.is_a?(String)
-
-
58
entry = pluralize(locale, entry, count) if count
-
58
entry = interpolate(locale, entry, values) if values
-
58
entry
-
end
-
-
2
def exists?(locale, key)
-
lookup(locale, key) != nil
-
end
-
-
# Acts the same as +strftime+, but uses a localized version of the
-
# format string. Takes a key from the date/time formats translations as
-
# a format argument (<em>e.g.</em>, <tt>:short</tt> in <tt>:'date.formats'</tt>).
-
2
def localize(locale, object, format = :default, options = {})
-
raise ArgumentError, "Object must be a Date, DateTime or Time object. #{object.inspect} given." unless object.respond_to?(:strftime)
-
-
if Symbol === format
-
key = format
-
type = object.respond_to?(:sec) ? 'time' : 'date'
-
options = options.merge(:raise => true, :object => object, :locale => locale)
-
format = I18n.t(:"#{type}.formats.#{key}", options)
-
end
-
-
# format = resolve(locale, object, format, options)
-
format = format.to_s.gsub(/%[aAbBpP]/) do |match|
-
case match
-
when '%a' then I18n.t(:"date.abbr_day_names", :locale => locale, :format => format)[object.wday]
-
when '%A' then I18n.t(:"date.day_names", :locale => locale, :format => format)[object.wday]
-
when '%b' then I18n.t(:"date.abbr_month_names", :locale => locale, :format => format)[object.mon]
-
when '%B' then I18n.t(:"date.month_names", :locale => locale, :format => format)[object.mon]
-
when '%p' then I18n.t(:"time.#{object.hour < 12 ? :am : :pm}", :locale => locale, :format => format).upcase if object.respond_to? :hour
-
when '%P' then I18n.t(:"time.#{object.hour < 12 ? :am : :pm}", :locale => locale, :format => format).downcase if object.respond_to? :hour
-
end
-
end
-
-
object.strftime(format)
-
end
-
-
# Returns an array of locales for which translations are available
-
# ignoring the reserved translation meta data key :i18n.
-
2
def available_locales
-
raise NotImplementedError
-
end
-
-
2
def reload!
-
end
-
-
2
protected
-
-
# The method which actually looks up for the translation in the store.
-
2
def lookup(locale, key, scope = [], options = {})
-
raise NotImplementedError
-
end
-
-
# Evaluates defaults.
-
# If given subject is an Array, it walks the array and returns the
-
# first translation that can be resolved. Otherwise it tries to resolve
-
# the translation directly.
-
2
def default(locale, object, subject, options = {})
-
176
options = options.dup.reject { |key, value| key == :default }
-
46
case subject
-
when Array
-
subject.each do |item|
-
84
result = resolve(locale, object, item, options) and return result
-
36
end and nil
-
else
-
10
resolve(locale, object, subject, options)
-
end
-
end
-
-
# Resolves a translation.
-
# If the given subject is a Symbol, it will be translated with the
-
# given options. If it is a Proc then it will be evaluated. All other
-
# subjects will be returned directly.
-
2
def resolve(locale, object, subject, options = {})
-
154
return subject if options[:resolve] == false
-
154
result = catch(:exception) do
-
154
case subject
-
when Symbol
-
60
I18n.translate(subject, options.merge(:locale => locale, :throw => true))
-
when Proc
-
date_or_time = options.delete(:object) || object
-
resolve(locale, object, subject.call(date_or_time, options))
-
else
-
94
subject
-
end
-
end
-
154
result unless result.is_a?(MissingTranslation)
-
end
-
-
# Picks a translation from a pluralized mnemonic subkey according to English
-
# pluralization rules :
-
# - It will pick the :one subkey if count is equal to 1.
-
# - It will pick the :other subkey otherwise.
-
# - It will pick the :zero subkey in the special case where count is
-
# equal to 0 and there is a :zero subkey present. This behaviour is
-
# not stand with regards to the CLDR pluralization rules.
-
# Other backends can implement more flexible or complex pluralization rules.
-
2
def pluralize(locale, entry, count)
-
28
return entry unless entry.is_a?(Hash) && count
-
-
key = :zero if count == 0 && entry.has_key?(:zero)
-
key ||= count == 1 ? :one : :other
-
raise InvalidPluralizationData.new(entry, count) unless entry.has_key?(key)
-
entry[key]
-
end
-
-
# Interpolates values into a given string.
-
#
-
# interpolate "file %{file} opened by %%{user}", :file => 'test.txt', :user => 'Mr. X'
-
# # => "file test.txt opened by %{user}"
-
2
def interpolate(locale, string, values = {})
-
58
if string.is_a?(::String) && !values.empty?
-
48
I18n.interpolate(string, values)
-
else
-
10
string
-
end
-
end
-
-
# Loads a single translations file by delegating to #load_rb or
-
# #load_yml depending on the file extension and directly merges the
-
# data to the existing translations. Raises I18n::UnknownFileType
-
# for all other file extensions.
-
2
def load_file(filename)
-
19
type = File.extname(filename).tr('.', '').downcase
-
19
raise UnknownFileType.new(type, filename) unless respond_to?(:"load_#{type}", true)
-
19
data = send(:"load_#{type}", filename)
-
19
unless data.is_a?(Hash)
-
raise InvalidLocaleData.new(filename, 'expects it to return a hash, but does not')
-
end
-
38
data.each { |locale, d| store_translations(locale, d || {}) }
-
end
-
-
# Loads a plain Ruby translations file. eval'ing the file must yield
-
# a Hash containing translation data with locales as toplevel keys.
-
2
def load_rb(filename)
-
eval(IO.read(filename), binding, filename)
-
end
-
-
# Loads a YAML translations file. The data must have locales as
-
# toplevel keys.
-
2
def load_yml(filename)
-
19
begin
-
19
YAML.load_file(filename)
-
rescue TypeError, ScriptError, StandardError => e
-
raise InvalidLocaleData.new(filename, e.inspect)
-
end
-
end
-
end
-
end
-
end
-
2
module I18n
-
2
module Backend
-
# A simple backend that reads translations from YAML files and stores them in
-
# an in-memory hash. Relies on the Base backend.
-
#
-
# The implementation is provided by a Implementation module allowing to easily
-
# extend Simple backend's behavior by including modules. E.g.:
-
#
-
# module I18n::Backend::Pluralization
-
# def pluralize(*args)
-
# # extended pluralization logic
-
# super
-
# end
-
# end
-
#
-
# I18n::Backend::Simple.include(I18n::Backend::Pluralization)
-
2
class Simple
-
6
(class << self; self; end).class_eval { public :include }
-
-
2
module Implementation
-
2
include Base
-
-
2
def initialized?
-
107
@initialized ||= false
-
end
-
-
# Stores translations for the given locale in memory.
-
# This uses a deep merge for the translations hash, so existing
-
# translations will be overwritten by new ones only at the deepest
-
# level of the hash.
-
2
def store_translations(locale, data, options = {})
-
19
locale = locale.to_sym
-
19
translations[locale] ||= {}
-
19
data = data.deep_symbolize_keys
-
19
translations[locale].deep_merge!(data)
-
end
-
-
# Get available locales from the translations hash
-
2
def available_locales
-
1
init_translations unless initialized?
-
1
translations.inject([]) do |locales, (locale, data)|
-
8
locales << locale unless (data.keys - [:i18n]).empty?
-
8
locales
-
end
-
end
-
-
# Clean up translations hash and set initialized to false on reload!
-
2
def reload!
-
2
@initialized = false
-
2
@translations = nil
-
2
super
-
end
-
-
2
protected
-
-
2
def init_translations
-
1
load_translations
-
1
@initialized = true
-
end
-
-
2
def translations
-
145
@translations ||= {}
-
end
-
-
# Looks up a translation from the translations hash. Returns nil if
-
# eiher key is nil, or locale, scope or key do not exist as a key in the
-
# nested translations hash. Splits keys or scopes containing dots
-
# into multiple keys, i.e. <tt>currency.format</tt> is regarded the same as
-
# <tt>%w(currency format)</tt>.
-
2
def lookup(locale, key, scope = [], options = {})
-
106
init_translations unless initialized?
-
106
keys = I18n.normalize_keys(locale, key, scope, options[:separator])
-
-
106
keys.inject(translations) do |result, _key|
-
366
_key = _key.to_sym
-
366
return nil unless result.is_a?(Hash) && result.has_key?(_key)
-
272
result = result[_key]
-
272
result = resolve(locale, _key, result, options.merge(:scope => nil)) if result.is_a?(Symbol)
-
272
result
-
end
-
end
-
end
-
-
2
include Implementation
-
end
-
end
-
end
-
# encoding: utf-8
-
2
module I18n
-
2
module Backend
-
2
module Transliterator
-
2
DEFAULT_REPLACEMENT_CHAR = "?"
-
-
# Given a locale and a UTF-8 string, return the locale's ASCII
-
# approximation for the string.
-
2
def transliterate(locale, string, replacement = nil)
-
@transliterators ||= {}
-
@transliterators[locale] ||= Transliterator.get I18n.t(:'i18n.transliterate.rule',
-
:locale => locale, :resolve => false, :default => {})
-
@transliterators[locale].transliterate(string, replacement)
-
end
-
-
# Get a transliterator instance.
-
2
def self.get(rule = nil)
-
if !rule || rule.kind_of?(Hash)
-
HashTransliterator.new(rule)
-
elsif rule.kind_of? Proc
-
ProcTransliterator.new(rule)
-
else
-
raise I18n::ArgumentError, "Transliteration rule must be a proc or a hash."
-
end
-
end
-
-
# A transliterator which accepts a Proc as its transliteration rule.
-
2
class ProcTransliterator
-
2
def initialize(rule)
-
@rule = rule
-
end
-
-
2
def transliterate(string, replacement = nil)
-
@rule.call(string)
-
end
-
end
-
-
# A transliterator which accepts a Hash of characters as its translation
-
# rule.
-
2
class HashTransliterator
-
2
DEFAULT_APPROXIMATIONS = {
-
"À"=>"A", "Á"=>"A", "Â"=>"A", "Ã"=>"A", "Ä"=>"A", "Å"=>"A", "Æ"=>"AE",
-
"Ç"=>"C", "È"=>"E", "É"=>"E", "Ê"=>"E", "Ë"=>"E", "Ì"=>"I", "Í"=>"I",
-
"Î"=>"I", "Ï"=>"I", "Ð"=>"D", "Ñ"=>"N", "Ò"=>"O", "Ó"=>"O", "Ô"=>"O",
-
"Õ"=>"O", "Ö"=>"O", "×"=>"x", "Ø"=>"O", "Ù"=>"U", "Ú"=>"U", "Û"=>"U",
-
"Ü"=>"U", "Ý"=>"Y", "Þ"=>"Th", "ß"=>"ss", "à"=>"a", "á"=>"a", "â"=>"a",
-
"ã"=>"a", "ä"=>"a", "å"=>"a", "æ"=>"ae", "ç"=>"c", "è"=>"e", "é"=>"e",
-
"ê"=>"e", "ë"=>"e", "ì"=>"i", "í"=>"i", "î"=>"i", "ï"=>"i", "ð"=>"d",
-
"ñ"=>"n", "ò"=>"o", "ó"=>"o", "ô"=>"o", "õ"=>"o", "ö"=>"o", "ø"=>"o",
-
"ù"=>"u", "ú"=>"u", "û"=>"u", "ü"=>"u", "ý"=>"y", "þ"=>"th", "ÿ"=>"y",
-
"Ā"=>"A", "ā"=>"a", "Ă"=>"A", "ă"=>"a", "Ą"=>"A", "ą"=>"a", "Ć"=>"C",
-
"ć"=>"c", "Ĉ"=>"C", "ĉ"=>"c", "Ċ"=>"C", "ċ"=>"c", "Č"=>"C", "č"=>"c",
-
"Ď"=>"D", "ď"=>"d", "Đ"=>"D", "đ"=>"d", "Ē"=>"E", "ē"=>"e", "Ĕ"=>"E",
-
"ĕ"=>"e", "Ė"=>"E", "ė"=>"e", "Ę"=>"E", "ę"=>"e", "Ě"=>"E", "ě"=>"e",
-
"Ĝ"=>"G", "ĝ"=>"g", "Ğ"=>"G", "ğ"=>"g", "Ġ"=>"G", "ġ"=>"g", "Ģ"=>"G",
-
"ģ"=>"g", "Ĥ"=>"H", "ĥ"=>"h", "Ħ"=>"H", "ħ"=>"h", "Ĩ"=>"I", "ĩ"=>"i",
-
"Ī"=>"I", "ī"=>"i", "Ĭ"=>"I", "ĭ"=>"i", "Į"=>"I", "į"=>"i", "İ"=>"I",
-
"ı"=>"i", "IJ"=>"IJ", "ij"=>"ij", "Ĵ"=>"J", "ĵ"=>"j", "Ķ"=>"K", "ķ"=>"k",
-
"ĸ"=>"k", "Ĺ"=>"L", "ĺ"=>"l", "Ļ"=>"L", "ļ"=>"l", "Ľ"=>"L", "ľ"=>"l",
-
"Ŀ"=>"L", "ŀ"=>"l", "Ł"=>"L", "ł"=>"l", "Ń"=>"N", "ń"=>"n", "Ņ"=>"N",
-
"ņ"=>"n", "Ň"=>"N", "ň"=>"n", "ʼn"=>"'n", "Ŋ"=>"NG", "ŋ"=>"ng",
-
"Ō"=>"O", "ō"=>"o", "Ŏ"=>"O", "ŏ"=>"o", "Ő"=>"O", "ő"=>"o", "Œ"=>"OE",
-
"œ"=>"oe", "Ŕ"=>"R", "ŕ"=>"r", "Ŗ"=>"R", "ŗ"=>"r", "Ř"=>"R", "ř"=>"r",
-
"Ś"=>"S", "ś"=>"s", "Ŝ"=>"S", "ŝ"=>"s", "Ş"=>"S", "ş"=>"s", "Š"=>"S",
-
"š"=>"s", "Ţ"=>"T", "ţ"=>"t", "Ť"=>"T", "ť"=>"t", "Ŧ"=>"T", "ŧ"=>"t",
-
"Ũ"=>"U", "ũ"=>"u", "Ū"=>"U", "ū"=>"u", "Ŭ"=>"U", "ŭ"=>"u", "Ů"=>"U",
-
"ů"=>"u", "Ű"=>"U", "ű"=>"u", "Ų"=>"U", "ų"=>"u", "Ŵ"=>"W", "ŵ"=>"w",
-
"Ŷ"=>"Y", "ŷ"=>"y", "Ÿ"=>"Y", "Ź"=>"Z", "ź"=>"z", "Ż"=>"Z", "ż"=>"z",
-
"Ž"=>"Z", "ž"=>"z"
-
}.freeze
-
-
2
def initialize(rule = nil)
-
@rule = rule
-
add DEFAULT_APPROXIMATIONS.dup
-
add rule if rule
-
end
-
-
2
def transliterate(string, replacement = nil)
-
string.gsub(/[^\x00-\x7f]/u) do |char|
-
approximations[char] || replacement || DEFAULT_REPLACEMENT_CHAR
-
end
-
end
-
-
2
private
-
-
2
def approximations
-
@approximations ||= {}
-
end
-
-
# Add transliteration rules to the approximations hash.
-
2
def add(hash)
-
hash.each do |key, value|
-
approximations[key.to_s] = value.to_s
-
end
-
end
-
end
-
end
-
end
-
end
-
2
class Hash
-
def slice(*keep_keys)
-
h = {}
-
keep_keys.each { |key| h[key] = fetch(key) }
-
h
-
2
end unless Hash.method_defined?(:slice)
-
-
def except(*less_keys)
-
slice(*keys - less_keys)
-
2
end unless Hash.method_defined?(:except)
-
-
def deep_symbolize_keys
-
inject({}) { |result, (key, value)|
-
value = value.deep_symbolize_keys if value.is_a?(Hash)
-
result[(key.to_sym rescue key) || key] = value
-
result
-
}
-
2
end unless Hash.method_defined?(:deep_symbolize_keys)
-
-
# deep_merge_hash! by Stefan Rusterholz, see http://www.ruby-forum.com/topic/142809
-
2
MERGER = proc do |key, v1, v2|
-
Hash === v1 && Hash === v2 ? v1.merge(v2, &MERGER) : v2
-
end
-
-
def deep_merge!(data)
-
merge!(data, &MERGER)
-
2
end unless Hash.method_defined?(:deep_merge!)
-
end
-
-
2
module Kernel
-
2
def suppress_warnings
-
original_verbosity, $VERBOSE = $VERBOSE, nil
-
yield
-
ensure
-
$VERBOSE = original_verbosity
-
end
-
end
-
2
require 'cgi'
-
-
2
module I18n
-
# Handles exceptions raised in the backend. All exceptions except for
-
# MissingTranslationData exceptions are re-thrown. When a MissingTranslationData
-
# was caught the handler returns an error message string containing the key/scope.
-
# Note that the exception handler is not called when the option :throw was given.
-
2
class ExceptionHandler
-
2
include Module.new {
-
2
def call(exception, locale, key, options)
-
case exception
-
when MissingTranslation
-
exception.message
-
when Exception
-
raise exception
-
else
-
throw :exception, exception
-
end
-
end
-
}
-
end
-
-
2
class ArgumentError < ::ArgumentError; end
-
-
2
class InvalidLocale < ArgumentError
-
2
attr_reader :locale
-
2
def initialize(locale)
-
@locale = locale
-
super "#{locale.inspect} is not a valid locale"
-
end
-
end
-
-
2
class InvalidLocaleData < ArgumentError
-
2
attr_reader :filename
-
2
def initialize(filename, exception_message)
-
@filename, @exception_message = filename, exception_message
-
super "can not load translations from #{filename}: #{exception_message}"
-
end
-
end
-
-
2
class MissingTranslation
-
2
module Base
-
2
attr_reader :locale, :key, :options
-
-
2
def initialize(locale, key, options = nil)
-
48
@key, @locale, @options = key, locale, options.dup || {}
-
174
options.each { |k, v| self.options[k] = v.inspect if v.is_a?(Proc) }
-
end
-
-
2
def keys
-
@keys ||= I18n.normalize_keys(locale, key, options[:scope]).tap do |keys|
-
keys << 'no key' if keys.size < 2
-
end
-
end
-
-
2
def message
-
"translation missing: #{keys.join('.')}"
-
end
-
2
alias :to_s :message
-
-
2
def to_exception
-
MissingTranslationData.new(locale, key, options)
-
end
-
end
-
-
2
include Base
-
end
-
-
2
class MissingTranslationData < ArgumentError
-
2
include MissingTranslation::Base
-
end
-
-
2
class InvalidPluralizationData < ArgumentError
-
2
attr_reader :entry, :count
-
2
def initialize(entry, count)
-
@entry, @count = entry, count
-
super "translation data #{entry.inspect} can not be used with :count => #{count}"
-
end
-
end
-
-
2
class MissingInterpolationArgument < ArgumentError
-
2
attr_reader :key, :values, :string
-
2
def initialize(key, values, string)
-
@key, @values, @string = key, values, string
-
super "missing interpolation argument #{key.inspect} in #{string.inspect} (#{values.inspect} given)"
-
end
-
end
-
-
2
class ReservedInterpolationKey < ArgumentError
-
2
attr_reader :key, :string
-
2
def initialize(key, string)
-
@key, @string = key, string
-
super "reserved key #{key.inspect} used in #{string.inspect}"
-
end
-
end
-
-
2
class UnknownFileType < ArgumentError
-
2
attr_reader :type, :filename
-
2
def initialize(type, filename)
-
@type, @filename = type, filename
-
super "can not load translations from #{filename}, the file type #{type} is not known"
-
end
-
end
-
end
-
# heavily based on Masao Mutoh's gettext String interpolation extension
-
# http://github.com/mutoh/gettext/blob/f6566738b981fe0952548c421042ad1e0cdfb31e/lib/gettext/core_ext/string.rb
-
-
2
module I18n
-
2
INTERPOLATION_PATTERN = Regexp.union(
-
/%%/,
-
/%\{(\w+)\}/, # matches placeholders like "%{foo}"
-
/%<(\w+)>(.*?\d*\.?\d*[bBdiouxXeEfgGcps])/ # matches placeholders like "%<foo>.d"
-
)
-
-
2
class << self
-
# Return String or raises MissingInterpolationArgument exception.
-
# Missing argument's logic is handled by I18n.config.missing_interpolation_argument_handler.
-
2
def interpolate(string, values)
-
48
raise ReservedInterpolationKey.new($1.to_sym, string) if string =~ RESERVED_KEYS_PATTERN
-
48
raise ArgumentError.new('Interpolation values must be a Hash.') unless values.kind_of?(Hash)
-
48
interpolate_hash(string, values)
-
end
-
-
2
def interpolate_hash(string, values)
-
48
string.gsub(INTERPOLATION_PATTERN) do |match|
-
2
if match == '%%'
-
'%'
-
else
-
2
key = ($1 || $2).to_sym
-
2
value = if values.key?(key)
-
2
values[key]
-
else
-
config.missing_interpolation_argument_handler.call(key, values, string)
-
end
-
2
value = value.call(values) if value.respond_to?(:call)
-
2
$3 ? sprintf("%#{$3}", value) : value
-
end
-
end
-
end
-
end
-
end
-
2
module I18n
-
2
VERSION = "0.7.0"
-
end
-
2
require 'jbuilder/jbuilder'
-
2
require 'jbuilder/blank'
-
2
require 'jbuilder/key_formatter'
-
2
require 'jbuilder/errors'
-
2
require 'multi_json'
-
2
require 'ostruct'
-
-
2
class Jbuilder
-
2
@@key_formatter = nil
-
2
@@ignore_nil = false
-
-
2
def initialize(options = {})
-
@attributes = {}
-
-
@key_formatter = options.fetch(:key_formatter){ @@key_formatter ? @@key_formatter.clone : nil}
-
@ignore_nil = options.fetch(:ignore_nil, @@ignore_nil)
-
-
yield self if ::Kernel.block_given?
-
end
-
-
# Yields a builder and automatically turns the result into a JSON string
-
2
def self.encode(*args, &block)
-
new(*args, &block).target!
-
end
-
-
2
BLANK = Blank.new
-
2
NON_ENUMERABLES = [ ::Struct, ::OpenStruct ].to_set
-
-
2
def set!(key, value = BLANK, *args)
-
result = if ::Kernel.block_given?
-
if !_blank?(value)
-
# json.comments @post.comments { |comment| ... }
-
# { "comments": [ { ... }, { ... } ] }
-
_scope{ array! value, &::Proc.new }
-
else
-
# json.comments { ... }
-
# { "comments": ... }
-
_merge_block(key){ yield self }
-
end
-
elsif args.empty?
-
if ::Jbuilder === value
-
# json.age 32
-
# json.person another_jbuilder
-
# { "age": 32, "person": { ... }
-
value.attributes!
-
else
-
# json.age 32
-
# { "age": 32 }
-
value
-
end
-
elsif _is_collection?(value)
-
# json.comments @post.comments, :content, :created_at
-
# { "comments": [ { "content": "hello", "created_at": "..." }, { "content": "world", "created_at": "..." } ] }
-
_scope{ array! value, *args }
-
else
-
# json.author @post.creator, :name, :email_address
-
# { "author": { "name": "David", "email_address": "david@loudthinking.com" } }
-
_merge_block(key){ extract! value, *args }
-
end
-
-
_set_value key, result
-
end
-
-
2
def method_missing(*args)
-
if ::Kernel.block_given?
-
set!(*args, &::Proc.new)
-
else
-
set!(*args)
-
end
-
end
-
-
# Specifies formatting to be applied to the key. Passing in a name of a function
-
# will cause that function to be called on the key. So :upcase will upper case
-
# the key. You can also pass in lambdas for more complex transformations.
-
#
-
# Example:
-
#
-
# json.key_format! :upcase
-
# json.author do
-
# json.name "David"
-
# json.age 32
-
# end
-
#
-
# { "AUTHOR": { "NAME": "David", "AGE": 32 } }
-
#
-
# You can pass parameters to the method using a hash pair.
-
#
-
# json.key_format! camelize: :lower
-
# json.first_name "David"
-
#
-
# { "firstName": "David" }
-
#
-
# Lambdas can also be used.
-
#
-
# json.key_format! ->(key){ "_" + key }
-
# json.first_name "David"
-
#
-
# { "_first_name": "David" }
-
#
-
2
def key_format!(*args)
-
@key_formatter = KeyFormatter.new(*args)
-
end
-
-
# Same as the instance method key_format! except sets the default.
-
2
def self.key_format(*args)
-
@@key_formatter = KeyFormatter.new(*args)
-
end
-
-
# If you want to skip adding nil values to your JSON hash. This is useful
-
# for JSON clients that don't deal well with nil values, and would prefer
-
# not to receive keys which have null values.
-
#
-
# Example:
-
# json.ignore_nil! false
-
# json.id User.new.id
-
#
-
# { "id": null }
-
#
-
# json.ignore_nil!
-
# json.id User.new.id
-
#
-
# {}
-
#
-
2
def ignore_nil!(value = true)
-
@ignore_nil = value
-
end
-
-
# Same as instance method ignore_nil! except sets the default.
-
2
def self.ignore_nil(value = true)
-
@@ignore_nil = value
-
end
-
-
# Turns the current element into an array and yields a builder to add a hash.
-
#
-
# Example:
-
#
-
# json.comments do
-
# json.child! { json.content "hello" }
-
# json.child! { json.content "world" }
-
# end
-
#
-
# { "comments": [ { "content": "hello" }, { "content": "world" } ]}
-
#
-
# More commonly, you'd use the combined iterator, though:
-
#
-
# json.comments(@post.comments) do |comment|
-
# json.content comment.formatted_content
-
# end
-
2
def child!
-
@attributes = [] unless ::Array === @attributes
-
@attributes << _scope{ yield self }
-
end
-
-
# Turns the current element into an array and iterates over the passed collection, adding each iteration as
-
# an element of the resulting array.
-
#
-
# Example:
-
#
-
# json.array!(@people) do |person|
-
# json.name person.name
-
# json.age calculate_age(person.birthday)
-
# end
-
#
-
# [ { "name": David", "age": 32 }, { "name": Jamie", "age": 31 } ]
-
#
-
# If you are using Ruby 1.9+, you can use the call syntax instead of an explicit extract! call:
-
#
-
# json.(@people) { |person| ... }
-
#
-
# It's generally only needed to use this method for top-level arrays. If you have named arrays, you can do:
-
#
-
# json.people(@people) do |person|
-
# json.name person.name
-
# json.age calculate_age(person.birthday)
-
# end
-
#
-
# { "people": [ { "name": David", "age": 32 }, { "name": Jamie", "age": 31 } ] }
-
#
-
# If you omit the block then you can set the top level array directly:
-
#
-
# json.array! [1, 2, 3]
-
#
-
# [1,2,3]
-
2
def array!(collection = [], *attributes)
-
array = if collection.nil?
-
[]
-
elsif ::Kernel.block_given?
-
_map_collection(collection, &::Proc.new)
-
elsif attributes.any?
-
_map_collection(collection) { |element| extract! element, *attributes }
-
else
-
collection.to_a
-
end
-
-
merge! array
-
end
-
-
# Extracts the mentioned attributes or hash elements from the passed object and turns them into attributes of the JSON.
-
#
-
# Example:
-
#
-
# @person = Struct.new(:name, :age).new('David', 32)
-
#
-
# or you can utilize a Hash
-
#
-
# @person = { name: 'David', age: 32 }
-
#
-
# json.extract! @person, :name, :age
-
#
-
# { "name": David", "age": 32 }, { "name": Jamie", "age": 31 }
-
#
-
# You can also use the call syntax instead of an explicit extract! call:
-
#
-
# json.(@person, :name, :age)
-
2
def extract!(object, *attributes)
-
if ::Hash === object
-
_extract_hash_values(object, attributes)
-
else
-
_extract_method_values(object, attributes)
-
end
-
end
-
-
2
def call(object, *attributes)
-
if ::Kernel.block_given?
-
array! object, &::Proc.new
-
else
-
extract! object, *attributes
-
end
-
end
-
-
# Returns the nil JSON.
-
2
def nil!
-
@attributes = nil
-
end
-
-
2
alias_method :null!, :nil!
-
-
# Returns the attributes of the current builder.
-
2
def attributes!
-
@attributes
-
end
-
-
# Merges hash or array into current builder.
-
2
def merge!(hash_or_array)
-
@attributes = _merge_values(@attributes, hash_or_array)
-
end
-
-
# Encodes the current builder as JSON.
-
2
def target!
-
::MultiJson.dump(@attributes)
-
end
-
-
2
private
-
-
2
def _extract_hash_values(object, attributes)
-
attributes.each{ |key| _set_value key, object.fetch(key) }
-
end
-
-
2
def _extract_method_values(object, attributes)
-
attributes.each{ |key| _set_value key, object.public_send(key) }
-
end
-
-
2
def _merge_block(key)
-
current_value = _blank? ? BLANK : @attributes.fetch(_key(key), BLANK)
-
raise NullError.build(key) if current_value.nil?
-
new_value = _scope{ yield self }
-
_merge_values(current_value, new_value)
-
end
-
-
2
def _merge_values(current_value, updates)
-
if _blank?(updates)
-
current_value
-
elsif _blank?(current_value) || updates.nil?
-
updates
-
elsif ::Array === updates
-
::Array === current_value ? current_value + updates : updates
-
elsif ::Hash === current_value
-
current_value.merge(updates)
-
else
-
raise "Can't merge #{updates.inspect} with #{current_value.inspect}"
-
end
-
end
-
-
2
def _key(key)
-
@key_formatter ? @key_formatter.format(key) : key.to_s
-
end
-
-
2
def _set_value(key, value)
-
raise NullError.build(key) if @attributes.nil?
-
raise ArrayError.build(key) if ::Array === @attributes
-
return if @ignore_nil && value.nil? or _blank?(value)
-
@attributes = {} if _blank?
-
@attributes[_key(key)] = value
-
end
-
-
2
def _map_collection(collection)
-
collection.map do |element|
-
_scope{ yield element }
-
end - [BLANK]
-
end
-
-
2
def _scope
-
parent_attributes, parent_formatter = @attributes, @key_formatter
-
@attributes = BLANK
-
yield
-
@attributes
-
ensure
-
@attributes, @key_formatter = parent_attributes, parent_formatter
-
end
-
-
2
def _is_collection?(object)
-
_object_respond_to?(object, :map, :count) && NON_ENUMERABLES.none?{ |klass| klass === object }
-
end
-
-
2
def _blank?(value=@attributes)
-
BLANK == value
-
end
-
-
2
def _object_respond_to?(object, *methods)
-
methods.all?{ |m| object.respond_to?(m) }
-
end
-
end
-
-
2
require 'jbuilder/railtie' if defined?(Rails)
-
2
class Jbuilder
-
2
class Blank
-
2
def ==(other)
-
super || Blank === other
-
end
-
-
2
def empty?
-
true
-
end
-
end
-
end
-
2
require 'jbuilder/jbuilder'
-
-
2
dependency_tracker = false
-
-
2
begin
-
2
require 'action_view'
-
2
require 'action_view/dependency_tracker'
-
2
dependency_tracker = ::ActionView::DependencyTracker
-
rescue LoadError
-
begin
-
require 'cache_digests'
-
dependency_tracker = ::CacheDigests::DependencyTracker
-
rescue LoadError
-
end
-
end
-
-
2
if dependency_tracker
-
2
class Jbuilder
-
2
module DependencyTrackerMethods
-
# Matches:
-
# json.partial! "messages/message"
-
# json.partial!('messages/message')
-
#
-
2
DIRECT_RENDERS = /
-
\w+\.partial! # json.partial!
-
\(?\s* # optional parenthesis
-
(['"])([^'"]+)\1 # quoted value
-
/x
-
-
# Matches:
-
# json.partial! partial: "comments/comment"
-
# json.comments @post.comments, partial: "comments/comment", as: :comment
-
# json.array! @posts, partial: "posts/post", as: :post
-
# = render partial: "account"
-
#
-
2
INDIRECT_RENDERS = /
-
(?::partial\s*=>|partial:) # partial: or :partial =>
-
\s* # optional whitespace
-
(['"])([^'"]+)\1 # quoted value
-
/x
-
-
2
def dependencies
-
direct_dependencies + indirect_dependencies + explicit_dependencies
-
end
-
-
2
private
-
-
2
def direct_dependencies
-
source.scan(DIRECT_RENDERS).map(&:second)
-
end
-
-
2
def indirect_dependencies
-
source.scan(INDIRECT_RENDERS).map(&:second)
-
end
-
end
-
end
-
-
2
::Jbuilder::DependencyTracker = Class.new(dependency_tracker::ERBTracker)
-
2
::Jbuilder::DependencyTracker.send :include, ::Jbuilder::DependencyTrackerMethods
-
2
dependency_tracker.register_tracker :jbuilder, ::Jbuilder::DependencyTracker
-
end
-
2
require 'jbuilder/jbuilder'
-
-
2
class Jbuilder
-
2
class NullError < ::NoMethodError
-
2
def self.build(key)
-
message = "Failed to add #{key.to_s.inspect} property to null object"
-
new(message)
-
end
-
end
-
-
2
class ArrayError < ::StandardError
-
2
def self.build(key)
-
message = "Failed to add #{key.to_s.inspect} property to an array"
-
new(message)
-
end
-
end
-
end
-
2
Jbuilder = Class.new(begin
-
2
require 'active_support/proxy_object'
-
2
ActiveSupport::ProxyObject
-
rescue LoadError
-
require 'active_support/basic_object'
-
ActiveSupport::BasicObject
-
end)
-
2
require 'jbuilder/jbuilder'
-
2
require 'action_dispatch/http/mime_type'
-
2
require 'active_support/cache'
-
-
2
class JbuilderTemplate < Jbuilder
-
2
class << self
-
2
attr_accessor :template_lookup_options
-
end
-
-
2
self.template_lookup_options = { handlers: [:jbuilder] }
-
-
2
def initialize(context, *args)
-
@context = context
-
super(*args)
-
end
-
-
2
def partial!(*args)
-
if args.one? && _is_active_model?(args.first)
-
_render_active_model_partial args.first
-
else
-
_render_explicit_partial(*args)
-
end
-
end
-
-
# Caches the json constructed within the block passed. Has the same signature as the `cache` helper
-
# method in `ActionView::Helpers::CacheHelper` and so can be used in the same way.
-
#
-
# Example:
-
#
-
# json.cache! ['v1', @person], expires_in: 10.minutes do
-
# json.extract! @person, :name, :age
-
# end
-
2
def cache!(key=nil, options={})
-
if @context.controller.perform_caching
-
value = ::Rails.cache.fetch(_cache_key(key, options), options) do
-
_scope { yield self }
-
end
-
-
merge! value
-
else
-
yield
-
end
-
end
-
-
# Conditionally caches the json depending in the condition given as first parameter. Has the same
-
# signature as the `cache` helper method in `ActionView::Helpers::CacheHelper` and so can be used in
-
# the same way.
-
#
-
# Example:
-
#
-
# json.cache_if! !admin?, @person, expires_in: 10.minutes do
-
# json.extract! @person, :name, :age
-
# end
-
2
def cache_if!(condition, *args)
-
condition ? cache!(*args, &::Proc.new) : yield
-
end
-
-
2
def array!(collection = [], *args)
-
options = args.first
-
-
if args.one? && _partial_options?(options)
-
partial! options.merge(collection: collection)
-
else
-
super
-
end
-
end
-
-
2
def set!(name, object = BLANK, *args)
-
options = args.first
-
-
if args.one? && _partial_options?(options)
-
_set_inline_partial name, object, options
-
else
-
super
-
end
-
end
-
-
2
private
-
-
2
def _render_partial_with_options(options)
-
options.reverse_merge! locals: {}
-
options.reverse_merge! ::JbuilderTemplate.template_lookup_options
-
as = options[:as]
-
-
if as && options.key?(:collection)
-
as = as.to_sym
-
collection = options.delete(:collection)
-
locals = options.delete(:locals)
-
array! collection do |member|
-
member_locals = locals.clone
-
member_locals.merge! collection: collection
-
member_locals.merge! as => member
-
_render_partial options.merge(locals: member_locals)
-
end
-
else
-
_render_partial options
-
end
-
end
-
-
2
def _render_partial(options)
-
options[:locals].merge! json: self
-
@context.render options
-
end
-
-
2
def _cache_key(key, options)
-
key = _fragment_name_with_digest(key, options)
-
key = url_for(key).split('://', 2).last if ::Hash === key
-
::ActiveSupport::Cache.expand_cache_key(key, :jbuilder)
-
end
-
-
2
def _fragment_name_with_digest(key, options)
-
if @context.respond_to?(:cache_fragment_name)
-
# Current compatibility, fragment_name_with_digest is private again and cache_fragment_name
-
# should be used instead.
-
@context.cache_fragment_name(key, options)
-
elsif @context.respond_to?(:fragment_name_with_digest)
-
# Backwards compatibility for period of time when fragment_name_with_digest was made public.
-
@context.fragment_name_with_digest(key)
-
else
-
key
-
end
-
end
-
-
2
def _partial_options?(options)
-
::Hash === options && options.key?(:as) && options.key?(:partial)
-
end
-
-
2
def _is_active_model?(object)
-
object.class.respond_to?(:model_name) && object.respond_to?(:to_partial_path)
-
end
-
-
2
def _set_inline_partial(name, object, options)
-
value = if object.nil?
-
[]
-
elsif _is_collection?(object)
-
_scope{ _render_partial_with_options options.merge(collection: object) }
-
else
-
locals = ::Hash[options[:as], object]
-
_scope{ _render_partial options.merge(locals: locals) }
-
end
-
-
set! name, value
-
end
-
-
2
def _render_explicit_partial(name_or_options, locals = {})
-
case name_or_options
-
when ::Hash
-
# partial! partial: 'name', foo: 'bar'
-
options = name_or_options
-
else
-
# partial! 'name', locals: {foo: 'bar'}
-
if locals.one? && (locals.keys.first == :locals)
-
options = locals.merge(partial: name_or_options)
-
else
-
options = { partial: name_or_options, locals: locals }
-
end
-
# partial! 'name', foo: 'bar'
-
as = locals.delete(:as)
-
options[:as] = as if as.present?
-
options[:collection] = locals[:collection] if locals.key?(:collection)
-
end
-
-
_render_partial_with_options options
-
end
-
-
2
def _render_active_model_partial(object)
-
@context.render object, json: self
-
end
-
end
-
-
2
class JbuilderHandler
-
2
cattr_accessor :default_format
-
2
self.default_format = Mime[:json]
-
-
2
def self.call(template)
-
# this juggling is required to keep line numbers right in the error
-
%{__already_defined = defined?(json); json||=JbuilderTemplate.new(self); #{template.source}
-
json.target! unless (__already_defined && __already_defined != "method")}
-
end
-
end
-
2
require 'jbuilder/jbuilder'
-
2
require 'active_support/core_ext/array'
-
-
2
class Jbuilder
-
2
class KeyFormatter
-
2
def initialize(*args)
-
@format = {}
-
@cache = {}
-
-
options = args.extract_options!
-
args.each do |name|
-
@format[name] = []
-
end
-
options.each do |name, paramaters|
-
@format[name] = paramaters
-
end
-
end
-
-
2
def initialize_copy(original)
-
@cache = {}
-
end
-
-
2
def format(key)
-
@cache[key] ||= @format.inject(key.to_s) do |result, args|
-
func, args = args
-
if ::Proc === func
-
func.call result, *args
-
else
-
result.send func, *args
-
end
-
end
-
end
-
end
-
end
-
2
require 'rails/railtie'
-
2
require 'jbuilder/jbuilder_template'
-
-
2
class Jbuilder
-
2
class Railtie < ::Rails::Railtie
-
2
initializer :jbuilder do |app|
-
2
ActiveSupport.on_load :action_view do
-
2
ActionView::Template.register_template_handler :jbuilder, JbuilderHandler
-
2
require 'jbuilder/dependency_tracker'
-
end
-
-
2
if app.config.respond_to?(:api_only) && app.config.api_only
-
ActiveSupport.on_load :action_controller do
-
include ActionView::Rendering
-
include ActionController::Helpers
-
include ActionController::ImplicitRender
-
end
-
end
-
end
-
-
2
if Rails::VERSION::MAJOR >= 4
-
2
generators do |app|
-
Rails::Generators.configure! app.config.generators
-
Rails::Generators.hidden_namespaces.uniq!
-
require 'generators/rails/scaffold_controller_generator'
-
end
-
end
-
end
-
end
-
2
module ActionDispatch
-
2
module Assertions
-
2
module SelectorAssertions
-
# Selects content from a JQuery response. Patterned loosely on
-
# assert_select_rjs.
-
#
-
# === Narrowing down
-
#
-
# With no arguments, asserts that one or more method calls are made.
-
#
-
# Use the +method+ argument to narrow down the assertion to only
-
# statements that call that specific method.
-
#
-
# Use the +opt+ argument to narrow down the assertion to only statements
-
# that pass +opt+ as the first argument.
-
#
-
# Use the +id+ argument to narrow down the assertion to only statements
-
# that invoke methods on the result of using that identifier as a
-
# selector.
-
#
-
# === Using blocks
-
#
-
# Without a block, +assert_select_jquery_ merely asserts that the
-
# response contains one or more statements that match the conditions
-
# specified above
-
#
-
# With a block +assert_select_jquery_ also asserts that the method call
-
# passes a javascript escaped string containing HTML. All such HTML
-
# fragments are selected and passed to the block. Nested assertions are
-
# supported.
-
#
-
# === Examples
-
#
-
# # asserts that the #notice element is hidden
-
# assert_select :hide, '#notice'
-
#
-
# # asserts that the #cart element is shown with a blind parameter
-
# assert_select :show, :blind, '#cart'
-
#
-
# # asserts that #cart content contains a #current_item
-
# assert_select :html, '#cart' do
-
# assert_select '#current_item'
-
# end
-
-
2
PATTERN_HTML = "\"((\\\\\"|[^\"])*)\""
-
2
PATTERN_UNICODE_ESCAPED_CHAR = /\\u([0-9a-zA-Z]{4})/
-
-
2
def assert_select_jquery(*args, &block)
-
jquery_method = args.first.is_a?(Symbol) ? args.shift : nil
-
jquery_opt = args.first.is_a?(Symbol) ? args.shift : nil
-
id = args.first.is_a?(String) ? args.shift : nil
-
-
pattern = "\\.#{jquery_method || '\\w+'}\\("
-
pattern = "#{pattern}['\"]#{jquery_opt}['\"],?\\s*" if jquery_opt
-
pattern = "#{pattern}#{PATTERN_HTML}"
-
pattern = "(?:jQuery|\\$)\\(['\"]#{id}['\"]\\)#{pattern}" if id
-
-
fragments = []
-
response.body.scan(Regexp.new(pattern)).each do |match|
-
doc = HTML::Document.new(unescape_js(match.first))
-
doc.root.children.each do |child|
-
fragments.push child if child.tag?
-
end
-
end
-
-
if fragments.empty?
-
opts = [jquery_method, jquery_opt, id].compact
-
flunk "No JQuery call matches #{opts.inspect}"
-
end
-
-
if block
-
begin
-
in_scope, @selected = @selected, fragments
-
yield
-
ensure
-
@selected = in_scope
-
end
-
end
-
end
-
-
2
private
-
-
# Unescapes a JS string.
-
2
def unescape_js(js_string)
-
# js encodes double quotes and line breaks.
-
unescaped= js_string.gsub('\"', '"')
-
unescaped.gsub!('\\\'', "'")
-
unescaped.gsub!(/\\\//, '/')
-
unescaped.gsub!('\n', "\n")
-
unescaped.gsub!('\076', '>')
-
unescaped.gsub!('\074', '<')
-
# js encodes non-ascii characters.
-
unescaped.gsub!(PATTERN_UNICODE_ESCAPED_CHAR) {|u| [$1.hex].pack('U*')}
-
unescaped
-
end
-
-
end
-
end
-
end
-
2
require 'jquery/assert_select' if ::Rails.env.test?
-
2
require 'jquery/rails/engine' if ::Rails.version >= '3.1'
-
2
require 'jquery/rails/railtie'
-
2
require 'jquery/rails/version'
-
-
2
module Jquery
-
2
module Rails
-
2
PROTOTYPE_JS = %w{prototype effects dragdrop controls}
-
end
-
end
-
2
module Jquery
-
2
module Rails
-
2
class Engine < ::Rails::Engine
-
end
-
end
-
end
-
# Used to ensure that Rails 3.0.x, as well as Rails >= 3.1 with asset pipeline disabled
-
# get the minified version of the scripts included into the layout in production.
-
2
module Jquery
-
2
module Rails
-
2
class Railtie < ::Rails::Railtie
-
2
config.before_configuration do
-
2
if config.action_view.javascript_expansions
-
jq_defaults = ::Rails.env.production? || ::Rails.env.test? ? %w(jquery.min) : %w(jquery)
-
-
# Merge the jQuery scripts, remove the Prototype defaults and finally add 'jquery_ujs'
-
# at the end, because load order is important
-
config.action_view.javascript_expansions[:defaults] -= PROTOTYPE_JS + ['rails']
-
config.action_view.javascript_expansions[:defaults] |= jq_defaults + ['jquery_ujs']
-
end
-
end
-
end
-
end
-
end
-
2
module Jquery
-
2
module Rails
-
2
VERSION = "3.1.4"
-
2
JQUERY_VERSION = "1.11.1"
-
2
JQUERY_UJS_VERSION = "1.0.4"
-
end
-
end
-
2
require 'set'
-
2
module Launchy
-
#
-
# Application is the base class of all the application types that launchy may
-
# invoke. It essentially defines the public api of the launchy system.
-
#
-
# Every class that inherits from Application must define:
-
#
-
# 1. A constructor taking no parameters
-
# 2. An instance method 'open' taking a string or URI as the first parameter and a
-
# hash as the second
-
# 3. A class method 'handles?' that takes a String and returns true if that
-
# class can handle the input.
-
2
class Application
-
2
extend DescendantTracker
-
-
2
class << self
-
# Find the application that handles the given uri.
-
#
-
# returns the Class that can handle the uri
-
2
def handling( uri )
-
klass = find_child( :handles?, uri )
-
return klass if klass
-
raise ApplicationNotFoundError, "No application found to handle '#{uri}'"
-
end
-
-
#
-
# Find the given executable in the available paths
-
2
def find_executable( bin, *paths )
-
paths = ENV['PATH'].split( File::PATH_SEPARATOR ) if paths.empty?
-
paths.each do |path|
-
file = File.join( path, bin )
-
if File.executable?( file ) then
-
Launchy.log "#{self.name} : found executable #{file}"
-
return file
-
end
-
end
-
Launchy.log "#{self.name} : Unable to find `#{bin}' in #{paths.join(", ")}"
-
return nil
-
end
-
end
-
-
2
attr_reader :host_os_family
-
2
attr_reader :ruby_engine
-
2
attr_reader :runner
-
-
2
def initialize
-
@host_os_family = Launchy::Detect::HostOsFamily.detect
-
@ruby_engine = Launchy::Detect::RubyEngine.detect
-
@runner = Launchy::Detect::Runner.detect
-
end
-
-
2
def find_executable( bin, *paths )
-
Application.find_executable( bin, *paths )
-
end
-
-
2
def run( cmd, *args )
-
runner.run( cmd, *args )
-
end
-
end
-
end
-
2
require 'launchy/applications/browser'
-
2
class Launchy::Application
-
#
-
# The class handling the browser application and all of its schemes
-
#
-
2
class Browser < Launchy::Application
-
2
def self.schemes
-
%w[ http https ftp file ]
-
end
-
-
2
def self.handles?( uri )
-
return true if schemes.include?( uri.scheme )
-
return true if File.exist?( uri.path )
-
end
-
-
2
def windows_app_list
-
[ 'start "launchy" /b' ]
-
end
-
-
2
def cygwin_app_list
-
[ 'cmd /C start "launchy" /b' ]
-
end
-
-
# hardcode this to open?
-
2
def darwin_app_list
-
[ find_executable( "open" ) ]
-
end
-
-
2
def nix_app_list
-
nix_de = Launchy::Detect::NixDesktopEnvironment.detect
-
list = nix_de.browsers
-
list.find_all { |argv| argv.valid? }
-
end
-
-
# use a call back mechanism to get the right app_list that is decided by the
-
# host_os_family class.
-
2
def app_list
-
host_os_family.app_list( self )
-
end
-
-
2
def browser_env
-
return [] unless ENV['BROWSER']
-
browser_env = ENV['BROWSER'].split( File::PATH_SEPARATOR )
-
browser_env.flatten!
-
browser_env.delete_if { |b| b.nil? || (b.strip.size == 0) }
-
return browser_env
-
end
-
-
# Get the full commandline of what we are going to add the uri to
-
2
def browser_cmdline
-
browser_env.each do |p|
-
Launchy.log "#{self.class.name} : possibility from BROWSER environment variable : #{p}"
-
end
-
app_list.each do |p|
-
Launchy.log "#{self.class.name} : possibility from app_list : #{p}"
-
end
-
-
possibilities = (browser_env + app_list).flatten
-
-
if browser = possibilities.shift then
-
Launchy.log "#{self.class.name} : Using browser value '#{browser}'"
-
return browser
-
end
-
raise Launchy::CommandNotFoundError, "Unable to find a browser command. If this is unexpected, #{Launchy.bug_report_message}"
-
end
-
-
2
def cmd_and_args( uri, options = {} )
-
cmd = browser_cmdline
-
args = [ uri.to_s ]
-
if cmd =~ /%s/ then
-
cmd.gsub!( /%s/, args.shift )
-
end
-
return [cmd, args]
-
end
-
-
# final assembly of the command and do %s substitution
-
# http://www.catb.org/~esr/BROWSER/index.html
-
2
def open( uri, options = {} )
-
cmd, args = cmd_and_args( uri, options )
-
run( cmd, args )
-
end
-
end
-
end
-
2
module Launchy
-
2
class Argv
-
2
attr_reader :argv
-
2
def initialize( *args )
-
@argv = args.flatten
-
end
-
-
2
def to_s
-
@argv.join(' ')
-
end
-
-
2
def to_str
-
to_s
-
end
-
-
2
def [](idx)
-
@argv[idx]
-
end
-
-
2
def valid?
-
(not blank?) && executable?
-
end
-
-
2
def blank?
-
@argv.empty? || (@argv.first.strip.size == 0)
-
end
-
-
2
def executable?
-
::Launchy::Application.find_executable( @argv.first )
-
end
-
-
2
def ==( other )
-
@argv == other.argv
-
end
-
end
-
end
-
2
require 'optparse'
-
-
2
module Launchy
-
2
class Cli
-
-
2
attr_reader :options
-
2
def initialize
-
@options = {}
-
end
-
-
2
def parser
-
@parser ||= OptionParser.new do |op|
-
op.banner = "Usage: launchy [options] thing-to-launch"
-
-
op.separator ""
-
op.separator "Launch Options:"
-
-
op.on( "-a", "--application APPLICATION",
-
"Explicitly specify the application class to use in the launch") do |app|
-
@options[:application] = app
-
end
-
-
op.on( "-d", "--debug",
-
"Force debug. Output lots of information.") do |d|
-
@options[:debug] = true
-
end
-
-
op.on( "-e", "--engine RUBY_ENGINE",
-
"Force launchy to behave as if it was on a particular ruby engine.") do |e|
-
@options[:ruby_engine] = e
-
end
-
-
op.on( "-n", "--dry-run", "Don't launchy, print the command to be executed on stdout" ) do |x|
-
@options[:dry_run] = true
-
end
-
-
op.on( "-o", "--host-os HOST_OS",
-
"Force launchy to behave as if it was on a particular host os.") do |os|
-
@options[:host_os] = os
-
end
-
-
-
op.separator ""
-
op.separator "Standard Options:"
-
-
op.on( "-h", "--help", "Print this message.") do |h|
-
$stdout.puts op.to_s
-
exit 0
-
end
-
-
op.on( "-v", "--version", "Output the version of Launchy") do |v|
-
$stdout.puts "Launchy version #{Launchy::VERSION}"
-
exit 0
-
end
-
-
end
-
end
-
-
2
def parse( argv, env )
-
parser.parse!( argv )
-
return true
-
rescue ::OptionParser::ParseError => pe
-
error_output( pe )
-
end
-
-
2
def good_run( argv, env )
-
if parse( argv, env ) then
-
Launchy.open( argv.shift, options ) { |e| error_output( e ) }
-
return true
-
else
-
return false
-
end
-
end
-
-
2
def error_output( error )
-
$stderr.puts "ERROR: #{error}"
-
Launchy.log "ERROR: #{error}"
-
error.backtrace.each do |bt|
-
Launchy.log bt
-
end
-
$stderr.puts "Try `#{parser.program_name} --help' for more information."
-
return false
-
end
-
-
2
def run( argv = ARGV, env = ENV )
-
exit 1 unless good_run( argv, env )
-
end
-
end
-
end
-
2
module Launchy
-
#
-
# This class is deprecated and will be removed
-
#
-
2
class Browser
-
2
def self.run( *args )
-
Browser.new.visit( args[0] )
-
end
-
-
2
def visit( url )
-
_warn "You made a call to a deprecated Launchy API. This call should be changed to 'Launchy.open( uri )'"
-
report_caller_context( caller )
-
-
::Launchy.open( url )
-
end
-
-
2
private
-
-
2
def find_caller_context( stack )
-
caller_file = stack.find do |line|
-
not line.index( __FILE__ )
-
end
-
if caller_file then
-
caller_fname, caller_line, _ = caller_file.split(":")
-
if File.readable?( caller_fname ) then
-
caller_lines = IO.readlines( caller_fname )
-
context = [ caller_file ]
-
context << caller_lines[(caller_line.to_i)-3, 5]
-
return context.flatten
-
end
-
end
-
return []
-
end
-
-
2
def report_caller_context( stack )
-
context = find_caller_context( stack )
-
if context.size > 0 then
-
_warn "I think I was able to find the location that needs to be fixed. Please go look at:"
-
_warn
-
context.each do |line|
-
_warn line.rstrip
-
end
-
_warn
-
_warn "If this is not the case, please file a bug. #{Launchy.bug_report_message}"
-
end
-
end
-
-
2
def _warn( msg = "" )
-
warn "WARNING: #{msg}"
-
end
-
end
-
end
-
2
require 'set'
-
-
2
module Launchy
-
#
-
# Use by either
-
#
-
# class Foo
-
# extend DescendantTracker
-
# end
-
#
-
# or
-
#
-
# class Foo
-
# class << self
-
# include DescendantTracker
-
# end
-
# end
-
#
-
# It will track all the classes that inherit from the extended class and keep
-
# them in a Set that is available via the 'children' method.
-
#
-
2
module DescendantTracker
-
2
def inherited( klass )
-
34
return unless klass.instance_of?( Class )
-
34
self.children << klass
-
end
-
-
#
-
# The list of children that are registered
-
#
-
2
def children
-
34
unless defined? @children
-
10
@children = Array.new
-
end
-
34
return @children
-
end
-
-
#
-
# Find one of the child classes by calling the given method
-
# and passing all the rest of the parameters to that method in
-
# each child
-
2
def find_child( method, *args )
-
children.find do |child|
-
Launchy.log "Checking if class #{child} is the one for #{method}(#{args.join(', ')})}"
-
child.send( method, *args )
-
end
-
end
-
end
-
end
-
2
module Launchy
-
2
module Detect
-
end
-
end
-
-
2
require 'launchy/detect/host_os'
-
2
require 'launchy/detect/host_os_family'
-
2
require 'launchy/detect/ruby_engine'
-
2
require 'launchy/detect/nix_desktop_environment'
-
2
require 'launchy/detect/runner'
-
2
require 'rbconfig'
-
-
2
module Launchy::Detect
-
2
class HostOs
-
-
2
attr_reader :host_os
-
2
alias to_s host_os
-
2
alias to_str host_os
-
-
2
def initialize( host_os = nil )
-
@host_os = host_os
-
-
if not @host_os then
-
if @host_os = override_host_os then
-
Launchy.log "Using LAUNCHY_HOST_OS override value of '#{Launchy.host_os}'"
-
else
-
@host_os = default_host_os
-
end
-
end
-
end
-
-
2
def default_host_os
-
::RbConfig::CONFIG['host_os']
-
end
-
-
2
def override_host_os
-
Launchy.host_os
-
end
-
-
end
-
-
end
-
2
module Launchy::Detect
-
# Detect the current host os family
-
#
-
# If the current host familiy cannot be detected then return
-
# HostOsFamily::Unknown
-
2
class HostOsFamily
-
2
class NotFoundError < Launchy::Error; end
-
2
extend ::Launchy::DescendantTracker
-
-
2
class << self
-
-
2
def detect( host_os = HostOs.new )
-
found = find_child( :matches?, host_os )
-
return found.new( host_os ) if found
-
raise NotFoundError, "Unknown OS family for host os '#{host_os}'. #{Launchy.bug_report_message}"
-
end
-
-
2
def matches?( host_os )
-
matching_regex.match( host_os.to_s )
-
end
-
-
2
def windows?() self == Windows; end
-
2
def darwin?() self == Darwin; end
-
2
def nix?() self == Nix; end
-
2
def cygwin?() self == Cygwin; end
-
end
-
-
-
2
attr_reader :host_os
-
2
def initialize( host_os = HostOs.new )
-
@host_os = host_os
-
end
-
-
2
def windows?() self.class.windows?; end
-
2
def darwin?() self.class.darwin?; end
-
2
def nix?() self.class.nix?; end
-
2
def cygwin?() self.class.cygwin?; end
-
-
#---------------------------
-
# All known host os families
-
#---------------------------
-
#
-
2
class Windows < HostOsFamily
-
2
def self.matching_regex
-
/(mingw|mswin|windows)/i
-
end
-
2
def app_list( app ) app.windows_app_list; end
-
end
-
-
2
class Darwin < HostOsFamily
-
2
def self.matching_regex
-
/(darwin|mac os)/i
-
end
-
2
def app_list( app ) app.darwin_app_list; end
-
end
-
-
2
class Nix < HostOsFamily
-
2
def self.matching_regex
-
/(linux|bsd|aix|solaris)/i
-
end
-
2
def app_list( app ) app.nix_app_list; end
-
end
-
-
2
class Cygwin < HostOsFamily
-
2
def self.matching_regex
-
/cygwin/i
-
end
-
2
def app_list( app ) app.cygwin_app_list; end
-
end
-
end
-
end
-
2
module Launchy::Detect
-
#
-
# Detect the current desktop environment for *nix machines
-
# Currently this is Linux centric. The detection is based upon the detection
-
# used by xdg-open from http://portland.freedesktop.org/
-
2
class NixDesktopEnvironment
-
2
class NotFoundError < Launchy::Error; end
-
-
2
extend ::Launchy::DescendantTracker
-
-
# Detect the current *nix desktop environment
-
#
-
# If the current dekstop environment be detected, the return
-
# NixDekstopEnvironment::Unknown
-
2
def self.detect
-
found = find_child( :is_current_desktop_environment? )
-
Launchy.log("Current Desktop environment not found. #{Launchy.bug_report_message}") unless found
-
return found
-
end
-
-
2
def self.fallback_browsers
-
%w[ firefox iceweasel seamonkey opera mozilla netscape galeon ].map { |x| ::Launchy::Argv.new( x ) }
-
end
-
-
2
def self.browsers
-
[ browser, fallback_browsers ].flatten
-
end
-
-
#---------------------------------------
-
# The list of known desktop environments
-
#---------------------------------------
-
-
2
class Kde < NixDesktopEnvironment
-
2
def self.is_current_desktop_environment?
-
ENV['KDE_FULL_SESSION']
-
end
-
-
2
def self.browser
-
::Launchy::Argv.new( %w[ kfmclient openURL ] )
-
end
-
end
-
-
2
class Gnome < NixDesktopEnvironment
-
2
def self.is_current_desktop_environment?
-
ENV['GNOME_DESKTOP_SESSION_ID'] &&
-
Launchy::Application.find_executable( 'gnome-open' )
-
end
-
-
2
def self.browser
-
::Launchy::Argv.new( 'gnome-open' )
-
end
-
end
-
-
2
class Xfce < NixDesktopEnvironment
-
2
def self.is_current_desktop_environment?
-
if Launchy::Application.find_executable( 'xprop' ) then
-
%x[ xprop -root _DT_SAVE_MODE].include?("xfce")
-
else
-
false
-
end
-
end
-
-
2
def self.browser
-
::Launchy::Argv.new( %w[ exo-open --launch WebBrowser ] )
-
end
-
end
-
-
# Fall back environment as the last case
-
2
class Xdg < NixDesktopEnvironment
-
2
def self.is_current_desktop_environment?
-
Launchy::Application.find_executable( browser )
-
end
-
-
2
def self.browser
-
::Launchy::Argv.new( 'xdg-open' )
-
end
-
end
-
-
# The one that is found when all else fails. And this must be declared last
-
2
class NotFound < NixDesktopEnvironment
-
2
def self.is_current_desktop_environment?
-
true
-
end
-
-
2
def self.browser
-
::Launchy::Argv.new
-
end
-
end
-
-
end
-
end
-
-
2
module Launchy::Detect
-
2
class RubyEngine
-
2
class NotFoundError < Launchy::Error; end
-
-
2
extend ::Launchy::DescendantTracker
-
-
# Detect the current ruby engine.
-
#
-
# If the current ruby engine cannot be detected, the return
-
# RubyEngine::Unknown
-
2
def self.detect( ruby_engine = RubyEngine.new )
-
found = find_child( :is_current_engine?, ruby_engine.to_s )
-
return found if found
-
raise NotFoundError, "#{ruby_engine_error_message( ruby_engine )} #{Launchy.bug_report_message}"
-
end
-
-
2
def self.ruby_engine_error_message( ruby_engine )
-
msg = "Unkonwn RUBY_ENGINE "
-
if ruby_engine then
-
msg += " '#{ruby_engine}'."
-
elsif defined?( RUBY_ENGINE ) then
-
msg += " '#{RUBY_ENGINE}'."
-
else
-
msg = "RUBY_ENGINE not defined for #{RUBY_DESCRIPTION}."
-
end
-
return msg
-
end
-
-
2
def self.is_current_engine?( ruby_engine )
-
return ruby_engine == self.engine_name
-
end
-
-
2
def self.mri?() self == Mri; end
-
2
def self.jruby?() self == Jruby; end
-
2
def self.rbx?() self == Rbx; end
-
2
def self.macruby?() self == MacRuby; end
-
-
2
attr_reader :ruby_engine
-
2
alias to_s ruby_engine
-
2
def initialize( ruby_engine = Launchy.ruby_engine )
-
if ruby_engine then
-
@ruby_engine = ruby_engine
-
else
-
@ruby_engine = defined?( RUBY_ENGINE ) ? RUBY_ENGINE : "ruby"
-
end
-
end
-
-
-
#-------------------------------
-
# The list of known ruby engines
-
#-------------------------------
-
-
#
-
# This is the ruby engine if the RUBY_ENGINE constant is not defined
-
2
class Mri < RubyEngine
-
2
def self.engine_name() "ruby"; end
-
2
def self.is_current_engine?( ruby_engine )
-
if ruby_engine then
-
super( ruby_engine )
-
else
-
return true if not Launchy.ruby_engine and not defined?( RUBY_ENGINE )
-
end
-
end
-
end
-
-
2
class Jruby < RubyEngine
-
2
def self.engine_name() "jruby"; end
-
end
-
-
2
class Rbx < RubyEngine
-
2
def self.engine_name() "rbx"; end
-
end
-
-
2
class MacRuby < RubyEngine
-
2
def self.engine_name() "macruby"; end
-
end
-
end
-
end
-
2
require 'shellwords'
-
2
require 'stringio'
-
-
2
module Launchy::Detect
-
2
class Runner
-
2
class NotFoundError < Launchy::Error; end
-
-
2
extend ::Launchy::DescendantTracker
-
-
# Detect the current command runner
-
#
-
# This will return an instance of the Runner to be used to do the
-
# application launching.
-
#
-
# If a runner cannot be detected then raise Runner::NotFoundError
-
#
-
# The runner rules are, in order:
-
#
-
# 1) If you are on windows, you use the Windows Runner no matter what
-
# 2) If you are using the jruby engine, use the Jruby Runner. Unless rule
-
# (1) took effect
-
# 3) Use Forkable (barring rules (1) and (2))
-
2
def self.detect
-
host_os_family = Launchy::Detect::HostOsFamily.detect
-
ruby_engine = Launchy::Detect::RubyEngine.detect
-
-
return Windows.new if host_os_family.windows?
-
if ruby_engine.jruby? then
-
return Jruby.new
-
end
-
return Forkable.new
-
end
-
-
#
-
# cut it down to just the shell commands that will be passed to exec or
-
# posix_spawn. The cmd argument is split according to shell rules and the
-
# args are not escaped because they whole set is passed to system as *args
-
# and in that case system shell escaping rules are not done.
-
#
-
2
def shell_commands( cmd, args )
-
cmdline = [ cmd.to_s.shellsplit ]
-
cmdline << args.flatten.collect{ |a| a.to_s }
-
return commandline_normalize( cmdline )
-
end
-
-
2
def commandline_normalize( cmdline )
-
c = cmdline.flatten!
-
c = c.find_all { |a| (not a.nil?) and ( a.size > 0 ) }
-
Launchy.log "commandline_normalized => #{c.join(' ')}"
-
return c
-
end
-
-
2
def dry_run( cmd, *args )
-
shell_commands(cmd, args).join(" ")
-
end
-
-
2
def run( cmd, *args )
-
raise Launchy::CommandNotFoundError, "No command found to run with args '#{args.join(' ')}'. If this is unexpected, #{Launchy.bug_report_message}" unless cmd
-
if Launchy.dry_run? then
-
$stdout.puts dry_run( cmd, *args )
-
else
-
wet_run( cmd, *args )
-
end
-
end
-
-
-
#---------------------------------------
-
# The list of known runners
-
#---------------------------------------
-
-
2
class Windows < Runner
-
-
2
def all_args( cmd, *args )
-
args = [ 'cmd', '/c', *shell_commands( cmd, *args ) ]
-
Launchy.log "Windows: all_args => #{args.inspect}"
-
return args
-
end
-
-
2
def dry_run( cmd, *args )
-
all_args( cmd, *args ).join(" ")
-
end
-
-
# escape the reserved shell characters in windows command shell
-
# http://technet.microsoft.com/en-us/library/cc723564.aspx
-
#
-
# Also make sure that the item after 'start' is guaranteed to be quoted.
-
# https://github.com/copiousfreetime/launchy/issues/62
-
2
def shell_commands( cmd, *args )
-
parts = cmd.shellsplit
-
-
if start_idx = parts.index('start') then
-
title_idx = start_idx + 1
-
title = parts[title_idx]
-
title = title.sub(/^/,'"') unless title[0] == '"'
-
title = title.sub(/$/,'"') unless title[-1] == '"'
-
parts[title_idx] = title
-
end
-
-
cmdline = [ parts ]
-
cmdline << args.flatten.collect { |a| a.to_s.gsub(/([&|()<>^])/, "^\\1") }
-
return commandline_normalize( cmdline )
-
end
-
-
2
def wet_run( cmd, *args )
-
system( *all_args( cmd, *args ) )
-
end
-
end
-
-
2
class Jruby < Runner
-
2
def wet_run( cmd, *args )
-
require 'spoon'
-
Spoon.spawnp( *shell_commands( cmd, *args ) )
-
end
-
end
-
-
2
class Forkable < Runner
-
2
attr_reader :child_pid
-
-
2
def wet_run( cmd, *args )
-
@child_pid = fork do
-
close_file_descriptors unless Launchy.debug?
-
Launchy.log("wet_run: before exec in child process")
-
exec_or_raise( cmd, *args )
-
exit!
-
end
-
Process.detach( @child_pid )
-
end
-
-
2
private
-
-
# attaching to a StringIO instead of reopening so we don't loose the
-
# STDERR, needed for exec_or_raise.
-
2
def close_file_descriptors
-
$stdin.reopen( "/dev/null")
-
-
@saved_stdout = $stdout
-
@saved_stderr = $stderr
-
-
$stdout = StringIO.new
-
$stderr = StringIO.new
-
end
-
-
2
def exec_or_raise( cmd, *args )
-
exec( *shell_commands( cmd, *args ))
-
rescue Exception => e
-
$stderr = @saved_stderr
-
$stdout = @saved_stdout
-
raise e
-
end
-
end
-
end
-
end
-
2
module Launchy
-
2
class Error < ::StandardError; end
-
2
class ApplicationNotFoundError < Error; end
-
2
class CommandNotFoundError < Error; end
-
2
class ArgumentError < Error; end
-
end
-
2
module Launchy
-
2
VERSION = "2.4.3"
-
-
2
module Version
-
-
2
MAJOR = Integer(VERSION.split('.')[0])
-
2
MINOR = Integer(VERSION.split('.')[1])
-
2
PATCH = Integer(VERSION.split('.')[2])
-
-
2
def self.to_a
-
[MAJOR, MINOR, PATCH]
-
end
-
-
2
def self.to_s
-
VERSION
-
end
-
end
-
end
-
2
require 'logger'
-
2
require 'listen/logger'
-
2
require 'listen/listener'
-
-
2
require 'listen/internals/thread_pool'
-
-
# Always set up logging by default first time file is required
-
#
-
# NOTE: If you need to clear the logger completely, do so *after*
-
# requiring this file. If you need to set a custom logger,
-
# require the listen/logger file and set the logger before requiring
-
# this file.
-
2
Listen.setup_default_logger_if_unset
-
-
# Won't print anything by default because of level - unless you've set
-
# LISTEN_GEM_DEBUGGING or provided your own logger with a high enough level
-
2
Listen::Logger.info "Listen loglevel set to: #{Listen.logger.level}"
-
2
Listen::Logger.info "Listen version: #{Listen::VERSION}"
-
-
2
module Listen
-
2
class << self
-
# Listens to file system modifications on a either single directory or
-
# multiple directories.
-
#
-
# @param (see Listen::Listener#new)
-
#
-
# @yield [modified, added, removed] the changed files
-
# @yieldparam [Array<String>] modified the list of modified files
-
# @yieldparam [Array<String>] added the list of added files
-
# @yieldparam [Array<String>] removed the list of removed files
-
#
-
# @return [Listen::Listener] the listener
-
#
-
2
def to(*args, &block)
-
@listeners ||= []
-
Listener.new(*args, &block).tap do |listener|
-
@listeners << listener
-
end
-
end
-
-
# This is used by the `listen` binary to handle Ctrl-C
-
#
-
2
def stop
-
Internals::ThreadPool.stop
-
@listeners ||= []
-
-
# TODO: should use a mutex for this
-
@listeners.each do |listener|
-
# call stop to halt the main loop
-
listener.stop
-
end
-
@listeners = nil
-
end
-
end
-
end
-
2
require 'listen/adapter/base'
-
2
require 'listen/adapter/bsd'
-
2
require 'listen/adapter/darwin'
-
2
require 'listen/adapter/linux'
-
2
require 'listen/adapter/polling'
-
2
require 'listen/adapter/windows'
-
-
2
module Listen
-
2
module Adapter
-
2
OPTIMIZED_ADAPTERS = [Darwin, Linux, BSD, Windows]
-
2
POLLING_FALLBACK_MESSAGE = 'Listen will be polling for changes.'\
-
'Learn more at https://github.com/guard/listen#listen-adapters.'
-
-
2
def self.select(options = {})
-
_log :debug, 'Adapter: considering polling ...'
-
return Polling if options[:force_polling]
-
_log :debug, 'Adapter: considering optimized backend...'
-
return _usable_adapter_class if _usable_adapter_class
-
_log :debug, 'Adapter: falling back to polling...'
-
_warn_polling_fallback(options)
-
Polling
-
rescue
-
_log :warn, format('Adapter: failed: %s:%s', $ERROR_POSITION.inspect,
-
$ERROR_POSITION * "\n")
-
raise
-
end
-
-
2
private
-
-
2
def self._usable_adapter_class
-
OPTIMIZED_ADAPTERS.detect(&:usable?)
-
end
-
-
2
def self._warn_polling_fallback(options)
-
msg = options.fetch(:polling_fallback_message, POLLING_FALLBACK_MESSAGE)
-
Kernel.warn "[Listen warning]:\n #{msg}" if msg
-
end
-
-
2
def self._log(type, message)
-
Listen::Logger.send(type, message)
-
end
-
end
-
end
-
2
require 'listen/options'
-
2
require 'listen/record'
-
2
require 'listen/change'
-
-
2
module Listen
-
2
module Adapter
-
2
class Base
-
2
attr_reader :options
-
-
# TODO: only used by tests
-
2
DEFAULTS = {}
-
-
2
attr_reader :config
-
-
2
def initialize(config)
-
@started = false
-
@config = config
-
-
@configured = nil
-
-
fail 'No directories to watch!' if config.directories.empty?
-
-
defaults = self.class.const_get('DEFAULTS')
-
@options = Listen::Options.new(config.adapter_options, defaults)
-
rescue
-
_log_exception 'adapter config failed: %s:%s called from: %s', caller
-
raise
-
end
-
-
# TODO: it's a separate method as a temporary workaround for tests
-
2
def configure
-
if @configured
-
_log(:warn, 'Adapter already configured!')
-
return
-
end
-
-
@configured = true
-
-
@callbacks ||= {}
-
config.directories.each do |dir|
-
callback = @callbacks[dir] || lambda do |event|
-
_process_event(dir, event)
-
end
-
@callbacks[dir] = callback
-
_configure(dir, &callback)
-
end
-
-
@snapshots ||= {}
-
# TODO: separate config per directory (some day maybe)
-
change_config = Change::Config.new(config.queue, config.silencer)
-
config.directories.each do |dir|
-
record = Record.new(dir)
-
snapshot = Change.new(change_config, record)
-
@snapshots[dir] = snapshot
-
end
-
end
-
-
2
def started?
-
@started
-
end
-
-
2
def start
-
configure
-
-
if started?
-
_log(:warn, 'Adapter already started!')
-
return
-
end
-
-
@started = true
-
-
calling_stack = caller.dup
-
Listen::Internals::ThreadPool.add do
-
begin
-
@snapshots.values.each do |snapshot|
-
_timed('Record.build()') { snapshot.record.build }
-
end
-
_run
-
rescue
-
msg = 'run() in thread failed: %s:\n'\
-
' %s\n\ncalled from:\n %s'
-
_log_exception(msg, calling_stack)
-
raise # for unit tests mostly
-
end
-
end
-
end
-
-
2
def stop
-
_stop
-
end
-
-
2
def self.usable?
-
const_get('OS_REGEXP') =~ RbConfig::CONFIG['target_os']
-
end
-
-
2
private
-
-
2
def _stop
-
end
-
-
2
def _timed(title)
-
start = Time.now.to_f
-
yield
-
diff = Time.now.to_f - start
-
Listen::Logger.info format('%s: %.05f seconds', title, diff)
-
rescue
-
Listen::Logger.warn "#{title} crashed: #{$ERROR_INFO.inspect}"
-
raise
-
end
-
-
# TODO: allow backend adapters to pass specific invalidation objects
-
# e.g. Darwin -> DirRescan, INotify -> MoveScan, etc.
-
2
def _queue_change(type, dir, rel_path, options)
-
@snapshots[dir].invalidate(type, rel_path, options)
-
end
-
-
2
def _log(*args, &block)
-
self.class.send(:_log, *args, &block)
-
end
-
-
2
def _log_exception(msg, caller_stack)
-
formatted = format(
-
msg,
-
$ERROR_INFO,
-
$ERROR_POSITION * "\n",
-
caller_stack * "\n"
-
)
-
-
_log(:error, formatted)
-
end
-
-
2
def self._log(*args, &block)
-
Listen::Logger.send(*args, &block)
-
end
-
end
-
end
-
end
-
# Listener implementation for BSD's `kqueue`.
-
# @see http://www.freebsd.org/cgi/man.cgi?query=kqueue
-
# @see https://github.com/mat813/rb-kqueue/blob/master/lib/rb-kqueue/queue.rb
-
#
-
2
module Listen
-
2
module Adapter
-
2
class BSD < Base
-
2
OS_REGEXP = /bsd|dragonfly/i
-
-
2
DEFAULTS = {
-
events: [
-
:delete,
-
:write,
-
:extend,
-
:attrib,
-
:rename
-
# :link, :revoke
-
]
-
}
-
-
2
BUNDLER_DECLARE_GEM = <<-EOS.gsub(/^ {6}/, '')
-
Please add the following to your Gemfile to avoid polling for changes:
-
require 'rbconfig'
-
if RbConfig::CONFIG['target_os'] =~ /#{OS_REGEXP}/
-
gem 'rb-kqueue', '>= 0.2'
-
end
-
EOS
-
-
2
def self.usable?
-
return false unless super
-
require 'rb-kqueue'
-
require 'find'
-
true
-
rescue LoadError
-
Kernel.warn BUNDLER_DECLARE_GEM
-
false
-
end
-
-
2
private
-
-
2
def _configure(directory, &_callback)
-
@worker ||= KQueue::Queue.new
-
@callback = _callback
-
# use Record to make a snapshot of dir, so we
-
# can detect new files
-
_find(directory.to_s) { |path| _watch_file(path, @worker) }
-
end
-
-
2
def _run
-
@worker.run
-
end
-
-
2
def _process_event(dir, event)
-
full_path = _event_path(event)
-
if full_path.directory?
-
# Force dir content tracking to kick in, or we won't have
-
# names of added files
-
_queue_change(:dir, dir, '.', recursive: true)
-
elsif full_path.exist?
-
path = full_path.relative_path_from(dir)
-
_queue_change(:file, dir, path.to_s, change: _change(event.flags))
-
end
-
-
# If it is a directory, and it has a write flag, it means a
-
# file has been added so find out which and deal with it.
-
# No need to check for removed files, kqueue will forget them
-
# when the vfs does.
-
_watch_for_new_file(event) if full_path.directory?
-
end
-
-
2
def _change(event_flags)
-
{ modified: [:attrib, :extend],
-
added: [:write],
-
removed: [:rename, :delete]
-
}.each do |change, flags|
-
return change unless (flags & event_flags).empty?
-
end
-
nil
-
end
-
-
2
def _event_path(event)
-
Pathname.new(event.watcher.path)
-
end
-
-
2
def _watch_for_new_file(event)
-
queue = event.watcher.queue
-
_find(_event_path(event).to_s) do |file_path|
-
unless queue.watchers.detect { |_, v| v.path == file_path.to_s }
-
_watch_file(file_path, queue)
-
end
-
end
-
end
-
-
2
def _watch_file(path, queue)
-
queue.watch_file(path, *options.events, &@callback)
-
rescue Errno::ENOENT => e
-
_log :warn, "kqueue: watch file failed: #{e.message}"
-
end
-
-
# Quick rubocop workaround
-
2
def _find(*paths, &block)
-
Find.send(:find, *paths, &block)
-
end
-
end
-
end
-
end
-
2
require 'pathname'
-
-
2
module Listen
-
2
module Adapter
-
2
class Config
-
2
attr_reader :directories
-
2
attr_reader :silencer
-
2
attr_reader :queue
-
2
attr_reader :adapter_options
-
-
2
def initialize(directories, queue, silencer, adapter_options)
-
# Default to current directory if no directories are supplied
-
directories = [Dir.pwd] if directories.to_a.empty?
-
-
# TODO: fix (flatten, array, compact?)
-
@directories = directories.map do |directory|
-
Pathname.new(directory.to_s).realpath
-
end
-
-
@silencer = silencer
-
@queue = queue
-
@adapter_options = adapter_options
-
end
-
end
-
end
-
end
-
2
require 'thread'
-
2
require 'listen/internals/thread_pool'
-
-
2
module Listen
-
2
module Adapter
-
# Adapter implementation for Mac OS X `FSEvents`.
-
#
-
2
class Darwin < Base
-
2
OS_REGEXP = /darwin(1.+)?$/i
-
-
# The default delay between checking for changes.
-
2
DEFAULTS = { latency: 0.1 }
-
-
2
private
-
-
# NOTE: each directory gets a DIFFERENT callback!
-
2
def _configure(dir, &callback)
-
require 'rb-fsevent'
-
-
opts = { latency: options.latency }
-
-
@workers ||= ::Queue.new
-
@workers << FSEvent.new.tap do |worker|
-
_log :debug, "fsevent: watching: #{dir.to_s.inspect}"
-
worker.watch(dir.to_s, opts, &callback)
-
end
-
end
-
-
2
def _run
-
first = @workers.pop
-
-
# NOTE: _run is called within a thread, so run every other
-
# worker in it's own thread
-
_run_workers_in_background(_to_array(@workers))
-
_run_worker(first)
-
end
-
-
2
def _process_event(dir, event)
-
_log :debug, "fsevent: processing event: #{event.inspect}"
-
event.each do |path|
-
new_path = Pathname.new(path.sub(/\/$/, ''))
-
_log :debug, "fsevent: #{new_path}"
-
# TODO: does this preserve symlinks?
-
rel_path = new_path.relative_path_from(dir).to_s
-
_queue_change(:dir, dir, rel_path, recursive: true)
-
end
-
end
-
-
2
def _run_worker(worker)
-
_log :debug, "fsevent: running worker: #{worker.inspect}"
-
worker.run
-
rescue
-
_log_exception 'fsevent: running worker failed: %s:%s called from: %s', caller
-
end
-
-
2
def _run_workers_in_background(workers)
-
workers.each do |worker|
-
# NOTE: while passing local variables to the block below is not
-
# thread safe, using 'worker' from the enumerator above is ok
-
Listen::Internals::ThreadPool.add { _run_worker(worker) }
-
end
-
end
-
-
2
def _to_array(queue)
-
workers = []
-
workers << queue.pop until queue.empty?
-
workers
-
end
-
end
-
end
-
end
-
2
module Listen
-
2
module Adapter
-
# @see https://github.com/nex3/rb-inotify
-
2
class Linux < Base
-
2
OS_REGEXP = /linux/i
-
-
2
DEFAULTS = {
-
events: [
-
:recursive,
-
:attrib,
-
:create,
-
:delete,
-
:move,
-
:close_write
-
],
-
wait_for_delay: 0.1
-
}
-
-
2
private
-
-
2
WIKI_URL = 'https://github.com/guard/listen'\
-
'/wiki/Increasing-the-amount-of-inotify-watchers'
-
-
2
INOTIFY_LIMIT_MESSAGE = <<-EOS.gsub(/^\s*/, '')
-
FATAL: Listen error: unable to monitor directories for changes.
-
Visit #{WIKI_URL} for info on how to fix this.
-
EOS
-
-
2
def _configure(directory, &callback)
-
require 'rb-inotify'
-
@worker ||= ::INotify::Notifier.new
-
@worker.watch(directory.to_s, *options.events, &callback)
-
rescue Errno::ENOSPC
-
abort(INOTIFY_LIMIT_MESSAGE)
-
end
-
-
2
def _run
-
@worker.run
-
end
-
-
2
def _process_event(dir, event)
-
# NOTE: avoid using event.absolute_name since new API
-
# will need to have a custom recursion implemented
-
# to properly match events to configured directories
-
path = Pathname.new(event.watcher.path) + event.name
-
rel_path = path.relative_path_from(dir).to_s
-
-
_log(:debug) { "inotify: #{rel_path} (#{event.flags.inspect})" }
-
-
if /1|true/ =~ ENV['LISTEN_GEM_SIMULATE_FSEVENT']
-
if (event.flags & [:moved_to, :moved_from]) || _dir_event?(event)
-
rel_path = path.dirname.relative_path_from(dir).to_s
-
_queue_change(:dir, dir, rel_path, {})
-
else
-
_queue_change(:dir, dir, rel_path, {})
-
end
-
return
-
end
-
-
return if _skip_event?(event)
-
-
cookie_params = event.cookie.zero? ? {} : { cookie: event.cookie }
-
-
# Note: don't pass options to force rescanning the directory, so we can
-
# detect moving/deleting a whole tree
-
if _dir_event?(event)
-
_queue_change(:dir, dir, rel_path, cookie_params)
-
return
-
end
-
-
params = cookie_params.merge(change: _change(event.flags))
-
-
_queue_change(:file, dir, rel_path, params)
-
end
-
-
2
def _skip_event?(event)
-
# Event on root directory
-
return true if event.name == ''
-
# INotify reports changes to files inside directories as events
-
# on the directories themselves too.
-
#
-
# @see http://linux.die.net/man/7/inotify
-
_dir_event?(event) && (event.flags & [:close, :modify]).any?
-
end
-
-
2
def _change(event_flags)
-
{ modified: [:attrib, :close_write],
-
moved_to: [:moved_to],
-
moved_from: [:moved_from],
-
added: [:create],
-
removed: [:delete] }.each do |change, flags|
-
return change unless (flags & event_flags).empty?
-
end
-
nil
-
end
-
-
2
def _dir_event?(event)
-
event.flags.include?(:isdir)
-
end
-
-
2
def _stop
-
@worker.close
-
end
-
end
-
end
-
end
-
2
module Listen
-
2
module Adapter
-
# Polling Adapter that works cross-platform and
-
# has no dependencies. This is the adapter that
-
# uses the most CPU processing power and has higher
-
# file IO than the other implementations.
-
#
-
2
class Polling < Base
-
2
OS_REGEXP = // # match every OS
-
-
2
DEFAULTS = { latency: 1.0, wait_for_delay: 0.05 }
-
-
2
private
-
-
2
def _configure(_, &callback)
-
@polling_callbacks ||= []
-
@polling_callbacks << callback
-
end
-
-
2
def _run
-
loop do
-
start = Time.now.to_f
-
@polling_callbacks.each do |callback|
-
callback.call(nil)
-
nap_time = options.latency - (Time.now.to_f - start)
-
# TODO: warn if nap_time is negative (polling too slow)
-
sleep(nap_time) if nap_time > 0
-
end
-
end
-
end
-
-
2
def _process_event(dir, _)
-
_queue_change(:dir, dir, '.', recursive: true)
-
end
-
end
-
end
-
end
-
2
module Listen
-
2
module Adapter
-
# Adapter implementation for Windows `wdm`.
-
#
-
2
class Windows < Base
-
2
OS_REGEXP = /mswin|mingw|cygwin/i
-
-
2
BUNDLER_DECLARE_GEM = <<-EOS.gsub(/^ {6}/, '')
-
Please add the following to your Gemfile to avoid polling for changes:
-
gem 'wdm', '>= 0.1.0' if Gem.win_platform?
-
EOS
-
-
2
def self.usable?
-
return false unless super
-
require 'wdm'
-
true
-
rescue LoadError
-
_log :debug, format('wdm - load failed: %s:%s', $ERROR_INFO,
-
$ERROR_POSITION * "\n")
-
-
Kernel.warn BUNDLER_DECLARE_GEM
-
false
-
end
-
-
2
private
-
-
2
def _configure(dir, &callback)
-
require 'wdm'
-
_log :debug, 'wdm - starting...'
-
@worker ||= WDM::Monitor.new
-
@worker.watch_recursively(dir.to_s, :files) do |change|
-
callback.call([:file, change])
-
end
-
-
@worker.watch_recursively(dir.to_s, :directories) do |change|
-
callback.call([:dir, change])
-
end
-
-
events = [:attributes, :last_write]
-
@worker.watch_recursively(dir.to_s, *events) do |change|
-
callback.call([:attr, change])
-
end
-
end
-
-
2
def _run
-
@worker.run!
-
end
-
-
2
def _process_event(dir, event)
-
_log :debug, "wdm - callback: #{event.inspect}"
-
-
type, change = event
-
-
full_path = Pathname(change.path)
-
-
rel_path = full_path.relative_path_from(dir).to_s
-
-
options = { change: _change(change.type) }
-
-
case type
-
when :file
-
_queue_change(:file, dir, rel_path, options)
-
when :attr
-
unless full_path.directory?
-
_queue_change(:file, dir, rel_path, options)
-
end
-
when :dir
-
if change.type == :removed
-
# TODO: check if watched dir?
-
_queue_change(:dir, dir, Pathname(rel_path).dirname.to_s, {})
-
elsif change.type == :added
-
_queue_change(:dir, dir, rel_path, {})
-
else
-
# do nothing - changed directory means either:
-
# - removed subdirs (handled above)
-
# - added subdirs (handled above)
-
# - removed files (handled by _file_callback)
-
# - added files (handled by _file_callback)
-
# so what's left?
-
end
-
end
-
rescue
-
details = event.inspect
-
_log :error, format('wdm - callback (%): %s:%s', details, $ERROR_INFO,
-
$ERROR_POSITION * "\n")
-
raise
-
end
-
-
2
def _change(type)
-
{ modified: [:modified, :attrib], # TODO: is attrib really passed?
-
added: [:added, :renamed_new_file],
-
removed: [:removed, :renamed_old_file] }.each do |change, types|
-
return change if types.include?(type)
-
end
-
nil
-
end
-
end
-
end
-
end
-
2
require 'listen/adapter'
-
2
require 'listen/adapter/base'
-
2
require 'listen/adapter/config'
-
-
# This class just aggregates configuration object to avoid Listener specs
-
# from exploding with huge test setup blocks
-
2
module Listen
-
2
class Backend
-
2
def initialize(directories, queue, silencer, config)
-
adapter_select_opts = config.adapter_select_options
-
-
adapter_class = Adapter.select(adapter_select_opts)
-
-
# Use default from adapter if possible
-
@min_delay_between_events = config.min_delay_between_events
-
@min_delay_between_events ||= adapter_class::DEFAULTS[:wait_for_delay]
-
@min_delay_between_events ||= 0.1
-
-
adapter_opts = config.adapter_instance_options(adapter_class)
-
-
aconfig = Adapter::Config.new(directories, queue, silencer, adapter_opts)
-
@adapter = adapter_class.new(aconfig)
-
end
-
-
2
def start
-
adapter.start
-
end
-
-
2
def stop
-
adapter.stop
-
end
-
-
2
def min_delay_between_events
-
@min_delay_between_events
-
end
-
-
2
private
-
-
2
attr_reader :adapter
-
end
-
end
-
2
require 'listen/file'
-
2
require 'listen/directory'
-
-
2
module Listen
-
# TODO: rename to Snapshot
-
2
class Change
-
# TODO: test this class for coverage
-
2
class Config
-
2
def initialize(queue, silencer)
-
@queue = queue
-
@silencer = silencer
-
end
-
-
2
def silenced?(path, type)
-
@silencer.silenced?(Pathname(path), type)
-
end
-
-
2
def queue(*args)
-
@queue << args
-
end
-
end
-
-
2
attr_reader :record
-
-
2
def initialize(config, record)
-
@config = config
-
@record = record
-
end
-
-
# Invalidate some part of the snapshot/record (dir, file, subtree, etc.)
-
2
def invalidate(type, rel_path, options)
-
watched_dir = Pathname.new(record.root)
-
-
change = options[:change]
-
cookie = options[:cookie]
-
-
if !cookie && config.silenced?(rel_path, type)
-
Listen::Logger.debug { "(silenced): #{rel_path.inspect}" }
-
return
-
end
-
-
path = watched_dir + rel_path
-
-
Listen::Logger.debug do
-
log_details = options[:silence] && 'recording' || change || 'unknown'
-
"#{log_details}: #{type}:#{path} (#{options.inspect})"
-
end
-
-
if change
-
options = cookie ? { cookie: cookie } : {}
-
config.queue(type, change, watched_dir, rel_path, options)
-
else
-
if type == :dir
-
# NOTE: POSSIBLE RECURSION
-
# TODO: fix - use a queue instead
-
Directory.scan(self, rel_path, options)
-
else
-
change = File.change(record, rel_path)
-
return if !change || options[:silence]
-
config.queue(:file, change, watched_dir, rel_path)
-
end
-
end
-
rescue RuntimeError => ex
-
msg = format(
-
'%s#%s crashed %s:%s',
-
self.class,
-
__method__,
-
exinspect,
-
ex.backtrace * "\n")
-
Listen::Logger.error(msg)
-
raise
-
end
-
-
2
private
-
-
2
attr_reader :config
-
end
-
end
-
2
require 'set'
-
-
2
module Listen
-
# TODO: refactor (turn it into a normal object, cache the stat, etc)
-
2
class Directory
-
2
def self.scan(snapshot, rel_path, options)
-
record = snapshot.record
-
dir = Pathname.new(record.root)
-
previous = record.dir_entries(rel_path)
-
-
record.add_dir(rel_path)
-
-
# TODO: use children(with_directory: false)
-
path = dir + rel_path
-
current = Set.new(path.children)
-
-
Listen::Logger.debug do
-
format('%s: %s(%s): %s -> %s',
-
(options[:silence] ? 'Recording' : 'Scanning'),
-
rel_path, options.inspect, previous.inspect, current.inspect)
-
end
-
-
begin
-
current.each do |full_path|
-
type = ::File.lstat(full_path.to_s).directory? ? :dir : :file
-
item_rel_path = full_path.relative_path_from(dir).to_s
-
_change(snapshot, type, item_rel_path, options)
-
end
-
rescue Errno::ENOENT
-
# The directory changed meanwhile, so rescan it
-
current = Set.new(path.children)
-
retry
-
end
-
-
# TODO: this is not tested properly
-
previous = previous.reject { |entry, _| current.include? path + entry }
-
-
_async_changes(snapshot, Pathname.new(rel_path), previous, options)
-
-
rescue Errno::ENOENT, Errno::EHOSTDOWN
-
record.unset_path(rel_path)
-
_async_changes(snapshot, Pathname.new(rel_path), previous, options)
-
-
rescue Errno::ENOTDIR
-
# TODO: path not tested
-
record.unset_path(rel_path)
-
_async_changes(snapshot, path, previous, options)
-
_change(snapshot, :file, rel_path, options)
-
rescue
-
Listen::Logger.warn do
-
format('scan DIED: %s:%s', $ERROR_INFO, $ERROR_POSITION * "\n")
-
end
-
raise
-
end
-
-
2
def self._async_changes(snapshot, path, previous, options)
-
fail "Not a Pathname: #{path.inspect}" unless path.respond_to?(:children)
-
previous.each do |entry, data|
-
# TODO: this is a hack with insufficient testing
-
type = data.key?(:mtime) ? :file : :dir
-
rel_path_s = (path + entry).to_s
-
_change(snapshot, type, rel_path_s, options)
-
end
-
end
-
-
2
def self._change(snapshot, type, path, options)
-
return snapshot.invalidate(type, path, options) if type == :dir
-
-
# Minor param cleanup for tests
-
# TODO: use a dedicated Event class
-
opts = options.dup
-
opts.delete(:recursive)
-
snapshot.invalidate(type, path, opts)
-
end
-
end
-
end
-
2
module Listen
-
2
module Event
-
2
class Config
-
2
def initialize(
-
listener,
-
event_queue,
-
queue_optimizer,
-
wait_for_delay,
-
&block)
-
-
@listener = listener
-
@event_queue = event_queue
-
@queue_optimizer = queue_optimizer
-
@min_delay_between_events = wait_for_delay
-
@block = block
-
end
-
-
2
def sleep(*args)
-
Kernel.sleep(*args)
-
end
-
-
2
def call(*args)
-
@block.call(*args) if @block
-
end
-
-
2
def timestamp
-
Time.now.to_f
-
end
-
-
2
def event_queue
-
@event_queue
-
end
-
-
2
def callable?
-
@block
-
end
-
-
2
def optimize_changes(changes)
-
@queue_optimizer.smoosh_changes(changes)
-
end
-
-
2
def min_delay_between_events
-
@min_delay_between_events
-
end
-
-
2
def stopped?
-
listener.state == :stopped
-
end
-
-
2
def paused?
-
listener.state == :paused
-
end
-
-
2
private
-
-
2
attr_reader :listener
-
end
-
end
-
end
-
2
require 'thread'
-
-
2
module Listen
-
2
module Event
-
2
class Queue
-
2
class Config
-
2
def initialize(relative)
-
@relative = relative
-
end
-
-
2
def relative?
-
@relative
-
end
-
end
-
-
2
def initialize(config, &block)
-
@event_queue = ::Queue.new
-
@block = block
-
@config = config
-
end
-
-
2
def <<(args)
-
type, change, dir, path, options = *args
-
fail "Invalid type: #{type.inspect}" unless [:dir, :file].include? type
-
fail "Invalid change: #{change.inspect}" unless change.is_a?(Symbol)
-
fail "Invalid path: #{path.inspect}" unless path.is_a?(String)
-
-
dir = _safe_relative_from_cwd(dir)
-
event_queue.public_send(:<<, [type, change, dir, path, options])
-
-
block.call(args) if block
-
end
-
-
2
def empty?
-
event_queue.empty?
-
end
-
-
2
def pop
-
event_queue.pop
-
end
-
-
2
private
-
-
2
attr_reader :event_queue
-
2
attr_reader :block
-
2
attr_reader :config
-
-
2
def _safe_relative_from_cwd(dir)
-
return dir unless config.relative?
-
dir.relative_path_from(Pathname.pwd)
-
rescue ArgumentError
-
dir
-
end
-
end
-
end
-
end
-
2
require 'digest/md5'
-
-
2
module Listen
-
2
class File
-
2
def self.change(record, rel_path)
-
path = Pathname.new(record.root) + rel_path
-
lstat = path.lstat
-
-
data = { mtime: lstat.mtime.to_f, mode: lstat.mode }
-
-
record_data = record.file_data(rel_path)
-
-
if record_data.empty?
-
record.update_file(rel_path, data)
-
return :added
-
end
-
-
if data[:mode] != record_data[:mode]
-
record.update_file(rel_path, data)
-
return :modified
-
end
-
-
if data[:mtime] != record_data[:mtime]
-
record.update_file(rel_path, data)
-
return :modified
-
end
-
-
return if /1|true/ =~ ENV['LISTEN_GEM_DISABLE_HASHING']
-
return unless self.inaccurate_mac_time?(lstat)
-
-
# Check if change happened within 1 second (maybe it's even
-
# too much, e.g. 0.3-0.5 could be sufficient).
-
#
-
# With rb-fsevent, there's a (configurable) latency between
-
# when file was changed and when the event was triggered.
-
#
-
# If a file is saved at ???14.998, by the time the event is
-
# actually received by Listen, the time could already be e.g.
-
# ???15.7.
-
#
-
# And since Darwin adapter uses directory scanning, the file
-
# mtime may be the same (e.g. file was changed at ???14.001,
-
# then at ???14.998, but the fstat time would be ???14.0 in
-
# both cases).
-
#
-
# If change happend at ???14.999997, the mtime is 14.0, so for
-
# an mtime=???14.0 we assume it could even be almost ???15.0
-
#
-
# So if Time.now.to_f is ???15.999998 and stat reports mtime
-
# at ???14.0, then event was due to that file'd change when:
-
#
-
# ???15.999997 - ???14.999998 < 1.0s
-
#
-
# So the "2" is "1 + 1" (1s to cover rb-fsevent latency +
-
# 1s maximum difference between real mtime and that recorded
-
# in the file system)
-
#
-
return if data[:mtime].to_i + 2 <= Time.now.to_f
-
-
md5 = Digest::MD5.file(path).digest
-
record.update_file(rel_path, data.merge(md5: md5))
-
:modified if record_data[:md5] && md5 != record_data[:md5]
-
rescue SystemCallError
-
record.unset_path(rel_path)
-
:removed
-
rescue
-
Listen::Logger.debug "lstat failed for: #{rel_path} (#{$ERROR_INFO})"
-
raise
-
end
-
-
2
def self.inaccurate_mac_time?(stat)
-
# 'mac' means Modified/Accessed/Created
-
-
# Since precision depends on mounted FS (e.g. you can have a FAT partiion
-
# mounted on Linux), check for fields with a remainder to detect this
-
-
[stat.mtime, stat.ctime, stat.atime].map(&:usec).all?(&:zero?)
-
end
-
end
-
end
-
# Code copied from https://github.com/celluloid/celluloid-fsm
-
2
module Listen
-
2
module FSM
-
2
DEFAULT_STATE = :default # Default state name unless one is explicitly set
-
-
# Included hook to extend class methods
-
2
def self.included(klass)
-
2
klass.send :extend, ClassMethods
-
end
-
-
2
module ClassMethods
-
# Obtain or set the default state
-
# Passing a state name sets the default state
-
2
def default_state(new_default = nil)
-
2
if new_default
-
2
@default_state = new_default.to_sym
-
else
-
defined?(@default_state) ? @default_state : DEFAULT_STATE
-
end
-
end
-
-
# Obtain the valid states for this FSM
-
2
def states
-
12
@states ||= {}
-
end
-
-
# Declare an FSM state and optionally provide a callback block to fire
-
# Options:
-
# * to: a state or array of states this state can transition to
-
2
def state(*args, &block)
-
12
if args.last.is_a? Hash
-
# Stringify keys :/
-
24
options = args.pop.each_with_object({}) { |(k, v), h| h[k.to_s] = v }
-
else
-
options = {}
-
end
-
-
12
args.each do |name|
-
12
name = name.to_sym
-
12
default_state name if options['default']
-
12
states[name] = State.new(name, options['to'], &block)
-
end
-
end
-
end
-
-
# Be kind and call super if you must redefine initialize
-
2
def initialize
-
@state = self.class.default_state
-
end
-
-
# Obtain the current state of the FSM
-
2
attr_reader :state
-
-
2
def transition(state_name)
-
new_state = validate_and_sanitize_new_state(state_name)
-
return unless new_state
-
transition_with_callbacks!(new_state)
-
end
-
-
# Immediate state transition with no checks, or callbacks. "Dangerous!"
-
2
def transition!(state_name)
-
@state = state_name
-
end
-
-
2
protected
-
-
2
def validate_and_sanitize_new_state(state_name)
-
state_name = state_name.to_sym
-
-
return if current_state_name == state_name
-
-
if current_state && !current_state.valid_transition?(state_name)
-
valid = current_state.transitions.map(&:to_s).join(', ')
-
msg = "#{self.class} can't change state from '#{@state}'"\
-
" to '#{state_name}', only to: #{valid}"
-
fail ArgumentError, msg
-
end
-
-
new_state = states[state_name]
-
-
unless new_state
-
return if state_name == default_state
-
fail ArgumentError, "invalid state for #{self.class}: #{state_name}"
-
end
-
-
new_state
-
end
-
-
2
def transition_with_callbacks!(state_name)
-
transition! state_name.name
-
state_name.call(self)
-
end
-
-
2
def states
-
self.class.states
-
end
-
-
2
def default_state
-
self.class.default_state
-
end
-
-
2
def current_state
-
states[@state]
-
end
-
-
2
def current_state_name
-
current_state && current_state.name || ''
-
end
-
-
2
class State
-
2
attr_reader :name, :transitions
-
-
2
def initialize(name, transitions = nil, &block)
-
12
@name, @block = name, block
-
12
@transitions = nil
-
12
@transitions = Array(transitions).map(&:to_sym) if transitions
-
end
-
-
2
def call(obj)
-
obj.instance_eval(&@block) if @block
-
end
-
-
2
def valid_transition?(new_state)
-
# All transitions are allowed unless expressly
-
return true unless @transitions
-
-
@transitions.include? new_state.to_sym
-
end
-
end
-
end
-
end
-
2
module Listen
-
# @private api
-
2
module Internals
-
2
module ThreadPool
-
2
def self.add(&block)
-
Thread.new { block.call }.tap do |th|
-
(@threads ||= Queue.new) << th
-
end
-
end
-
-
2
def self.stop
-
return unless @threads ||= nil
-
return if @threads.empty? # return to avoid using possibly stubbed Queue
-
-
killed = Queue.new
-
killed << @threads.pop.kill until @threads.empty?
-
killed.pop.join until killed.empty?
-
end
-
end
-
end
-
end
-
2
require 'English'
-
-
2
require 'listen/version'
-
-
2
require 'listen/backend'
-
-
2
require 'listen/silencer'
-
2
require 'listen/silencer/controller'
-
-
2
require 'listen/queue_optimizer'
-
-
2
require 'listen/fsm'
-
-
2
require 'listen/event/loop'
-
2
require 'listen/event/queue'
-
2
require 'listen/event/config'
-
-
2
require 'listen/listener/config'
-
-
2
module Listen
-
2
class Listener
-
2
include Listen::FSM
-
-
# Initializes the directories listener.
-
#
-
# @param [String] directory the directories to listen to
-
# @param [Hash] options the listen options (see Listen::Listener::Options)
-
#
-
# @yield [modified, added, removed] the changed files
-
# @yieldparam [Array<String>] modified the list of modified files
-
# @yieldparam [Array<String>] added the list of added files
-
# @yieldparam [Array<String>] removed the list of removed files
-
#
-
2
def initialize(*dirs, &block)
-
options = dirs.last.is_a?(Hash) ? dirs.pop : {}
-
-
@config = Config.new(options)
-
-
eq_config = Event::Queue::Config.new(@config.relative?)
-
queue = Event::Queue.new(eq_config) { @processor.wakeup_on_event }
-
-
silencer = Silencer.new
-
rules = @config.silencer_rules
-
@silencer_controller = Silencer::Controller.new(silencer, rules)
-
-
@backend = Backend.new(dirs, queue, silencer, @config)
-
-
optimizer_config = QueueOptimizer::Config.new(@backend, silencer)
-
-
pconfig = Event::Config.new(
-
self,
-
queue,
-
QueueOptimizer.new(optimizer_config),
-
@backend.min_delay_between_events,
-
&block)
-
-
@processor = Event::Loop.new(pconfig)
-
-
super() # FSM
-
end
-
-
2
default_state :initializing
-
-
2
state :initializing, to: :backend_started
-
-
2
state :backend_started, to: [:frontend_ready] do
-
backend.start
-
end
-
-
2
state :frontend_ready, to: [:processing_events] do
-
processor.setup
-
end
-
-
2
state :processing_events, to: [:paused, :stopped] do
-
processor.resume
-
end
-
-
2
state :paused, to: [:processing_events, :stopped] do
-
processor.pause
-
end
-
-
2
state :stopped, to: [:backend_started] do
-
backend.stop # should be before processor.teardown to halt events ASAP
-
processor.teardown
-
end
-
-
# Starts processing events and starts adapters
-
# or resumes invoking callbacks if paused
-
2
def start
-
transition :backend_started if state == :initializing
-
transition :frontend_ready if state == :backend_started
-
transition :processing_events if state == :frontend_ready
-
transition :processing_events if state == :paused
-
end
-
-
# Stops both listening for events and processing them
-
2
def stop
-
transition :stopped
-
end
-
-
# Stops invoking callbacks (messages pile up)
-
2
def pause
-
transition :paused
-
end
-
-
# processing means callbacks are called
-
2
def processing?
-
state == :processing_events
-
end
-
-
2
def paused?
-
state == :paused
-
end
-
-
2
def ignore(regexps)
-
@silencer_controller.append_ignores(regexps)
-
end
-
-
2
def ignore!(regexps)
-
@silencer_controller.replace_with_bang_ignores(regexps)
-
end
-
-
2
def only(regexps)
-
@silencer_controller.replace_with_only(regexps)
-
end
-
-
2
private
-
-
2
attr_reader :processor
-
2
attr_reader :backend
-
end
-
end
-
2
module Listen
-
2
class Listener
-
2
class Config
-
2
DEFAULTS = {
-
# Listener options
-
debug: false, # TODO: is this broken?
-
wait_for_delay: nil, # NOTE: should be provided by adapter if possible
-
relative: false,
-
-
# Backend selecting options
-
force_polling: false,
-
polling_fallback_message: nil
-
}
-
-
2
def initialize(opts)
-
@options = DEFAULTS.merge(opts)
-
@relative = @options[:relative]
-
@min_delay_between_events = @options[:wait_for_delay]
-
@silencer_rules = @options # silencer will extract what it needs
-
end
-
-
2
def relative?
-
@relative
-
end
-
-
2
def min_delay_between_events
-
@min_delay_between_events
-
end
-
-
2
def silencer_rules
-
@silencer_rules
-
end
-
-
2
def adapter_instance_options(klass)
-
valid_keys = klass.const_get('DEFAULTS').keys
-
Hash[@options.select { |key, _| valid_keys.include?(key) }]
-
end
-
-
2
def adapter_select_options
-
valid_keys = %w(force_polling polling_fallback_message).map(&:to_sym)
-
Hash[@options.select { |key, _| valid_keys.include?(key) }]
-
end
-
end
-
end
-
end
-
2
module Listen
-
2
def self.logger
-
12
@logger ||= nil
-
end
-
-
2
def self.logger=(logger)
-
2
@logger = logger
-
end
-
-
2
def self.setup_default_logger_if_unset
-
2
self.logger ||= ::Logger.new(STDERR).tap do |logger|
-
2
debugging = ENV['LISTEN_GEM_DEBUGGING']
-
2
logger.level =
-
case debugging.to_s
-
when /2/
-
::Logger::DEBUG
-
when /true|yes|1/i
-
::Logger::INFO
-
else
-
2
::Logger::ERROR
-
end
-
end
-
end
-
-
2
class Logger
-
2
[:fatal, :error, :warn, :info, :debug].each do |meth|
-
10
define_singleton_method(meth) do |*args, &block|
-
4
Listen.logger.public_send(meth, *args, &block) if Listen.logger
-
end
-
end
-
end
-
end
-
2
module Listen
-
2
class Options
-
2
def initialize(opts, defaults)
-
@options = {}
-
given_options = opts.dup
-
defaults.keys.each do |key|
-
@options[key] = given_options.delete(key) || defaults[key]
-
end
-
-
return if given_options.empty?
-
-
msg = "Unknown options: #{given_options.inspect}"
-
Listen::Logger.warn msg
-
fail msg
-
end
-
-
2
def method_missing(name, *_)
-
return @options[name] if @options.key?(name)
-
msg = "Bad option: #{name.inspect} (valid:#{@options.keys.inspect})"
-
fail NameError, msg
-
end
-
end
-
end
-
2
module Listen
-
2
class QueueOptimizer
-
2
class Config
-
2
def initialize(adapter_class, silencer)
-
@adapter_class = adapter_class
-
@silencer = silencer
-
end
-
-
2
def exist?(path)
-
Pathname(path).exist?
-
end
-
-
2
def silenced?(path, type)
-
@silencer.silenced?(path, type)
-
end
-
-
2
def debug(*args, &block)
-
Listen.logger.debug(*args, &block)
-
end
-
end
-
-
2
def smoosh_changes(changes)
-
# TODO: adapter could be nil at this point (shutdown)
-
cookies = changes.group_by do |_, _, _, _, options|
-
(options || {})[:cookie]
-
end
-
_squash_changes(_reinterpret_related_changes(cookies))
-
end
-
-
2
def initialize(config)
-
@config = config
-
end
-
-
2
private
-
-
2
attr_reader :config
-
-
# groups changes into the expected structure expected by
-
# clients
-
2
def _squash_changes(changes)
-
# We combine here for backward compatibility
-
# Newer clients should receive dir and path separately
-
changes = changes.map { |change, dir, path| [change, dir + path] }
-
-
actions = changes.group_by(&:last).map do |path, action_list|
-
[_logical_action_for(path, action_list.map(&:first)), path.to_s]
-
end
-
-
config.debug("listen: raw changes: #{actions.inspect}")
-
-
{ modified: [], added: [], removed: [] }.tap do |squashed|
-
actions.each do |type, path|
-
squashed[type] << path unless type.nil?
-
end
-
config.debug("listen: final changes: #{squashed.inspect}")
-
end
-
end
-
-
2
def _logical_action_for(path, actions)
-
actions << :added if actions.delete(:moved_to)
-
actions << :removed if actions.delete(:moved_from)
-
-
modified = actions.detect { |x| x == :modified }
-
_calculate_add_remove_difference(actions, path, modified)
-
end
-
-
2
def _calculate_add_remove_difference(actions, path, default_if_exists)
-
added = actions.count { |x| x == :added }
-
removed = actions.count { |x| x == :removed }
-
diff = added - removed
-
-
# TODO: avoid checking if path exists and instead assume the events are
-
# in order (if last is :removed, it doesn't exist, etc.)
-
if config.exist?(path)
-
if diff > 0
-
:added
-
elsif diff.zero? && added > 0
-
:modified
-
else
-
default_if_exists
-
end
-
else
-
diff < 0 ? :removed : nil
-
end
-
end
-
-
# remove extraneous rb-inotify events, keeping them only if it's a possible
-
# editor rename() call (e.g. Kate and Sublime)
-
2
def _reinterpret_related_changes(cookies)
-
table = { moved_to: :added, moved_from: :removed }
-
cookies.map do |_, changes|
-
data = _detect_possible_editor_save(changes)
-
if data
-
to_dir, to_file = data
-
[[:modified, to_dir, to_file]]
-
else
-
not_silenced = changes.reject do |type, _, _, path, _|
-
config.silenced?(Pathname(path), type)
-
end
-
not_silenced.map do |_, change, dir, path, _|
-
[table.fetch(change, change), dir, path]
-
end
-
end
-
end.flatten(1)
-
end
-
-
2
def _detect_possible_editor_save(changes)
-
return unless changes.size == 2
-
-
from_type = from_change = from = nil
-
to_type = to_change = to_dir = to = nil
-
-
changes.each do |data|
-
case data[1]
-
when :moved_from
-
from_type, from_change, _, from, _ = data
-
when :moved_to
-
to_type, to_change, to_dir, to, _ = data
-
else
-
return nil
-
end
-
end
-
-
return unless from && to
-
-
# Expect an ignored moved_from and non-ignored moved_to
-
# to qualify as an "editor modify"
-
return unless config.silenced?(Pathname(from), from_type)
-
config.silenced?(Pathname(to), to_type) ? nil : [to_dir, to]
-
end
-
end
-
end
-
2
require 'thread'
-
2
require 'listen/record/entry'
-
2
require 'listen/record/symlink_detector'
-
-
2
module Listen
-
2
class Record
-
# TODO: one Record object per watched directory?
-
# TODO: deprecate
-
-
2
attr_reader :root
-
2
def initialize(directory)
-
@tree = _auto_hash
-
@root = directory.to_s
-
end
-
-
2
def add_dir(rel_path)
-
return if [nil, '', '.'].include? rel_path
-
@tree[rel_path] ||= {}
-
end
-
-
2
def update_file(rel_path, data)
-
dirname, basename = Pathname(rel_path).split.map(&:to_s)
-
_fast_update_file(dirname, basename, data)
-
end
-
-
2
def unset_path(rel_path)
-
dirname, basename = Pathname(rel_path).split.map(&:to_s)
-
_fast_unset_path(dirname, basename)
-
end
-
-
2
def file_data(rel_path)
-
dirname, basename = Pathname(rel_path).split.map(&:to_s)
-
if [nil, '', '.'].include? dirname
-
tree[basename] ||= {}
-
tree[basename].dup
-
else
-
tree[dirname] ||= {}
-
tree[dirname][basename] ||= {}
-
tree[dirname][basename].dup
-
end
-
end
-
-
2
def dir_entries(rel_path)
-
subtree =
-
if [nil, '', '.'].include? rel_path.to_s
-
tree
-
else
-
tree[rel_path.to_s] ||= _auto_hash
-
tree[rel_path.to_s]
-
end
-
-
result = {}
-
subtree.each do |key, values|
-
# only get data for file entries
-
result[key] = values.key?(:mtime) ? values : {}
-
end
-
result
-
end
-
-
2
def build
-
@tree = _auto_hash
-
# TODO: test with a file name given
-
# TODO: test other permissions
-
# TODO: test with mixed encoding
-
symlink_detector = SymlinkDetector.new
-
remaining = ::Queue.new
-
remaining << Entry.new(root, nil, nil)
-
_fast_build_dir(remaining, symlink_detector) until remaining.empty?
-
end
-
-
2
private
-
-
2
def _auto_hash
-
Hash.new { |h, k| h[k] = Hash.new }
-
end
-
-
2
def tree
-
@tree
-
end
-
-
2
def _fast_update_file(dirname, basename, data)
-
if [nil, '', '.'].include? dirname
-
tree[basename] = (tree[basename] || {}).merge(data)
-
else
-
tree[dirname] ||= {}
-
tree[dirname][basename] = (tree[dirname][basename] || {}).merge(data)
-
end
-
end
-
-
2
def _fast_unset_path(dirname, basename)
-
# this may need to be reworked to properly remove
-
# entries from a tree, without adding non-existing dirs to the record
-
if [nil, '', '.'].include? dirname
-
return unless tree.key?(basename)
-
tree.delete(basename)
-
else
-
return unless tree.key?(dirname)
-
tree[dirname].delete(basename)
-
end
-
end
-
-
2
def _fast_build_dir(remaining, symlink_detector)
-
entry = remaining.pop
-
children = entry.children # NOTE: children() implicitly tests if dir
-
symlink_detector.verify_unwatched!(entry)
-
children.each { |child| remaining << child }
-
add_dir(entry.record_dir_key)
-
rescue Errno::ENOTDIR
-
_fast_try_file(entry)
-
rescue SystemCallError, SymlinkDetector::Error
-
_fast_unset_path(entry.relative, entry.name)
-
end
-
-
2
def _fast_try_file(entry)
-
_fast_update_file(entry.relative, entry.name, entry.meta)
-
rescue SystemCallError
-
_fast_unset_path(entry.relative, entry.name)
-
end
-
end
-
end
-
2
module Listen
-
# @private api
-
2
class Record
-
# Represents a directory entry (dir or file)
-
2
class Entry
-
# file: "/home/me/watched_dir", "app/models", "foo.rb"
-
# dir, "/home/me/watched_dir", "."
-
2
def initialize(root, relative, name = nil)
-
@root, @relative, @name = root, relative, name
-
end
-
-
2
attr_reader :root, :relative, :name
-
-
2
def children
-
child_relative = _join
-
(Dir.entries(sys_path) - %w(. ..)).map do |name|
-
Entry.new(@root, child_relative, name)
-
end
-
end
-
-
2
def meta
-
lstat = ::File.lstat(sys_path)
-
{ mtime: lstat.mtime.to_f, mode: lstat.mode }
-
end
-
-
# record hash is e.g.
-
# if @record["/home/me/watched_dir"]["project/app/models"]["foo.rb"]
-
# if @record["/home/me/watched_dir"]["project/app"]["models"]
-
# record_dir_key is "project/app/models"
-
2
def record_dir_key
-
::File.join(*[@relative, @name].compact)
-
end
-
-
2
def sys_path
-
# Use full path in case someone uses chdir
-
::File.join(*[@root, @relative, @name].compact)
-
end
-
-
2
def real_path
-
@real_path ||= ::File.realpath(sys_path)
-
end
-
-
2
private
-
-
2
def _join
-
args = [@relative, @name].compact
-
args.empty? ? nil : ::File.join(*args)
-
end
-
end
-
end
-
end
-
2
require 'set'
-
-
2
module Listen
-
# @private api
-
2
class Record
-
2
class SymlinkDetector
-
2
WIKI = 'https://github.com/guard/listen/wiki/Duplicate-directory-errors'
-
-
2
SYMLINK_LOOP_ERROR = <<-EOS
-
** ERROR: directory is already being watched! **
-
-
Directory: %s
-
-
is already being watched through: %s
-
-
MORE INFO: #{WIKI}
-
EOS
-
-
2
class Error < RuntimeError
-
end
-
-
2
def initialize
-
@real_dirs = Set.new
-
end
-
-
2
def verify_unwatched!(entry)
-
real_path = entry.real_path
-
@real_dirs.add?(real_path) || _fail(entry.sys_path, real_path)
-
end
-
-
2
private
-
-
2
def _fail(symlinked, real_path)
-
STDERR.puts format(SYMLINK_LOOP_ERROR, symlinked, real_path)
-
fail Error, 'Failed due to looped symlinks'
-
end
-
end
-
end
-
end
-
2
module Listen
-
2
class Silencer
-
# The default list of directories that get ignored.
-
2
DEFAULT_IGNORED_DIRECTORIES = %r{^(?:
-
\.git
-
| \.svn
-
| \.hg
-
| \.rbx
-
| \.bundle
-
| bundle
-
| vendor/bundle
-
| log
-
| tmp
-
|vendor/ruby
-
)(/|$)}x
-
-
# The default list of files that get ignored.
-
2
DEFAULT_IGNORED_EXTENSIONS = /(?:
-
# Kate's tmp\/swp files
-
\..*\d+\.new
-
| \.kate-swp
-
-
# Gedit tmp files
-
| \.goutputstream-.{6}
-
-
# Intellij files
-
| ___jb_bak___
-
| ___jb_old___
-
-
# Vim swap files and write test
-
| \.sw[px]
-
| \.swpx
-
| ^4913
-
-
# Sed temporary files - but without actual words, like 'sedatives'
-
| (?:^
-
sed
-
-
(?:
-
[a-zA-Z0-9]{0}[A-Z]{1}[a-zA-Z0-9]{5} |
-
[a-zA-Z0-9]{1}[A-Z]{1}[a-zA-Z0-9]{4} |
-
[a-zA-Z0-9]{2}[A-Z]{1}[a-zA-Z0-9]{3} |
-
[a-zA-Z0-9]{3}[A-Z]{1}[a-zA-Z0-9]{2} |
-
[a-zA-Z0-9]{4}[A-Z]{1}[a-zA-Z0-9]{1} |
-
[a-zA-Z0-9]{5}[A-Z]{1}[a-zA-Z0-9]{0}
-
)
-
)
-
-
# other files
-
| \.DS_Store
-
| \.tmp
-
| ~
-
)$/x
-
-
2
attr_accessor :only_patterns, :ignore_patterns
-
-
2
def initialize
-
configure({})
-
end
-
-
2
def configure(options)
-
@only_patterns = options[:only] ? Array(options[:only]) : nil
-
@ignore_patterns = _init_ignores(options[:ignore], options[:ignore!])
-
end
-
-
# Note: relative_path is temporarily expected to be a relative Pathname to
-
# make refactoring easier (ideally, it would take a string)
-
-
# TODO: switch type and path places - and verify
-
2
def silenced?(relative_path, type)
-
path = relative_path.to_s
-
-
if only_patterns && type == :file
-
return true unless only_patterns.any? { |pattern| path =~ pattern }
-
end
-
-
ignore_patterns.any? { |pattern| path =~ pattern }
-
end
-
-
2
private
-
-
2
attr_reader :options
-
-
2
def _init_ignores(ignores, overrides)
-
patterns = []
-
unless overrides
-
patterns << DEFAULT_IGNORED_DIRECTORIES
-
patterns << DEFAULT_IGNORED_EXTENSIONS
-
end
-
-
patterns << ignores
-
patterns << overrides
-
-
patterns.compact.flatten
-
end
-
end
-
end
-
2
module Listen
-
2
class Silencer
-
2
class Controller
-
2
def initialize(silencer, default_options)
-
@silencer = silencer
-
-
opts = default_options
-
-
@prev_silencer_options = {}
-
rules = [:only, :ignore, :ignore!].map do |option|
-
[option, opts[option]] if opts.key? option
-
end
-
-
_reconfigure_silencer(Hash[rules.compact])
-
end
-
-
2
def append_ignores(*regexps)
-
prev_ignores = Array(@prev_silencer_options[:ignore])
-
_reconfigure_silencer(ignore: [prev_ignores + regexps])
-
end
-
-
2
def replace_with_bang_ignores(regexps)
-
_reconfigure_silencer(ignore!: regexps)
-
end
-
-
2
def replace_with_only(regexps)
-
_reconfigure_silencer(only: regexps)
-
end
-
-
2
private
-
-
2
def _reconfigure_silencer(extra_options)
-
opts = extra_options.dup
-
opts = opts.map do |key, value|
-
[key, Array(value).flatten.compact]
-
end
-
opts = Hash[opts]
-
-
if opts.key?(:ignore) && opts[:ignore].empty?
-
opts.delete(:ignore)
-
end
-
-
@prev_silencer_options = opts
-
@silencer.configure(@prev_silencer_options.dup.freeze)
-
end
-
end
-
end
-
end
-
2
module Listen
-
2
VERSION = '3.0.6'
-
end
-
2
require 'rbconfig'
-
2
require 'time'
-
2
require 'thread'
-
2
require 'securerandom'
-
-
2
module Lumberjack
-
2
LINE_SEPARATOR = (RbConfig::CONFIG['host_os'].match(/mswin/i) ? "\r\n" : "\n")
-
-
2
require File.expand_path("../lumberjack/severity.rb", __FILE__)
-
2
require File.expand_path("../lumberjack/log_entry.rb", __FILE__)
-
2
require File.expand_path("../lumberjack/formatter.rb", __FILE__)
-
2
require File.expand_path("../lumberjack/device.rb", __FILE__)
-
2
require File.expand_path("../lumberjack/logger.rb", __FILE__)
-
2
require File.expand_path("../lumberjack/template.rb", __FILE__)
-
2
require File.expand_path("../lumberjack/rack.rb", __FILE__)
-
-
2
class << self
-
# Define a unit of work within a block. Within the block supplied to this
-
# method, calling +unit_of_work_id+ will return the same value that can
-
# This can then be used for tying together log entries.
-
#
-
# You can specify the id for the unit of work if desired. If you don't supply
-
# it, a 12 digit hexidecimal number will be automatically generated for you.
-
#
-
# For the common use case of treating a single web request as a unit of work, see the
-
# Lumberjack::Rack::UnitOfWork class.
-
2
def unit_of_work(id = nil)
-
save_val = Thread.current[:lumberjack_logger_unit_of_work_id]
-
id ||= SecureRandom.hex(6)
-
Thread.current[:lumberjack_logger_unit_of_work_id] = id
-
begin
-
return yield
-
ensure
-
Thread.current[:lumberjack_logger_unit_of_work_id] = save_val
-
end
-
end
-
-
# Get the UniqueIdentifier for the current unit of work.
-
2
def unit_of_work_id
-
Thread.current[:lumberjack_logger_unit_of_work_id]
-
end
-
end
-
end
-
2
module Lumberjack
-
# This is an abstract class for logging devices. Subclasses must implement the +write+ method and
-
# may implement the +close+ and +flush+ methods if applicable.
-
2
class Device
-
2
require File.expand_path("../device/writer.rb", __FILE__)
-
2
require File.expand_path("../device/log_file.rb", __FILE__)
-
2
require File.expand_path("../device/rolling_log_file.rb", __FILE__)
-
2
require File.expand_path("../device/date_rolling_log_file.rb", __FILE__)
-
2
require File.expand_path("../device/size_rolling_log_file.rb", __FILE__)
-
2
require File.expand_path("../device/null.rb", __FILE__)
-
-
# Subclasses must implement this method to write a LogEntry.
-
2
def write(entry)
-
raise NotImplementedError
-
end
-
-
# Subclasses may implement this method to close the device.
-
2
def close
-
flush
-
end
-
-
# Subclasses may implement this method to flush any buffers used by the device.
-
2
def flush
-
end
-
end
-
end
-
2
require 'date'
-
-
2
module Lumberjack
-
2
class Device
-
# This log device will append entries to a file and roll the file periodically by date. Files
-
# are rolled at midnight and can be rolled daily, weekly, or monthly. Archive file names will
-
# have the date appended to them in the format ".YYYY-MM-DD" for daily, ".week-of-YYYY-MM-DD" for weekly
-
# and ".YYYY-MM" for monthly. It is not guaranteed that log messages will break exactly on the
-
# roll period as buffered entries will always be written to the same file.
-
2
class DateRollingLogFile < RollingLogFile
-
# Create a new logging device to the specified file. The period to roll the file is specified
-
# with the <tt>:roll</tt> option which may contain a value of <tt>:daily</tt>, <tt>:weekly</tt>,
-
# or <tt>:monthly</tt>.
-
2
def initialize(path, options = {})
-
@manual = options[:manual]
-
@file_date = Date.today
-
if options[:roll] && options[:roll].to_s.match(/(daily)|(weekly)|(monthly)/i)
-
@roll_period = $~[0].downcase.to_sym
-
options.delete(:roll)
-
else
-
raise ArgumentError.new("illegal value for :roll (#{options[:roll].inspect})")
-
end
-
super
-
end
-
-
2
def archive_file_suffix
-
case @roll_period
-
when :weekly
-
"#{@file_date.strftime('week-of-%Y-%m-%d')}"
-
when :monthly
-
"#{@file_date.strftime('%Y-%m')}"
-
else
-
"#{@file_date.strftime('%Y-%m-%d')}"
-
end
-
end
-
-
2
def roll_file?
-
if @manual
-
true
-
else
-
date = Date.today
-
if date.year > @file_date.year
-
true
-
elsif @roll_period == :daily && date.yday > @file_date.yday
-
true
-
elsif @roll_period == :weekly && date.cweek != @file_date.cweek
-
true
-
elsif @roll_period == :monthly && date.month > @file_date.month
-
true
-
else
-
false
-
end
-
end
-
end
-
-
2
protected
-
-
2
def after_roll
-
@file_date = Date.today
-
end
-
end
-
end
-
end
-
2
require 'fileutils'
-
-
2
module Lumberjack
-
2
class Device
-
# This is a logging device that appends log entries to a file.
-
2
class LogFile < Writer
-
2
EXTERNAL_ENCODING = "ascii-8bit"
-
-
# The absolute path of the file being logged to.
-
2
attr_reader :path
-
-
# Create a logger to the file at +path+. Options are passed through to the Writer constructor.
-
2
def initialize(path, options = {})
-
@path = File.expand_path(path)
-
FileUtils.mkdir_p(File.dirname(@path))
-
super(File.new(@path, 'a', :encoding => EXTERNAL_ENCODING), options)
-
end
-
end
-
end
-
end
-
2
require 'date'
-
-
2
module Lumberjack
-
2
class Device
-
# This is a logging device that produces no output. It can be useful in
-
# testing environments when log file output is not useful.
-
2
class Null < Device
-
2
def initialize(*args)
-
end
-
-
2
def write(entry)
-
end
-
end
-
end
-
end
-
2
module Lumberjack
-
2
class Device
-
# This is a log device that appends entries to a file and rolls the file when it reaches a specified
-
# size threshold. When a file is rolled, it will have an number extension appended to the file name.
-
# For example, if the log file is named production.log, the first time it is rolled it will be renamed
-
# production.log.1, then production.log.2, etc.
-
2
class SizeRollingLogFile < RollingLogFile
-
2
attr_reader :max_size
-
-
# Create an new log device to the specified file. The maximum size of the log file is specified with
-
# the <tt>:max_size</tt> option. The unit can also be specified: "32K", "100M", "2G" are all valid.
-
2
def initialize(path, options = {})
-
@manual = options[:manual]
-
@max_size = options[:max_size]
-
if @max_size.is_a?(String)
-
if @max_size.match(/^(\d+(\.\d+)?)([KMG])?$/i)
-
@max_size = $~[1].to_f
-
units = $~[3].to_s.upcase
-
case units
-
when "K"
-
@max_size *= 1024
-
when "M"
-
@max_size *= 1024 ** 2
-
when "G"
-
@max_size *= 1024 ** 3
-
end
-
@max_size = @max_size.round
-
else
-
raise ArgumentError.new("illegal value for :max_size (#{@max_size})")
-
end
-
end
-
-
super
-
end
-
-
2
def archive_file_suffix
-
next_archive_number.to_s
-
end
-
-
2
def roll_file?
-
@manual || stream.stat.size > @max_size
-
rescue SystemCallError
-
false
-
end
-
-
2
protected
-
-
# Calculate the next archive file name extension.
-
2
def next_archive_number # :nodoc:
-
max = 0
-
Dir.glob("#{path}.*").each do |filename|
-
if filename.match(/\.\d+$/)
-
suffix = filename.split('.').last.to_i
-
max = suffix if suffix > max
-
end
-
end
-
max + 1
-
end
-
end
-
end
-
end
-
2
module Lumberjack
-
# This class controls the conversion of log entry messages into strings. This allows you
-
# to log any object you want and have the logging system worry about converting it into a string.
-
#
-
# Formats are added to a Formatter by associating them with a class using the +add+ method. Formats
-
# are any object that responds to the +call+ method.
-
#
-
# By default, all object will be converted to strings using their inspect method except for Strings
-
# and Exceptions. Strings are not converted and Exceptions are converted using the ExceptionFormatter.
-
2
class Formatter
-
2
require File.expand_path("../formatter/exception_formatter.rb", __FILE__)
-
2
require File.expand_path("../formatter/inspect_formatter.rb", __FILE__)
-
2
require File.expand_path("../formatter/pretty_print_formatter.rb", __FILE__)
-
2
require File.expand_path("../formatter/string_formatter.rb", __FILE__)
-
-
2
def initialize
-
@class_formatters = {}
-
@_default_formatter = InspectFormatter.new
-
add(Object, @_default_formatter)
-
add(String, :string)
-
add(Exception, :exception)
-
end
-
-
# Add a formatter for a class. The formatter can be specified as either an object
-
# that responds to the +call+ method or as a symbol representing one of the predefined
-
# formatters, or as a block to the method call.
-
#
-
# The predefined formatters are: <tt>:inspect</tt>, <tt>:string</tt>, <tt>:exception</tt>, and <tt>:pretty_print</tt>.
-
#
-
# === Examples
-
#
-
# # Use a predefined formatter
-
# formatter.add(MyClass, :pretty_print)
-
#
-
# # Pass in a formatter object
-
# formatter.add(MyClass, Lumberjack::Formatter::PrettyPrintFormatter.new)
-
#
-
# # Use a block
-
# formatter.add(MyClass){|obj| obj.humanize}
-
#
-
# # Add statements can be chained together
-
# formatter.add(MyClass, :pretty_print).add(YourClass){|obj| obj.humanize}
-
2
def add(klass, formatter = nil, &block)
-
formatter ||= block
-
if formatter.is_a?(Symbol)
-
formatter_class_name = "#{formatter.to_s.gsub(/(^|_)([a-z])/){|m| $~[2].upcase}}Formatter"
-
formatter = Formatter.const_get(formatter_class_name).new
-
end
-
@class_formatters[klass] = formatter
-
self
-
end
-
-
# Remove the formatter associated with a class. Remove statements can be chained together.
-
2
def remove(klass)
-
@class_formatters.delete(klass)
-
self
-
end
-
-
# Format a message object as a string.
-
2
def format(message)
-
formatter_for(message.class).call(message)
-
end
-
-
# Hack for compatibility with Logger::Formatter
-
2
def call(severity, timestamp, progname, msg)
-
"#{format(msg)}\n"
-
end
-
-
2
private
-
-
# Find the formatter for a class by looking it up using the class hierarchy.
-
2
def formatter_for(klass) #:nodoc:
-
while klass != nil do
-
formatter = @class_formatters[klass]
-
return formatter if formatter
-
klass = klass.superclass
-
end
-
@_default_formatter
-
end
-
end
-
end
-
2
module Lumberjack
-
2
class Formatter
-
# Format an exception including the backtrace.
-
2
class ExceptionFormatter
-
2
def call(exception)
-
message = "#{exception.class.name}: #{exception.message}"
-
message << "#{Lumberjack::LINE_SEPARATOR} #{exception.backtrace.join("#{Lumberjack::LINE_SEPARATOR} ")}" if exception.backtrace
-
message
-
end
-
end
-
end
-
end
-
2
module Lumberjack
-
2
class Formatter
-
# Format an object by calling +inspect+ on it.
-
2
class InspectFormatter
-
2
def call(obj)
-
obj.inspect
-
end
-
end
-
end
-
end
-
2
require 'pp'
-
2
require 'stringio'
-
-
2
module Lumberjack
-
2
class Formatter
-
# Format an object with it's pretty print method.
-
2
class PrettyPrintFormatter
-
2
attr_accessor :width
-
-
# Create a new formatter. The maximum width of the message can be specified with the width
-
# parameter (defaults to 79 characters).
-
2
def initialize(width = 79)
-
@width = width
-
end
-
-
2
def call(obj)
-
s = StringIO.new
-
PP.pp(obj, s)
-
s.string.chomp
-
end
-
end
-
end
-
end
-
2
module Lumberjack
-
2
class Formatter
-
# Format an object by calling +to_s+ on it.
-
2
class StringFormatter
-
2
def call(obj)
-
obj.to_s
-
end
-
end
-
end
-
end
-
2
module Lumberjack
-
# An entry in a log is a data structure that captures the log message as well as
-
# information about the system that logged the message.
-
2
class LogEntry
-
2
attr_accessor :time, :message, :severity, :progname, :pid, :unit_of_work_id
-
-
2
TIME_FORMAT = "%Y-%m-%dT%H:%M:%S".freeze
-
-
2
def initialize(time, severity, message, progname, pid, unit_of_work_id)
-
@time = time
-
@severity = (severity.is_a?(Fixnum) ? severity : Severity.label_to_level(severity))
-
@message = message
-
@progname = progname
-
@pid = pid
-
@unit_of_work_id = unit_of_work_id
-
end
-
-
2
def severity_label
-
Severity.level_to_label(severity)
-
end
-
-
2
def to_s
-
buf = "[#{time.strftime(TIME_FORMAT)}.#{(time.usec / 1000.0).round.to_s.rjust(3, '0')} #{severity_label} #{progname}(#{pid})"
-
if unit_of_work_id
-
buf << " #"
-
buf << unit_of_work_id
-
end
-
buf << "] "
-
buf << message
-
end
-
-
2
def inspect
-
to_s
-
end
-
end
-
end
-
2
module Lumberjack
-
# Logger is a thread safe logging object. It has a compatible API with the Ruby
-
# standard library Logger class, the Log4r gem, and ActiveSupport::BufferedLogger.
-
#
-
# === Example
-
#
-
# logger = Lumberjack::Logger.new
-
# logger.info("Starting processing")
-
# logger.debug("Processing options #{options.inspect}")
-
# logger.fatal("OMG the application is on fire!")
-
#
-
# Log entries are written to a logging Device if their severity meets or exceeds the log level.
-
#
-
# Devices may use buffers internally and the log entries are not guaranteed to be written until you call
-
# the +flush+ method. Sometimes this can result in problems when trying to track down extraordinarily
-
# long running sections of code since it is likely that none of the messages logged before the long
-
# running code will appear in the log until the entire process finishes. You can set the +:flush_seconds+
-
# option on the constructor to force the device to be flushed periodically. This will create a new
-
# monitoring thread, but its use is highly recommended.
-
#
-
# Each log entry records the log message and severity along with the time it was logged, the
-
# program name, process id, and unit of work id. The message will be converted to a string, but
-
# otherwise, it is up to the device how these values are recorded. Messages are converted to strings
-
# using a Formatter associated with the logger.
-
2
class Logger
-
2
include Severity
-
-
# The time that the device was last flushed.
-
2
attr_reader :last_flushed_at
-
-
# The name of the program associated with log messages.
-
2
attr_writer :progname
-
-
# The device being written to.
-
2
attr_reader :device
-
-
# Set +silencer+ to false to disable silencing the log.
-
2
attr_accessor :silencer
-
-
# Create a new logger to log to a Device.
-
#
-
# The +device+ argument can be in any one of several formats.
-
#
-
# If it is a Device object, that object will be used.
-
# If it has a +write+ method, it will be wrapped in a Device::Writer class.
-
# If it is <tt>:null</tt>, it will be a Null device that won't record any output.
-
# Otherwise, it will be assumed to be file path and wrapped in a Device::LogFile class.
-
#
-
# This method can take the following options:
-
#
-
# * <tt>:level</tt> - The logging level below which messages will be ignored.
-
# * <tt>:progname</tt> - The name of the program that will be recorded with each log entry.
-
# * <tt>:flush_seconds</tt> - The maximum number of seconds between flush calls.
-
# * <tt>:roll</tt> - If the log device is a file path, it will be a Device::DateRollingLogFile if this is set.
-
# * <tt>:max_size</tt> - If the log device is a file path, it will be a Device::SizeRollingLogFile if this is set.
-
#
-
# All other options are passed to the device constuctor.
-
2
def initialize(device = STDOUT, options = {})
-
@thread_settings = {}
-
-
options = options.dup
-
self.level = options.delete(:level) || INFO
-
self.progname = options.delete(:progname)
-
max_flush_seconds = options.delete(:flush_seconds).to_f
-
-
@device = open_device(device, options)
-
@_formatter = Formatter.new
-
@lock = Mutex.new
-
@last_flushed_at = Time.now
-
@silencer = true
-
-
create_flusher_thread(max_flush_seconds) if max_flush_seconds > 0
-
end
-
-
# Get the Formatter object used to convert messages into strings.
-
2
def formatter
-
@_formatter
-
end
-
-
# Get the level of severity of entries that are logged. Entries with a lower
-
# severity level will be ignored.
-
2
def level
-
thread_local_value(:lumberjack_logger_level) || @level
-
end
-
-
# Add a message to the log with a given severity. The message can be either
-
# passed in the +message+ argument or supplied with a block. This method
-
# is not normally called. Instead call one of the helper functions
-
# +fatal+, +error+, +warn+, +info+, or +debug+.
-
#
-
# The severity can be passed in either as one of the Severity constants,
-
# or as a Severity label.
-
#
-
# === Example
-
#
-
# logger.add(Lumberjack::Severity::ERROR, exception)
-
# logger.add(Lumberjack::Severity::INFO, "Request completed")
-
# logger.add(:warn, "Request took a long time")
-
# logger.add(Lumberjack::Severity::DEBUG){"Start processing with options #{options.inspect}"}
-
2
def add(severity, message = nil, progname = nil)
-
severity = Severity.label_to_level(severity) if severity.is_a?(String) || severity.is_a?(Symbol)
-
-
return unless severity && severity >= level
-
-
time = Time.now
-
if message.nil?
-
if block_given?
-
message = yield
-
else
-
message = progname
-
progname = nil
-
end
-
end
-
-
message = @_formatter.format(message)
-
progname ||= self.progname
-
entry = LogEntry.new(time, severity, message, progname, $$, Lumberjack.unit_of_work_id)
-
begin
-
device.write(entry)
-
rescue => e
-
$stderr.puts("#{e.class.name}: #{e.message}#{' at ' + e.backtrace.first if e.backtrace}")
-
$stderr.puts(entry.to_s)
-
end
-
-
nil
-
end
-
-
2
alias_method :log, :add
-
-
# Flush the logging device. Messages are not guaranteed to be written until this method is called.
-
2
def flush
-
device.flush
-
@last_flushed_at = Time.now
-
nil
-
end
-
-
# Close the logging device.
-
2
def close
-
flush
-
@device.close if @device.respond_to?(:close)
-
end
-
-
# Log a +FATAL+ message. The message can be passed in either the +message+ argument or in a block.
-
2
def fatal(message = nil, progname = nil, &block)
-
add(FATAL, message, progname, &block)
-
end
-
-
# Return +true+ if +FATAL+ messages are being logged.
-
2
def fatal?
-
level <= FATAL
-
end
-
-
# Log an +ERROR+ message. The message can be passed in either the +message+ argument or in a block.
-
2
def error(message = nil, progname = nil, &block)
-
add(ERROR, message, progname, &block)
-
end
-
-
# Return +true+ if +ERROR+ messages are being logged.
-
2
def error?
-
level <= ERROR
-
end
-
-
# Log a +WARN+ message. The message can be passed in either the +message+ argument or in a block.
-
2
def warn(message = nil, progname = nil, &block)
-
add(WARN, message, progname, &block)
-
end
-
-
# Return +true+ if +WARN+ messages are being logged.
-
2
def warn?
-
level <= WARN
-
end
-
-
# Log an +INFO+ message. The message can be passed in either the +message+ argument or in a block.
-
2
def info(message = nil, progname = nil, &block)
-
add(INFO, message, progname, &block)
-
end
-
-
# Return +true+ if +INFO+ messages are being logged.
-
2
def info?
-
level <= INFO
-
end
-
-
# Log a +DEBUG+ message. The message can be passed in either the +message+ argument or in a block.
-
2
def debug(message = nil, progname = nil, &block)
-
add(DEBUG, message, progname, &block)
-
end
-
-
# Return +true+ if +DEBUG+ messages are being logged.
-
2
def debug?
-
level <= DEBUG
-
end
-
-
# Log a message when the severity is not known. Unknown messages will always appear in the log.
-
# The message can be passed in either the +message+ argument or in a block.
-
2
def unknown(message = nil, progname = nil, &block)
-
add(UNKNOWN, message, progname, &block)
-
end
-
-
2
alias_method :<<, :unknown
-
-
# Set the minimum level of severity of messages to log.
-
2
def level=(severity)
-
if severity.is_a?(Fixnum)
-
@level = severity
-
else
-
@level = Severity.label_to_level(severity)
-
end
-
end
-
-
# Silence the logger by setting a new log level inside a block. By default, only +ERROR+ or +FATAL+
-
# messages will be logged.
-
#
-
# === Example
-
#
-
# logger.level = Lumberjack::Severity::INFO
-
# logger.silence do
-
# do_something # Log level inside the block is +ERROR+
-
# end
-
2
def silence(temporary_level = ERROR, &block)
-
if silencer
-
push_thread_local_value(:lumberjack_logger_level, temporary_level, &block)
-
else
-
yield
-
end
-
end
-
-
# Set the program name that is associated with log messages. If a block
-
# is given, the program name will be valid only within the block.
-
2
def set_progname(value, &block)
-
if block
-
push_thread_local_value(:lumberjack_logger_progname, value, &block)
-
else
-
self.progname = value
-
end
-
end
-
-
# Get the program name associated with log messages.
-
2
def progname
-
thread_local_value(:lumberjack_logger_progname) || @progname
-
end
-
-
2
private
-
-
# Set a local value for a thread tied to this object.
-
2
def set_thread_local_value(name, value) #:nodoc:
-
values = Thread.current[name]
-
unless values
-
values = {}
-
Thread.current[name] = values
-
end
-
if value.nil?
-
values.delete(self)
-
Thread.current[name] = nil if values.empty?
-
else
-
values[self] = value
-
end
-
end
-
-
# Get a local value for a thread tied to this object.
-
2
def thread_local_value(name) #:nodoc:
-
values = Thread.current[name]
-
values[self] if values
-
end
-
-
# Set a local value for a thread tied to this object within a block.
-
2
def push_thread_local_value(name, value) #:nodoc:
-
save_val = thread_local_value(name)
-
set_thread_local_value(name, value)
-
begin
-
yield
-
ensure
-
set_thread_local_value(name, save_val)
-
end
-
end
-
-
# Open a logging device.
-
2
def open_device(device, options) #:nodoc:
-
if device.is_a?(Device)
-
device
-
elsif device.respond_to?(:write) && device.respond_to?(:flush)
-
Device::Writer.new(device, options)
-
elsif device == :null
-
Device::Null.new
-
else
-
device = device.to_s
-
if options[:roll]
-
Device::DateRollingLogFile.new(device, options)
-
elsif options[:max_size]
-
Device::SizeRollingLogFile.new(device, options)
-
else
-
Device::LogFile.new(device, options)
-
end
-
end
-
end
-
-
# Create a thread that will periodically call flush.
-
2
def create_flusher_thread(flush_seconds) #:nodoc:
-
if flush_seconds > 0
-
begin
-
logger = self
-
Thread.new do
-
loop do
-
begin
-
sleep(flush_seconds)
-
logger.flush if Time.now - logger.last_flushed_at >= flush_seconds
-
rescue => e
-
STDERR.puts("Error flushing log: #{e.inspect}")
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
2
module Lumberjack
-
2
module Rack
-
2
require File.expand_path("../rack/unit_of_work.rb", __FILE__)
-
end
-
end
-
2
module Lumberjack
-
2
module Rack
-
2
class UnitOfWork
-
2
def initialize(app)
-
@app = app
-
end
-
-
2
def call(env)
-
Lumberjack.unit_of_work do
-
@app.call(env)
-
end
-
end
-
end
-
end
-
end
-
2
module Lumberjack
-
# The standard severity levels for logging messages.
-
2
module Severity
-
2
UNKNOWN = 5
-
2
FATAL = 4
-
2
ERROR = 3
-
2
WARN = 2
-
2
INFO = 1
-
2
DEBUG = 0
-
-
2
SEVERITY_LABELS = %w(DEBUG INFO WARN ERROR FATAL UNKNOWN).freeze
-
-
2
class << self
-
2
def level_to_label(severity)
-
SEVERITY_LABELS[severity] || SEVERITY_LABELS.last
-
end
-
-
2
def label_to_level(label)
-
SEVERITY_LABELS.index(label.to_s.upcase) || UNKNOWN
-
end
-
end
-
end
-
end
-
2
module Lumberjack
-
# A template converts entries to strings. Templates can contain the following place holders to
-
# reference log entry values:
-
#
-
# * <tt>:time</tt>
-
# * <tt>:severity</tt>
-
# * <tt>:progname</tt>
-
# * <tt>:unit_of_work_id</tt>
-
# * <tt>:message</tt>
-
2
class Template
-
2
TEMPLATE_ARGUMENT_ORDER = %w(:time :severity :progname :pid :unit_of_work_id :message).freeze
-
2
DEFAULT_TIME_FORMAT = "%Y-%m-%dT%H:%M:%S."
-
2
MILLISECOND_FORMAT = "%03d"
-
2
MICROSECOND_FORMAT = "%06d"
-
-
# Create a new template from the markup. The +first_line+ argument is used to format only the first
-
# line of a message. Additional lines will be added to the message unformatted. If you wish to format
-
# the additional lines, use the <tt>:additional_lines</tt> options to specify a template. Note that you'll need
-
# to provide the line separator character in this template if you want to keep the message on multiple lines.
-
#
-
# The time will be formatted as YYYY-MM-DDTHH:MM:SSS.SSS by default. If you wish to change the format, you
-
# can specify the <tt>:time_format</tt> option which can be either a time format template as documented in
-
# +Time#strftime+ or the values +:milliseconds+ or +:microseconds+ to use the standard format with the
-
# specified precision.
-
#
-
# Messages will have white space stripped from both ends.
-
2
def initialize(first_line, options = {})
-
@first_line_template = compile(first_line)
-
additional_lines = options[:additional_lines] || "#{Lumberjack::LINE_SEPARATOR}:message"
-
@additional_line_template = compile(additional_lines)
-
# Formatting the time is relatively expensive, so only do it if it will be used
-
@template_include_time = first_line.include?(":time") || additional_lines.include?(":time")
-
@time_format = options[:time_format] || :milliseconds
-
end
-
-
# Convert an entry into a string using the template.
-
2
def call(entry)
-
lines = entry.message.strip.split(Lumberjack::LINE_SEPARATOR)
-
formatted_time = format_time(entry.time) if @template_include_time
-
message = @first_line_template % [formatted_time, entry.severity_label, entry.progname, entry.pid, entry.unit_of_work_id, lines.shift]
-
lines.each do |line|
-
message << @additional_line_template % [formatted_time, entry.severity_label, entry.progname, entry.pid, entry.unit_of_work_id, line]
-
end
-
message
-
end
-
-
2
private
-
-
2
def format_time(time) #:nodoc:
-
if @time_format.is_a?(String)
-
time.strftime(@time_format)
-
elsif @time_format == :milliseconds
-
time.strftime(DEFAULT_TIME_FORMAT) << MILLISECOND_FORMAT % (time.usec / 1000.0).round
-
else
-
time.strftime(DEFAULT_TIME_FORMAT) << MICROSECOND_FORMAT % time.usec
-
end
-
end
-
-
# Compile the template string into a value that can be used with sprintf.
-
2
def compile(template) #:nodoc:
-
template.gsub(/:[a-z0-9_]+/) do |match|
-
position = TEMPLATE_ARGUMENT_ORDER.index(match)
-
if position
-
"%#{position + 1}$s"
-
else
-
match
-
end
-
end
-
end
-
end
-
end
-
# encoding: utf-8
-
2
module Mail # :doc:
-
-
2
require 'date'
-
2
require 'shellwords'
-
-
2
require 'uri'
-
2
require 'net/smtp'
-
2
require 'mime/types'
-
-
2
if RUBY_VERSION <= '1.8.6'
-
begin
-
require 'tlsmail'
-
rescue LoadError
-
raise "You need to install tlsmail if you are using ruby <= 1.8.6"
-
end
-
end
-
-
2
if RUBY_VERSION >= "1.9.0"
-
2
require 'mail/version_specific/ruby_1_9'
-
2
RubyVer = Ruby19
-
else
-
require 'mail/version_specific/ruby_1_8'
-
RubyVer = Ruby18
-
end
-
-
2
require 'mail/version'
-
-
2
require 'mail/core_extensions/nil'
-
2
require 'mail/core_extensions/object'
-
2
require 'mail/core_extensions/string'
-
2
require 'mail/core_extensions/smtp' if RUBY_VERSION < '1.9.3'
-
2
require 'mail/indifferent_hash'
-
-
# Only load our multibyte extensions if AS is not already loaded
-
2
if defined?(ActiveSupport)
-
2
require 'active_support/inflector'
-
else
-
require 'mail/core_extensions/string/access'
-
require 'mail/core_extensions/string/multibyte'
-
require 'mail/multibyte'
-
end
-
-
2
require 'mail/constants'
-
2
require 'mail/utilities'
-
2
require 'mail/configuration'
-
-
2
@@autoloads = {}
-
2
def self.register_autoload(name, path)
-
108
@@autoloads[name] = path
-
108
autoload(name, path)
-
end
-
-
# This runs through the autoload list and explictly requires them for you.
-
# Useful when running mail in a threaded process.
-
#
-
# Usage:
-
#
-
# require 'mail'
-
# Mail.eager_autoload!
-
2
def self.eager_autoload!
-
@@autoloads.each { |_,path| require(path) }
-
end
-
-
# Autoload mail send and receive classes.
-
2
require 'mail/network'
-
-
2
require 'mail/message'
-
2
require 'mail/part'
-
2
require 'mail/header'
-
2
require 'mail/parts_list'
-
2
require 'mail/attachments_list'
-
2
require 'mail/body'
-
2
require 'mail/field'
-
2
require 'mail/field_list'
-
-
2
require 'mail/envelope'
-
-
2
register_autoload :Parsers, "mail/parsers"
-
-
# Autoload header field elements and transfer encodings.
-
2
require 'mail/elements'
-
2
require 'mail/encodings'
-
2
require 'mail/encodings/base64'
-
2
require 'mail/encodings/quoted_printable'
-
2
require 'mail/encodings/unix_to_unix'
-
-
2
require 'mail/matchers/has_sent_mail'
-
-
# Finally... require all the Mail.methods
-
2
require 'mail/mail'
-
end
-
# encoding: utf-8
-
2
module Mail
-
-
# = Body
-
#
-
# The body is where the text of the email is stored. Mail treats the body
-
# as a single object. The body itself has no information about boundaries
-
# used in the MIME standard, it just looks at its content as either a single
-
# block of text, or (if it is a multipart message) as an array of blocks of text.
-
#
-
# A body has to be told to split itself up into a multipart message by calling
-
# #split with the correct boundary. This is because the body object has no way
-
# of knowing what the correct boundary is for itself (there could be many
-
# boundaries in a body in the case of a nested MIME text).
-
#
-
# Once split is called, Mail::Body will slice itself up on this boundary,
-
# assigning anything that appears before the first part to the preamble, and
-
# anything that appears after the closing boundary to the epilogue, then
-
# each part gets initialized into a Mail::Part object.
-
#
-
# The boundary that is used to split up the Body is also stored in the Body
-
# object for use on encoding itself back out to a string. You can
-
# overwrite this if it needs to be changed.
-
#
-
# On encoding, the body will return the preamble, then each part joined by
-
# the boundary, followed by a closing boundary string and then the epilogue.
-
2
class Body
-
-
2
def initialize(string = '')
-
@boundary = nil
-
@preamble = nil
-
@epilogue = nil
-
@charset = nil
-
@part_sort_order = [ "text/plain", "text/enriched", "text/html" ]
-
@parts = Mail::PartsList.new
-
if string.blank?
-
@raw_source = ''
-
else
-
# Do join first incase we have been given an Array in Ruby 1.9
-
if string.respond_to?(:join)
-
@raw_source = string.join('')
-
elsif string.respond_to?(:to_s)
-
@raw_source = string.to_s
-
else
-
raise "You can only assign a string or an object that responds_to? :join or :to_s to a body."
-
end
-
end
-
@encoding = (only_us_ascii? ? '7bit' : '8bit')
-
set_charset
-
end
-
-
# Matches this body with another body. Also matches the decoded value of this
-
# body with a string.
-
#
-
# Examples:
-
#
-
# body = Mail::Body.new('The body')
-
# body == body #=> true
-
#
-
# body = Mail::Body.new('The body')
-
# body == 'The body' #=> true
-
#
-
# body = Mail::Body.new("VGhlIGJvZHk=\n")
-
# body.encoding = 'base64'
-
# body == "The body" #=> true
-
2
def ==(other)
-
if other.class == String
-
self.decoded == other
-
else
-
super
-
end
-
end
-
-
# Accepts a string and performs a regular expression against the decoded text
-
#
-
# Examples:
-
#
-
# body = Mail::Body.new('The body')
-
# body =~ /The/ #=> 0
-
#
-
# body = Mail::Body.new("VGhlIGJvZHk=\n")
-
# body.encoding = 'base64'
-
# body =~ /The/ #=> 0
-
2
def =~(regexp)
-
self.decoded =~ regexp
-
end
-
-
# Accepts a string and performs a regular expression against the decoded text
-
#
-
# Examples:
-
#
-
# body = Mail::Body.new('The body')
-
# body.match(/The/) #=> #<MatchData "The">
-
#
-
# body = Mail::Body.new("VGhlIGJvZHk=\n")
-
# body.encoding = 'base64'
-
# body.match(/The/) #=> #<MatchData "The">
-
2
def match(regexp)
-
self.decoded.match(regexp)
-
end
-
-
# Accepts anything that responds to #to_s and checks if it's a substring of the decoded text
-
#
-
# Examples:
-
#
-
# body = Mail::Body.new('The body')
-
# body.include?('The') #=> true
-
#
-
# body = Mail::Body.new("VGhlIGJvZHk=\n")
-
# body.encoding = 'base64'
-
# body.include?('The') #=> true
-
2
def include?(other)
-
self.decoded.include?(other.to_s)
-
end
-
-
# Allows you to set the sort order of the parts, overriding the default sort order.
-
# Defaults to 'text/plain', then 'text/enriched', then 'text/html' with any other content
-
# type coming after.
-
2
def set_sort_order(order)
-
@part_sort_order = order
-
end
-
-
# Allows you to sort the parts according to the default sort order, or the sort order you
-
# set with :set_sort_order.
-
#
-
# sort_parts! is also called from :encode, so there is no need for you to call this explicitly
-
2
def sort_parts!
-
@parts.each do |p|
-
p.body.set_sort_order(@part_sort_order)
-
p.body.sort_parts!
-
end
-
@parts.sort!(@part_sort_order)
-
end
-
-
# Returns the raw source that the body was initialized with, without
-
# any tampering
-
2
def raw_source
-
@raw_source
-
end
-
-
2
def get_best_encoding(target)
-
target_encoding = Mail::Encodings.get_encoding(target)
-
target_encoding.get_best_compatible(encoding, raw_source)
-
end
-
-
# Returns a body encoded using transfer_encoding. Multipart always uses an
-
# identiy encoding (i.e. no encoding).
-
# Calling this directly is not a good idea, but supported for compatibility
-
# TODO: Validate that preamble and epilogue are valid for requested encoding
-
2
def encoded(transfer_encoding = '8bit')
-
if multipart?
-
self.sort_parts!
-
encoded_parts = parts.map { |p| p.encoded }
-
([preamble] + encoded_parts).join(crlf_boundary) + end_boundary + epilogue.to_s
-
else
-
be = get_best_encoding(transfer_encoding)
-
dec = Mail::Encodings::get_encoding(encoding)
-
enc = Mail::Encodings::get_encoding(be)
-
if transfer_encoding == encoding and dec.nil?
-
# Cannot decode, so skip normalization
-
raw_source
-
else
-
# Decode then encode to normalize and allow transforming
-
# from base64 to Q-P and vice versa
-
decoded = dec.decode(raw_source)
-
if defined?(Encoding) && charset && charset != "US-ASCII"
-
decoded.encode!(charset)
-
decoded.force_encoding('BINARY') unless Encoding.find(charset).ascii_compatible?
-
end
-
enc.encode(decoded)
-
end
-
end
-
end
-
-
2
def decoded
-
if !Encodings.defined?(encoding)
-
raise UnknownEncodingType, "Don't know how to decode #{encoding}, please call #encoded and decode it yourself."
-
else
-
Encodings.get_encoding(encoding).decode(raw_source)
-
end
-
end
-
-
2
def to_s
-
decoded
-
end
-
-
2
def charset
-
@charset
-
end
-
-
2
def charset=( val )
-
@charset = val
-
end
-
-
2
def encoding(val = nil)
-
if val
-
self.encoding = val
-
else
-
@encoding
-
end
-
end
-
-
2
def encoding=( val )
-
@encoding = if val == "text" || val.blank?
-
(only_us_ascii? ? '7bit' : '8bit')
-
else
-
val
-
end
-
end
-
-
# Returns the preamble (any text that is before the first MIME boundary)
-
2
def preamble
-
@preamble
-
end
-
-
# Sets the preamble to a string (adds text before the first MIME boundary)
-
2
def preamble=( val )
-
@preamble = val
-
end
-
-
# Returns the epilogue (any text that is after the last MIME boundary)
-
2
def epilogue
-
@epilogue
-
end
-
-
# Sets the epilogue to a string (adds text after the last MIME boundary)
-
2
def epilogue=( val )
-
@epilogue = val
-
end
-
-
# Returns true if there are parts defined in the body
-
2
def multipart?
-
true unless parts.empty?
-
end
-
-
# Returns the boundary used by the body
-
2
def boundary
-
@boundary
-
end
-
-
# Allows you to change the boundary of this Body object
-
2
def boundary=( val )
-
@boundary = val
-
end
-
-
2
def parts
-
@parts
-
end
-
-
2
def <<( val )
-
if @parts
-
@parts << val
-
else
-
@parts = Mail::PartsList.new[val]
-
end
-
end
-
-
2
def split!(boundary)
-
self.boundary = boundary
-
parts = extract_parts
-
-
# Make the preamble equal to the preamble (if any)
-
self.preamble = parts[0].to_s.strip
-
# Make the epilogue equal to the epilogue (if any)
-
self.epilogue = parts[-1].to_s.strip
-
parts[1...-1].to_a.each { |part| @parts << Mail::Part.new(part) }
-
self
-
end
-
-
2
def only_us_ascii?
-
!(raw_source =~ /[^\x01-\x7f]/)
-
end
-
-
2
def empty?
-
!!raw_source.to_s.empty?
-
end
-
-
2
private
-
-
# split parts by boundary, ignore first part if empty, append final part when closing boundary was missing
-
2
def extract_parts
-
parts_regex = /
-
(?: # non-capturing group
-
\A | # start of string OR
-
\r\n # line break
-
)
-
(
-
--#{Regexp.escape(boundary || "")} # boundary delimiter
-
(?:--)? # with non-capturing optional closing
-
)
-
(?=\s*$) # lookahead matching zero or more spaces followed by line-ending
-
/x
-
parts = raw_source.split(parts_regex).each_slice(2).to_a
-
parts.each_with_index { |(part, _), index| parts.delete_at(index) if index > 0 && part.blank? }
-
-
if parts.size > 1
-
final_separator = parts[-2][1]
-
parts << [""] if final_separator != "--#{boundary}--"
-
end
-
parts.map(&:first)
-
end
-
-
2
def crlf_boundary
-
"\r\n--#{boundary}\r\n"
-
end
-
-
2
def end_boundary
-
"\r\n--#{boundary}--\r\n"
-
end
-
-
2
def set_charset
-
only_us_ascii? ? @charset = 'US-ASCII' : @charset = nil
-
end
-
end
-
end
-
2
module Mail
-
2
module CheckDeliveryParams
-
2
def check_delivery_params(mail)
-
if mail.smtp_envelope_from.blank?
-
raise ArgumentError.new('An SMTP From address is required to send a message. Set the message smtp_envelope_from, return_path, sender, or from address.')
-
end
-
-
if mail.smtp_envelope_to.blank?
-
raise ArgumentError.new('An SMTP To address is required to send a message. Set the message smtp_envelope_to, to, cc, or bcc address.')
-
end
-
-
message = mail.encoded if mail.respond_to?(:encoded)
-
if message.blank?
-
raise ArgumentError.new('An encoded message is required to send an email')
-
end
-
-
[mail.smtp_envelope_from, mail.smtp_envelope_to, message]
-
end
-
end
-
end
-
# encoding: utf-8
-
#
-
# Thanks to Nicolas Fouché for this wrapper
-
#
-
2
require 'singleton'
-
-
2
module Mail
-
-
# The Configuration class is a Singleton used to hold the default
-
# configuration for all Mail objects.
-
#
-
# Each new mail object gets a copy of these values at initialization
-
# which can be overwritten on a per mail object basis.
-
2
class Configuration
-
2
include Singleton
-
-
2
def initialize
-
@delivery_method = nil
-
@retriever_method = nil
-
super
-
end
-
-
2
def delivery_method(method = nil, settings = {})
-
return @delivery_method if @delivery_method && method.nil?
-
@delivery_method = lookup_delivery_method(method).new(settings)
-
end
-
-
2
def lookup_delivery_method(method)
-
case method.is_a?(String) ? method.to_sym : method
-
when nil
-
Mail::SMTP
-
when :smtp
-
Mail::SMTP
-
when :sendmail
-
Mail::Sendmail
-
when :exim
-
Mail::Exim
-
when :file
-
Mail::FileDelivery
-
when :smtp_connection
-
Mail::SMTPConnection
-
when :test
-
Mail::TestMailer
-
else
-
method
-
end
-
end
-
-
2
def retriever_method(method = nil, settings = {})
-
return @retriever_method if @retriever_method && method.nil?
-
@retriever_method = lookup_retriever_method(method).new(settings)
-
end
-
-
2
def lookup_retriever_method(method)
-
case method
-
when nil
-
Mail::POP3
-
when :pop3
-
Mail::POP3
-
when :imap
-
Mail::IMAP
-
when :test
-
Mail::TestRetriever
-
else
-
method
-
end
-
end
-
-
2
def param_encode_language(value = nil)
-
value ? @encode_language = value : @encode_language ||= 'en'
-
end
-
-
end
-
-
end
-
# encoding: us-ascii
-
2
module Mail
-
2
module Constants
-
2
white_space = %Q|\x9\x20|
-
2
text = %Q|\x1-\x8\xB\xC\xE-\x7f|
-
2
field_name = %Q|\x21-\x39\x3b-\x7e|
-
2
qp_safe = %Q|\x20-\x3c\x3e-\x7e|
-
-
2
aspecial = %Q|()<>[]:;@\\,."| # RFC5322
-
2
tspecial = %Q|()<>@,;:\\"/[]?=| # RFC2045
-
2
sp = %Q| |
-
2
control = %Q|\x00-\x1f\x7f-\xff|
-
-
2
if control.respond_to?(:force_encoding)
-
2
control = control.force_encoding(Encoding::BINARY)
-
end
-
-
2
CRLF = /\r\n/
-
2
WSP = /[#{white_space}]/
-
2
FWS = /#{CRLF}#{WSP}*/
-
2
TEXT = /[#{text}]/ # + obs-text
-
2
FIELD_NAME = /[#{field_name}]+/
-
2
FIELD_PREFIX = /\A(#{FIELD_NAME})/
-
2
FIELD_BODY = /.+/m
-
2
FIELD_LINE = /^[#{field_name}]+:\s*.+$/
-
2
FIELD_SPLIT = /^(#{FIELD_NAME})\s*:\s*(#{FIELD_BODY})?$/
-
2
HEADER_LINE = /^([#{field_name}]+:\s*.+)$/
-
2
HEADER_SPLIT = /#{CRLF}(?!#{WSP})/
-
-
2
QP_UNSAFE = /[^#{qp_safe}]/
-
2
QP_SAFE = /[#{qp_safe}]/
-
2
CONTROL_CHAR = /[#{control}]/n
-
2
ATOM_UNSAFE = /[#{Regexp.quote aspecial}#{control}#{sp}]/n
-
2
PHRASE_UNSAFE = /[#{Regexp.quote aspecial}#{control}]/n
-
2
TOKEN_UNSAFE = /[#{Regexp.quote tspecial}#{control}#{sp}]/n
-
2
ENCODED_VALUE = /\=\?[^?]+\?([QB])\?[^?]*?\?\=/mi
-
-
2
EMPTY = ''
-
2
SPACE = ' '
-
2
UNDERSCORE = '_'
-
2
HYPHEN = '-'
-
2
COLON = ':'
-
2
ASTERISK = '*'
-
2
CR = "\r"
-
2
LF = "\n"
-
2
CR_ENCODED = "=0D"
-
2
LF_ENCODED = "=0A"
-
2
CAPITAL_M = 'M'
-
2
EQUAL_LF = "=\n"
-
2
NULL_SENDER = '<>'
-
-
2
Q_VALUES = ['Q','q']
-
2
B_VALUES = ['B','b']
-
end
-
end
-
# encoding: utf-8
-
-
# This is not loaded if ActiveSupport is already loaded
-
-
2
class NilClass #:nodoc:
-
2
unless nil.respond_to? :blank?
-
def blank?
-
true
-
end
-
end
-
-
2
def to_crlf
-
''
-
end
-
-
2
def to_lf
-
''
-
end
-
end
-
# encoding: utf-8
-
-
2
unless Object.method_defined? :blank?
-
class Object
-
def blank?
-
if respond_to?(:empty?)
-
empty?
-
else
-
!self
-
end
-
end
-
end
-
end
-
# encoding: utf-8
-
2
class String #:nodoc:
-
-
2
CRLF = "\r\n"
-
2
LF = "\n"
-
-
2
if RUBY_VERSION >= '1.9'
-
# This 1.9 only regex can save a reasonable amount of time (~20%)
-
# by not matching "\r\n" so the string is returned unchanged in
-
# the common case.
-
2
CRLF_REGEX = Regexp.new("(?<!\r)\n|\r(?!\n)")
-
else
-
CRLF_REGEX = /\n|\r\n|\r/
-
end
-
-
2
def to_crlf
-
to_str.gsub(CRLF_REGEX, CRLF)
-
end
-
-
2
def to_lf
-
to_str.gsub(/\r\n|\r/, LF)
-
end
-
-
354
unless String.instance_methods(false).map {|m| m.to_sym}.include?(:blank?)
-
def blank?
-
self !~ /\S/
-
end
-
end
-
-
2
unless method_defined?(:ascii_only?)
-
# Backport from Ruby 1.9 checks for non-us-ascii characters.
-
def ascii_only?
-
self !~ MATCH_NON_US_ASCII
-
end
-
-
MATCH_NON_US_ASCII = /[^\x00-\x7f]/
-
end
-
-
2
def not_ascii_only?
-
!ascii_only?
-
end
-
-
2
unless method_defined?(:bytesize)
-
alias :bytesize :length
-
end
-
end
-
2
module Mail
-
2
register_autoload :Address, 'mail/elements/address'
-
2
register_autoload :AddressList, 'mail/elements/address_list'
-
2
register_autoload :ContentDispositionElement, 'mail/elements/content_disposition_element'
-
2
register_autoload :ContentLocationElement, 'mail/elements/content_location_element'
-
2
register_autoload :ContentTransferEncodingElement, 'mail/elements/content_transfer_encoding_element'
-
2
register_autoload :ContentTypeElement, 'mail/elements/content_type_element'
-
2
register_autoload :DateTimeElement, 'mail/elements/date_time_element'
-
2
register_autoload :EnvelopeFromElement, 'mail/elements/envelope_from_element'
-
2
register_autoload :MessageIdsElement, 'mail/elements/message_ids_element'
-
2
register_autoload :MimeVersionElement, 'mail/elements/mime_version_element'
-
2
register_autoload :PhraseList, 'mail/elements/phrase_list'
-
2
register_autoload :ReceivedElement, 'mail/elements/received_element'
-
end
-
# encoding: utf-8
-
-
2
module Mail
-
# Raised when attempting to decode an unknown encoding type
-
2
class UnknownEncodingType < StandardError #:nodoc:
-
end
-
-
2
module Encodings
-
-
2
include Mail::Constants
-
2
extend Mail::Utilities
-
-
2
@transfer_encodings = {}
-
-
# Register transfer encoding
-
#
-
# Example
-
#
-
# Encodings.register "base64", Mail::Encodings::Base64
-
2
def Encodings.register(name, cls)
-
12
@transfer_encodings[get_name(name)] = cls
-
end
-
-
# Is the encoding we want defined?
-
#
-
# Example:
-
#
-
# Encodings.defined?(:base64) #=> true
-
2
def Encodings.defined?( str )
-
@transfer_encodings.include? get_name(str)
-
end
-
-
# Gets a defined encoding type, QuotedPrintable or Base64 for now.
-
#
-
# Each encoding needs to be defined as a Mail::Encodings::ClassName for
-
# this to work, allows us to add other encodings in the future.
-
#
-
# Example:
-
#
-
# Encodings.get_encoding(:base64) #=> Mail::Encodings::Base64
-
2
def Encodings.get_encoding( str )
-
@transfer_encodings[get_name(str)]
-
end
-
-
2
def Encodings.get_all
-
@transfer_encodings.values
-
end
-
-
2
def Encodings.get_name(enc)
-
12
enc = underscoreize(enc).downcase
-
end
-
-
# Encodes a parameter value using URI Escaping, note the language field 'en' can
-
# be set using Mail::Configuration, like so:
-
#
-
# Mail.defaults do
-
# param_encode_language 'jp'
-
# end
-
#
-
# The character set used for encoding will either be the value of $KCODE for
-
# Ruby < 1.9 or the encoding on the string passed in.
-
#
-
# Example:
-
#
-
# Mail::Encodings.param_encode("This is fun") #=> "us-ascii'en'This%20is%20fun"
-
2
def Encodings.param_encode(str)
-
case
-
when str.ascii_only? && str =~ TOKEN_UNSAFE
-
%Q{"#{str}"}
-
when str.ascii_only?
-
str
-
else
-
RubyVer.param_encode(str)
-
end
-
end
-
-
# Decodes a parameter value using URI Escaping.
-
#
-
# Example:
-
#
-
# Mail::Encodings.param_decode("This%20is%20fun", 'us-ascii') #=> "This is fun"
-
#
-
# str = Mail::Encodings.param_decode("This%20is%20fun", 'iso-8559-1')
-
# str.encoding #=> 'ISO-8859-1' ## Only on Ruby 1.9
-
# str #=> "This is fun"
-
2
def Encodings.param_decode(str, encoding)
-
RubyVer.param_decode(str, encoding)
-
end
-
-
# Decodes or encodes a string as needed for either Base64 or QP encoding types in
-
# the =?<encoding>?[QB]?<string>?=" format.
-
#
-
# The output type needs to be :decode to decode the input string or :encode to
-
# encode the input string. The character set used for encoding will either be
-
# the value of $KCODE for Ruby < 1.9 or the encoding on the string passed in.
-
#
-
# On encoding, will only send out Base64 encoded strings.
-
2
def Encodings.decode_encode(str, output_type)
-
case
-
when output_type == :decode
-
Encodings.value_decode(str)
-
else
-
if str.ascii_only?
-
str
-
else
-
Encodings.b_value_encode(str, find_encoding(str))
-
end
-
end
-
end
-
-
# Decodes a given string as Base64 or Quoted Printable, depending on what
-
# type it is.
-
#
-
# String has to be of the format =?<encoding>?[QB]?<string>?=
-
2
def Encodings.value_decode(str)
-
# Optimization: If there's no encoded-words in the string, just return it
-
return str unless str =~ ENCODED_VALUE
-
-
lines = collapse_adjacent_encodings(str)
-
-
# Split on white-space boundaries with capture, so we capture the white-space as well
-
lines.each do |line|
-
line.gsub!(ENCODED_VALUE) do |string|
-
case $1
-
when *B_VALUES then b_value_decode(string)
-
when *Q_VALUES then q_value_decode(string)
-
end
-
end
-
end.join("")
-
end
-
-
# Takes an encoded string of the format =?<encoding>?[QB]?<string>?=
-
2
def Encodings.unquote_and_convert_to(str, to_encoding)
-
output = value_decode( str ).to_s # output is already converted to UTF-8
-
-
if 'utf8' == to_encoding.to_s.downcase.gsub("-", "")
-
output
-
elsif to_encoding
-
begin
-
if RUBY_VERSION >= '1.9'
-
output.encode(to_encoding)
-
else
-
require 'iconv'
-
Iconv.iconv(to_encoding, 'UTF-8', output).first
-
end
-
rescue Iconv::IllegalSequence, Iconv::InvalidEncoding, Errno::EINVAL
-
# the 'from' parameter specifies a charset other than what the text
-
# actually is...not much we can do in this case but just return the
-
# unconverted text.
-
#
-
# Ditto if either parameter represents an unknown charset, like
-
# X-UNKNOWN.
-
output
-
end
-
else
-
output
-
end
-
end
-
-
2
def Encodings.address_encode(address, charset = 'utf-8')
-
if address.is_a?(Array)
-
# loop back through for each element
-
address.compact.map { |a| Encodings.address_encode(a, charset) }.join(", ")
-
else
-
# find any word boundary that is not ascii and encode it
-
encode_non_usascii(address, charset) if address
-
end
-
end
-
-
2
def Encodings.encode_non_usascii(address, charset)
-
return address if address.ascii_only? or charset.nil?
-
us_ascii = %Q{\x00-\x7f}
-
# Encode any non usascii strings embedded inside of quotes
-
address = address.gsub(/(".*?[^#{us_ascii}].*?")/) { |s| Encodings.b_value_encode(unquote(s), charset) }
-
# Then loop through all remaining items and encode as needed
-
tokens = address.split(/\s/)
-
map_with_index(tokens) do |word, i|
-
if word.ascii_only?
-
word
-
else
-
previous_non_ascii = i>0 && tokens[i-1] && !tokens[i-1].ascii_only?
-
if previous_non_ascii #why are we adding an extra space here?
-
word = " #{word}"
-
end
-
Encodings.b_value_encode(word, charset)
-
end
-
end.join(' ')
-
end
-
-
# Encode a string with Base64 Encoding and returns it ready to be inserted
-
# as a value for a field, that is, in the =?<charset>?B?<string>?= format
-
#
-
# Example:
-
#
-
# Encodings.b_value_encode('This is あ string', 'UTF-8')
-
# #=> "=?UTF-8?B?VGhpcyBpcyDjgYIgc3RyaW5n?="
-
2
def Encodings.b_value_encode(encoded_str, encoding = nil)
-
return encoded_str if encoded_str.to_s.ascii_only?
-
string, encoding = RubyVer.b_value_encode(encoded_str, encoding)
-
map_lines(string) do |str|
-
"=?#{encoding}?B?#{str.chomp}?="
-
end.join(" ")
-
end
-
-
# Encode a string with Quoted-Printable Encoding and returns it ready to be inserted
-
# as a value for a field, that is, in the =?<charset>?Q?<string>?= format
-
#
-
# Example:
-
#
-
# Encodings.q_value_encode('This is あ string', 'UTF-8')
-
# #=> "=?UTF-8?Q?This_is_=E3=81=82_string?="
-
2
def Encodings.q_value_encode(encoded_str, encoding = nil)
-
return encoded_str if encoded_str.to_s.ascii_only?
-
string, encoding = RubyVer.q_value_encode(encoded_str, encoding)
-
string.gsub!("=\r\n", '') # We already have limited the string to the length we want
-
map_lines(string) do |str|
-
"=?#{encoding}?Q?#{str.chomp.gsub(/ /, '_')}?="
-
end.join(" ")
-
end
-
-
2
private
-
-
# Decodes a Base64 string from the "=?UTF-8?B?VGhpcyBpcyDjgYIgc3RyaW5n?=" format
-
#
-
# Example:
-
#
-
# Encodings.b_value_decode("=?UTF-8?B?VGhpcyBpcyDjgYIgc3RyaW5n?=")
-
# #=> 'This is あ string'
-
2
def Encodings.b_value_decode(str)
-
RubyVer.b_value_decode(str)
-
end
-
-
# Decodes a Quoted-Printable string from the "=?UTF-8?Q?This_is_=E3=81=82_string?=" format
-
#
-
# Example:
-
#
-
# Encodings.q_value_decode("=?UTF-8?Q?This_is_=E3=81=82_string?=")
-
# #=> 'This is あ string'
-
2
def Encodings.q_value_decode(str)
-
RubyVer.q_value_decode(str)
-
end
-
-
2
def Encodings.split_encoding_from_string( str )
-
match = str.match(/\=\?([^?]+)?\?[QB]\?(.*)\?\=/mi)
-
if match
-
match[1]
-
else
-
nil
-
end
-
end
-
-
2
def Encodings.find_encoding(str)
-
RUBY_VERSION >= '1.9' ? str.encoding : $KCODE
-
end
-
-
# Gets the encoding type (Q or B) from the string.
-
2
def Encodings.split_value_encoding_from_string(str)
-
match = str.match(/\=\?[^?]+?\?([QB])\?(.*)\?\=/mi)
-
if match
-
match[1]
-
else
-
nil
-
end
-
end
-
-
# When the encoded string consists of multiple lines, lines with the same
-
# encoding (Q or B) can be joined together.
-
#
-
# String has to be of the format =?<encoding>?[QB]?<string>?=
-
2
def Encodings.collapse_adjacent_encodings(str)
-
lines = str.split(/(\?=)\s*(=\?)/).each_slice(2).map(&:join)
-
results = []
-
previous_encoding = nil
-
-
lines.each do |line|
-
encoding = split_value_encoding_from_string(line)
-
-
if encoding == previous_encoding
-
line = results.pop + line
-
end
-
-
previous_encoding = encoding
-
results << line
-
end
-
-
results
-
end
-
end
-
end
-
# encoding: utf-8
-
2
require 'mail/encodings/8bit'
-
-
2
module Mail
-
2
module Encodings
-
2
class SevenBit < EightBit
-
2
NAME = '7bit'
-
-
2
PRIORITY = 1
-
-
# 7bit and 8bit operate the same
-
-
# Decode the string
-
2
def self.decode(str)
-
super
-
end
-
-
# Encode the string
-
2
def self.encode(str)
-
super
-
end
-
-
# Idenity encodings have a fixed cost, 1 byte out per 1 byte in
-
2
def self.cost(str)
-
super
-
end
-
-
2
Encodings.register(NAME, self)
-
end
-
end
-
end
-
# encoding: utf-8
-
2
require 'mail/encodings/binary'
-
-
2
module Mail
-
2
module Encodings
-
2
class EightBit < Binary
-
2
NAME = '8bit'
-
-
2
PRIORITY = 4
-
-
# 8bit is an identiy encoding, meaning nothing to do
-
-
# Decode the string
-
2
def self.decode(str)
-
str.to_lf
-
end
-
-
# Encode the string
-
2
def self.encode(str)
-
str.to_crlf
-
end
-
-
# Idenity encodings have a fixed cost, 1 byte out per 1 byte in
-
2
def self.cost(str)
-
1.0
-
end
-
-
2
Encodings.register(NAME, self)
-
end
-
end
-
end
-
# encoding: utf-8
-
2
require 'mail/encodings/7bit'
-
-
2
module Mail
-
2
module Encodings
-
2
class Base64 < SevenBit
-
2
NAME = 'base64'
-
-
2
PRIORITY = 3
-
-
2
def self.can_encode?(enc)
-
true
-
end
-
-
# Decode the string from Base64
-
2
def self.decode(str)
-
RubyVer.decode_base64( str )
-
end
-
-
# Encode the string to Base64
-
2
def self.encode(str)
-
RubyVer.encode_base64( str ).to_crlf
-
end
-
-
# Base64 has a fixed cost, 4 bytes out per 3 bytes in
-
2
def self.cost(str)
-
4.0/3
-
end
-
-
2
Encodings.register(NAME, self)
-
end
-
end
-
end
-
# encoding: utf-8
-
2
require 'mail/encodings/transfer_encoding'
-
-
2
module Mail
-
2
module Encodings
-
2
class Binary < TransferEncoding
-
2
NAME = 'binary'
-
-
2
PRIORITY = 5
-
-
# Binary is an identiy encoding, meaning nothing to do
-
-
# Decode the string
-
2
def self.decode(str)
-
str
-
end
-
-
# Encode the string
-
2
def self.encode(str)
-
str
-
end
-
-
# Idenity encodings have a fixed cost, 1 byte out per 1 byte in
-
2
def self.cost(str)
-
1.0
-
end
-
-
2
Encodings.register(NAME, self)
-
end
-
end
-
end
-
# encoding: utf-8
-
2
require 'mail/encodings/7bit'
-
-
2
module Mail
-
2
module Encodings
-
2
class QuotedPrintable < SevenBit
-
2
NAME='quoted-printable'
-
-
2
PRIORITY = 2
-
-
2
def self.can_encode?(str)
-
EightBit.can_encode? str
-
end
-
-
# Decode the string from Quoted-Printable. Cope with hard line breaks
-
# that were incorrectly encoded as hex instead of literal CRLF.
-
2
def self.decode(str)
-
str.gsub(/(?:=0D=0A|=0D|=0A)\r\n/, "\r\n").unpack("M*").first.to_lf
-
end
-
-
2
def self.encode(str)
-
[str.to_lf].pack("M").to_crlf
-
end
-
-
2
def self.cost(str)
-
# These bytes probably do not need encoding
-
c = str.count("\x9\xA\xD\x20-\x3C\x3E-\x7E")
-
# Everything else turns into =XX where XX is a
-
# two digit hex number (taking 3 bytes)
-
total = (str.bytesize - c)*3 + c
-
total.to_f/str.bytesize
-
end
-
-
2
private
-
-
2
Encodings.register(NAME, self)
-
end
-
end
-
end
-
# encoding: utf-8
-
2
module Mail
-
2
module Encodings
-
2
class TransferEncoding
-
2
NAME = ''
-
-
2
PRIORITY = -1
-
-
2
def self.can_transport?(enc)
-
enc = Encodings.get_name(enc)
-
if Encodings.defined? enc
-
Encodings.get_encoding(enc).new.is_a? self
-
else
-
false
-
end
-
end
-
-
2
def self.can_encode?(enc)
-
can_transport? enc
-
end
-
-
2
def self.cost(str)
-
raise "Unimplemented"
-
end
-
-
2
def self.to_s
-
self::NAME
-
end
-
-
2
def self.get_best_compatible(source_encoding, str)
-
if self.can_transport? source_encoding then
-
source_encoding
-
else
-
choices = []
-
Encodings.get_all.each do |enc|
-
choices << enc if self.can_transport? enc and enc.can_encode? source_encoding
-
end
-
best = nil
-
best_cost = 100
-
choices.each do |enc|
-
this_cost = enc.cost str
-
if this_cost < best_cost then
-
best_cost = this_cost
-
best = enc
-
elsif this_cost == best_cost then
-
best = enc if enc::PRIORITY < best::PRIORITY
-
end
-
end
-
best
-
end
-
end
-
-
2
def to_s
-
self.class.to_s
-
end
-
end
-
end
-
end
-
2
module Mail
-
2
module Encodings
-
2
module UnixToUnix
-
2
NAME = "x-uuencode"
-
-
2
def self.decode(str)
-
str.sub(/\Abegin \d+ [^\n]*\n/, '').unpack('u').first
-
end
-
-
2
def self.encode(str)
-
[str].pack("u")
-
end
-
-
2
Encodings.register(NAME, self)
-
end
-
end
-
end
-
# encoding: utf-8
-
#
-
# = Mail Envelope
-
#
-
# The Envelope class provides a field for the first line in an
-
# mbox file, that looks like "From mikel@test.lindsaar.net DATETIME"
-
#
-
# This envelope class reads that line, and turns it into an
-
# Envelope.from and Envelope.date for your use.
-
2
module Mail
-
2
class Envelope < StructuredField
-
-
2
def initialize(*args)
-
super(FIELD_NAME, strip_field(FIELD_NAME, args.last))
-
end
-
-
2
def element
-
@element ||= Mail::EnvelopeFromElement.new(value)
-
end
-
-
2
def date
-
::DateTime.parse("#{element.date_time}")
-
end
-
-
2
def from
-
element.address
-
end
-
-
end
-
end
-
2
require 'mail/fields'
-
-
# encoding: utf-8
-
2
module Mail
-
# Provides a single class to call to create a new structured or unstructured
-
# field. Works out per RFC what field of field it is being given and returns
-
# the correct field of class back on new.
-
#
-
# ===Per RFC 2822
-
#
-
# 2.2. Header Fields
-
#
-
# Header fields are lines composed of a field name, followed by a colon
-
# (":"), followed by a field body, and terminated by CRLF. A field
-
# name MUST be composed of printable US-ASCII characters (i.e.,
-
# characters that have values between 33 and 126, inclusive), except
-
# colon. A field body may be composed of any US-ASCII characters,
-
# except for CR and LF. However, a field body may contain CRLF when
-
# used in header "folding" and "unfolding" as described in section
-
# 2.2.3. All field bodies MUST conform to the syntax described in
-
# sections 3 and 4 of this standard.
-
#
-
2
class Field
-
-
2
include Utilities
-
2
include Comparable
-
-
2
STRUCTURED_FIELDS = %w[ bcc cc content-description content-disposition
-
content-id content-location content-transfer-encoding
-
content-type date from in-reply-to keywords message-id
-
mime-version received references reply-to
-
resent-bcc resent-cc resent-date resent-from
-
resent-message-id resent-sender resent-to
-
return-path sender to ]
-
-
2
KNOWN_FIELDS = STRUCTURED_FIELDS + ['comments', 'subject']
-
-
2
FIELDS_MAP = {
-
"to" => ToField,
-
"cc" => CcField,
-
"bcc" => BccField,
-
"message-id" => MessageIdField,
-
"in-reply-to" => InReplyToField,
-
"references" => ReferencesField,
-
"subject" => SubjectField,
-
"comments" => CommentsField,
-
"keywords" => KeywordsField,
-
"date" => DateField,
-
"from" => FromField,
-
"sender" => SenderField,
-
"reply-to" => ReplyToField,
-
"resent-date" => ResentDateField,
-
"resent-from" => ResentFromField,
-
"resent-sender" => ResentSenderField,
-
"resent-to" => ResentToField,
-
"resent-cc" => ResentCcField,
-
"resent-bcc" => ResentBccField,
-
"resent-message-id" => ResentMessageIdField,
-
"return-path" => ReturnPathField,
-
"received" => ReceivedField,
-
"mime-version" => MimeVersionField,
-
"content-transfer-encoding" => ContentTransferEncodingField,
-
"content-description" => ContentDescriptionField,
-
"content-disposition" => ContentDispositionField,
-
"content-type" => ContentTypeField,
-
"content-id" => ContentIdField,
-
"content-location" => ContentLocationField,
-
}
-
-
2
FIELD_NAME_MAP = FIELDS_MAP.inject({}) do |map, (field, field_klass)|
-
58
map.update(field => field_klass::CAPITALIZED_FIELD)
-
end
-
-
# Generic Field Exception
-
2
class FieldError < StandardError
-
end
-
-
# Raised when a parsing error has occurred (ie, a StructuredField has tried
-
# to parse a field that is invalid or improperly written)
-
2
class ParseError < FieldError #:nodoc:
-
2
attr_accessor :element, :value, :reason
-
-
2
def initialize(element, value, reason)
-
@element = element
-
@value = value
-
@reason = reason
-
super("#{element} can not parse |#{value}|\nReason was: #{reason}")
-
end
-
end
-
-
# Raised when attempting to set a structured field's contents to an invalid syntax
-
2
class SyntaxError < FieldError #:nodoc:
-
end
-
-
# Accepts a string:
-
#
-
# Field.new("field-name: field data")
-
#
-
# Or name, value pair:
-
#
-
# Field.new("field-name", "value")
-
#
-
# Or a name by itself:
-
#
-
# Field.new("field-name")
-
#
-
# Note, does not want a terminating carriage return. Returns
-
# self appropriately parsed. If value is not a string, then
-
# it will be passed through as is, for example, content-type
-
# field can accept an array with the type and a hash of
-
# parameters:
-
#
-
# Field.new('content-type', ['text', 'plain', {:charset => 'UTF-8'}])
-
2
def initialize(name, value = nil, charset = 'utf-8')
-
case
-
when name.index(COLON) # Field.new("field-name: field data")
-
@charset = value.blank? ? charset : value
-
@name = name[FIELD_PREFIX]
-
@raw_value = name
-
@value = nil
-
when value.blank? # Field.new("field-name")
-
@name = name
-
@value = nil
-
@raw_value = nil
-
@charset = charset
-
else # Field.new("field-name", "value")
-
@name = name
-
@value = value
-
@raw_value = nil
-
@charset = charset
-
end
-
@name = FIELD_NAME_MAP[@name.to_s.downcase] || @name
-
end
-
-
2
def field=(value)
-
@field = value
-
end
-
-
2
def field
-
_, @value = split(@raw_value) if @raw_value && !@value
-
@field ||= create_field(@name, @value, @charset)
-
end
-
-
2
def name
-
@name
-
end
-
-
2
def value
-
field.value
-
end
-
-
2
def value=(val)
-
@field = create_field(name, val, @charset)
-
end
-
-
2
def to_s
-
field.to_s
-
end
-
-
2
def inspect
-
"#<#{self.class.name} 0x#{(object_id * 2).to_s(16)} #{instance_variables.map do |ivar|
-
"#{ivar}=#{instance_variable_get(ivar).inspect}"
-
end.join(" ")}>"
-
end
-
-
2
def update(name, value)
-
@field = create_field(name, value, @charset)
-
end
-
-
2
def same( other )
-
match_to_s(other.name, self.name)
-
end
-
-
2
def responsible_for?( val )
-
name.to_s.casecmp(val.to_s) == 0
-
end
-
-
2
alias_method :==, :same
-
-
2
def <=>( other )
-
self.field_order_id <=> other.field_order_id
-
end
-
-
2
def field_order_id
-
@field_order_id ||= (FIELD_ORDER_LOOKUP[self.name.to_s.downcase] || 100)
-
end
-
-
2
def method_missing(name, *args, &block)
-
field.send(name, *args, &block)
-
end
-
-
2
FIELD_ORDER = %w[ return-path received
-
resent-date resent-from resent-sender resent-to
-
resent-cc resent-bcc resent-message-id
-
date from sender reply-to to cc bcc
-
message-id in-reply-to references
-
subject comments keywords
-
mime-version content-type content-transfer-encoding
-
content-location content-disposition content-description ]
-
-
2
FIELD_ORDER_LOOKUP = Hash[FIELD_ORDER.each_with_index.to_a]
-
-
2
private
-
-
2
def split(raw_field)
-
match_data = raw_field.mb_chars.match(FIELD_SPLIT)
-
[match_data[1].to_s.mb_chars.strip, match_data[2].to_s.mb_chars.strip.to_s]
-
rescue
-
STDERR.puts "WARNING: Could not parse (and so ignoring) '#{raw_field}'"
-
end
-
-
# 2.2.3. Long Header Fields
-
#
-
# The process of moving from this folded multiple-line representation
-
# of a header field to its single line representation is called
-
# "unfolding". Unfolding is accomplished by simply removing any CRLF
-
# that is immediately followed by WSP. Each header field should be
-
# treated in its unfolded form for further syntactic and semantic
-
# evaluation.
-
2
def unfold(string)
-
string.gsub(/[\r\n \t]+/m, ' ')
-
end
-
-
2
def create_field(name, value, charset)
-
value = unfold(value) if value.is_a?(String)
-
-
begin
-
new_field(name, value, charset)
-
rescue Mail::Field::ParseError => e
-
field = Mail::UnstructuredField.new(name, value)
-
field.errors << [name, value, e]
-
field
-
end
-
end
-
-
2
def new_field(name, value, charset)
-
lower_case_name = name.to_s.downcase
-
if field_klass = FIELDS_MAP[lower_case_name]
-
field_klass.new(value, charset)
-
else
-
OptionalField.new(name, value, charset)
-
end
-
end
-
-
end
-
-
end
-
# encoding: utf-8
-
2
module Mail
-
-
# Field List class provides an enhanced array that keeps a list of
-
# email fields in order. And allows you to insert new fields without
-
# having to worry about the order they will appear in.
-
2
class FieldList < Array
-
-
2
include Enumerable
-
-
# Insert the field in sorted order.
-
#
-
# Heavily based on bisect.insort from Python, which is:
-
# Copyright (C) 2001-2013 Python Software Foundation.
-
# Licensed under <http://docs.python.org/license.html>
-
# From <http://hg.python.org/cpython/file/2.7/Lib/bisect.py>
-
2
def <<( new_field )
-
lo = 0
-
hi = size
-
-
while lo < hi
-
mid = (lo + hi).div(2)
-
if new_field < self[mid]
-
hi = mid
-
else
-
lo = mid + 1
-
end
-
end
-
-
insert(lo, new_field)
-
end
-
end
-
end
-
2
module Mail
-
2
register_autoload :UnstructuredField, 'mail/fields/unstructured_field'
-
2
register_autoload :StructuredField, 'mail/fields/structured_field'
-
2
register_autoload :OptionalField, 'mail/fields/optional_field'
-
-
2
register_autoload :BccField, 'mail/fields/bcc_field'
-
2
register_autoload :CcField, 'mail/fields/cc_field'
-
2
register_autoload :CommentsField, 'mail/fields/comments_field'
-
2
register_autoload :ContentDescriptionField, 'mail/fields/content_description_field'
-
2
register_autoload :ContentDispositionField, 'mail/fields/content_disposition_field'
-
2
register_autoload :ContentIdField, 'mail/fields/content_id_field'
-
2
register_autoload :ContentLocationField, 'mail/fields/content_location_field'
-
2
register_autoload :ContentTransferEncodingField, 'mail/fields/content_transfer_encoding_field'
-
2
register_autoload :ContentTypeField, 'mail/fields/content_type_field'
-
2
register_autoload :DateField, 'mail/fields/date_field'
-
2
register_autoload :FromField, 'mail/fields/from_field'
-
2
register_autoload :InReplyToField, 'mail/fields/in_reply_to_field'
-
2
register_autoload :KeywordsField, 'mail/fields/keywords_field'
-
2
register_autoload :MessageIdField, 'mail/fields/message_id_field'
-
2
register_autoload :MimeVersionField, 'mail/fields/mime_version_field'
-
2
register_autoload :ReceivedField, 'mail/fields/received_field'
-
2
register_autoload :ReferencesField, 'mail/fields/references_field'
-
2
register_autoload :ReplyToField, 'mail/fields/reply_to_field'
-
2
register_autoload :ResentBccField, 'mail/fields/resent_bcc_field'
-
2
register_autoload :ResentCcField, 'mail/fields/resent_cc_field'
-
2
register_autoload :ResentDateField, 'mail/fields/resent_date_field'
-
2
register_autoload :ResentFromField, 'mail/fields/resent_from_field'
-
2
register_autoload :ResentMessageIdField, 'mail/fields/resent_message_id_field'
-
2
register_autoload :ResentSenderField, 'mail/fields/resent_sender_field'
-
2
register_autoload :ResentToField, 'mail/fields/resent_to_field'
-
2
register_autoload :ReturnPathField, 'mail/fields/return_path_field'
-
2
register_autoload :SenderField, 'mail/fields/sender_field'
-
2
register_autoload :SubjectField, 'mail/fields/subject_field'
-
2
register_autoload :ToField, 'mail/fields/to_field'
-
end
-
# encoding: utf-8
-
#
-
# = Blind Carbon Copy Field
-
#
-
# The Bcc field inherits from StructuredField and handles the Bcc: header
-
# field in the email.
-
#
-
# Sending bcc to a mail message will instantiate a Mail::Field object that
-
# has a BccField as its field type. This includes all Mail::CommonAddress
-
# module instance metods.
-
#
-
# Only one Bcc field can appear in a header, though it can have multiple
-
# addresses and groups of addresses.
-
#
-
# == Examples:
-
#
-
# mail = Mail.new
-
# mail.bcc = 'Mikel Lindsaar <mikel@test.lindsaar.net>, ada@test.lindsaar.net'
-
# mail.bcc #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
-
# mail[:bcc] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::BccField:0x180e1c4
-
# mail['bcc'] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::BccField:0x180e1c4
-
# mail['Bcc'] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::BccField:0x180e1c4
-
#
-
# mail[:bcc].encoded #=> '' # Bcc field does not get output into an email
-
# mail[:bcc].decoded #=> 'Mikel Lindsaar <mikel@test.lindsaar.net>, ada@test.lindsaar.net'
-
# mail[:bcc].addresses #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
-
# mail[:bcc].formatted #=> ['Mikel Lindsaar <mikel@test.lindsaar.net>', 'ada@test.lindsaar.net']
-
#
-
2
require 'mail/fields/common/common_address'
-
-
2
module Mail
-
2
class BccField < StructuredField
-
-
2
include Mail::CommonAddress
-
-
2
FIELD_NAME = 'bcc'
-
2
CAPITALIZED_FIELD = 'Bcc'
-
-
2
def initialize(value = '', charset = 'utf-8')
-
@charset = charset
-
super(CAPITALIZED_FIELD, strip_field(FIELD_NAME, value), charset)
-
self.parse
-
self
-
end
-
-
# Bcc field should never be :encoded
-
2
def encoded
-
''
-
end
-
-
2
def decoded
-
do_decode
-
end
-
-
end
-
end
-
# encoding: utf-8
-
#
-
# = Carbon Copy Field
-
#
-
# The Cc field inherits from StructuredField and handles the Cc: header
-
# field in the email.
-
#
-
# Sending cc to a mail message will instantiate a Mail::Field object that
-
# has a CcField as its field type. This includes all Mail::CommonAddress
-
# module instance metods.
-
#
-
# Only one Cc field can appear in a header, though it can have multiple
-
# addresses and groups of addresses.
-
#
-
# == Examples:
-
#
-
# mail = Mail.new
-
# mail.cc = 'Mikel Lindsaar <mikel@test.lindsaar.net>, ada@test.lindsaar.net'
-
# mail.cc #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
-
# mail[:cc] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::CcField:0x180e1c4
-
# mail['cc'] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::CcField:0x180e1c4
-
# mail['Cc'] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::CcField:0x180e1c4
-
#
-
# mail[:cc].encoded #=> 'Cc: Mikel Lindsaar <mikel@test.lindsaar.net>, ada@test.lindsaar.net\r\n'
-
# mail[:cc].decoded #=> 'Mikel Lindsaar <mikel@test.lindsaar.net>, ada@test.lindsaar.net'
-
# mail[:cc].addresses #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
-
# mail[:cc].formatted #=> ['Mikel Lindsaar <mikel@test.lindsaar.net>', 'ada@test.lindsaar.net']
-
#
-
2
require 'mail/fields/common/common_address'
-
-
2
module Mail
-
2
class CcField < StructuredField
-
-
2
include Mail::CommonAddress
-
-
2
FIELD_NAME = 'cc'
-
2
CAPITALIZED_FIELD = 'Cc'
-
-
2
def initialize(value = nil, charset = 'utf-8')
-
self.charset = charset
-
super(CAPITALIZED_FIELD, strip_field(FIELD_NAME, value), charset)
-
self.parse
-
self
-
end
-
-
2
def encoded
-
do_encode(CAPITALIZED_FIELD)
-
end
-
-
2
def decoded
-
do_decode
-
end
-
-
end
-
end
-
# encoding: utf-8
-
#
-
# = Comments Field
-
#
-
# The Comments field inherits from UnstructuredField and handles the Comments:
-
# header field in the email.
-
#
-
# Sending comments to a mail message will instantiate a Mail::Field object that
-
# has a CommentsField as its field type.
-
#
-
# An email header can have as many comments fields as it wants. There is no upper
-
# limit, the comments field is also optional (that is, no comment is needed)
-
#
-
# == Examples:
-
#
-
# mail = Mail.new
-
# mail.comments = 'This is a comment'
-
# mail.comments #=> 'This is a comment'
-
# mail[:comments] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::CommentsField:0x180e1c4
-
# mail['comments'] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::CommentsField:0x180e1c4
-
# mail['comments'] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::CommentsField:0x180e1c4
-
#
-
# mail.comments = "This is another comment"
-
# mail[:comments].map { |c| c.to_s }
-
# #=> ['This is a comment', "This is another comment"]
-
#
-
2
module Mail
-
2
class CommentsField < UnstructuredField
-
-
2
FIELD_NAME = 'comments'
-
2
CAPITALIZED_FIELD = 'Comments'
-
-
2
def initialize(value = nil, charset = 'utf-8')
-
@charset = charset
-
super(CAPITALIZED_FIELD, strip_field(FIELD_NAME, value))
-
self.parse
-
self
-
end
-
-
end
-
end
-
2
module Mail
-
-
2
class AddressContainer < Array
-
-
2
def initialize(field, list = [])
-
@field = field
-
super(list)
-
end
-
-
2
def << (address)
-
@field << address
-
end
-
-
end
-
-
end
-
# encoding: utf-8
-
2
require 'mail/fields/common/address_container'
-
-
2
module Mail
-
2
module CommonAddress # :nodoc:
-
-
2
def parse(val = value)
-
unless val.blank?
-
@address_list = AddressList.new(encode_if_needed(val))
-
else
-
nil
-
end
-
end
-
-
2
def charset
-
@charset
-
end
-
-
2
def encode_if_needed(val)
-
Encodings.address_encode(val, charset)
-
end
-
-
# Allows you to iterate through each address object in the address_list
-
2
def each
-
address_list.addresses.each do |address|
-
yield(address)
-
end
-
end
-
-
# Returns the address string of all the addresses in the address list
-
2
def addresses
-
list = address_list.addresses.map { |a| a.address }
-
Mail::AddressContainer.new(self, list)
-
end
-
-
# Returns the formatted string of all the addresses in the address list
-
2
def formatted
-
list = address_list.addresses.map { |a| a.format }
-
Mail::AddressContainer.new(self, list)
-
end
-
-
# Returns the display name of all the addresses in the address list
-
2
def display_names
-
list = address_list.addresses.map { |a| a.display_name }
-
Mail::AddressContainer.new(self, list)
-
end
-
-
# Returns the actual address objects in the address list
-
2
def addrs
-
list = address_list.addresses
-
Mail::AddressContainer.new(self, list)
-
end
-
-
# Returns a hash of group name => address strings for the address list
-
2
def groups
-
address_list.addresses_grouped_by_group
-
end
-
-
# Returns the addresses that are part of groups
-
2
def group_addresses
-
decoded_group_addresses
-
end
-
-
# Returns a list of decoded group addresses
-
2
def decoded_group_addresses
-
groups.map { |k,v| v.map { |a| a.decoded } }.flatten
-
end
-
-
# Returns a list of encoded group addresses
-
2
def encoded_group_addresses
-
groups.map { |k,v| v.map { |a| a.encoded } }.flatten
-
end
-
-
# Returns the name of all the groups in a string
-
2
def group_names # :nodoc:
-
address_list.group_names
-
end
-
-
2
def default
-
addresses
-
end
-
-
2
def <<(val)
-
case
-
when val.nil?
-
raise ArgumentError, "Need to pass an address to <<"
-
when val.blank?
-
parse(encoded)
-
else
-
self.value = [self.value, val].reject {|a| a.blank? }.join(", ")
-
end
-
end
-
-
2
def value=(val)
-
super
-
parse(self.value)
-
end
-
-
2
private
-
-
2
def do_encode(field_name)
-
return '' if value.blank?
-
address_array = address_list.addresses.reject { |a| encoded_group_addresses.include?(a.encoded) }.compact.map { |a| a.encoded }
-
address_text = address_array.join(", \r\n\s")
-
group_array = groups.map { |k,v| "#{k}: #{v.map { |a| a.encoded }.join(", \r\n\s")};" }
-
group_text = group_array.join(" \r\n\s")
-
return_array = [address_text, group_text].reject { |a| a.blank? }
-
"#{field_name}: #{return_array.join(", \r\n\s")}\r\n"
-
end
-
-
2
def do_decode
-
return nil if value.blank?
-
address_array = address_list.addresses.reject { |a| decoded_group_addresses.include?(a.decoded) }.map { |a| a.decoded }
-
address_text = address_array.join(", ")
-
group_array = groups.map { |k,v| "#{k}: #{v.map { |a| a.decoded }.join(", ")};" }
-
group_text = group_array.join(" ")
-
return_array = [address_text, group_text].reject { |a| a.blank? }
-
return_array.join(", ")
-
end
-
-
2
def address_list # :nodoc:
-
@address_list ||= AddressList.new(value)
-
end
-
-
2
def get_group_addresses(group_list)
-
if group_list.respond_to?(:addresses)
-
group_list.addresses.map do |address|
-
Mail::Address.new(address)
-
end
-
else
-
[]
-
end
-
end
-
end
-
end
-
# encoding: utf-8
-
2
module Mail
-
2
module CommonDate # :nodoc:
-
# Returns a date time object of the parsed date
-
2
def date_time
-
::DateTime.parse("#{element.date_string} #{element.time_string}")
-
end
-
-
2
def default
-
date_time
-
end
-
-
2
def parse(val = value)
-
unless val.blank?
-
@element = Mail::DateTimeElement.new(val)
-
else
-
nil
-
end
-
end
-
-
2
private
-
-
2
def do_encode(field_name)
-
"#{field_name}: #{value}\r\n"
-
end
-
-
2
def do_decode
-
"#{value}"
-
end
-
-
2
def element
-
@element ||= Mail::DateTimeElement.new(value)
-
end
-
end
-
end
-
# encoding: utf-8
-
2
module Mail
-
2
module CommonField # :nodoc:
-
2
include Mail::Constants
-
-
2
def name=(value)
-
@name = value
-
end
-
-
2
def name
-
@name ||= nil
-
end
-
-
2
def value=(value)
-
@length = nil
-
@tree = nil
-
@element = nil
-
@value = value
-
end
-
-
2
def value
-
@value
-
end
-
-
2
def to_s
-
decoded.to_s
-
end
-
-
2
def default
-
decoded
-
end
-
-
2
def field_length
-
@length ||= "#{name}: #{encode(decoded)}".length
-
end
-
-
2
def responsible_for?( val )
-
name.to_s.casecmp(val.to_s) == 0
-
end
-
-
2
private
-
-
2
def strip_field(field_name, value)
-
if value.is_a?(Array)
-
value
-
else
-
value.to_s.sub(/#{field_name}:\s+/i, EMPTY)
-
end
-
end
-
-
2
FILENAME_RE = /\b(filename|name)=([^;"\r\n]+\s[^;"\r\n]+)/
-
2
def ensure_filename_quoted(value)
-
if value.is_a?(String)
-
value.sub! FILENAME_RE, '\1="\2"'
-
end
-
end
-
end
-
end
-
# encoding: utf-8
-
2
module Mail
-
2
module CommonMessageId # :nodoc:
-
2
def element
-
@element ||= Mail::MessageIdsElement.new(value) unless value.blank?
-
end
-
-
2
def parse(val = value)
-
unless val.blank?
-
@element = Mail::MessageIdsElement.new(val)
-
else
-
nil
-
end
-
end
-
-
2
def message_id
-
element.message_id if element
-
end
-
-
2
def message_ids
-
element.message_ids if element
-
end
-
-
2
def default
-
return nil unless message_ids
-
if message_ids.length == 1
-
message_ids[0]
-
else
-
message_ids
-
end
-
end
-
-
2
private
-
-
2
def do_encode(field_name)
-
%Q{#{field_name}: #{formated_message_ids("\r\n ")}\r\n}
-
end
-
-
2
def do_decode
-
formated_message_ids(' ')
-
end
-
-
2
def formated_message_ids(join)
-
message_ids.map{ |m| "<#{m}>" }.join(join) if message_ids
-
end
-
-
end
-
end
-
# encoding: utf-8
-
2
module Mail
-
-
# ParameterHash is an intelligent Hash that allows you to add
-
# parameter values including the MIME extension paramaters that
-
# have the name*0="blah", name*1="bleh" keys, and will just return
-
# a single key called name="blahbleh" and do any required un-encoding
-
# to make that happen
-
# Parameters are defined in RFC2045, split keys are in RFC2231
-
-
2
class ParameterHash < IndifferentHash
-
-
2
include Mail::Utilities
-
-
2
def [](key_name)
-
key_pattern = Regexp.escape(key_name.to_s)
-
pairs = []
-
exact = nil
-
each do |k,v|
-
if k =~ /^#{key_pattern}(\*|$)/i
-
if $1 == ASTERISK
-
pairs << [k, v]
-
else
-
exact = k
-
end
-
end
-
end
-
if pairs.empty? # Just dealing with a single value pair
-
super(exact || key_name)
-
else # Dealing with a multiple value pair or a single encoded value pair
-
string = pairs.sort { |a,b| a.first.to_s <=> b.first.to_s }.map { |v| v.last }.join('')
-
if mt = string.match(/([\w\-]+)'(\w\w)'(.*)/)
-
string = mt[3]
-
encoding = mt[1]
-
else
-
encoding = nil
-
end
-
Mail::Encodings.param_decode(string, encoding)
-
end
-
end
-
-
2
def encoded
-
map.sort_by { |a| a.first.to_s }.map! do |key_name, value|
-
unless value.ascii_only?
-
value = Mail::Encodings.param_encode(value)
-
key_name = "#{key_name}*"
-
end
-
%Q{#{key_name}=#{quote_token(value)}}
-
end.join(";\r\n\s")
-
end
-
-
2
def decoded
-
map.sort_by { |a| a.first.to_s }.map! do |key_name, value|
-
%Q{#{key_name}=#{quote_token(value)}}
-
end.join("; ")
-
end
-
end
-
end
-
# encoding: utf-8
-
#
-
#
-
#
-
2
module Mail
-
2
class ContentDescriptionField < UnstructuredField
-
-
2
FIELD_NAME = 'content-description'
-
2
CAPITALIZED_FIELD = 'Content-Description'
-
-
2
def initialize(value = nil, charset = 'utf-8')
-
self.charset = charset
-
super(CAPITALIZED_FIELD, strip_field(FIELD_NAME, value), charset)
-
self.parse
-
self
-
end
-
-
end
-
end
-
# encoding: utf-8
-
2
require 'mail/fields/common/parameter_hash'
-
-
2
module Mail
-
2
class ContentDispositionField < StructuredField
-
-
2
FIELD_NAME = 'content-disposition'
-
2
CAPITALIZED_FIELD = 'Content-Disposition'
-
-
2
def initialize(value = nil, charset = 'utf-8')
-
self.charset = charset
-
ensure_filename_quoted(value)
-
super(CAPITALIZED_FIELD, strip_field(FIELD_NAME, value), charset)
-
self.parse
-
self
-
end
-
-
2
def parse(val = value)
-
unless val.blank?
-
@element = Mail::ContentDispositionElement.new(val)
-
end
-
end
-
-
2
def element
-
@element ||= Mail::ContentDispositionElement.new(value)
-
end
-
-
2
def disposition_type
-
element.disposition_type
-
end
-
-
2
def parameters
-
@parameters = ParameterHash.new
-
element.parameters.each { |p| @parameters.merge!(p) }
-
@parameters
-
end
-
-
2
def filename
-
case
-
when !parameters['filename'].blank?
-
@filename = parameters['filename']
-
when !parameters['name'].blank?
-
@filename = parameters['name']
-
else
-
@filename = nil
-
end
-
@filename
-
end
-
-
# TODO: Fix this up
-
2
def encoded
-
if parameters.length > 0
-
p = ";\r\n\s#{parameters.encoded}\r\n"
-
else
-
p = "\r\n"
-
end
-
"#{CAPITALIZED_FIELD}: #{disposition_type}" + p
-
end
-
-
2
def decoded
-
if parameters.length > 0
-
p = "; #{parameters.decoded}"
-
else
-
p = ""
-
end
-
"#{disposition_type}" + p
-
end
-
-
end
-
end
-
# encoding: utf-8
-
#
-
#
-
#
-
2
module Mail
-
2
class ContentIdField < StructuredField
-
-
2
FIELD_NAME = 'content-id'
-
2
CAPITALIZED_FIELD = "Content-ID"
-
-
2
def initialize(value = nil, charset = 'utf-8')
-
self.charset = charset
-
@uniq = 1
-
if value.blank?
-
value = generate_content_id
-
else
-
value = strip_field(FIELD_NAME, value)
-
end
-
super(CAPITALIZED_FIELD, strip_field(FIELD_NAME, value), charset)
-
self.parse
-
self
-
end
-
-
2
def parse(val = value)
-
unless val.blank?
-
@element = Mail::MessageIdsElement.new(val)
-
end
-
end
-
-
2
def element
-
@element ||= Mail::MessageIdsElement.new(value)
-
end
-
-
2
def name
-
'Content-ID'
-
end
-
-
2
def content_id
-
element.message_id
-
end
-
-
2
def to_s
-
"<#{content_id}>"
-
end
-
-
# TODO: Fix this up
-
2
def encoded
-
"#{CAPITALIZED_FIELD}: #{to_s}\r\n"
-
end
-
-
2
def decoded
-
"#{to_s}"
-
end
-
-
2
private
-
-
2
def generate_content_id
-
"<#{Mail.random_tag}@#{::Socket.gethostname}.mail>"
-
end
-
-
end
-
end
-
# encoding: utf-8
-
#
-
#
-
#
-
2
module Mail
-
2
class ContentLocationField < StructuredField
-
-
2
FIELD_NAME = 'content-location'
-
2
CAPITALIZED_FIELD = 'Content-Location'
-
-
2
def initialize(value = nil, charset = 'utf-8')
-
self.charset = charset
-
super(CAPITALIZED_FIELD, strip_field(FIELD_NAME, value), charset)
-
self.parse
-
self
-
end
-
-
2
def parse(val = value)
-
unless val.blank?
-
@element = Mail::ContentLocationElement.new(val)
-
end
-
end
-
-
2
def element
-
@element ||= Mail::ContentLocationElement.new(value)
-
end
-
-
2
def location
-
element.location
-
end
-
-
# TODO: Fix this up
-
2
def encoded
-
"#{CAPITALIZED_FIELD}: #{location}\r\n"
-
end
-
-
2
def decoded
-
location
-
end
-
-
end
-
end
-
# encoding: utf-8
-
#
-
#
-
#
-
2
module Mail
-
2
class ContentTransferEncodingField < StructuredField
-
-
2
FIELD_NAME = 'content-transfer-encoding'
-
2
CAPITALIZED_FIELD = 'Content-Transfer-Encoding'
-
-
2
def initialize(value = nil, charset = 'utf-8')
-
self.charset = charset
-
value = '7bit' if value.to_s =~ /7-?bits?/i
-
value = '8bit' if value.to_s =~ /8-?bits?/i
-
super(CAPITALIZED_FIELD, strip_field(FIELD_NAME, value), charset)
-
self.parse
-
self
-
end
-
-
2
def parse(val = value)
-
unless val.blank?
-
@element = Mail::ContentTransferEncodingElement.new(val)
-
end
-
end
-
-
2
def element
-
@element ||= Mail::ContentTransferEncodingElement.new(value)
-
end
-
-
2
def encoding
-
element.encoding
-
end
-
-
# TODO: Fix this up
-
2
def encoded
-
"#{CAPITALIZED_FIELD}: #{encoding}\r\n"
-
end
-
-
2
def decoded
-
encoding
-
end
-
-
end
-
end
-
# encoding: utf-8
-
2
require 'mail/fields/common/parameter_hash'
-
-
2
module Mail
-
2
class ContentTypeField < StructuredField
-
-
2
FIELD_NAME = 'content-type'
-
2
CAPITALIZED_FIELD = 'Content-Type'
-
-
2
def initialize(value = nil, charset = 'utf-8')
-
self.charset = charset
-
if value.class == Array
-
@main_type = value[0]
-
@sub_type = value[1]
-
@parameters = ParameterHash.new.merge!(value.last)
-
else
-
@main_type = nil
-
@sub_type = nil
-
@parameters = nil
-
value = strip_field(FIELD_NAME, value)
-
end
-
ensure_filename_quoted(value)
-
super(CAPITALIZED_FIELD, value, charset)
-
self.parse
-
self
-
end
-
-
2
def parse(val = value)
-
unless val.blank?
-
self.value = val
-
@element = nil
-
element
-
end
-
end
-
-
2
def element
-
begin
-
@element ||= Mail::ContentTypeElement.new(value)
-
rescue
-
attempt_to_clean
-
end
-
end
-
-
2
def attempt_to_clean
-
# Sanitize the value, handle special cases
-
@element ||= Mail::ContentTypeElement.new(sanatize(value))
-
rescue
-
# All else fails, just get the MIME media type
-
@element ||= Mail::ContentTypeElement.new(get_mime_type(value))
-
end
-
-
2
def main_type
-
@main_type ||= element.main_type
-
end
-
-
2
def sub_type
-
@sub_type ||= element.sub_type
-
end
-
-
2
def string
-
"#{main_type}/#{sub_type}"
-
end
-
-
2
def default
-
decoded
-
end
-
-
2
alias :content_type :string
-
-
2
def parameters
-
unless @parameters
-
@parameters = ParameterHash.new
-
element.parameters.each { |p| @parameters.merge!(p) }
-
end
-
@parameters
-
end
-
-
2
def ContentTypeField.with_boundary(type)
-
new("#{type}; boundary=#{generate_boundary}")
-
end
-
-
2
def ContentTypeField.generate_boundary
-
"--==_mimepart_#{Mail.random_tag}"
-
end
-
-
2
def value
-
if @value.class == Array
-
"#{@main_type}/#{@sub_type}; #{stringify(parameters)}"
-
else
-
@value
-
end
-
end
-
-
2
def stringify(params)
-
params.map { |k,v| "#{k}=#{Encodings.param_encode(v)}" }.join("; ")
-
end
-
-
2
def filename
-
case
-
when parameters['filename']
-
@filename = parameters['filename']
-
when parameters['name']
-
@filename = parameters['name']
-
else
-
@filename = nil
-
end
-
@filename
-
end
-
-
# TODO: Fix this up
-
2
def encoded
-
if parameters.length > 0
-
p = ";\r\n\s#{parameters.encoded}"
-
else
-
p = ""
-
end
-
"#{CAPITALIZED_FIELD}: #{content_type}#{p}\r\n"
-
end
-
-
2
def decoded
-
if parameters.length > 0
-
p = "; #{parameters.decoded}"
-
else
-
p = ""
-
end
-
"#{content_type}" + p
-
end
-
-
2
private
-
-
2
def method_missing(name, *args, &block)
-
if name.to_s =~ /(\w+)=/
-
self.parameters[$1] = args.first
-
@value = "#{content_type}; #{stringify(parameters)}"
-
else
-
super
-
end
-
end
-
-
# Various special cases from random emails found that I am not going to change
-
# the parser for
-
2
def sanatize( val )
-
-
# TODO: check if there are cases where whitespace is not a separator
-
val = val.
-
gsub(/\s*=\s*/,'='). # remove whitespaces around equal sign
-
tr(' ',';').
-
squeeze(';').
-
gsub(';', '; '). #use '; ' as a separator (or EOL)
-
gsub(/;\s*$/,'') #remove trailing to keep examples below
-
-
if val =~ /(boundary=(\S*))/i
-
val = "#{$`.downcase}boundary=#{$2}#{$'.downcase}"
-
else
-
val.downcase!
-
end
-
-
case
-
when val.chomp =~ /^\s*([\w\-]+)\/([\w\-]+)\s*;;+(.*)$/i
-
# Handles 'text/plain;; format="flowed"' (double semi colon)
-
"#{$1}/#{$2}; #{$3}"
-
when val.chomp =~ /^\s*([\w\-]+)\/([\w\-]+)\s*;\s?(ISO[\w\-]+)$/i
-
# Microsoft helper:
-
# Handles 'type/subtype;ISO-8559-1'
-
"#{$1}/#{$2}; charset=#{quote_atom($3)}"
-
when val.chomp =~ /^text;?$/i
-
# Handles 'text;' and 'text'
-
"text/plain;"
-
when val.chomp =~ /^(\w+);\s(.*)$/i
-
# Handles 'text; <parameters>'
-
"text/plain; #{$2}"
-
when val =~ /([\w\-]+\/[\w\-]+);\scharset="charset="(\w+)""/i
-
# Handles text/html; charset="charset="GB2312""
-
"#{$1}; charset=#{quote_atom($2)}"
-
when val =~ /([\w\-]+\/[\w\-]+);\s+(.*)/i
-
type = $1
-
# Handles misquoted param values
-
# e.g: application/octet-stream; name=archiveshelp1[1].htm
-
# and: audio/x-midi;\r\n\sname=Part .exe
-
params = $2.to_s.split(/\s+/)
-
params = params.map { |i| i.to_s.chomp.strip }
-
params = params.map { |i| i.split(/\s*\=\s*/) }
-
params = params.map { |i| "#{i[0]}=#{dquote(i[1].to_s.gsub(/;$/,""))}" }.join('; ')
-
"#{type}; #{params}"
-
when val =~ /^\s*$/
-
'text/plain'
-
else
-
''
-
end
-
end
-
-
2
def get_mime_type( val )
-
case
-
when val =~ /^([\w\-]+)\/([\w\-]+);.+$/i
-
"#{$1}/#{$2}"
-
else
-
'text/plain'
-
end
-
end
-
end
-
end
-
# encoding: utf-8
-
#
-
# = Date Field
-
#
-
# The Date field inherits from StructuredField and handles the Date: header
-
# field in the email.
-
#
-
# Sending date to a mail message will instantiate a Mail::Field object that
-
# has a DateField as its field type. This includes all Mail::CommonAddress
-
# module instance methods.
-
#
-
# There must be excatly one Date field in an RFC2822 email.
-
#
-
# == Examples:
-
#
-
# mail = Mail.new
-
# mail.date = 'Mon, 24 Nov 1997 14:22:01 -0800'
-
# mail.date #=> #<DateTime: 211747170121/86400,-1/3,2299161>
-
# mail.date.to_s #=> 'Mon, 24 Nov 1997 14:22:01 -0800'
-
# mail[:date] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::DateField:0x180e1c4
-
# mail['date'] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::DateField:0x180e1c4
-
# mail['Date'] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::DateField:0x180e1c4
-
#
-
2
require 'mail/fields/common/common_date'
-
-
2
module Mail
-
2
class DateField < StructuredField
-
-
2
include Mail::CommonDate
-
-
2
FIELD_NAME = 'date'
-
2
CAPITALIZED_FIELD = "Date"
-
-
2
def initialize(value = nil, charset = 'utf-8')
-
self.charset = charset
-
if value.blank?
-
value = ::DateTime.now.strftime('%a, %d %b %Y %H:%M:%S %z')
-
else
-
value = strip_field(FIELD_NAME, value)
-
value.to_s.gsub!(/\(.*?\)/, '')
-
value = ::DateTime.parse(value.to_s.squeeze(" ")).strftime('%a, %d %b %Y %H:%M:%S %z')
-
end
-
super(CAPITALIZED_FIELD, value, charset)
-
rescue ArgumentError => e
-
raise e unless "invalid date"==e.message
-
end
-
-
2
def encoded
-
do_encode(CAPITALIZED_FIELD)
-
end
-
-
2
def decoded
-
do_decode
-
end
-
-
end
-
end
-
# encoding: utf-8
-
#
-
# = From Field
-
#
-
# The From field inherits from StructuredField and handles the From: header
-
# field in the email.
-
#
-
# Sending from to a mail message will instantiate a Mail::Field object that
-
# has a FromField as its field type. This includes all Mail::CommonAddress
-
# module instance metods.
-
#
-
# Only one From field can appear in a header, though it can have multiple
-
# addresses and groups of addresses.
-
#
-
# == Examples:
-
#
-
# mail = Mail.new
-
# mail.from = 'Mikel Lindsaar <mikel@test.lindsaar.net>, ada@test.lindsaar.net'
-
# mail.from #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
-
# mail[:from] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::FromField:0x180e1c4
-
# mail['from'] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::FromField:0x180e1c4
-
# mail['From'] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::FromField:0x180e1c4
-
#
-
# mail[:from].encoded #=> 'from: Mikel Lindsaar <mikel@test.lindsaar.net>, ada@test.lindsaar.net\r\n'
-
# mail[:from].decoded #=> 'Mikel Lindsaar <mikel@test.lindsaar.net>, ada@test.lindsaar.net'
-
# mail[:from].addresses #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
-
# mail[:from].formatted #=> ['Mikel Lindsaar <mikel@test.lindsaar.net>', 'ada@test.lindsaar.net']
-
#
-
2
require 'mail/fields/common/common_address'
-
-
2
module Mail
-
2
class FromField < StructuredField
-
-
2
include Mail::CommonAddress
-
-
2
FIELD_NAME = 'from'
-
2
CAPITALIZED_FIELD = 'From'
-
-
2
def initialize(value = nil, charset = 'utf-8')
-
self.charset = charset
-
super(CAPITALIZED_FIELD, strip_field(FIELD_NAME, value), charset)
-
self.parse
-
self
-
end
-
-
2
def encoded
-
do_encode(CAPITALIZED_FIELD)
-
end
-
-
2
def decoded
-
do_decode
-
end
-
-
end
-
end
-
# encoding: utf-8
-
#
-
# = In-Reply-To Field
-
#
-
# The In-Reply-To field inherits from StructuredField and handles the
-
# In-Reply-To: header field in the email.
-
#
-
# Sending in_reply_to to a mail message will instantiate a Mail::Field object that
-
# has a InReplyToField as its field type. This includes all Mail::CommonMessageId
-
# module instance metods.
-
#
-
# Note that, the #message_ids method will return an array of message IDs without the
-
# enclosing angle brackets which per RFC are not syntactically part of the message id.
-
#
-
# Only one InReplyTo field can appear in a header, though it can have multiple
-
# Message IDs.
-
#
-
# == Examples:
-
#
-
# mail = Mail.new
-
# mail.in_reply_to = '<F6E2D0B4-CC35-4A91-BA4C-C7C712B10C13@test.me.dom>'
-
# mail.in_reply_to #=> '<F6E2D0B4-CC35-4A91-BA4C-C7C712B10C13@test.me.dom>'
-
# mail[:in_reply_to] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::InReplyToField:0x180e1c4
-
# mail['in_reply_to'] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::InReplyToField:0x180e1c4
-
# mail['In-Reply-To'] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::InReplyToField:0x180e1c4
-
#
-
# mail[:in_reply_to].message_ids #=> ['F6E2D0B4-CC35-4A91-BA4C-C7C712B10C13@test.me.dom']
-
#
-
2
require 'mail/fields/common/common_message_id'
-
-
2
module Mail
-
2
class InReplyToField < StructuredField
-
-
2
include Mail::CommonMessageId
-
-
2
FIELD_NAME = 'in-reply-to'
-
2
CAPITALIZED_FIELD = 'In-Reply-To'
-
-
2
def initialize(value = nil, charset = 'utf-8')
-
self.charset = charset
-
value = value.join("\r\n\s") if value.is_a?(Array)
-
super(CAPITALIZED_FIELD, strip_field(FIELD_NAME, value), charset)
-
self.parse
-
self
-
end
-
-
2
def encoded
-
do_encode(CAPITALIZED_FIELD)
-
end
-
-
2
def decoded
-
do_decode
-
end
-
-
end
-
end
-
# encoding: utf-8
-
#
-
# keywords = "Keywords:" phrase *("," phrase) CRLF
-
2
module Mail
-
2
class KeywordsField < StructuredField
-
-
2
FIELD_NAME = 'keywords'
-
2
CAPITALIZED_FIELD = 'Keywords'
-
-
2
def initialize(value = nil, charset = 'utf-8')
-
self.charset = charset
-
super(CAPITALIZED_FIELD, strip_field(FIELD_NAME, value), charset)
-
self.parse
-
self
-
end
-
-
2
def parse(val = value)
-
unless val.blank?
-
@phrase_list ||= PhraseList.new(value)
-
end
-
end
-
-
2
def phrase_list
-
@phrase_list ||= PhraseList.new(value)
-
end
-
-
2
def keywords
-
phrase_list.phrases
-
end
-
-
2
def encoded
-
"#{CAPITALIZED_FIELD}: #{keywords.join(",\r\n ")}\r\n"
-
end
-
-
2
def decoded
-
keywords.join(', ')
-
end
-
-
2
def default
-
keywords
-
end
-
-
end
-
end
-
# encoding: utf-8
-
#
-
# = Message-ID Field
-
#
-
# The Message-ID field inherits from StructuredField and handles the
-
# Message-ID: header field in the email.
-
#
-
# Sending message_id to a mail message will instantiate a Mail::Field object that
-
# has a MessageIdField as its field type. This includes all Mail::CommonMessageId
-
# module instance metods.
-
#
-
# Only one MessageId field can appear in a header, and syntactically it can only have
-
# one Message ID. The message_ids method call has been left in however as it will only
-
# return the one message id, ie, an array of length 1.
-
#
-
# Note that, the #message_ids method will return an array of message IDs without the
-
# enclosing angle brackets which per RFC are not syntactically part of the message id.
-
#
-
# == Examples:
-
#
-
# mail = Mail.new
-
# mail.message_id = '<F6E2D0B4-CC35-4A91-BA4C-C7C712B10C13@test.me.dom>'
-
# mail.message_id #=> '<F6E2D0B4-CC35-4A91-BA4C-C7C712B10C13@test.me.dom>'
-
# mail[:message_id] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::MessageIdField:0x180e1c4
-
# mail['message_id'] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::MessageIdField:0x180e1c4
-
# mail['Message-ID'] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::MessageIdField:0x180e1c4
-
#
-
# mail[:message_id].message_id #=> 'F6E2D0B4-CC35-4A91-BA4C-C7C712B10C13@test.me.dom'
-
# mail[:message_id].message_ids #=> ['F6E2D0B4-CC35-4A91-BA4C-C7C712B10C13@test.me.dom']
-
#
-
2
require 'mail/fields/common/common_message_id'
-
-
2
module Mail
-
2
class MessageIdField < StructuredField
-
-
2
include Mail::CommonMessageId
-
-
2
FIELD_NAME = 'message-id'
-
2
CAPITALIZED_FIELD = 'Message-ID'
-
-
2
def initialize(value = nil, charset = 'utf-8')
-
self.charset = charset
-
@uniq = 1
-
if value.blank?
-
self.name = CAPITALIZED_FIELD
-
self.value = generate_message_id
-
else
-
super(CAPITALIZED_FIELD, strip_field(FIELD_NAME, value), charset)
-
end
-
self.parse
-
self
-
-
end
-
-
2
def name
-
'Message-ID'
-
end
-
-
2
def message_ids
-
[message_id]
-
end
-
-
2
def to_s
-
"<#{message_id}>"
-
end
-
-
2
def encoded
-
do_encode(CAPITALIZED_FIELD)
-
end
-
-
2
def decoded
-
do_decode
-
end
-
-
2
private
-
-
2
def generate_message_id
-
"<#{Mail.random_tag}@#{::Socket.gethostname}.mail>"
-
end
-
-
end
-
end
-
# encoding: utf-8
-
#
-
#
-
#
-
2
module Mail
-
2
class MimeVersionField < StructuredField
-
-
2
FIELD_NAME = 'mime-version'
-
2
CAPITALIZED_FIELD = 'Mime-Version'
-
-
2
def initialize(value = nil, charset = 'utf-8')
-
self.charset = charset
-
if value.blank?
-
value = '1.0'
-
end
-
super(CAPITALIZED_FIELD, strip_field(FIELD_NAME, value), charset)
-
self.parse
-
self
-
-
end
-
-
2
def parse(val = value)
-
unless val.blank?
-
@element = Mail::MimeVersionElement.new(val)
-
end
-
end
-
-
2
def element
-
@element ||= Mail::MimeVersionElement.new(value)
-
end
-
-
2
def version
-
"#{element.major}.#{element.minor}"
-
end
-
-
2
def major
-
element.major.to_i
-
end
-
-
2
def minor
-
element.minor.to_i
-
end
-
-
2
def encoded
-
"#{CAPITALIZED_FIELD}: #{version}\r\n"
-
end
-
-
2
def decoded
-
version
-
end
-
-
end
-
end
-
# encoding: utf-8
-
#
-
# trace = [return]
-
# 1*received
-
#
-
# return = "Return-Path:" path CRLF
-
#
-
# path = ([CFWS] "<" ([CFWS] / addr-spec) ">" [CFWS]) /
-
# obs-path
-
#
-
# received = "Received:" name-val-list ";" date-time CRLF
-
#
-
# name-val-list = [CFWS] [name-val-pair *(CFWS name-val-pair)]
-
#
-
# name-val-pair = item-name CFWS item-value
-
#
-
# item-name = ALPHA *(["-"] (ALPHA / DIGIT))
-
#
-
# item-value = 1*angle-addr / addr-spec /
-
# atom / domain / msg-id
-
#
-
2
module Mail
-
2
class ReceivedField < StructuredField
-
-
2
FIELD_NAME = 'received'
-
2
CAPITALIZED_FIELD = 'Received'
-
-
2
def initialize(value = nil, charset = 'utf-8')
-
self.charset = charset
-
super(CAPITALIZED_FIELD, strip_field(FIELD_NAME, value), charset)
-
self.parse
-
self
-
-
end
-
-
2
def parse(val = value)
-
unless val.blank?
-
@element = Mail::ReceivedElement.new(val)
-
end
-
end
-
-
2
def element
-
@element ||= Mail::ReceivedElement.new(value)
-
end
-
-
2
def date_time
-
@datetime ||= ::DateTime.parse("#{element.date_time}")
-
end
-
-
2
def info
-
element.info
-
end
-
-
2
def formatted_date
-
date_time.strftime("%a, %d %b %Y %H:%M:%S ") + date_time.zone.delete(':')
-
end
-
-
2
def encoded
-
if value.blank?
-
"#{CAPITALIZED_FIELD}: \r\n"
-
else
-
"#{CAPITALIZED_FIELD}: #{info}; #{formatted_date}\r\n"
-
end
-
end
-
-
2
def decoded
-
if value.blank?
-
""
-
else
-
"#{info}; #{formatted_date}"
-
end
-
end
-
-
end
-
end
-
# encoding: utf-8
-
#
-
# = References Field
-
#
-
# The References field inherits references StructuredField and handles the References: header
-
# field in the email.
-
#
-
# Sending references to a mail message will instantiate a Mail::Field object that
-
# has a ReferencesField as its field type. This includes all Mail::CommonAddress
-
# module instance metods.
-
#
-
# Note that, the #message_ids method will return an array of message IDs without the
-
# enclosing angle brackets which per RFC are not syntactically part of the message id.
-
#
-
# Only one References field can appear in a header, though it can have multiple
-
# Message IDs.
-
#
-
# == Examples:
-
#
-
# mail = Mail.new
-
# mail.references = '<F6E2D0B4-CC35-4A91-BA4C-C7C712B10C13@test.me.dom>'
-
# mail.references #=> '<F6E2D0B4-CC35-4A91-BA4C-C7C712B10C13@test.me.dom>'
-
# mail[:references] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::ReferencesField:0x180e1c4
-
# mail['references'] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::ReferencesField:0x180e1c4
-
# mail['References'] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::ReferencesField:0x180e1c4
-
#
-
# mail[:references].message_ids #=> ['F6E2D0B4-CC35-4A91-BA4C-C7C712B10C13@test.me.dom']
-
#
-
2
require 'mail/fields/common/common_message_id'
-
-
2
module Mail
-
2
class ReferencesField < StructuredField
-
-
2
include CommonMessageId
-
-
2
FIELD_NAME = 'references'
-
2
CAPITALIZED_FIELD = 'References'
-
-
2
def initialize(value = nil, charset = 'utf-8')
-
self.charset = charset
-
value = value.join("\r\n\s") if value.is_a?(Array)
-
super(CAPITALIZED_FIELD, strip_field(FIELD_NAME, value), charset)
-
self.parse
-
self
-
end
-
-
2
def encoded
-
do_encode(CAPITALIZED_FIELD)
-
end
-
-
2
def decoded
-
do_decode
-
end
-
-
end
-
end
-
# encoding: utf-8
-
#
-
# = Reply-To Field
-
#
-
# The Reply-To field inherits reply-to StructuredField and handles the Reply-To: header
-
# field in the email.
-
#
-
# Sending reply_to to a mail message will instantiate a Mail::Field object that
-
# has a ReplyToField as its field type. This includes all Mail::CommonAddress
-
# module instance metods.
-
#
-
# Only one Reply-To field can appear in a header, though it can have multiple
-
# addresses and groups of addresses.
-
#
-
# == Examples:
-
#
-
# mail = Mail.new
-
# mail.reply_to = 'Mikel Lindsaar <mikel@test.lindsaar.net>, ada@test.lindsaar.net'
-
# mail.reply_to #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
-
# mail[:reply_to] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::ReplyToField:0x180e1c4
-
# mail['reply-to'] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::ReplyToField:0x180e1c4
-
# mail['Reply-To'] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::ReplyToField:0x180e1c4
-
#
-
# mail[:reply_to].encoded #=> 'Reply-To: Mikel Lindsaar <mikel@test.lindsaar.net>, ada@test.lindsaar.net\r\n'
-
# mail[:reply_to].decoded #=> 'Mikel Lindsaar <mikel@test.lindsaar.net>, ada@test.lindsaar.net'
-
# mail[:reply_to].addresses #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
-
# mail[:reply_to].formatted #=> ['Mikel Lindsaar <mikel@test.lindsaar.net>', 'ada@test.lindsaar.net']
-
#
-
2
require 'mail/fields/common/common_address'
-
-
2
module Mail
-
2
class ReplyToField < StructuredField
-
-
2
include Mail::CommonAddress
-
-
2
FIELD_NAME = 'reply-to'
-
2
CAPITALIZED_FIELD = 'Reply-To'
-
-
2
def initialize(value = nil, charset = 'utf-8')
-
self.charset = charset
-
super(CAPITALIZED_FIELD, strip_field(FIELD_NAME, value), charset)
-
self.parse
-
self
-
end
-
-
2
def encoded
-
do_encode(CAPITALIZED_FIELD)
-
end
-
-
2
def decoded
-
do_decode
-
end
-
-
end
-
end
-
# encoding: utf-8
-
#
-
# = Resent-Bcc Field
-
#
-
# The Resent-Bcc field inherits resent-bcc StructuredField and handles the
-
# Resent-Bcc: header field in the email.
-
#
-
# Sending resent_bcc to a mail message will instantiate a Mail::Field object that
-
# has a ResentBccField as its field type. This includes all Mail::CommonAddress
-
# module instance metods.
-
#
-
# Only one Resent-Bcc field can appear in a header, though it can have multiple
-
# addresses and groups of addresses.
-
#
-
# == Examples:
-
#
-
# mail = Mail.new
-
# mail.resent_bcc = 'Mikel Lindsaar <mikel@test.lindsaar.net>, ada@test.lindsaar.net'
-
# mail.resent_bcc #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
-
# mail[:resent_bcc] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::ResentBccField:0x180e1c4
-
# mail['resent-bcc'] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::ResentBccField:0x180e1c4
-
# mail['Resent-Bcc'] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::ResentBccField:0x180e1c4
-
#
-
# mail[:resent_bcc].encoded #=> 'Resent-Bcc: Mikel Lindsaar <mikel@test.lindsaar.net>, ada@test.lindsaar.net\r\n'
-
# mail[:resent_bcc].decoded #=> 'Mikel Lindsaar <mikel@test.lindsaar.net>, ada@test.lindsaar.net'
-
# mail[:resent_bcc].addresses #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
-
# mail[:resent_bcc].formatted #=> ['Mikel Lindsaar <mikel@test.lindsaar.net>', 'ada@test.lindsaar.net']
-
#
-
2
require 'mail/fields/common/common_address'
-
-
2
module Mail
-
2
class ResentBccField < StructuredField
-
-
2
include Mail::CommonAddress
-
-
2
FIELD_NAME = 'resent-bcc'
-
2
CAPITALIZED_FIELD = 'Resent-Bcc'
-
-
2
def initialize(value = nil, charset = 'utf-8')
-
self.charset = charset
-
super(CAPITALIZED_FIELD, strip_field(FIELD_NAME, value), charset)
-
self.parse
-
self
-
end
-
-
2
def encoded
-
do_encode(CAPITALIZED_FIELD)
-
end
-
-
2
def decoded
-
do_decode
-
end
-
-
end
-
end
-
# encoding: utf-8
-
#
-
# = Resent-Cc Field
-
#
-
# The Resent-Cc field inherits resent-cc StructuredField and handles the Resent-Cc: header
-
# field in the email.
-
#
-
# Sending resent_cc to a mail message will instantiate a Mail::Field object that
-
# has a ResentCcField as its field type. This includes all Mail::CommonAddress
-
# module instance metods.
-
#
-
# Only one Resent-Cc field can appear in a header, though it can have multiple
-
# addresses and groups of addresses.
-
#
-
# == Examples:
-
#
-
# mail = Mail.new
-
# mail.resent_cc = 'Mikel Lindsaar <mikel@test.lindsaar.net>, ada@test.lindsaar.net'
-
# mail.resent_cc #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
-
# mail[:resent_cc] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::ResentCcField:0x180e1c4
-
# mail['resent-cc'] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::ResentCcField:0x180e1c4
-
# mail['Resent-Cc'] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::ResentCcField:0x180e1c4
-
#
-
# mail[:resent_cc].encoded #=> 'Resent-Cc: Mikel Lindsaar <mikel@test.lindsaar.net>, ada@test.lindsaar.net\r\n'
-
# mail[:resent_cc].decoded #=> 'Mikel Lindsaar <mikel@test.lindsaar.net>, ada@test.lindsaar.net'
-
# mail[:resent_cc].addresses #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
-
# mail[:resent_cc].formatted #=> ['Mikel Lindsaar <mikel@test.lindsaar.net>', 'ada@test.lindsaar.net']
-
#
-
2
require 'mail/fields/common/common_address'
-
-
2
module Mail
-
2
class ResentCcField < StructuredField
-
-
2
include Mail::CommonAddress
-
-
2
FIELD_NAME = 'resent-cc'
-
2
CAPITALIZED_FIELD = 'Resent-Cc'
-
-
2
def initialize(value = nil, charset = 'utf-8')
-
self.charset = charset
-
super(CAPITALIZED_FIELD, strip_field(FIELD_NAME, value), charset)
-
self.parse
-
self
-
end
-
-
2
def encoded
-
do_encode(CAPITALIZED_FIELD)
-
end
-
-
2
def decoded
-
do_decode
-
end
-
-
end
-
end
-
# encoding: utf-8
-
#
-
# resent-date = "Resent-Date:" date-time CRLF
-
2
require 'mail/fields/common/common_date'
-
-
2
module Mail
-
2
class ResentDateField < StructuredField
-
-
2
include Mail::CommonDate
-
-
2
FIELD_NAME = 'resent-date'
-
2
CAPITALIZED_FIELD = 'Resent-Date'
-
-
2
def initialize(value = nil, charset = 'utf-8')
-
self.charset = charset
-
if value.blank?
-
value = ::DateTime.now.strftime('%a, %d %b %Y %H:%M:%S %z')
-
else
-
value = strip_field(FIELD_NAME, value)
-
value = ::DateTime.parse(value.to_s).strftime('%a, %d %b %Y %H:%M:%S %z')
-
end
-
super(CAPITALIZED_FIELD, value, charset)
-
self
-
end
-
-
2
def encoded
-
do_encode(CAPITALIZED_FIELD)
-
end
-
-
2
def decoded
-
do_decode
-
end
-
-
end
-
end
-
# encoding: utf-8
-
#
-
# = Resent-From Field
-
#
-
# The Resent-From field inherits resent-from StructuredField and handles the Resent-From: header
-
# field in the email.
-
#
-
# Sending resent_from to a mail message will instantiate a Mail::Field object that
-
# has a ResentFromField as its field type. This includes all Mail::CommonAddress
-
# module instance metods.
-
#
-
# Only one Resent-From field can appear in a header, though it can have multiple
-
# addresses and groups of addresses.
-
#
-
# == Examples:
-
#
-
# mail = Mail.new
-
# mail.resent_from = 'Mikel Lindsaar <mikel@test.lindsaar.net>, ada@test.lindsaar.net'
-
# mail.resent_from #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
-
# mail[:resent_from] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::ResentFromField:0x180e1c4
-
# mail['resent-from'] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::ResentFromField:0x180e1c4
-
# mail['Resent-From'] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::ResentFromField:0x180e1c4
-
#
-
# mail[:resent_from].encoded #=> 'Resent-From: Mikel Lindsaar <mikel@test.lindsaar.net>, ada@test.lindsaar.net\r\n'
-
# mail[:resent_from].decoded #=> 'Mikel Lindsaar <mikel@test.lindsaar.net>, ada@test.lindsaar.net'
-
# mail[:resent_from].addresses #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
-
# mail[:resent_from].formatted #=> ['Mikel Lindsaar <mikel@test.lindsaar.net>', 'ada@test.lindsaar.net']
-
#
-
2
require 'mail/fields/common/common_address'
-
-
2
module Mail
-
2
class ResentFromField < StructuredField
-
-
2
include Mail::CommonAddress
-
-
2
FIELD_NAME = 'resent-from'
-
2
CAPITALIZED_FIELD = 'Resent-From'
-
-
2
def initialize(value = nil, charset = 'utf-8')
-
self.charset = charset
-
super(CAPITALIZED_FIELD, strip_field(FIELD_NAME, value), charset)
-
self.parse
-
self
-
end
-
-
2
def encoded
-
do_encode(CAPITALIZED_FIELD)
-
end
-
-
2
def decoded
-
do_decode
-
end
-
-
end
-
end
-
# encoding: utf-8
-
#
-
# resent-msg-id = "Resent-Message-ID:" msg-id CRLF
-
2
require 'mail/fields/common/common_message_id'
-
-
2
module Mail
-
2
class ResentMessageIdField < StructuredField
-
-
2
include CommonMessageId
-
-
2
FIELD_NAME = 'resent-message-id'
-
2
CAPITALIZED_FIELD = 'Resent-Message-ID'
-
-
2
def initialize(value = nil, charset = 'utf-8')
-
self.charset = charset
-
super(CAPITALIZED_FIELD, strip_field(FIELD_NAME, value), charset)
-
self.parse
-
self
-
end
-
-
2
def name
-
'Resent-Message-ID'
-
end
-
-
2
def encoded
-
do_encode(CAPITALIZED_FIELD)
-
end
-
-
2
def decoded
-
do_decode
-
end
-
-
end
-
end
-
# encoding: utf-8
-
#
-
# = Resent-Sender Field
-
#
-
# The Resent-Sender field inherits resent-sender StructuredField and handles the Resent-Sender: header
-
# field in the email.
-
#
-
# Sending resent_sender to a mail message will instantiate a Mail::Field object that
-
# has a ResentSenderField as its field type. This includes all Mail::CommonAddress
-
# module instance metods.
-
#
-
# Only one Resent-Sender field can appear in a header, though it can have multiple
-
# addresses and groups of addresses.
-
#
-
# == Examples:
-
#
-
# mail = Mail.new
-
# mail.resent_sender = 'Mikel Lindsaar <mikel@test.lindsaar.net>, ada@test.lindsaar.net'
-
# mail.resent_sender #=> ['mikel@test.lindsaar.net']
-
# mail[:resent_sender] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::ResentSenderField:0x180e1c4
-
# mail['resent-sender'] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::ResentSenderField:0x180e1c4
-
# mail['Resent-Sender'] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::ResentSenderField:0x180e1c4
-
#
-
# mail.resent_sender.to_s #=> 'Mikel Lindsaar <mikel@test.lindsaar.net>, ada@test.lindsaar.net'
-
# mail.resent_sender.addresses #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
-
# mail.resent_sender.formatted #=> ['Mikel Lindsaar <mikel@test.lindsaar.net>', 'ada@test.lindsaar.net']
-
#
-
2
require 'mail/fields/common/common_address'
-
-
2
module Mail
-
2
class ResentSenderField < StructuredField
-
-
2
include Mail::CommonAddress
-
-
2
FIELD_NAME = 'resent-sender'
-
2
CAPITALIZED_FIELD = 'Resent-Sender'
-
-
2
def initialize(value = nil, charset = 'utf-8')
-
self.charset = charset
-
super(CAPITALIZED_FIELD, strip_field(FIELD_NAME, value), charset)
-
self.parse
-
self
-
end
-
-
2
def addresses
-
[address.address]
-
end
-
-
2
def address
-
address_list.addresses.first
-
end
-
-
2
def encoded
-
do_encode(CAPITALIZED_FIELD)
-
end
-
-
2
def decoded
-
do_decode
-
end
-
-
end
-
end
-
# encoding: utf-8
-
#
-
# = Resent-To Field
-
#
-
# The Resent-To field inherits resent-to StructuredField and handles the Resent-To: header
-
# field in the email.
-
#
-
# Sending resent_to to a mail message will instantiate a Mail::Field object that
-
# has a ResentToField as its field type. This includes all Mail::CommonAddress
-
# module instance metods.
-
#
-
# Only one Resent-To field can appear in a header, though it can have multiple
-
# addresses and groups of addresses.
-
#
-
# == Examples:
-
#
-
# mail = Mail.new
-
# mail.resent_to = 'Mikel Lindsaar <mikel@test.lindsaar.net>, ada@test.lindsaar.net'
-
# mail.resent_to #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
-
# mail[:resent_to] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::ResentToField:0x180e1c4
-
# mail['resent-to'] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::ResentToField:0x180e1c4
-
# mail['Resent-To'] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::ResentToField:0x180e1c4
-
#
-
# mail[:resent_to].encoded #=> 'Resent-To: Mikel Lindsaar <mikel@test.lindsaar.net>, ada@test.lindsaar.net\r\n'
-
# mail[:resent_to].decoded #=> 'Mikel Lindsaar <mikel@test.lindsaar.net>, ada@test.lindsaar.net'
-
# mail[:resent_to].addresses #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
-
# mail[:resent_to].formatted #=> ['Mikel Lindsaar <mikel@test.lindsaar.net>', 'ada@test.lindsaar.net']
-
#
-
2
require 'mail/fields/common/common_address'
-
-
2
module Mail
-
2
class ResentToField < StructuredField
-
-
2
include Mail::CommonAddress
-
-
2
FIELD_NAME = 'resent-to'
-
2
CAPITALIZED_FIELD = 'Resent-To'
-
-
2
def initialize(value = nil, charset = 'utf-8')
-
self.charset = charset
-
super(CAPITALIZED_FIELD, strip_field(FIELD_NAME, value), charset)
-
self.parse
-
self
-
end
-
-
2
def encoded
-
do_encode(CAPITALIZED_FIELD)
-
end
-
-
2
def decoded
-
do_decode
-
end
-
-
end
-
end
-
# encoding: utf-8
-
#
-
# 4.4.3. REPLY-TO / RESENT-REPLY-TO
-
#
-
# Note: The "Return-Path" field is added by the mail transport
-
# service, at the time of final deliver. It is intended
-
# to identify a path back to the orginator of the mes-
-
# sage. The "Reply-To" field is added by the message
-
# originator and is intended to direct replies.
-
#
-
# trace = [return]
-
# 1*received
-
#
-
# return = "Return-Path:" path CRLF
-
#
-
# path = ([CFWS] "<" ([CFWS] / addr-spec) ">" [CFWS]) /
-
# obs-path
-
#
-
# received = "Received:" name-val-list ";" date-time CRLF
-
#
-
# name-val-list = [CFWS] [name-val-pair *(CFWS name-val-pair)]
-
#
-
# name-val-pair = item-name CFWS item-value
-
#
-
# item-name = ALPHA *(["-"] (ALPHA / DIGIT))
-
#
-
# item-value = 1*angle-addr / addr-spec /
-
# atom / domain / msg-id
-
#
-
2
require 'mail/fields/common/common_address'
-
-
2
module Mail
-
2
class ReturnPathField < StructuredField
-
-
2
include Mail::CommonAddress
-
-
2
FIELD_NAME = 'return-path'
-
2
CAPITALIZED_FIELD = 'Return-Path'
-
-
2
def initialize(value = nil, charset = 'utf-8')
-
value = nil if value == '<>'
-
self.charset = charset
-
super(CAPITALIZED_FIELD, strip_field(FIELD_NAME, value), charset)
-
self.parse
-
self
-
end
-
-
2
def encoded
-
"#{CAPITALIZED_FIELD}: <#{address}>\r\n"
-
end
-
-
2
def decoded
-
do_decode
-
end
-
-
2
def address
-
addresses.first
-
end
-
-
2
def default
-
address
-
end
-
-
end
-
end
-
# encoding: utf-8
-
#
-
# = Sender Field
-
#
-
# The Sender field inherits sender StructuredField and handles the Sender: header
-
# field in the email.
-
#
-
# Sending sender to a mail message will instantiate a Mail::Field object that
-
# has a SenderField as its field type. This includes all Mail::CommonAddress
-
# module instance metods.
-
#
-
# Only one Sender field can appear in a header, though it can have multiple
-
# addresses and groups of addresses.
-
#
-
# == Examples:
-
#
-
# mail = Mail.new
-
# mail.sender = 'Mikel Lindsaar <mikel@test.lindsaar.net>'
-
# mail.sender #=> 'mikel@test.lindsaar.net'
-
# mail[:sender] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::SenderField:0x180e1c4
-
# mail['sender'] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::SenderField:0x180e1c4
-
# mail['Sender'] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::SenderField:0x180e1c4
-
#
-
# mail[:sender].encoded #=> "Sender: Mikel Lindsaar <mikel@test.lindsaar.net>\r\n"
-
# mail[:sender].decoded #=> 'Mikel Lindsaar <mikel@test.lindsaar.net>'
-
# mail[:sender].addresses #=> ['mikel@test.lindsaar.net']
-
# mail[:sender].formatted #=> ['Mikel Lindsaar <mikel@test.lindsaar.net>']
-
#
-
2
require 'mail/fields/common/common_address'
-
-
2
module Mail
-
2
class SenderField < StructuredField
-
-
2
include Mail::CommonAddress
-
-
2
FIELD_NAME = 'sender'
-
2
CAPITALIZED_FIELD = 'Sender'
-
-
2
def initialize(value = nil, charset = 'utf-8')
-
self.charset = charset
-
super(CAPITALIZED_FIELD, strip_field(FIELD_NAME, value), charset)
-
self.parse
-
self
-
end
-
-
2
def addresses
-
[address.address]
-
end
-
-
2
def address
-
address_list.addresses.first
-
end
-
-
2
def encoded
-
do_encode(CAPITALIZED_FIELD)
-
end
-
-
2
def decoded
-
do_decode
-
end
-
-
2
def default
-
address.address
-
end
-
-
end
-
end
-
# encoding: utf-8
-
2
require 'mail/fields/common/common_field'
-
-
2
module Mail
-
# Provides access to a structured header field
-
#
-
# ===Per RFC 2822:
-
# 2.2.2. Structured Header Field Bodies
-
#
-
# Some field bodies in this standard have specific syntactical
-
# structure more restrictive than the unstructured field bodies
-
# described above. These are referred to as "structured" field bodies.
-
# Structured field bodies are sequences of specific lexical tokens as
-
# described in sections 3 and 4 of this standard. Many of these tokens
-
# are allowed (according to their syntax) to be introduced or end with
-
# comments (as described in section 3.2.3) as well as the space (SP,
-
# ASCII value 32) and horizontal tab (HTAB, ASCII value 9) characters
-
# (together known as the white space characters, WSP), and those WSP
-
# characters are subject to header "folding" and "unfolding" as
-
# described in section 2.2.3. Semantic analysis of structured field
-
# bodies is given along with their syntax.
-
2
class StructuredField
-
-
2
include Mail::CommonField
-
2
include Mail::Utilities
-
-
2
def initialize(name = nil, value = nil, charset = nil)
-
self.name = name
-
self.value = value
-
self.charset = charset
-
self
-
end
-
-
2
def charset
-
@charset
-
end
-
-
2
def charset=(val)
-
@charset = val
-
end
-
-
2
def default
-
decoded
-
end
-
-
2
def errors
-
[]
-
end
-
-
end
-
end
-
# encoding: utf-8
-
#
-
# subject = "Subject:" unstructured CRLF
-
2
module Mail
-
2
class SubjectField < UnstructuredField
-
-
2
FIELD_NAME = 'subject'
-
2
CAPITALIZED_FIELD = "Subject"
-
-
2
def initialize(value = nil, charset = 'utf-8')
-
self.charset = charset
-
super(CAPITALIZED_FIELD, strip_field(FIELD_NAME, value), charset)
-
end
-
-
end
-
end
-
# encoding: utf-8
-
#
-
# = To Field
-
#
-
# The To field inherits to StructuredField and handles the To: header
-
# field in the email.
-
#
-
# Sending to to a mail message will instantiate a Mail::Field object that
-
# has a ToField as its field type. This includes all Mail::CommonAddress
-
# module instance metods.
-
#
-
# Only one To field can appear in a header, though it can have multiple
-
# addresses and groups of addresses.
-
#
-
# == Examples:
-
#
-
# mail = Mail.new
-
# mail.to = 'Mikel Lindsaar <mikel@test.lindsaar.net>, ada@test.lindsaar.net'
-
# mail.to #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
-
# mail[:to] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::ToField:0x180e1c4
-
# mail['to'] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::ToField:0x180e1c4
-
# mail['To'] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::ToField:0x180e1c4
-
#
-
# mail[:to].encoded #=> 'To: Mikel Lindsaar <mikel@test.lindsaar.net>, ada@test.lindsaar.net\r\n'
-
# mail[:to].decoded #=> 'Mikel Lindsaar <mikel@test.lindsaar.net>, ada@test.lindsaar.net'
-
# mail[:to].addresses #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
-
# mail[:to].formatted #=> ['Mikel Lindsaar <mikel@test.lindsaar.net>', 'ada@test.lindsaar.net']
-
#
-
2
require 'mail/fields/common/common_address'
-
-
2
module Mail
-
2
class ToField < StructuredField
-
-
2
include Mail::CommonAddress
-
-
2
FIELD_NAME = 'to'
-
2
CAPITALIZED_FIELD = 'To'
-
-
2
def initialize(value = nil, charset = 'utf-8')
-
self.charset = charset
-
super(CAPITALIZED_FIELD, strip_field(FIELD_NAME, value), charset)
-
self.parse
-
self
-
end
-
-
2
def encoded
-
do_encode(CAPITALIZED_FIELD)
-
end
-
-
2
def decoded
-
do_decode
-
end
-
-
end
-
end
-
# encoding: utf-8
-
2
require 'mail/fields/common/common_field'
-
-
2
module Mail
-
# Provides access to an unstructured header field
-
#
-
# ===Per RFC 2822:
-
# 2.2.1. Unstructured Header Field Bodies
-
#
-
# Some field bodies in this standard are defined simply as
-
# "unstructured" (which is specified below as any US-ASCII characters,
-
# except for CR and LF) with no further restrictions. These are
-
# referred to as unstructured field bodies. Semantically, unstructured
-
# field bodies are simply to be treated as a single line of characters
-
# with no further processing (except for header "folding" and
-
# "unfolding" as described in section 2.2.3).
-
2
class UnstructuredField
-
-
2
include Mail::CommonField
-
2
include Mail::Utilities
-
-
2
attr_accessor :charset
-
2
attr_reader :errors
-
-
2
def initialize(name, value, charset = nil)
-
@errors = []
-
-
if value.is_a?(Array)
-
# Probably has arrived here from a failed parse of an AddressList Field
-
value = value.join(', ')
-
else
-
# Ensure we are dealing with a string
-
value = value.to_s
-
end
-
-
if charset
-
self.charset = charset
-
else
-
if value.respond_to?(:encoding)
-
self.charset = value.encoding
-
else
-
self.charset = $KCODE
-
end
-
end
-
self.name = name
-
self.value = value
-
self
-
end
-
-
2
def encoded
-
do_encode
-
end
-
-
2
def decoded
-
do_decode
-
end
-
-
2
def default
-
decoded
-
end
-
-
2
def parse # An unstructured field does not parse
-
self
-
end
-
-
2
private
-
-
2
def do_encode
-
value.nil? ? '' : "#{wrapped_value}\r\n"
-
end
-
-
2
def do_decode
-
value.blank? ? nil : Encodings.decode_encode(value, :decode)
-
end
-
-
# 2.2.3. Long Header Fields
-
#
-
# Each header field is logically a single line of characters comprising
-
# the field name, the colon, and the field body. For convenience
-
# however, and to deal with the 998/78 character limitations per line,
-
# the field body portion of a header field can be split into a multiple
-
# line representation; this is called "folding". The general rule is
-
# that wherever this standard allows for folding white space (not
-
# simply WSP characters), a CRLF may be inserted before any WSP. For
-
# example, the header field:
-
#
-
# Subject: This is a test
-
#
-
# can be represented as:
-
#
-
# Subject: This
-
# is a test
-
#
-
# Note: Though structured field bodies are defined in such a way that
-
# folding can take place between many of the lexical tokens (and even
-
# within some of the lexical tokens), folding SHOULD be limited to
-
# placing the CRLF at higher-level syntactic breaks. For instance, if
-
# a field body is defined as comma-separated values, it is recommended
-
# that folding occur after the comma separating the structured items in
-
# preference to other places where the field could be folded, even if
-
# it is allowed elsewhere.
-
2
def wrapped_value # :nodoc:
-
wrap_lines(name, fold("#{name}: ".length))
-
end
-
-
# 6.2. Display of 'encoded-word's
-
#
-
# When displaying a particular header field that contains multiple
-
# 'encoded-word's, any 'linear-white-space' that separates a pair of
-
# adjacent 'encoded-word's is ignored. (This is to allow the use of
-
# multiple 'encoded-word's to represent long strings of unencoded text,
-
# without having to separate 'encoded-word's where spaces occur in the
-
# unencoded text.)
-
2
def wrap_lines(name, folded_lines)
-
result = ["#{name}: #{folded_lines.shift}"]
-
result.concat(folded_lines)
-
result.join("\r\n\s")
-
end
-
-
2
def fold(prepend = 0) # :nodoc:
-
encoding = normalized_encoding
-
decoded_string = decoded.to_s
-
should_encode = decoded_string.not_ascii_only?
-
if should_encode
-
first = true
-
words = decoded_string.split(/[ \t]/).map do |word|
-
if first
-
first = !first
-
else
-
word = " " << word
-
end
-
if word.not_ascii_only?
-
word
-
else
-
word.scan(/.{7}|.+$/)
-
end
-
end.flatten
-
else
-
words = decoded_string.split(/[ \t]/)
-
end
-
-
folded_lines = []
-
while !words.empty?
-
limit = 78 - prepend
-
limit = limit - 7 - encoding.length if should_encode
-
line = ""
-
first_word = true
-
while !words.empty?
-
break unless word = words.first.dup
-
word.encode!(charset) if charset && word.respond_to?(:encode!)
-
word = encode(word) if should_encode
-
word = encode_crlf(word)
-
# Skip to next line if we're going to go past the limit
-
# Unless this is the first word, in which case we're going to add it anyway
-
# Note: This means that a word that's longer than 998 characters is going to break the spec. Please fix if this is a problem for you.
-
# (The fix, it seems, would be to use encoded-word encoding on it, because that way you can break it across multiple lines and
-
# the linebreak will be ignored)
-
break if !line.empty? && (line.length + word.length + 1 > limit)
-
# Remove the word from the queue ...
-
words.shift
-
# Add word separator
-
if first_word
-
first_word = false
-
else
-
line << " " if !should_encode
-
end
-
-
# ... add it in encoded form to the current line
-
line << word
-
end
-
# Encode the line if necessary
-
line = "=?#{encoding}?Q?#{line}?=" if should_encode
-
# Add the line to the output and reset the prepend
-
folded_lines << line
-
prepend = 0
-
end
-
folded_lines
-
end
-
-
2
def encode(value)
-
value = [value].pack(CAPITAL_M).gsub(EQUAL_LF, EMPTY)
-
value.gsub!(/"/, '=22')
-
value.gsub!(/\(/, '=28')
-
value.gsub!(/\)/, '=29')
-
value.gsub!(/\?/, '=3F')
-
value.gsub!(/_/, '=5F')
-
value.gsub!(/ /, '_')
-
value
-
end
-
-
2
def encode_crlf(value)
-
value.gsub!(CR, CR_ENCODED)
-
value.gsub!(LF, LF_ENCODED)
-
value
-
end
-
-
2
def normalized_encoding
-
encoding = charset.to_s.upcase.gsub('_', '-')
-
encoding = 'UTF-8' if encoding == 'UTF8' # Ruby 1.8.x and $KCODE == 'u'
-
encoding
-
end
-
-
end
-
end
-
# encoding: utf-8
-
2
module Mail
-
-
# Provides access to a header object.
-
#
-
# ===Per RFC2822
-
#
-
# 2.2. Header Fields
-
#
-
# Header fields are lines composed of a field name, followed by a colon
-
# (":"), followed by a field body, and terminated by CRLF. A field
-
# name MUST be composed of printable US-ASCII characters (i.e.,
-
# characters that have values between 33 and 126, inclusive), except
-
# colon. A field body may be composed of any US-ASCII characters,
-
# except for CR and LF. However, a field body may contain CRLF when
-
# used in header "folding" and "unfolding" as described in section
-
# 2.2.3. All field bodies MUST conform to the syntax described in
-
# sections 3 and 4 of this standard.
-
2
class Header
-
2
include Constants
-
2
include Utilities
-
2
include Enumerable
-
-
2
@@maximum_amount = 1000
-
-
# Large amount of headers in Email might create extra high CPU load
-
# Use this parameter to limit number of headers that will be parsed by
-
# mail library.
-
# Default: 1000
-
2
def self.maximum_amount
-
@@maximum_amount
-
end
-
-
2
def self.maximum_amount=(value)
-
@@maximum_amount = value
-
end
-
-
# Creates a new header object.
-
#
-
# Accepts raw text or nothing. If given raw text will attempt to parse
-
# it and split it into the various fields, instantiating each field as
-
# it goes.
-
#
-
# If it finds a field that should be a structured field (such as content
-
# type), but it fails to parse it, it will simply make it an unstructured
-
# field and leave it alone. This will mean that the data is preserved but
-
# no automatic processing of that field will happen. If you find one of
-
# these cases, please make a patch and send it in, or at the least, send
-
# me the example so we can fix it.
-
2
def initialize(header_text = nil, charset = nil)
-
@charset = charset
-
self.raw_source = header_text.to_crlf.lstrip
-
split_header if header_text
-
end
-
-
2
def initialize_copy(original)
-
super
-
@fields = @fields.dup
-
end
-
-
# The preserved raw source of the header as you passed it in, untouched
-
# for your Regexing glory.
-
2
def raw_source
-
@raw_source
-
end
-
-
# Returns an array of all the fields in the header in order that they
-
# were read in.
-
2
def fields
-
@fields ||= FieldList.new
-
end
-
-
# 3.6. Field definitions
-
#
-
# It is important to note that the header fields are not guaranteed to
-
# be in a particular order. They may appear in any order, and they
-
# have been known to be reordered occasionally when transported over
-
# the Internet. However, for the purposes of this standard, header
-
# fields SHOULD NOT be reordered when a message is transported or
-
# transformed. More importantly, the trace header fields and resent
-
# header fields MUST NOT be reordered, and SHOULD be kept in blocks
-
# prepended to the message. See sections 3.6.6 and 3.6.7 for more
-
# information.
-
#
-
# Populates the fields container with Field objects in the order it
-
# receives them in.
-
#
-
# Acceps an array of field string values, for example:
-
#
-
# h = Header.new
-
# h.fields = ['From: mikel@me.com', 'To: bob@you.com']
-
2
def fields=(unfolded_fields)
-
@fields = Mail::FieldList.new
-
warn "Warning: more than #{self.class.maximum_amount} header fields only using the first #{self.class.maximum_amount}" if unfolded_fields.length > self.class.maximum_amount
-
unfolded_fields[0..(self.class.maximum_amount-1)].each do |field|
-
-
field = Field.new(field, nil, charset)
-
if limited_field?(field.name) && (selected = select_field_for(field.name)) && selected.any?
-
selected.first.update(field.name, field.value)
-
else
-
@fields << field
-
end
-
end
-
-
end
-
-
2
def errors
-
@fields.map(&:errors).flatten(1)
-
end
-
-
# 3.6. Field definitions
-
#
-
# The following table indicates limits on the number of times each
-
# field may occur in a message header as well as any special
-
# limitations on the use of those fields. An asterisk next to a value
-
# in the minimum or maximum column indicates that a special restriction
-
# appears in the Notes column.
-
#
-
# <snip table from 3.6>
-
#
-
# As per RFC, many fields can appear more than once, we will return a string
-
# of the value if there is only one header, or if there is more than one
-
# matching header, will return an array of values in order that they appear
-
# in the header ordered from top to bottom.
-
#
-
# Example:
-
#
-
# h = Header.new
-
# h.fields = ['To: mikel@me.com', 'X-Mail-SPAM: 15', 'X-Mail-SPAM: 20']
-
# h['To'] #=> 'mikel@me.com'
-
# h['X-Mail-SPAM'] #=> ['15', '20']
-
2
def [](name)
-
name = dasherize(name)
-
name.downcase!
-
selected = select_field_for(name)
-
case
-
when selected.length > 1
-
selected.map { |f| f }
-
when !selected.blank?
-
selected.first
-
else
-
nil
-
end
-
end
-
-
# Sets the FIRST matching field in the header to passed value, or deletes
-
# the FIRST field matched from the header if passed nil
-
#
-
# Example:
-
#
-
# h = Header.new
-
# h.fields = ['To: mikel@me.com', 'X-Mail-SPAM: 15', 'X-Mail-SPAM: 20']
-
# h['To'] = 'bob@you.com'
-
# h['To'] #=> 'bob@you.com'
-
# h['X-Mail-SPAM'] = '10000'
-
# h['X-Mail-SPAM'] # => ['15', '20', '10000']
-
# h['X-Mail-SPAM'] = nil
-
# h['X-Mail-SPAM'] # => nil
-
2
def []=(name, value)
-
name = dasherize(name)
-
if name.include?(':')
-
raise ArgumentError, "Header names may not contain a colon: #{name.inspect}"
-
end
-
fn = name.downcase
-
selected = select_field_for(fn)
-
-
case
-
# User wants to delete the field
-
when !selected.blank? && value == nil
-
fields.delete_if { |f| selected.include?(f) }
-
-
# User wants to change the field
-
when !selected.blank? && limited_field?(fn)
-
selected.first.update(fn, value)
-
-
# User wants to create the field
-
else
-
# Need to insert in correct order for trace fields
-
self.fields << Field.new(name.to_s, value, charset)
-
end
-
if dasherize(fn) == "content-type"
-
# Update charset if specified in Content-Type
-
params = self[:content_type].parameters rescue nil
-
@charset = params[:charset] if params && params[:charset]
-
end
-
end
-
-
2
def charset
-
@charset
-
end
-
-
2
def charset=(val)
-
params = self[:content_type].parameters rescue nil
-
if params
-
params[:charset] = val
-
end
-
@charset = val
-
end
-
-
2
LIMITED_FIELDS = %w[ date from sender reply-to to cc bcc
-
message-id in-reply-to references subject
-
return-path content-type mime-version
-
content-transfer-encoding content-description
-
content-id content-disposition content-location]
-
-
2
def encoded
-
buffer = ''
-
buffer.force_encoding('us-ascii') if buffer.respond_to?(:force_encoding)
-
fields.each do |field|
-
buffer << field.encoded
-
end
-
buffer
-
end
-
-
2
def to_s
-
encoded
-
end
-
-
2
def decoded
-
raise NoMethodError, 'Can not decode an entire header as there could be character set conflicts, try calling #decoded on the various fields.'
-
end
-
-
2
def field_summary
-
fields.map { |f| "<#{f.name}: #{f.value}>" }.join(", ")
-
end
-
-
# Returns true if the header has a Message-ID defined (empty or not)
-
2
def has_message_id?
-
!fields.select { |f| f.responsible_for?('Message-ID') }.empty?
-
end
-
-
# Returns true if the header has a Content-ID defined (empty or not)
-
2
def has_content_id?
-
!fields.select { |f| f.responsible_for?('Content-ID') }.empty?
-
end
-
-
# Returns true if the header has a Date defined (empty or not)
-
2
def has_date?
-
!fields.select { |f| f.responsible_for?('Date') }.empty?
-
end
-
-
# Returns true if the header has a MIME version defined (empty or not)
-
2
def has_mime_version?
-
!fields.select { |f| f.responsible_for?('Mime-Version') }.empty?
-
end
-
-
2
private
-
-
2
def raw_source=(val)
-
@raw_source = val
-
end
-
-
# Splits an unfolded and line break cleaned header into individual field
-
# strings.
-
2
def split_header
-
self.fields = raw_source.split(HEADER_SPLIT)
-
end
-
-
2
def select_field_for(name)
-
fields.select { |f| f.responsible_for?(name) }
-
end
-
-
2
def limited_field?(name)
-
LIMITED_FIELDS.include?(name.to_s.downcase)
-
end
-
-
# Enumerable support; yield each field in order to the block if there is one,
-
# or return an Enumerator for them if there isn't.
-
2
def each( &block )
-
return self.fields.each( &block ) if block
-
self.fields.each
-
end
-
-
end
-
end
-
# encoding: utf-8
-
-
# This is an almost cut and paste from ActiveSupport v3.0.6, copied in here so that Mail
-
# itself does not depend on ActiveSupport to avoid versioning conflicts
-
-
2
module Mail
-
2
class IndifferentHash < Hash
-
-
2
def initialize(constructor = {})
-
if constructor.is_a?(Hash)
-
super()
-
update(constructor)
-
else
-
super(constructor)
-
end
-
end
-
-
2
def default(key = nil)
-
if key.is_a?(Symbol) && include?(key = key.to_s)
-
self[key]
-
else
-
super
-
end
-
end
-
-
2
def self.new_from_hash_copying_default(hash)
-
IndifferentHash.new(hash).tap do |new_hash|
-
new_hash.default = hash.default
-
end
-
end
-
-
2
alias_method :regular_writer, :[]= unless method_defined?(:regular_writer)
-
2
alias_method :regular_update, :update unless method_defined?(:regular_update)
-
-
# Assigns a new value to the hash:
-
#
-
# hash = HashWithIndifferentAccess.new
-
# hash[:key] = "value"
-
#
-
2
def []=(key, value)
-
regular_writer(convert_key(key), convert_value(value))
-
end
-
-
2
alias_method :store, :[]=
-
-
# Updates the instantized hash with values from the second:
-
#
-
# hash_1 = HashWithIndifferentAccess.new
-
# hash_1[:key] = "value"
-
#
-
# hash_2 = HashWithIndifferentAccess.new
-
# hash_2[:key] = "New Value!"
-
#
-
# hash_1.update(hash_2) # => {"key"=>"New Value!"}
-
#
-
2
def update(other_hash)
-
other_hash.each_pair { |key, value| regular_writer(convert_key(key), convert_value(value)) }
-
self
-
end
-
-
2
alias_method :merge!, :update
-
-
# Checks the hash for a key matching the argument passed in:
-
#
-
# hash = HashWithIndifferentAccess.new
-
# hash["key"] = "value"
-
# hash.key? :key # => true
-
# hash.key? "key" # => true
-
#
-
2
def key?(key)
-
super(convert_key(key))
-
end
-
-
2
alias_method :include?, :key?
-
2
alias_method :has_key?, :key?
-
2
alias_method :member?, :key?
-
-
# Fetches the value for the specified key, same as doing hash[key]
-
2
def fetch(key, *extras)
-
super(convert_key(key), *extras)
-
end
-
-
# Returns an array of the values at the specified indices:
-
#
-
# hash = HashWithIndifferentAccess.new
-
# hash[:a] = "x"
-
# hash[:b] = "y"
-
# hash.values_at("a", "b") # => ["x", "y"]
-
#
-
2
def values_at(*indices)
-
indices.collect {|key| self[convert_key(key)]}
-
end
-
-
# Returns an exact copy of the hash.
-
2
def dup
-
IndifferentHash.new(self)
-
end
-
-
# Merges the instantized and the specified hashes together, giving precedence to the values from the second hash
-
# Does not overwrite the existing hash.
-
2
def merge(hash)
-
self.dup.update(hash)
-
end
-
-
# Performs the opposite of merge, with the keys and values from the first hash taking precedence over the second.
-
# This overloaded definition prevents returning a regular hash, if reverse_merge is called on a HashWithDifferentAccess.
-
2
def reverse_merge(other_hash)
-
super self.class.new_from_hash_copying_default(other_hash)
-
end
-
-
2
def reverse_merge!(other_hash)
-
replace(reverse_merge( other_hash ))
-
end
-
-
# Removes a specified key from the hash.
-
2
def delete(key)
-
super(convert_key(key))
-
end
-
-
2
def stringify_keys!; self end
-
2
def stringify_keys; dup end
-
2
def symbolize_keys; to_hash.symbolize_keys end
-
2
def to_options!; self end
-
-
2
def to_hash
-
Hash.new(default).merge!(self)
-
end
-
-
2
protected
-
-
2
def convert_key(key)
-
key.kind_of?(Symbol) ? key.to_s : key
-
end
-
-
2
def convert_value(value)
-
if value.class == Hash
-
self.class.new_from_hash_copying_default(value)
-
elsif value.is_a?(Array)
-
value.dup.replace(value.map { |e| convert_value(e) })
-
else
-
value
-
end
-
end
-
-
end
-
end
-
# encoding: utf-8
-
2
module Mail
-
-
# Allows you to create a new Mail::Message object.
-
#
-
# You can make an email via passing a string or passing a block.
-
#
-
# For example, the following two examples will create the same email
-
# message:
-
#
-
# Creating via a string:
-
#
-
# string = "To: mikel@test.lindsaar.net\r\n"
-
# string << "From: bob@test.lindsaar.net\r\n"
-
# string << "Subject: This is an email\r\n"
-
# string << "\r\n"
-
# string << "This is the body"
-
# Mail.new(string)
-
#
-
# Or creating via a block:
-
#
-
# message = Mail.new do
-
# to 'mikel@test.lindsaar.net'
-
# from 'bob@test.lindsaar.net'
-
# subject 'This is an email'
-
# body 'This is the body'
-
# end
-
#
-
# Or creating via a hash (or hash like object):
-
#
-
# message = Mail.new({:to => 'mikel@test.lindsaar.net',
-
# 'from' => 'bob@test.lindsaar.net',
-
# :subject => 'This is an email',
-
# :body => 'This is the body' })
-
#
-
# Note, the hash keys can be strings or symbols, the passed in object
-
# does not need to be a hash, it just needs to respond to :each_pair
-
# and yield each key value pair.
-
#
-
# As a side note, you can also create a new email through creating
-
# a Mail::Message object directly and then passing in values via string,
-
# symbol or direct method calls. See Mail::Message for more information.
-
#
-
# mail = Mail.new
-
# mail.to = 'mikel@test.lindsaar.net'
-
# mail[:from] = 'bob@test.lindsaar.net'
-
# mail['subject'] = 'This is an email'
-
# mail.body = 'This is the body'
-
2
def self.new(*args, &block)
-
Message.new(args, &block)
-
end
-
-
# Sets the default delivery method and retriever method for all new Mail objects.
-
# The delivery_method and retriever_method default to :smtp and :pop3, with defaults
-
# set.
-
#
-
# So sending a new email, if you have an SMTP server running on localhost is
-
# as easy as:
-
#
-
# Mail.deliver do
-
# to 'mikel@test.lindsaar.net'
-
# from 'bob@test.lindsaar.net'
-
# subject 'hi there!'
-
# body 'this is a body'
-
# end
-
#
-
# If you do not specify anything, you will get the following equivalent code set in
-
# every new mail object:
-
#
-
# Mail.defaults do
-
# delivery_method :smtp, { :address => "localhost",
-
# :port => 25,
-
# :domain => 'localhost.localdomain',
-
# :user_name => nil,
-
# :password => nil,
-
# :authentication => nil,
-
# :enable_starttls_auto => true }
-
#
-
# retriever_method :pop3, { :address => "localhost",
-
# :port => 995,
-
# :user_name => nil,
-
# :password => nil,
-
# :enable_ssl => true }
-
# end
-
#
-
# Mail.delivery_method.new #=> Mail::SMTP instance
-
# Mail.retriever_method.new #=> Mail::POP3 instance
-
#
-
# Each mail object inherits the default set in Mail.delivery_method, however, on
-
# a per email basis, you can override the method:
-
#
-
# mail.delivery_method :sendmail
-
#
-
# Or you can override the method and pass in settings:
-
#
-
# mail.delivery_method :sendmail, { :address => 'some.host' }
-
#
-
# You can also just modify the settings:
-
#
-
# mail.delivery_settings = { :address => 'some.host' }
-
#
-
# The passed in hash is just merged against the defaults with +merge!+ and the result
-
# assigned the mail object. So the above example will change only the :address value
-
# of the global smtp_settings to be 'some.host', keeping all other values
-
2
def self.defaults(&block)
-
Configuration.instance.instance_eval(&block)
-
end
-
-
# Returns the delivery method selected, defaults to an instance of Mail::SMTP
-
2
def self.delivery_method
-
Configuration.instance.delivery_method
-
end
-
-
# Returns the retriever method selected, defaults to an instance of Mail::POP3
-
2
def self.retriever_method
-
Configuration.instance.retriever_method
-
end
-
-
# Send an email using the default configuration. You do need to set a default
-
# configuration first before you use self.deliver, if you don't, an appropriate
-
# error will be raised telling you to.
-
#
-
# If you do not specify a delivery type, SMTP will be used.
-
#
-
# Mail.deliver do
-
# to 'mikel@test.lindsaar.net'
-
# from 'ada@test.lindsaar.net'
-
# subject 'This is a test email'
-
# body 'Not much to say here'
-
# end
-
#
-
# You can also do:
-
#
-
# mail = Mail.read('email.eml')
-
# mail.deliver!
-
#
-
# And your email object will be created and sent.
-
2
def self.deliver(*args, &block)
-
mail = self.new(args, &block)
-
mail.deliver
-
mail
-
end
-
-
# Find emails from the default retriever
-
# See Mail::Retriever for a complete documentation.
-
2
def self.find(*args, &block)
-
retriever_method.find(*args, &block)
-
end
-
-
# Finds and then deletes retrieved emails from the default retriever
-
# See Mail::Retriever for a complete documentation.
-
2
def self.find_and_delete(*args, &block)
-
retriever_method.find_and_delete(*args, &block)
-
end
-
-
# Receive the first email(s) from the default retriever
-
# See Mail::Retriever for a complete documentation.
-
2
def self.first(*args, &block)
-
retriever_method.first(*args, &block)
-
end
-
-
# Receive the first email(s) from the default retriever
-
# See Mail::Retriever for a complete documentation.
-
2
def self.last(*args, &block)
-
retriever_method.last(*args, &block)
-
end
-
-
# Receive all emails from the default retriever
-
# See Mail::Retriever for a complete documentation.
-
2
def self.all(*args, &block)
-
retriever_method.all(*args, &block)
-
end
-
-
# Reads in an email message from a path and instantiates it as a new Mail::Message
-
2
def self.read(filename)
-
self.new(File.open(filename, 'rb') { |f| f.read })
-
end
-
-
# Delete all emails from the default retriever
-
# See Mail::Retriever for a complete documentation.
-
2
def self.delete_all(*args, &block)
-
retriever_method.delete_all(*args, &block)
-
end
-
-
# Instantiates a new Mail::Message using a string
-
2
def Mail.read_from_string(mail_as_string)
-
Mail.new(mail_as_string)
-
end
-
-
2
def Mail.connection(&block)
-
retriever_method.connection(&block)
-
end
-
-
# Initialize the observers and interceptors arrays
-
2
@@delivery_notification_observers = []
-
2
@@delivery_interceptors = []
-
-
# You can register an object to be informed of every email that is sent through
-
# this method.
-
#
-
# Your object needs to respond to a single method #delivered_email(mail)
-
# which receives the email that is sent.
-
2
def self.register_observer(observer)
-
unless @@delivery_notification_observers.include?(observer)
-
@@delivery_notification_observers << observer
-
end
-
end
-
-
# Unregister the given observer, allowing mail to resume operations
-
# without it.
-
2
def self.unregister_observer(observer)
-
@@delivery_notification_observers.delete(observer)
-
end
-
-
# You can register an object to be given every mail object that will be sent,
-
# before it is sent. So if you want to add special headers or modify any
-
# email that gets sent through the Mail library, you can do so.
-
#
-
# Your object needs to respond to a single method #delivering_email(mail)
-
# which receives the email that is about to be sent. Make your modifications
-
# directly to this object.
-
2
def self.register_interceptor(interceptor)
-
unless @@delivery_interceptors.include?(interceptor)
-
@@delivery_interceptors << interceptor
-
end
-
end
-
-
# Unregister the given interceptor, allowing mail to resume operations
-
# without it.
-
2
def self.unregister_interceptor(interceptor)
-
@@delivery_interceptors.delete(interceptor)
-
end
-
-
2
def self.inform_observers(mail)
-
@@delivery_notification_observers.each do |observer|
-
observer.delivered_email(mail)
-
end
-
end
-
-
2
def self.inform_interceptors(mail)
-
@@delivery_interceptors.each do |interceptor|
-
interceptor.delivering_email(mail)
-
end
-
end
-
-
2
protected
-
-
2
RANDOM_TAG='%x%x_%x%x%d%x'
-
-
2
def self.random_tag
-
t = Time.now
-
sprintf(RANDOM_TAG,
-
t.to_i, t.tv_usec,
-
$$, Thread.current.object_id.abs, self.uniq, rand(255))
-
end
-
-
2
private
-
-
2
def self.something_random
-
2
(Thread.current.object_id * rand(255) / Time.now.to_f).to_s.slice(-3..-1).to_i
-
end
-
-
2
def self.uniq
-
@@uniq += 1
-
end
-
-
2
@@uniq = self.something_random
-
-
end
-
# encoding: utf-8
-
2
require "yaml"
-
-
2
module Mail
-
# The Message class provides a single point of access to all things to do with an
-
# email message.
-
#
-
# You create a new email message by calling the Mail::Message.new method, or just
-
# Mail.new
-
#
-
# A Message object by default has the following objects inside it:
-
#
-
# * A Header object which contains all information and settings of the header of the email
-
# * Body object which contains all parts of the email that are not part of the header, this
-
# includes any attachments, body text, MIME parts etc.
-
#
-
# ==Per RFC2822
-
#
-
# 2.1. General Description
-
#
-
# At the most basic level, a message is a series of characters. A
-
# message that is conformant with this standard is comprised of
-
# characters with values in the range 1 through 127 and interpreted as
-
# US-ASCII characters [ASCII]. For brevity, this document sometimes
-
# refers to this range of characters as simply "US-ASCII characters".
-
#
-
# Note: This standard specifies that messages are made up of characters
-
# in the US-ASCII range of 1 through 127. There are other documents,
-
# specifically the MIME document series [RFC2045, RFC2046, RFC2047,
-
# RFC2048, RFC2049], that extend this standard to allow for values
-
# outside of that range. Discussion of those mechanisms is not within
-
# the scope of this standard.
-
#
-
# Messages are divided into lines of characters. A line is a series of
-
# characters that is delimited with the two characters carriage-return
-
# and line-feed; that is, the carriage return (CR) character (ASCII
-
# value 13) followed immediately by the line feed (LF) character (ASCII
-
# value 10). (The carriage-return/line-feed pair is usually written in
-
# this document as "CRLF".)
-
#
-
# A message consists of header fields (collectively called "the header
-
# of the message") followed, optionally, by a body. The header is a
-
# sequence of lines of characters with special syntax as defined in
-
# this standard. The body is simply a sequence of characters that
-
# follows the header and is separated from the header by an empty line
-
# (i.e., a line with nothing preceding the CRLF).
-
2
class Message
-
-
2
include Constants
-
2
include Utilities
-
-
# ==Making an email
-
#
-
# You can make an new mail object via a block, passing a string, file or direct assignment.
-
#
-
# ===Making an email via a block
-
#
-
# mail = Mail.new do
-
# from 'mikel@test.lindsaar.net'
-
# to 'you@test.lindsaar.net'
-
# subject 'This is a test email'
-
# body File.read('body.txt')
-
# end
-
#
-
# mail.to_s #=> "From: mikel@test.lindsaar.net\r\nTo: you@...
-
#
-
# ===Making an email via passing a string
-
#
-
# mail = Mail.new("To: mikel@test.lindsaar.net\r\nSubject: Hello\r\n\r\nHi there!")
-
# mail.body.to_s #=> 'Hi there!'
-
# mail.subject #=> 'Hello'
-
# mail.to #=> 'mikel@test.lindsaar.net'
-
#
-
# ===Making an email from a file
-
#
-
# mail = Mail.read('path/to/file.eml')
-
# mail.body.to_s #=> 'Hi there!'
-
# mail.subject #=> 'Hello'
-
# mail.to #=> 'mikel@test.lindsaar.net'
-
#
-
# ===Making an email via assignment
-
#
-
# You can assign values to a mail object via four approaches:
-
#
-
# * Message#field_name=(value)
-
# * Message#field_name(value)
-
# * Message#['field_name']=(value)
-
# * Message#[:field_name]=(value)
-
#
-
# Examples:
-
#
-
# mail = Mail.new
-
# mail['from'] = 'mikel@test.lindsaar.net'
-
# mail[:to] = 'you@test.lindsaar.net'
-
# mail.subject 'This is a test email'
-
# mail.body = 'This is a body'
-
#
-
# mail.to_s #=> "From: mikel@test.lindsaar.net\r\nTo: you@...
-
#
-
2
def initialize(*args, &block)
-
@body = nil
-
@body_raw = nil
-
@separate_parts = false
-
@text_part = nil
-
@html_part = nil
-
@errors = nil
-
@header = nil
-
@charset = self.class.default_charset
-
@defaulted_charset = true
-
-
@smtp_envelope_from = nil
-
@smtp_envelope_to = nil
-
-
@perform_deliveries = true
-
@raise_delivery_errors = true
-
-
@delivery_handler = nil
-
-
@delivery_method = Mail.delivery_method.dup
-
-
@transport_encoding = Mail::Encodings.get_encoding('7bit')
-
-
@mark_for_delete = false
-
-
if args.flatten.first.respond_to?(:each_pair)
-
init_with_hash(args.flatten.first)
-
else
-
init_with_string(args.flatten[0].to_s)
-
end
-
-
if block_given?
-
instance_eval(&block)
-
end
-
-
self
-
end
-
-
# If you assign a delivery handler, mail will call :deliver_mail on the
-
# object you assign to delivery_handler, it will pass itself as the
-
# single argument.
-
#
-
# If you define a delivery_handler, then you are responsible for the
-
# following actions in the delivery cycle:
-
#
-
# * Appending the mail object to Mail.deliveries as you see fit.
-
# * Checking the mail.perform_deliveries flag to decide if you should
-
# actually call :deliver! the mail object or not.
-
# * Checking the mail.raise_delivery_errors flag to decide if you
-
# should raise delivery errors if they occur.
-
# * Actually calling :deliver! (with the bang) on the mail object to
-
# get it to deliver itself.
-
#
-
# A simplest implementation of a delivery_handler would be
-
#
-
# class MyObject
-
#
-
# def initialize
-
# @mail = Mail.new('To: mikel@test.lindsaar.net')
-
# @mail.delivery_handler = self
-
# end
-
#
-
# attr_accessor :mail
-
#
-
# def deliver_mail(mail)
-
# yield
-
# end
-
# end
-
#
-
# Then doing:
-
#
-
# obj = MyObject.new
-
# obj.mail.deliver
-
#
-
# Would cause Mail to call obj.deliver_mail passing itself as a parameter,
-
# which then can just yield and let Mail do its own private do_delivery
-
# method.
-
2
attr_accessor :delivery_handler
-
-
# If set to false, mail will go through the motions of doing a delivery,
-
# but not actually call the delivery method or append the mail object to
-
# the Mail.deliveries collection. Useful for testing.
-
#
-
# Mail.deliveries.size #=> 0
-
# mail.delivery_method :smtp
-
# mail.perform_deliveries = false
-
# mail.deliver # Mail::SMTP not called here
-
# Mail.deliveries.size #=> 0
-
#
-
# If you want to test and query the Mail.deliveries collection to see what
-
# mail you sent, you should set perform_deliveries to true and use
-
# the :test mail delivery_method:
-
#
-
# Mail.deliveries.size #=> 0
-
# mail.delivery_method :test
-
# mail.perform_deliveries = true
-
# mail.deliver
-
# Mail.deliveries.size #=> 1
-
#
-
# This setting is ignored by mail (though still available as a flag) if you
-
# define a delivery_handler
-
2
attr_accessor :perform_deliveries
-
-
# If set to false, mail will silently catch and ignore any exceptions
-
# raised through attempting to deliver an email.
-
#
-
# This setting is ignored by mail (though still available as a flag) if you
-
# define a delivery_handler
-
2
attr_accessor :raise_delivery_errors
-
-
2
def self.default_charset; @@default_charset; end
-
4
def self.default_charset=(charset); @@default_charset = charset; end
-
2
self.default_charset = 'UTF-8'
-
-
2
def register_for_delivery_notification(observer)
-
STDERR.puts("Message#register_for_delivery_notification is deprecated, please call Mail.register_observer instead")
-
Mail.register_observer(observer)
-
end
-
-
2
def inform_observers
-
Mail.inform_observers(self)
-
end
-
-
2
def inform_interceptors
-
Mail.inform_interceptors(self)
-
end
-
-
# Delivers an mail object.
-
#
-
# Examples:
-
#
-
# mail = Mail.read('file.eml')
-
# mail.deliver
-
2
def deliver
-
inform_interceptors
-
if delivery_handler
-
delivery_handler.deliver_mail(self) { do_delivery }
-
else
-
do_delivery
-
end
-
inform_observers
-
self
-
end
-
-
# This method bypasses checking perform_deliveries and raise_delivery_errors,
-
# so use with caution.
-
#
-
# It still however fires off the interceptors and calls the observers callbacks if they are defined.
-
#
-
# Returns self
-
2
def deliver!
-
inform_interceptors
-
response = delivery_method.deliver!(self)
-
inform_observers
-
delivery_method.settings[:return_response] ? response : self
-
end
-
-
2
def delivery_method(method = nil, settings = {})
-
unless method
-
@delivery_method
-
else
-
@delivery_method = Configuration.instance.lookup_delivery_method(method).new(settings)
-
end
-
end
-
-
2
def reply(*args, &block)
-
self.class.new.tap do |reply|
-
if message_id
-
bracketed_message_id = "<#{message_id}>"
-
reply.in_reply_to = bracketed_message_id
-
if !references.nil?
-
refs = [references].flatten.map { |r| "<#{r}>" }
-
refs << bracketed_message_id
-
reply.references = refs.join(' ')
-
elsif !in_reply_to.nil? && !in_reply_to.kind_of?(Array)
-
reply.references = "<#{in_reply_to}> #{bracketed_message_id}"
-
end
-
reply.references ||= bracketed_message_id
-
end
-
if subject
-
reply.subject = subject =~ /^Re:/i ? subject : "RE: #{subject}"
-
end
-
if reply_to || from
-
reply.to = self[reply_to ? :reply_to : :from].to_s
-
end
-
if to
-
reply.from = self[:to].formatted.first.to_s
-
end
-
-
unless args.empty?
-
if args.flatten.first.respond_to?(:each_pair)
-
reply.send(:init_with_hash, args.flatten.first)
-
else
-
reply.send(:init_with_string, args.flatten[0].to_s.strip)
-
end
-
end
-
-
if block_given?
-
reply.instance_eval(&block)
-
end
-
end
-
end
-
-
# Provides the operator needed for sort et al.
-
#
-
# Compares this mail object with another mail object, this is done by date, so an
-
# email that is older than another will appear first.
-
#
-
# Example:
-
#
-
# mail1 = Mail.new do
-
# date(Time.now)
-
# end
-
# mail2 = Mail.new do
-
# date(Time.now - 86400) # 1 day older
-
# end
-
# [mail2, mail1].sort #=> [mail2, mail1]
-
2
def <=>(other)
-
if other.nil?
-
1
-
else
-
self.date <=> other.date
-
end
-
end
-
-
# Two emails are the same if they have the same fields and body contents. One
-
# gotcha here is that Mail will insert Message-IDs when calling encoded, so doing
-
# mail1.encoded == mail2.encoded is most probably not going to return what you think
-
# as the assigned Message-IDs by Mail (if not already defined as the same) will ensure
-
# that the two objects are unique, and this comparison will ALWAYS return false.
-
#
-
# So the == operator has been defined like so: Two messages are the same if they have
-
# the same content, ignoring the Message-ID field, unless BOTH emails have a defined and
-
# different Message-ID value, then they are false.
-
#
-
# So, in practice the == operator works like this:
-
#
-
# m1 = Mail.new("Subject: Hello\r\n\r\nHello")
-
# m2 = Mail.new("Subject: Hello\r\n\r\nHello")
-
# m1 == m2 #=> true
-
#
-
# m1 = Mail.new("Subject: Hello\r\n\r\nHello")
-
# m2 = Mail.new("Message-ID: <1234@test>\r\nSubject: Hello\r\n\r\nHello")
-
# m1 == m2 #=> true
-
#
-
# m1 = Mail.new("Message-ID: <1234@test>\r\nSubject: Hello\r\n\r\nHello")
-
# m2 = Mail.new("Subject: Hello\r\n\r\nHello")
-
# m1 == m2 #=> true
-
#
-
# m1 = Mail.new("Message-ID: <1234@test>\r\nSubject: Hello\r\n\r\nHello")
-
# m2 = Mail.new("Message-ID: <1234@test>\r\nSubject: Hello\r\n\r\nHello")
-
# m1 == m2 #=> true
-
#
-
# m1 = Mail.new("Message-ID: <1234@test>\r\nSubject: Hello\r\n\r\nHello")
-
# m2 = Mail.new("Message-ID: <DIFFERENT@test>\r\nSubject: Hello\r\n\r\nHello")
-
# m1 == m2 #=> false
-
2
def ==(other)
-
return false unless other.respond_to?(:encoded)
-
-
if self.message_id && other.message_id
-
self.encoded == other.encoded
-
else
-
self_message_id, other_message_id = self.message_id, other.message_id
-
begin
-
self.message_id, other.message_id = '<temp@test>', '<temp@test>'
-
self.encoded == other.encoded
-
ensure
-
self.message_id, other.message_id = self_message_id, other_message_id
-
end
-
end
-
end
-
-
2
def initialize_copy(original)
-
super
-
@header = @header.dup
-
end
-
-
# Provides access to the raw source of the message as it was when it
-
# was instantiated. This is set at initialization and so is untouched
-
# by the parsers or decoder / encoders
-
#
-
# Example:
-
#
-
# mail = Mail.new('This is an invalid email message')
-
# mail.raw_source #=> "This is an invalid email message"
-
2
def raw_source
-
@raw_source
-
end
-
-
# Sets the envelope from for the email
-
2
def set_envelope( val )
-
@raw_envelope = val
-
@envelope = Mail::Envelope.new( val )
-
end
-
-
# The raw_envelope is the From mikel@test.lindsaar.net Mon May 2 16:07:05 2009
-
# type field that you can see at the top of any email that has come
-
# from a mailbox
-
2
def raw_envelope
-
@raw_envelope
-
end
-
-
2
def envelope_from
-
@envelope ? @envelope.from : nil
-
end
-
-
2
def envelope_date
-
@envelope ? @envelope.date : nil
-
end
-
-
# Sets the header of the message object.
-
#
-
# Example:
-
#
-
# mail.header = 'To: mikel@test.lindsaar.net\r\nFrom: Bob@bob.com'
-
# mail.header #=> <#Mail::Header
-
2
def header=(value)
-
@header = Mail::Header.new(value, charset)
-
end
-
-
# Returns the header object of the message object. Or, if passed
-
# a parameter sets the value.
-
#
-
# Example:
-
#
-
# mail = Mail::Message.new('To: mikel\r\nFrom: you')
-
# mail.header #=> #<Mail::Header:0x13ce14 @raw_source="To: mikel\r\nFr...
-
#
-
# mail.header #=> nil
-
# mail.header 'To: mikel\r\nFrom: you'
-
# mail.header #=> #<Mail::Header:0x13ce14 @raw_source="To: mikel\r\nFr...
-
2
def header(value = nil)
-
value ? self.header = value : @header
-
end
-
-
# Provides a way to set custom headers, by passing in a hash
-
2
def headers(hash = {})
-
hash.each_pair do |k,v|
-
header[k] = v
-
end
-
end
-
-
# Returns a list of parser errors on the header, each field that had an error
-
# will be reparsed as an unstructured field to preserve the data inside, but
-
# will not be used for further processing.
-
#
-
# It returns a nested array of [field_name, value, original_error_message]
-
# per error found.
-
#
-
# Example:
-
#
-
# message = Mail.new("Content-Transfer-Encoding: weirdo\r\n")
-
# message.errors.size #=> 1
-
# message.errors.first[0] #=> "Content-Transfer-Encoding"
-
# message.errors.first[1] #=> "weirdo"
-
# message.errors.first[3] #=> <The original error message exception>
-
#
-
# This is a good first defence on detecting spam by the way. Some spammers send
-
# invalid emails to try and get email parsers to give up parsing them.
-
2
def errors
-
header.errors
-
end
-
-
# Returns the Bcc value of the mail object as an array of strings of
-
# address specs.
-
#
-
# Example:
-
#
-
# mail.bcc = 'Mikel <mikel@test.lindsaar.net>'
-
# mail.bcc #=> ['mikel@test.lindsaar.net']
-
# mail.bcc = 'Mikel <mikel@test.lindsaar.net>, ada@test.lindsaar.net'
-
# mail.bcc #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
-
#
-
# Also allows you to set the value by passing a value as a parameter
-
#
-
# Example:
-
#
-
# mail.bcc 'Mikel <mikel@test.lindsaar.net>'
-
# mail.bcc #=> ['mikel@test.lindsaar.net']
-
#
-
# Additionally, you can append new addresses to the returned Array like
-
# object.
-
#
-
# Example:
-
#
-
# mail.bcc 'Mikel <mikel@test.lindsaar.net>'
-
# mail.bcc << 'ada@test.lindsaar.net'
-
# mail.bcc #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
-
2
def bcc( val = nil )
-
default :bcc, val
-
end
-
-
# Sets the Bcc value of the mail object, pass in a string of the field
-
#
-
# Example:
-
#
-
# mail.bcc = 'Mikel <mikel@test.lindsaar.net>'
-
# mail.bcc #=> ['mikel@test.lindsaar.net']
-
# mail.bcc = 'Mikel <mikel@test.lindsaar.net>, ada@test.lindsaar.net'
-
# mail.bcc #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
-
2
def bcc=( val )
-
header[:bcc] = val
-
end
-
-
# Returns the Cc value of the mail object as an array of strings of
-
# address specs.
-
#
-
# Example:
-
#
-
# mail.cc = 'Mikel <mikel@test.lindsaar.net>'
-
# mail.cc #=> ['mikel@test.lindsaar.net']
-
# mail.cc = 'Mikel <mikel@test.lindsaar.net>, ada@test.lindsaar.net'
-
# mail.cc #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
-
#
-
# Also allows you to set the value by passing a value as a parameter
-
#
-
# Example:
-
#
-
# mail.cc 'Mikel <mikel@test.lindsaar.net>'
-
# mail.cc #=> ['mikel@test.lindsaar.net']
-
#
-
# Additionally, you can append new addresses to the returned Array like
-
# object.
-
#
-
# Example:
-
#
-
# mail.cc 'Mikel <mikel@test.lindsaar.net>'
-
# mail.cc << 'ada@test.lindsaar.net'
-
# mail.cc #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
-
2
def cc( val = nil )
-
default :cc, val
-
end
-
-
# Sets the Cc value of the mail object, pass in a string of the field
-
#
-
# Example:
-
#
-
# mail.cc = 'Mikel <mikel@test.lindsaar.net>'
-
# mail.cc #=> ['mikel@test.lindsaar.net']
-
# mail.cc = 'Mikel <mikel@test.lindsaar.net>, ada@test.lindsaar.net'
-
# mail.cc #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
-
2
def cc=( val )
-
header[:cc] = val
-
end
-
-
2
def comments( val = nil )
-
default :comments, val
-
end
-
-
2
def comments=( val )
-
header[:comments] = val
-
end
-
-
2
def content_description( val = nil )
-
default :content_description, val
-
end
-
-
2
def content_description=( val )
-
header[:content_description] = val
-
end
-
-
2
def content_disposition( val = nil )
-
default :content_disposition, val
-
end
-
-
2
def content_disposition=( val )
-
header[:content_disposition] = val
-
end
-
-
2
def content_id( val = nil )
-
default :content_id, val
-
end
-
-
2
def content_id=( val )
-
header[:content_id] = val
-
end
-
-
2
def content_location( val = nil )
-
default :content_location, val
-
end
-
-
2
def content_location=( val )
-
header[:content_location] = val
-
end
-
-
2
def content_transfer_encoding( val = nil )
-
default :content_transfer_encoding, val
-
end
-
-
2
def content_transfer_encoding=( val )
-
header[:content_transfer_encoding] = val
-
end
-
-
2
def content_type( val = nil )
-
default :content_type, val
-
end
-
-
2
def content_type=( val )
-
header[:content_type] = val
-
end
-
-
2
def date( val = nil )
-
default :date, val
-
end
-
-
2
def date=( val )
-
header[:date] = val
-
end
-
-
2
def transport_encoding( val = nil)
-
if val
-
self.transport_encoding = val
-
else
-
@transport_encoding
-
end
-
end
-
-
2
def transport_encoding=( val )
-
@transport_encoding = Mail::Encodings.get_encoding(val)
-
end
-
-
# Returns the From value of the mail object as an array of strings of
-
# address specs.
-
#
-
# Example:
-
#
-
# mail.from = 'Mikel <mikel@test.lindsaar.net>'
-
# mail.from #=> ['mikel@test.lindsaar.net']
-
# mail.from = 'Mikel <mikel@test.lindsaar.net>, ada@test.lindsaar.net'
-
# mail.from #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
-
#
-
# Also allows you to set the value by passing a value as a parameter
-
#
-
# Example:
-
#
-
# mail.from 'Mikel <mikel@test.lindsaar.net>'
-
# mail.from #=> ['mikel@test.lindsaar.net']
-
#
-
# Additionally, you can append new addresses to the returned Array like
-
# object.
-
#
-
# Example:
-
#
-
# mail.from 'Mikel <mikel@test.lindsaar.net>'
-
# mail.from << 'ada@test.lindsaar.net'
-
# mail.from #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
-
2
def from( val = nil )
-
default :from, val
-
end
-
-
# Sets the From value of the mail object, pass in a string of the field
-
#
-
# Example:
-
#
-
# mail.from = 'Mikel <mikel@test.lindsaar.net>'
-
# mail.from #=> ['mikel@test.lindsaar.net']
-
# mail.from = 'Mikel <mikel@test.lindsaar.net>, ada@test.lindsaar.net'
-
# mail.from #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
-
2
def from=( val )
-
header[:from] = val
-
end
-
-
2
def in_reply_to( val = nil )
-
default :in_reply_to, val
-
end
-
-
2
def in_reply_to=( val )
-
header[:in_reply_to] = val
-
end
-
-
2
def keywords( val = nil )
-
default :keywords, val
-
end
-
-
2
def keywords=( val )
-
header[:keywords] = val
-
end
-
-
# Returns the Message-ID of the mail object. Note, per RFC 2822 the Message ID
-
# consists of what is INSIDE the < > usually seen in the mail header, so this method
-
# will return only what is inside.
-
#
-
# Example:
-
#
-
# mail.message_id = '<1234@message.id>'
-
# mail.message_id #=> '1234@message.id'
-
#
-
# Also allows you to set the Message-ID by passing a string as a parameter
-
#
-
# mail.message_id '<1234@message.id>'
-
# mail.message_id #=> '1234@message.id'
-
2
def message_id( val = nil )
-
default :message_id, val
-
end
-
-
# Sets the Message-ID. Note, per RFC 2822 the Message ID consists of what is INSIDE
-
# the < > usually seen in the mail header, so this method will return only what is inside.
-
#
-
# mail.message_id = '<1234@message.id>'
-
# mail.message_id #=> '1234@message.id'
-
2
def message_id=( val )
-
header[:message_id] = val
-
end
-
-
# Returns the MIME version of the email as a string
-
#
-
# Example:
-
#
-
# mail.mime_version = '1.0'
-
# mail.mime_version #=> '1.0'
-
#
-
# Also allows you to set the MIME version by passing a string as a parameter.
-
#
-
# Example:
-
#
-
# mail.mime_version '1.0'
-
# mail.mime_version #=> '1.0'
-
2
def mime_version( val = nil )
-
default :mime_version, val
-
end
-
-
# Sets the MIME version of the email by accepting a string
-
#
-
# Example:
-
#
-
# mail.mime_version = '1.0'
-
# mail.mime_version #=> '1.0'
-
2
def mime_version=( val )
-
header[:mime_version] = val
-
end
-
-
2
def received( val = nil )
-
if val
-
header[:received] = val
-
else
-
header[:received]
-
end
-
end
-
-
2
def received=( val )
-
header[:received] = val
-
end
-
-
2
def references( val = nil )
-
default :references, val
-
end
-
-
2
def references=( val )
-
header[:references] = val
-
end
-
-
# Returns the Reply-To value of the mail object as an array of strings of
-
# address specs.
-
#
-
# Example:
-
#
-
# mail.reply_to = 'Mikel <mikel@test.lindsaar.net>'
-
# mail.reply_to #=> ['mikel@test.lindsaar.net']
-
# mail.reply_to = 'Mikel <mikel@test.lindsaar.net>, ada@test.lindsaar.net'
-
# mail.reply_to #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
-
#
-
# Also allows you to set the value by passing a value as a parameter
-
#
-
# Example:
-
#
-
# mail.reply_to 'Mikel <mikel@test.lindsaar.net>'
-
# mail.reply_to #=> ['mikel@test.lindsaar.net']
-
#
-
# Additionally, you can append new addresses to the returned Array like
-
# object.
-
#
-
# Example:
-
#
-
# mail.reply_to 'Mikel <mikel@test.lindsaar.net>'
-
# mail.reply_to << 'ada@test.lindsaar.net'
-
# mail.reply_to #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
-
2
def reply_to( val = nil )
-
default :reply_to, val
-
end
-
-
# Sets the Reply-To value of the mail object, pass in a string of the field
-
#
-
# Example:
-
#
-
# mail.reply_to = 'Mikel <mikel@test.lindsaar.net>'
-
# mail.reply_to #=> ['mikel@test.lindsaar.net']
-
# mail.reply_to = 'Mikel <mikel@test.lindsaar.net>, ada@test.lindsaar.net'
-
# mail.reply_to #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
-
2
def reply_to=( val )
-
header[:reply_to] = val
-
end
-
-
# Returns the Resent-Bcc value of the mail object as an array of strings of
-
# address specs.
-
#
-
# Example:
-
#
-
# mail.resent_bcc = 'Mikel <mikel@test.lindsaar.net>'
-
# mail.resent_bcc #=> ['mikel@test.lindsaar.net']
-
# mail.resent_bcc = 'Mikel <mikel@test.lindsaar.net>, ada@test.lindsaar.net'
-
# mail.resent_bcc #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
-
#
-
# Also allows you to set the value by passing a value as a parameter
-
#
-
# Example:
-
#
-
# mail.resent_bcc 'Mikel <mikel@test.lindsaar.net>'
-
# mail.resent_bcc #=> ['mikel@test.lindsaar.net']
-
#
-
# Additionally, you can append new addresses to the returned Array like
-
# object.
-
#
-
# Example:
-
#
-
# mail.resent_bcc 'Mikel <mikel@test.lindsaar.net>'
-
# mail.resent_bcc << 'ada@test.lindsaar.net'
-
# mail.resent_bcc #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
-
2
def resent_bcc( val = nil )
-
default :resent_bcc, val
-
end
-
-
# Sets the Resent-Bcc value of the mail object, pass in a string of the field
-
#
-
# Example:
-
#
-
# mail.resent_bcc = 'Mikel <mikel@test.lindsaar.net>'
-
# mail.resent_bcc #=> ['mikel@test.lindsaar.net']
-
# mail.resent_bcc = 'Mikel <mikel@test.lindsaar.net>, ada@test.lindsaar.net'
-
# mail.resent_bcc #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
-
2
def resent_bcc=( val )
-
header[:resent_bcc] = val
-
end
-
-
# Returns the Resent-Cc value of the mail object as an array of strings of
-
# address specs.
-
#
-
# Example:
-
#
-
# mail.resent_cc = 'Mikel <mikel@test.lindsaar.net>'
-
# mail.resent_cc #=> ['mikel@test.lindsaar.net']
-
# mail.resent_cc = 'Mikel <mikel@test.lindsaar.net>, ada@test.lindsaar.net'
-
# mail.resent_cc #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
-
#
-
# Also allows you to set the value by passing a value as a parameter
-
#
-
# Example:
-
#
-
# mail.resent_cc 'Mikel <mikel@test.lindsaar.net>'
-
# mail.resent_cc #=> ['mikel@test.lindsaar.net']
-
#
-
# Additionally, you can append new addresses to the returned Array like
-
# object.
-
#
-
# Example:
-
#
-
# mail.resent_cc 'Mikel <mikel@test.lindsaar.net>'
-
# mail.resent_cc << 'ada@test.lindsaar.net'
-
# mail.resent_cc #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
-
2
def resent_cc( val = nil )
-
default :resent_cc, val
-
end
-
-
# Sets the Resent-Cc value of the mail object, pass in a string of the field
-
#
-
# Example:
-
#
-
# mail.resent_cc = 'Mikel <mikel@test.lindsaar.net>'
-
# mail.resent_cc #=> ['mikel@test.lindsaar.net']
-
# mail.resent_cc = 'Mikel <mikel@test.lindsaar.net>, ada@test.lindsaar.net'
-
# mail.resent_cc #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
-
2
def resent_cc=( val )
-
header[:resent_cc] = val
-
end
-
-
2
def resent_date( val = nil )
-
default :resent_date, val
-
end
-
-
2
def resent_date=( val )
-
header[:resent_date] = val
-
end
-
-
# Returns the Resent-From value of the mail object as an array of strings of
-
# address specs.
-
#
-
# Example:
-
#
-
# mail.resent_from = 'Mikel <mikel@test.lindsaar.net>'
-
# mail.resent_from #=> ['mikel@test.lindsaar.net']
-
# mail.resent_from = 'Mikel <mikel@test.lindsaar.net>, ada@test.lindsaar.net'
-
# mail.resent_from #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
-
#
-
# Also allows you to set the value by passing a value as a parameter
-
#
-
# Example:
-
#
-
# mail.resent_from ['Mikel <mikel@test.lindsaar.net>']
-
# mail.resent_from #=> 'mikel@test.lindsaar.net'
-
#
-
# Additionally, you can append new addresses to the returned Array like
-
# object.
-
#
-
# Example:
-
#
-
# mail.resent_from 'Mikel <mikel@test.lindsaar.net>'
-
# mail.resent_from << 'ada@test.lindsaar.net'
-
# mail.resent_from #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
-
2
def resent_from( val = nil )
-
default :resent_from, val
-
end
-
-
# Sets the Resent-From value of the mail object, pass in a string of the field
-
#
-
# Example:
-
#
-
# mail.resent_from = 'Mikel <mikel@test.lindsaar.net>'
-
# mail.resent_from #=> ['mikel@test.lindsaar.net']
-
# mail.resent_from = 'Mikel <mikel@test.lindsaar.net>, ada@test.lindsaar.net'
-
# mail.resent_from #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
-
2
def resent_from=( val )
-
header[:resent_from] = val
-
end
-
-
2
def resent_message_id( val = nil )
-
default :resent_message_id, val
-
end
-
-
2
def resent_message_id=( val )
-
header[:resent_message_id] = val
-
end
-
-
# Returns the Resent-Sender value of the mail object, as a single string of an address
-
# spec. A sender per RFC 2822 must be a single address, so you can not append to
-
# this address.
-
#
-
# Example:
-
#
-
# mail.resent_sender = 'Mikel <mikel@test.lindsaar.net>'
-
# mail.resent_sender #=> 'mikel@test.lindsaar.net'
-
#
-
# Also allows you to set the value by passing a value as a parameter
-
#
-
# Example:
-
#
-
# mail.resent_sender 'Mikel <mikel@test.lindsaar.net>'
-
# mail.resent_sender #=> 'mikel@test.lindsaar.net'
-
2
def resent_sender( val = nil )
-
default :resent_sender, val
-
end
-
-
# Sets the Resent-Sender value of the mail object, pass in a string of the field
-
#
-
# Example:
-
#
-
# mail.resent_sender = 'Mikel <mikel@test.lindsaar.net>'
-
# mail.resent_sender #=> 'mikel@test.lindsaar.net'
-
2
def resent_sender=( val )
-
header[:resent_sender] = val
-
end
-
-
# Returns the Resent-To value of the mail object as an array of strings of
-
# address specs.
-
#
-
# Example:
-
#
-
# mail.resent_to = 'Mikel <mikel@test.lindsaar.net>'
-
# mail.resent_to #=> ['mikel@test.lindsaar.net']
-
# mail.resent_to = 'Mikel <mikel@test.lindsaar.net>, ada@test.lindsaar.net'
-
# mail.resent_to #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
-
#
-
# Also allows you to set the value by passing a value as a parameter
-
#
-
# Example:
-
#
-
# mail.resent_to 'Mikel <mikel@test.lindsaar.net>'
-
# mail.resent_to #=> ['mikel@test.lindsaar.net']
-
#
-
# Additionally, you can append new addresses to the returned Array like
-
# object.
-
#
-
# Example:
-
#
-
# mail.resent_to 'Mikel <mikel@test.lindsaar.net>'
-
# mail.resent_to << 'ada@test.lindsaar.net'
-
# mail.resent_to #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
-
2
def resent_to( val = nil )
-
default :resent_to, val
-
end
-
-
# Sets the Resent-To value of the mail object, pass in a string of the field
-
#
-
# Example:
-
#
-
# mail.resent_to = 'Mikel <mikel@test.lindsaar.net>'
-
# mail.resent_to #=> ['mikel@test.lindsaar.net']
-
# mail.resent_to = 'Mikel <mikel@test.lindsaar.net>, ada@test.lindsaar.net'
-
# mail.resent_to #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
-
2
def resent_to=( val )
-
header[:resent_to] = val
-
end
-
-
# Returns the return path of the mail object, or sets it if you pass a string
-
2
def return_path( val = nil )
-
default :return_path, val
-
end
-
-
# Sets the return path of the object
-
2
def return_path=( val )
-
header[:return_path] = val
-
end
-
-
# Returns the Sender value of the mail object, as a single string of an address
-
# spec. A sender per RFC 2822 must be a single address.
-
#
-
# Example:
-
#
-
# mail.sender = 'Mikel <mikel@test.lindsaar.net>'
-
# mail.sender #=> 'mikel@test.lindsaar.net'
-
#
-
# Also allows you to set the value by passing a value as a parameter
-
#
-
# Example:
-
#
-
# mail.sender 'Mikel <mikel@test.lindsaar.net>'
-
# mail.sender #=> 'mikel@test.lindsaar.net'
-
2
def sender( val = nil )
-
default :sender, val
-
end
-
-
# Sets the Sender value of the mail object, pass in a string of the field
-
#
-
# Example:
-
#
-
# mail.sender = 'Mikel <mikel@test.lindsaar.net>'
-
# mail.sender #=> 'mikel@test.lindsaar.net'
-
2
def sender=( val )
-
header[:sender] = val
-
end
-
-
# Returns the SMTP Envelope From value of the mail object, as a single
-
# string of an address spec.
-
#
-
# Defaults to Return-Path, Sender, or the first From address.
-
#
-
# Example:
-
#
-
# mail.smtp_envelope_from = 'Mikel <mikel@test.lindsaar.net>'
-
# mail.smtp_envelope_from #=> 'mikel@test.lindsaar.net'
-
#
-
# Also allows you to set the value by passing a value as a parameter
-
#
-
# Example:
-
#
-
# mail.smtp_envelope_from 'Mikel <mikel@test.lindsaar.net>'
-
# mail.smtp_envelope_from #=> 'mikel@test.lindsaar.net'
-
2
def smtp_envelope_from( val = nil )
-
if val
-
self.smtp_envelope_from = val
-
else
-
@smtp_envelope_from || return_path || sender || from_addrs.first
-
end
-
end
-
-
# Sets the From address on the SMTP Envelope.
-
#
-
# Example:
-
#
-
# mail.smtp_envelope_from = 'Mikel <mikel@test.lindsaar.net>'
-
# mail.smtp_envelope_from #=> 'mikel@test.lindsaar.net'
-
2
def smtp_envelope_from=( val )
-
@smtp_envelope_from = val
-
end
-
-
# Returns the SMTP Envelope To value of the mail object.
-
#
-
# Defaults to #destinations: To, Cc, and Bcc addresses.
-
#
-
# Example:
-
#
-
# mail.smtp_envelope_to = 'Mikel <mikel@test.lindsaar.net>'
-
# mail.smtp_envelope_to #=> 'mikel@test.lindsaar.net'
-
#
-
# Also allows you to set the value by passing a value as a parameter
-
#
-
# Example:
-
#
-
# mail.smtp_envelope_to ['Mikel <mikel@test.lindsaar.net>', 'Lindsaar <lindsaar@test.lindsaar.net>']
-
# mail.smtp_envelope_to #=> ['mikel@test.lindsaar.net', 'lindsaar@test.lindsaar.net']
-
2
def smtp_envelope_to( val = nil )
-
if val
-
self.smtp_envelope_to = val
-
else
-
@smtp_envelope_to || destinations
-
end
-
end
-
-
# Sets the To addresses on the SMTP Envelope.
-
#
-
# Example:
-
#
-
# mail.smtp_envelope_to = 'Mikel <mikel@test.lindsaar.net>'
-
# mail.smtp_envelope_to #=> 'mikel@test.lindsaar.net'
-
#
-
# mail.smtp_envelope_to = ['Mikel <mikel@test.lindsaar.net>', 'Lindsaar <lindsaar@test.lindsaar.net>']
-
# mail.smtp_envelope_to #=> ['mikel@test.lindsaar.net', 'lindsaar@test.lindsaar.net']
-
2
def smtp_envelope_to=( val )
-
@smtp_envelope_to =
-
case val
-
when Array, NilClass
-
val
-
else
-
[val]
-
end
-
end
-
-
# Returns the decoded value of the subject field, as a single string.
-
#
-
# Example:
-
#
-
# mail.subject = "G'Day mate"
-
# mail.subject #=> "G'Day mate"
-
# mail.subject = '=?UTF-8?Q?This_is_=E3=81=82_string?='
-
# mail.subject #=> "This is あ string"
-
#
-
# Also allows you to set the value by passing a value as a parameter
-
#
-
# Example:
-
#
-
# mail.subject "G'Day mate"
-
# mail.subject #=> "G'Day mate"
-
2
def subject( val = nil )
-
default :subject, val
-
end
-
-
# Sets the Subject value of the mail object, pass in a string of the field
-
#
-
# Example:
-
#
-
# mail.subject = '=?UTF-8?Q?This_is_=E3=81=82_string?='
-
# mail.subject #=> "This is あ string"
-
2
def subject=( val )
-
header[:subject] = val
-
end
-
-
# Returns the To value of the mail object as an array of strings of
-
# address specs.
-
#
-
# Example:
-
#
-
# mail.to = 'Mikel <mikel@test.lindsaar.net>'
-
# mail.to #=> ['mikel@test.lindsaar.net']
-
# mail.to = 'Mikel <mikel@test.lindsaar.net>, ada@test.lindsaar.net'
-
# mail.to #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
-
#
-
# Also allows you to set the value by passing a value as a parameter
-
#
-
# Example:
-
#
-
# mail.to 'Mikel <mikel@test.lindsaar.net>'
-
# mail.to #=> ['mikel@test.lindsaar.net']
-
#
-
# Additionally, you can append new addresses to the returned Array like
-
# object.
-
#
-
# Example:
-
#
-
# mail.to 'Mikel <mikel@test.lindsaar.net>'
-
# mail.to << 'ada@test.lindsaar.net'
-
# mail.to #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
-
2
def to( val = nil )
-
default :to, val
-
end
-
-
# Sets the To value of the mail object, pass in a string of the field
-
#
-
# Example:
-
#
-
# mail.to = 'Mikel <mikel@test.lindsaar.net>'
-
# mail.to #=> ['mikel@test.lindsaar.net']
-
# mail.to = 'Mikel <mikel@test.lindsaar.net>, ada@test.lindsaar.net'
-
# mail.to #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
-
2
def to=( val )
-
header[:to] = val
-
end
-
-
# Returns the default value of the field requested as a symbol.
-
#
-
# Each header field has a :default method which returns the most common use case for
-
# that field, for example, the date field types will return a DateTime object when
-
# sent :default, the subject, or unstructured fields will return a decoded string of
-
# their value, the address field types will return a single addr_spec or an array of
-
# addr_specs if there is more than one.
-
2
def default( sym, val = nil )
-
if val
-
header[sym] = val
-
else
-
header[sym].default if header[sym]
-
end
-
end
-
-
# Sets the body object of the message object.
-
#
-
# Example:
-
#
-
# mail.body = 'This is the body'
-
# mail.body #=> #<Mail::Body:0x13919c @raw_source="This is the bo...
-
#
-
# You can also reset the body of an Message object by setting body to nil
-
#
-
# Example:
-
#
-
# mail.body = 'this is the body'
-
# mail.body.encoded #=> 'this is the body'
-
# mail.body = nil
-
# mail.body.encoded #=> ''
-
#
-
# If you try and set the body of an email that is a multipart email, then instead
-
# of deleting all the parts of your email, mail will add a text/plain part to
-
# your email:
-
#
-
# mail.add_file 'somefilename.png'
-
# mail.parts.length #=> 1
-
# mail.body = "This is a body"
-
# mail.parts.length #=> 2
-
# mail.parts.last.content_type.content_type #=> 'This is a body'
-
2
def body=(value)
-
body_lazy(value)
-
end
-
-
# Returns the body of the message object. Or, if passed
-
# a parameter sets the value.
-
#
-
# Example:
-
#
-
# mail = Mail::Message.new('To: mikel\r\n\r\nThis is the body')
-
# mail.body #=> #<Mail::Body:0x13919c @raw_source="This is the bo...
-
#
-
# mail.body 'This is another body'
-
# mail.body #=> #<Mail::Body:0x13919c @raw_source="This is anothe...
-
2
def body(value = nil)
-
if value
-
self.body = value
-
# add_encoding_to_body
-
else
-
process_body_raw if @body_raw
-
@body
-
end
-
end
-
-
2
def body_encoding(value)
-
if value.nil?
-
body.encoding
-
else
-
body.encoding = value
-
end
-
end
-
-
2
def body_encoding=(value)
-
body.encoding = value
-
end
-
-
# Returns the list of addresses this message should be sent to by
-
# collecting the addresses off the to, cc and bcc fields.
-
#
-
# Example:
-
#
-
# mail.to = 'mikel@test.lindsaar.net'
-
# mail.cc = 'sam@test.lindsaar.net'
-
# mail.bcc = 'bob@test.lindsaar.net'
-
# mail.destinations.length #=> 3
-
# mail.destinations.first #=> 'mikel@test.lindsaar.net'
-
2
def destinations
-
[to_addrs, cc_addrs, bcc_addrs].compact.flatten
-
end
-
-
# Returns an array of addresses (the encoded value) in the From field,
-
# if no From field, returns an empty array
-
2
def from_addrs
-
from ? [from].flatten : []
-
end
-
-
# Returns an array of addresses (the encoded value) in the To field,
-
# if no To field, returns an empty array
-
2
def to_addrs
-
to ? [to].flatten : []
-
end
-
-
# Returns an array of addresses (the encoded value) in the Cc field,
-
# if no Cc field, returns an empty array
-
2
def cc_addrs
-
cc ? [cc].flatten : []
-
end
-
-
# Returns an array of addresses (the encoded value) in the Bcc field,
-
# if no Bcc field, returns an empty array
-
2
def bcc_addrs
-
bcc ? [bcc].flatten : []
-
end
-
-
# Allows you to add an arbitrary header
-
#
-
# Example:
-
#
-
# mail['foo'] = '1234'
-
# mail['foo'].to_s #=> '1234'
-
2
def []=(name, value)
-
if name.to_s == 'body'
-
self.body = value
-
elsif name.to_s =~ /content[-_]type/i
-
header[name] = value
-
elsif name.to_s == 'charset'
-
self.charset = value
-
else
-
header[name] = value
-
end
-
end
-
-
# Allows you to read an arbitrary header
-
#
-
# Example:
-
#
-
# mail['foo'] = '1234'
-
# mail['foo'].to_s #=> '1234'
-
2
def [](name)
-
header[underscoreize(name)]
-
end
-
-
# Method Missing in this implementation allows you to set any of the
-
# standard fields directly as you would the "to", "subject" etc.
-
#
-
# Those fields used most often (to, subject et al) are given their
-
# own method for ease of documentation and also to avoid the hook
-
# call to method missing.
-
#
-
# This will only catch the known fields listed in:
-
#
-
# Mail::Field::KNOWN_FIELDS
-
#
-
# as per RFC 2822, any ruby string or method name could pretty much
-
# be a field name, so we don't want to just catch ANYTHING sent to
-
# a message object and interpret it as a header.
-
#
-
# This method provides all three types of header call to set, read
-
# and explicitly set with the = operator
-
#
-
# Examples:
-
#
-
# mail.comments = 'These are some comments'
-
# mail.comments #=> 'These are some comments'
-
#
-
# mail.comments 'These are other comments'
-
# mail.comments #=> 'These are other comments'
-
#
-
#
-
# mail.date = 'Tue, 1 Jul 2003 10:52:37 +0200'
-
# mail.date.to_s #=> 'Tue, 1 Jul 2003 10:52:37 +0200'
-
#
-
# mail.date 'Tue, 1 Jul 2003 10:52:37 +0200'
-
# mail.date.to_s #=> 'Tue, 1 Jul 2003 10:52:37 +0200'
-
#
-
#
-
# mail.resent_msg_id = '<1234@resent_msg_id.lindsaar.net>'
-
# mail.resent_msg_id #=> '<1234@resent_msg_id.lindsaar.net>'
-
#
-
# mail.resent_msg_id '<4567@resent_msg_id.lindsaar.net>'
-
# mail.resent_msg_id #=> '<4567@resent_msg_id.lindsaar.net>'
-
2
def method_missing(name, *args, &block)
-
#:nodoc:
-
# Only take the structured fields, as we could take _anything_ really
-
# as it could become an optional field... "but therin lies the dark side"
-
field_name = underscoreize(name).chomp("=")
-
if Mail::Field::KNOWN_FIELDS.include?(field_name)
-
if args.empty?
-
header[field_name]
-
else
-
header[field_name] = args.first
-
end
-
else
-
super # otherwise pass it on
-
end
-
#:startdoc:
-
end
-
-
# Returns an FieldList of all the fields in the header in the order that
-
# they appear in the header
-
2
def header_fields
-
header.fields
-
end
-
-
# Returns true if the message has a message ID field, the field may or may
-
# not have a value, but the field exists or not.
-
2
def has_message_id?
-
header.has_message_id?
-
end
-
-
# Returns true if the message has a Date field, the field may or may
-
# not have a value, but the field exists or not.
-
2
def has_date?
-
header.has_date?
-
end
-
-
# Returns true if the message has a Mime-Version field, the field may or may
-
# not have a value, but the field exists or not.
-
2
def has_mime_version?
-
header.has_mime_version?
-
end
-
-
2
def has_content_type?
-
tmp = header[:content_type].main_type rescue nil
-
!!tmp
-
end
-
-
2
def has_charset?
-
tmp = header[:content_type].parameters rescue nil
-
!!(has_content_type? && tmp && tmp['charset'])
-
end
-
-
2
def has_content_transfer_encoding?
-
header[:content_transfer_encoding] && header[:content_transfer_encoding].errors.blank?
-
end
-
-
2
def has_transfer_encoding? # :nodoc:
-
STDERR.puts(":has_transfer_encoding? is deprecated in Mail 1.4.3. Please use has_content_transfer_encoding?\n#{caller}")
-
has_content_transfer_encoding?
-
end
-
-
# Creates a new empty Message-ID field and inserts it in the correct order
-
# into the Header. The MessageIdField object will automatically generate
-
# a unique message ID if you try and encode it or output it to_s without
-
# specifying a message id.
-
#
-
# It will preserve the message ID you specify if you do.
-
2
def add_message_id(msg_id_val = '')
-
header['message-id'] = msg_id_val
-
end
-
-
# Creates a new empty Date field and inserts it in the correct order
-
# into the Header. The DateField object will automatically generate
-
# DateTime.now's date if you try and encode it or output it to_s without
-
# specifying a date yourself.
-
#
-
# It will preserve any date you specify if you do.
-
2
def add_date(date_val = '')
-
header['date'] = date_val
-
end
-
-
# Creates a new empty Mime Version field and inserts it in the correct order
-
# into the Header. The MimeVersion object will automatically generate
-
# set itself to '1.0' if you try and encode it or output it to_s without
-
# specifying a version yourself.
-
#
-
# It will preserve any date you specify if you do.
-
2
def add_mime_version(ver_val = '')
-
header['mime-version'] = ver_val
-
end
-
-
# Adds a content type and charset if the body is US-ASCII
-
#
-
# Otherwise raises a warning
-
2
def add_content_type
-
header[:content_type] = 'text/plain'
-
end
-
-
# Adds a content type and charset if the body is US-ASCII
-
#
-
# Otherwise raises a warning
-
2
def add_charset
-
if !body.empty?
-
# Only give a warning if this isn't an attachment, has non US-ASCII and the user
-
# has not specified an encoding explicitly.
-
if @defaulted_charset && body.raw_source.not_ascii_only? && !self.attachment?
-
warning = "Non US-ASCII detected and no charset defined.\nDefaulting to UTF-8, set your own if this is incorrect.\n"
-
STDERR.puts(warning)
-
end
-
header[:content_type].parameters['charset'] = @charset
-
end
-
end
-
-
# Adds a content transfer encoding
-
#
-
# Otherwise raises a warning
-
2
def add_content_transfer_encoding
-
if body.only_us_ascii?
-
header[:content_transfer_encoding] = '7bit'
-
else
-
warning = "Non US-ASCII detected and no content-transfer-encoding defined.\nDefaulting to 8bit, set your own if this is incorrect.\n"
-
STDERR.puts(warning)
-
header[:content_transfer_encoding] = '8bit'
-
end
-
end
-
-
2
def add_transfer_encoding # :nodoc:
-
STDERR.puts(":add_transfer_encoding is deprecated in Mail 1.4.3. Please use add_content_transfer_encoding\n#{caller}")
-
add_content_transfer_encoding
-
end
-
-
2
def transfer_encoding # :nodoc:
-
STDERR.puts(":transfer_encoding is deprecated in Mail 1.4.3. Please use content_transfer_encoding\n#{caller}")
-
content_transfer_encoding
-
end
-
-
# Returns the MIME media type of part we are on, this is taken from the content-type header
-
2
def mime_type
-
has_content_type? ? header[:content_type].string : nil rescue nil
-
end
-
-
2
def message_content_type
-
STDERR.puts(":message_content_type is deprecated in Mail 1.4.3. Please use mime_type\n#{caller}")
-
mime_type
-
end
-
-
# Returns the character set defined in the content type field
-
2
def charset
-
if @header
-
has_content_type? ? content_type_parameters['charset'] : @charset
-
else
-
@charset
-
end
-
end
-
-
# Sets the charset to the supplied value.
-
2
def charset=(value)
-
@defaulted_charset = false
-
@charset = value
-
@header.charset = value
-
end
-
-
# Returns the main content type
-
2
def main_type
-
has_content_type? ? header[:content_type].main_type : nil rescue nil
-
end
-
-
# Returns the sub content type
-
2
def sub_type
-
has_content_type? ? header[:content_type].sub_type : nil rescue nil
-
end
-
-
# Returns the content type parameters
-
2
def mime_parameters
-
STDERR.puts(':mime_parameters is deprecated in Mail 1.4.3, please use :content_type_parameters instead')
-
content_type_parameters
-
end
-
-
# Returns the content type parameters
-
2
def content_type_parameters
-
has_content_type? ? header[:content_type].parameters : nil rescue nil
-
end
-
-
# Returns true if the message is multipart
-
2
def multipart?
-
has_content_type? ? !!(main_type =~ /^multipart$/i) : false
-
end
-
-
# Returns true if the message is a multipart/report
-
2
def multipart_report?
-
multipart? && sub_type =~ /^report$/i
-
end
-
-
# Returns true if the message is a multipart/report; report-type=delivery-status;
-
2
def delivery_status_report?
-
multipart_report? && content_type_parameters['report-type'] =~ /^delivery-status$/i
-
end
-
-
# returns the part in a multipart/report email that has the content-type delivery-status
-
2
def delivery_status_part
-
@delivery_stats_part ||= parts.select { |p| p.delivery_status_report_part? }.first
-
end
-
-
2
def bounced?
-
delivery_status_part and delivery_status_part.bounced?
-
end
-
-
2
def action
-
delivery_status_part and delivery_status_part.action
-
end
-
-
2
def final_recipient
-
delivery_status_part and delivery_status_part.final_recipient
-
end
-
-
2
def error_status
-
delivery_status_part and delivery_status_part.error_status
-
end
-
-
2
def diagnostic_code
-
delivery_status_part and delivery_status_part.diagnostic_code
-
end
-
-
2
def remote_mta
-
delivery_status_part and delivery_status_part.remote_mta
-
end
-
-
2
def retryable?
-
delivery_status_part and delivery_status_part.retryable?
-
end
-
-
# Returns the current boundary for this message part
-
2
def boundary
-
content_type_parameters ? content_type_parameters['boundary'] : nil
-
end
-
-
# Returns a parts list object of all the parts in the message
-
2
def parts
-
body.parts
-
end
-
-
# Returns an AttachmentsList object, which holds all of the attachments in
-
# the receiver object (either the entire email or a part within) and all
-
# of its descendants.
-
#
-
# It also allows you to add attachments to the mail object directly, like so:
-
#
-
# mail.attachments['filename.jpg'] = File.read('/path/to/filename.jpg')
-
#
-
# If you do this, then Mail will take the file name and work out the MIME media type
-
# set the Content-Type, Content-Disposition, Content-Transfer-Encoding and
-
# base64 encode the contents of the attachment all for you.
-
#
-
# You can also specify overrides if you want by passing a hash instead of a string:
-
#
-
# mail.attachments['filename.jpg'] = {:mime_type => 'application/x-gzip',
-
# :content => File.read('/path/to/filename.jpg')}
-
#
-
# If you want to use a different encoding than Base64, you can pass an encoding in,
-
# but then it is up to you to pass in the content pre-encoded, and don't expect
-
# Mail to know how to decode this data:
-
#
-
# file_content = SpecialEncode(File.read('/path/to/filename.jpg'))
-
# mail.attachments['filename.jpg'] = {:mime_type => 'application/x-gzip',
-
# :encoding => 'SpecialEncoding',
-
# :content => file_content }
-
#
-
# You can also search for specific attachments:
-
#
-
# # By Filename
-
# mail.attachments['filename.jpg'] #=> Mail::Part object or nil
-
#
-
# # or by index
-
# mail.attachments[0] #=> Mail::Part (first attachment)
-
#
-
2
def attachments
-
parts.attachments
-
end
-
-
2
def has_attachments?
-
!attachments.empty?
-
end
-
-
# Accessor for html_part
-
2
def html_part(&block)
-
if block_given?
-
self.html_part = Mail::Part.new(:content_type => 'text/html', &block)
-
else
-
@html_part || find_first_mime_type('text/html')
-
end
-
end
-
-
# Accessor for text_part
-
2
def text_part(&block)
-
if block_given?
-
self.text_part = Mail::Part.new(:content_type => 'text/plain', &block)
-
else
-
@text_part || find_first_mime_type('text/plain')
-
end
-
end
-
-
# Helper to add a html part to a multipart/alternative email. If this and
-
# text_part are both defined in a message, then it will be a multipart/alternative
-
# message and set itself that way.
-
2
def html_part=(msg)
-
# Assign the html part and set multipart/alternative if there's a text part.
-
if msg
-
@html_part = msg
-
@html_part.content_type = 'text/html' unless @html_part.has_content_type?
-
add_multipart_alternate_header if text_part
-
add_part @html_part
-
-
# If nil, delete the html part and back out of multipart/alternative.
-
elsif @html_part
-
parts.delete_if { |p| p.object_id == @html_part.object_id }
-
@html_part = nil
-
if text_part
-
self.content_type = nil
-
body.boundary = nil
-
end
-
end
-
end
-
-
# Helper to add a text part to a multipart/alternative email. If this and
-
# html_part are both defined in a message, then it will be a multipart/alternative
-
# message and set itself that way.
-
2
def text_part=(msg)
-
# Assign the text part and set multipart/alternative if there's an html part.
-
if msg
-
@text_part = msg
-
@text_part.content_type = 'text/plain' unless @text_part.has_content_type?
-
add_multipart_alternate_header if html_part
-
add_part @text_part
-
-
# If nil, delete the text part and back out of multipart/alternative.
-
elsif @text_part
-
parts.delete_if { |p| p.object_id == @text_part.object_id }
-
@text_part = nil
-
if html_part
-
self.content_type = nil
-
body.boundary = nil
-
end
-
end
-
end
-
-
# Adds a part to the parts list or creates the part list
-
2
def add_part(part)
-
if !body.multipart? && !self.body.decoded.blank?
-
@text_part = Mail::Part.new('Content-Type: text/plain;')
-
@text_part.body = body.decoded
-
self.body << @text_part
-
add_multipart_alternate_header
-
end
-
add_boundary
-
self.body << part
-
end
-
-
# Allows you to add a part in block form to an existing mail message object
-
#
-
# Example:
-
#
-
# mail = Mail.new do
-
# part :content_type => "multipart/alternative", :content_disposition => "inline" do |p|
-
# p.part :content_type => "text/plain", :body => "test text\nline #2"
-
# p.part :content_type => "text/html", :body => "<b>test</b> HTML<br/>\nline #2"
-
# end
-
# end
-
2
def part(params = {})
-
new_part = Part.new(params)
-
yield new_part if block_given?
-
add_part(new_part)
-
end
-
-
# Adds a file to the message. You have two options with this method, you can
-
# just pass in the absolute path to the file you want and Mail will read the file,
-
# get the filename from the path you pass in and guess the MIME media type, or you
-
# can pass in the filename as a string, and pass in the file content as a blob.
-
#
-
# Example:
-
#
-
# m = Mail.new
-
# m.add_file('/path/to/filename.png')
-
#
-
# m = Mail.new
-
# m.add_file(:filename => 'filename.png', :content => File.read('/path/to/file.jpg'))
-
#
-
# Note also that if you add a file to an existing message, Mail will convert that message
-
# to a MIME multipart email, moving whatever plain text body you had into its own text
-
# plain part.
-
#
-
# Example:
-
#
-
# m = Mail.new do
-
# body 'this is some text'
-
# end
-
# m.multipart? #=> false
-
# m.add_file('/path/to/filename.png')
-
# m.multipart? #=> true
-
# m.parts.first.content_type.content_type #=> 'text/plain'
-
# m.parts.last.content_type.content_type #=> 'image/png'
-
#
-
# See also #attachments
-
2
def add_file(values)
-
convert_to_multipart unless self.multipart? || self.body.decoded.blank?
-
add_multipart_mixed_header
-
if values.is_a?(String)
-
basename = File.basename(values)
-
filedata = File.open(values, 'rb') { |f| f.read }
-
else
-
basename = values[:filename]
-
filedata = values[:content] || File.open(values[:filename], 'rb') { |f| f.read }
-
end
-
self.attachments[basename] = filedata
-
end
-
-
2
def convert_to_multipart
-
text = body.decoded
-
self.body = ''
-
text_part = Mail::Part.new({:content_type => 'text/plain;',
-
:body => text})
-
text_part.charset = charset unless @defaulted_charset
-
self.body << text_part
-
end
-
-
# Encodes the message, calls encode on all its parts, gets an email message
-
# ready to send
-
2
def ready_to_send!
-
identify_and_set_transfer_encoding
-
parts.sort!([ "text/plain", "text/enriched", "text/html", "multipart/alternative" ])
-
parts.each do |part|
-
part.transport_encoding = transport_encoding
-
part.ready_to_send!
-
end
-
add_required_fields
-
end
-
-
2
def encode!
-
STDERR.puts("Deprecated in 1.1.0 in favour of :ready_to_send! as it is less confusing with encoding and decoding.")
-
ready_to_send!
-
end
-
-
# Outputs an encoded string representation of the mail message including
-
# all headers, attachments, etc. This is an encoded email in US-ASCII,
-
# so it is able to be directly sent to an email server.
-
2
def encoded
-
ready_to_send!
-
buffer = header.encoded
-
buffer << "\r\n"
-
buffer << body.encoded(content_transfer_encoding)
-
buffer
-
end
-
-
2
def without_attachments!
-
return self unless has_attachments?
-
-
parts.delete_if { |p| p.attachment? }
-
body_raw = if parts.empty?
-
''
-
else
-
body.encoded
-
end
-
-
@body = Mail::Body.new(body_raw)
-
-
self
-
end
-
-
2
def to_yaml(opts = {})
-
hash = {}
-
hash['headers'] = {}
-
header.fields.each do |field|
-
hash['headers'][field.name] = field.value
-
end
-
hash['delivery_handler'] = delivery_handler.to_s if delivery_handler
-
hash['transport_encoding'] = transport_encoding.to_s
-
special_variables = [:@header, :@delivery_handler, :@transport_encoding]
-
if multipart?
-
hash['multipart_body'] = []
-
body.parts.map { |part| hash['multipart_body'] << part.to_yaml }
-
special_variables.push(:@body, :@text_part, :@html_part)
-
end
-
(instance_variables.map(&:to_sym) - special_variables).each do |var|
-
hash[var.to_s] = instance_variable_get(var)
-
end
-
hash.to_yaml(opts)
-
end
-
-
2
def self.from_yaml(str)
-
hash = YAML.load(str)
-
m = self.new(:headers => hash['headers'])
-
hash.delete('headers')
-
hash.each do |k,v|
-
case
-
when k == 'delivery_handler'
-
begin
-
m.delivery_handler = Object.const_get(v) unless v.blank?
-
rescue NameError
-
end
-
when k == 'transport_encoding'
-
m.transport_encoding(v)
-
when k == 'multipart_body'
-
v.map {|part| m.add_part Mail::Part.from_yaml(part) }
-
when k =~ /^@/
-
m.instance_variable_set(k.to_sym, v)
-
end
-
end
-
m
-
end
-
-
2
def self.from_hash(hash)
-
Mail::Message.new(hash)
-
end
-
-
2
def to_s
-
encoded
-
end
-
-
2
def inspect
-
"#<#{self.class}:#{self.object_id}, Multipart: #{multipart?}, Headers: #{header.field_summary}>"
-
end
-
-
2
def decoded
-
case
-
when self.text?
-
decode_body_as_text
-
when self.attachment?
-
decode_body
-
when !self.multipart?
-
body.decoded
-
else
-
raise NoMethodError, 'Can not decode an entire message, try calling #decoded on the various fields and body or parts if it is a multipart message.'
-
end
-
end
-
-
2
def read
-
if self.attachment?
-
decode_body
-
else
-
raise NoMethodError, 'Can not call read on a part unless it is an attachment.'
-
end
-
end
-
-
2
def decode_body
-
body.decoded
-
end
-
-
# Returns true if this part is an attachment,
-
# false otherwise.
-
2
def attachment?
-
!!find_attachment
-
end
-
-
# Returns the attachment data if there is any
-
2
def attachment
-
@attachment
-
end
-
-
# Returns the filename of the attachment
-
2
def filename
-
find_attachment
-
end
-
-
2
def all_parts
-
parts.map { |p| [p, p.all_parts] }.flatten
-
end
-
-
2
def find_first_mime_type(mt)
-
all_parts.detect { |p| p.mime_type == mt && !p.attachment? }
-
end
-
-
# Skips the deletion of this message. All other messages
-
# flagged for delete still will be deleted at session close (i.e. when
-
# #find exits). Only has an effect if you're using #find_and_delete
-
# or #find with :delete_after_find set to true.
-
2
def skip_deletion
-
@mark_for_delete = false
-
end
-
-
# Sets whether this message should be deleted at session close (i.e.
-
# after #find). Message will only be deleted if messages are retrieved
-
# using the #find_and_delete method, or by calling #find with
-
# :delete_after_find set to true.
-
2
def mark_for_delete=(value = true)
-
@mark_for_delete = value
-
end
-
-
# Returns whether message will be marked for deletion.
-
# If so, the message will be deleted at session close (i.e. after #find
-
# exits), but only if also using the #find_and_delete method, or by
-
# calling #find with :delete_after_find set to true.
-
#
-
# Side-note: Just to be clear, this method will return true even if
-
# the message hasn't yet been marked for delete on the mail server.
-
# However, if this method returns true, it *will be* marked on the
-
# server after each block yields back to #find or #find_and_delete.
-
2
def is_marked_for_delete?
-
return @mark_for_delete
-
end
-
-
2
def text?
-
has_content_type? ? !!(main_type =~ /^text$/i) : false
-
end
-
-
2
private
-
-
2
HEADER_SEPARATOR = /#{CRLF}#{CRLF}|#{CRLF}#{WSP}*#{CRLF}(?!#{WSP})/m
-
-
# 2.1. General Description
-
# A message consists of header fields (collectively called "the header
-
# of the message") followed, optionally, by a body. The header is a
-
# sequence of lines of characters with special syntax as defined in
-
# this standard. The body is simply a sequence of characters that
-
# follows the header and is separated from the header by an empty line
-
# (i.e., a line with nothing preceding the CRLF).
-
#
-
# Additionally, I allow for the case where someone might have put whitespace
-
# on the "gap line"
-
2
def parse_message
-
header_part, body_part = raw_source.lstrip.split(HEADER_SEPARATOR, 2)
-
self.header = header_part
-
self.body = body_part
-
end
-
-
2
def raw_source=(value)
-
value = value.dup.force_encoding(Encoding::BINARY) if RUBY_VERSION >= "1.9.1"
-
@raw_source = value.to_crlf
-
end
-
-
# see comments to body=. We take data and process it lazily
-
2
def body_lazy(value)
-
process_body_raw if @body_raw && value
-
case
-
when value == nil || value.length<=0
-
@body = Mail::Body.new('')
-
@body_raw = nil
-
add_encoding_to_body
-
when @body && @body.multipart?
-
@body << Mail::Part.new(value)
-
add_encoding_to_body
-
else
-
@body_raw = value
-
# process_body_raw
-
end
-
end
-
-
-
2
def process_body_raw
-
@body = Mail::Body.new(@body_raw)
-
@body_raw = nil
-
separate_parts if @separate_parts
-
-
add_encoding_to_body
-
end
-
-
2
def set_envelope_header
-
raw_string = raw_source.to_s
-
if match_data = raw_source.to_s.match(/\AFrom\s(#{TEXT}+)#{CRLF}/m)
-
set_envelope(match_data[1])
-
self.raw_source = raw_string.sub(match_data[0], "")
-
end
-
end
-
-
2
def separate_parts
-
body.split!(boundary)
-
end
-
-
2
def add_encoding_to_body
-
if has_content_transfer_encoding?
-
@body.encoding = content_transfer_encoding
-
end
-
end
-
-
2
def identify_and_set_transfer_encoding
-
if body && body.multipart?
-
self.content_transfer_encoding = @transport_encoding
-
else
-
self.content_transfer_encoding = body.get_best_encoding(@transport_encoding)
-
end
-
end
-
-
2
def add_required_fields
-
add_required_message_fields
-
add_multipart_mixed_header if body.multipart?
-
add_content_type unless has_content_type?
-
add_charset unless has_charset?
-
add_content_transfer_encoding unless has_content_transfer_encoding?
-
end
-
-
2
def add_required_message_fields
-
add_date unless has_date?
-
add_mime_version unless has_mime_version?
-
add_message_id unless has_message_id?
-
end
-
-
2
def add_multipart_alternate_header
-
header['content-type'] = ContentTypeField.with_boundary('multipart/alternative').value
-
header['content_type'].parameters[:charset] = @charset
-
body.boundary = boundary
-
end
-
-
2
def add_boundary
-
unless body.boundary && boundary
-
header['content-type'] = 'multipart/mixed' unless header['content-type']
-
header['content-type'].parameters[:boundary] = ContentTypeField.generate_boundary
-
header['content_type'].parameters[:charset] = @charset
-
body.boundary = boundary
-
end
-
end
-
-
2
def add_multipart_mixed_header
-
unless header['content-type']
-
header['content-type'] = ContentTypeField.with_boundary('multipart/mixed').value
-
header['content_type'].parameters[:charset] = @charset
-
body.boundary = boundary
-
end
-
end
-
-
2
def init_with_hash(hash)
-
passed_in_options = IndifferentHash.new(hash)
-
self.raw_source = ''
-
-
@header = Mail::Header.new
-
@body = Mail::Body.new
-
@body_raw = nil
-
-
# We need to store the body until last, as we need all headers added first
-
body_content = nil
-
-
passed_in_options.each_pair do |k,v|
-
k = underscoreize(k).to_sym if k.class == String
-
if k == :headers
-
self.headers(v)
-
elsif k == :body
-
body_content = v
-
else
-
self[k] = v
-
end
-
end
-
-
if body_content
-
self.body = body_content
-
if has_content_transfer_encoding?
-
body.encoding = content_transfer_encoding
-
end
-
end
-
end
-
-
2
def init_with_string(string)
-
self.raw_source = string
-
set_envelope_header
-
parse_message
-
@separate_parts = multipart?
-
end
-
-
# Returns the filename of the attachment (if it exists) or returns nil
-
2
def find_attachment
-
content_type_name = header[:content_type].filename rescue nil
-
content_disp_name = header[:content_disposition].filename rescue nil
-
content_loc_name = header[:content_location].location rescue nil
-
case
-
when content_type && content_type_name
-
filename = content_type_name
-
when content_disposition && content_disp_name
-
filename = content_disp_name
-
when content_location && content_loc_name
-
filename = content_loc_name
-
else
-
filename = nil
-
end
-
filename = Mail::Encodings.decode_encode(filename, :decode) if filename rescue filename
-
filename
-
end
-
-
2
def do_delivery
-
begin
-
if perform_deliveries
-
delivery_method.deliver!(self)
-
end
-
rescue => e # Net::SMTP errors or sendmail pipe errors
-
raise e if raise_delivery_errors
-
end
-
end
-
-
2
def decode_body_as_text
-
body_text = decode_body
-
if charset
-
if RUBY_VERSION < '1.9'
-
require 'iconv'
-
return Iconv.conv("UTF-8//TRANSLIT//IGNORE", charset, body_text)
-
else
-
if encoding = Encoding.find(charset) rescue nil
-
body_text.force_encoding(encoding)
-
return body_text.encode(Encoding::UTF_8, :undef => :replace, :invalid => :replace, :replace => '')
-
end
-
end
-
end
-
body_text
-
end
-
-
end
-
end
-
2
require 'mail/network/retriever_methods/base'
-
-
2
module Mail
-
2
register_autoload :SMTP, 'mail/network/delivery_methods/smtp'
-
2
register_autoload :FileDelivery, 'mail/network/delivery_methods/file_delivery'
-
2
register_autoload :Sendmail, 'mail/network/delivery_methods/sendmail'
-
2
register_autoload :Exim, 'mail/network/delivery_methods/exim'
-
2
register_autoload :SMTPConnection, 'mail/network/delivery_methods/smtp_connection'
-
2
register_autoload :TestMailer, 'mail/network/delivery_methods/test_mailer'
-
-
2
register_autoload :POP3, 'mail/network/retriever_methods/pop3'
-
2
register_autoload :IMAP, 'mail/network/retriever_methods/imap'
-
2
register_autoload :TestRetriever, 'mail/network/retriever_methods/test_retriever'
-
end
-
2
require 'mail/check_delivery_params'
-
-
2
module Mail
-
-
# FileDelivery class delivers emails into multiple files based on the destination
-
# address. Each file is appended to if it already exists.
-
#
-
# So if you have an email going to fred@test, bob@test, joe@anothertest, and you
-
# set your location path to /path/to/mails then FileDelivery will create the directory
-
# if it does not exist, and put one copy of the email in three files, called
-
# by their message id
-
#
-
# Make sure the path you specify with :location is writable by the Ruby process
-
# running Mail.
-
2
class FileDelivery
-
2
include Mail::CheckDeliveryParams
-
-
2
if RUBY_VERSION >= '1.9.1'
-
2
require 'fileutils'
-
else
-
require 'ftools'
-
end
-
-
2
def initialize(values)
-
self.settings = { :location => './mails' }.merge!(values)
-
end
-
-
2
attr_accessor :settings
-
-
2
def deliver!(mail)
-
check_delivery_params(mail)
-
-
if ::File.respond_to?(:makedirs)
-
::File.makedirs settings[:location]
-
else
-
::FileUtils.mkdir_p settings[:location]
-
end
-
-
mail.destinations.uniq.each do |to|
-
::File.open(::File.join(settings[:location], File.basename(to.to_s)), 'a') { |f| "#{f.write(mail.encoded)}\r\n\r\n" }
-
end
-
end
-
-
end
-
end
-
2
require 'mail/check_delivery_params'
-
-
2
module Mail
-
# A delivery method implementation which sends via sendmail.
-
#
-
# To use this, first find out where the sendmail binary is on your computer,
-
# if you are on a mac or unix box, it is usually in /usr/sbin/sendmail, this will
-
# be your sendmail location.
-
#
-
# Mail.defaults do
-
# delivery_method :sendmail
-
# end
-
#
-
# Or if your sendmail binary is not at '/usr/sbin/sendmail'
-
#
-
# Mail.defaults do
-
# delivery_method :sendmail, :location => '/absolute/path/to/your/sendmail'
-
# end
-
#
-
# Then just deliver the email as normal:
-
#
-
# Mail.deliver do
-
# to 'mikel@test.lindsaar.net'
-
# from 'ada@test.lindsaar.net'
-
# subject 'testing sendmail'
-
# body 'testing sendmail'
-
# end
-
#
-
# Or by calling deliver on a Mail message
-
#
-
# mail = Mail.new do
-
# to 'mikel@test.lindsaar.net'
-
# from 'ada@test.lindsaar.net'
-
# subject 'testing sendmail'
-
# body 'testing sendmail'
-
# end
-
#
-
# mail.deliver!
-
2
class Sendmail
-
2
include Mail::CheckDeliveryParams
-
-
2
def initialize(values)
-
self.settings = { :location => '/usr/sbin/sendmail',
-
:arguments => '-i' }.merge(values)
-
end
-
-
2
attr_accessor :settings
-
-
2
def deliver!(mail)
-
smtp_from, smtp_to, message = check_delivery_params(mail)
-
-
from = "-f #{self.class.shellquote(smtp_from)}"
-
to = smtp_to.map { |_to| self.class.shellquote(_to) }.join(' ')
-
-
arguments = "#{settings[:arguments]} #{from} --"
-
self.class.call(settings[:location], arguments, to, message)
-
end
-
-
2
def self.call(path, arguments, destinations, encoded_message)
-
popen "#{path} #{arguments} #{destinations}" do |io|
-
io.puts encoded_message.to_lf
-
io.flush
-
end
-
end
-
-
2
if RUBY_VERSION < '1.9.0'
-
def self.popen(command, &block)
-
IO.popen "#{command} 2>&1", 'w+', &block
-
end
-
else
-
2
def self.popen(command, &block)
-
IO.popen command, 'w+', :err => :out, &block
-
end
-
end
-
-
# The following is an adaptation of ruby 1.9.2's shellwords.rb file,
-
# it is modified to include '+' in the allowed list to allow for
-
# sendmail to accept email addresses as the sender with a + in them.
-
2
def self.shellquote(address)
-
# Process as a single byte sequence because not all shell
-
# implementations are multibyte aware.
-
#
-
# A LF cannot be escaped with a backslash because a backslash + LF
-
# combo is regarded as line continuation and simply ignored. Strip it.
-
escaped = address.gsub(/([^A-Za-z0-9_\s\+\-.,:\/@])/n, "\\\\\\1").gsub("\n", '')
-
%("#{escaped}")
-
end
-
end
-
end
-
2
require 'mail/check_delivery_params'
-
-
2
module Mail
-
# == Sending Email with SMTP
-
#
-
# Mail allows you to send emails using SMTP. This is done by wrapping Net::SMTP in
-
# an easy to use manner.
-
#
-
# === Sending via SMTP server on Localhost
-
#
-
# Sending locally (to a postfix or sendmail server running on localhost) requires
-
# no special setup. Just to Mail.deliver &block or message.deliver! and it will
-
# be sent in this method.
-
#
-
# === Sending via MobileMe
-
#
-
# Mail.defaults do
-
# delivery_method :smtp, { :address => "smtp.me.com",
-
# :port => 587,
-
# :domain => 'your.host.name',
-
# :user_name => '<username>',
-
# :password => '<password>',
-
# :authentication => 'plain',
-
# :enable_starttls_auto => true }
-
# end
-
#
-
# === Sending via GMail
-
#
-
# Mail.defaults do
-
# delivery_method :smtp, { :address => "smtp.gmail.com",
-
# :port => 587,
-
# :domain => 'your.host.name',
-
# :user_name => '<username>',
-
# :password => '<password>',
-
# :authentication => 'plain',
-
# :enable_starttls_auto => true }
-
# end
-
#
-
# === Certificate verification
-
#
-
# When using TLS, some mail servers provide certificates that are self-signed
-
# or whose names do not exactly match the hostname given in the address.
-
# OpenSSL will reject these by default. The best remedy is to use the correct
-
# hostname or update the certificate authorities trusted by your ruby. If
-
# that isn't possible, you can control this behavior with
-
# an :openssl_verify_mode setting. Its value may be either an OpenSSL
-
# verify mode constant (OpenSSL::SSL::VERIFY_NONE), or a string containing
-
# the name of an OpenSSL verify mode (none, peer, client_once,
-
# fail_if_no_peer_cert).
-
#
-
# === Others
-
#
-
# Feel free to send me other examples that were tricky
-
#
-
# === Delivering the email
-
#
-
# Once you have the settings right, sending the email is done by:
-
#
-
# Mail.deliver do
-
# to 'mikel@test.lindsaar.net'
-
# from 'ada@test.lindsaar.net'
-
# subject 'testing sendmail'
-
# body 'testing sendmail'
-
# end
-
#
-
# Or by calling deliver on a Mail message
-
#
-
# mail = Mail.new do
-
# to 'mikel@test.lindsaar.net'
-
# from 'ada@test.lindsaar.net'
-
# subject 'testing sendmail'
-
# body 'testing sendmail'
-
# end
-
#
-
# mail.deliver!
-
2
class SMTP
-
2
include Mail::CheckDeliveryParams
-
-
2
def initialize(values)
-
self.settings = { :address => "localhost",
-
:port => 25,
-
:domain => 'localhost.localdomain',
-
:user_name => nil,
-
:password => nil,
-
:authentication => nil,
-
:enable_starttls_auto => true,
-
:openssl_verify_mode => nil,
-
:ssl => nil,
-
:tls => nil
-
}.merge!(values)
-
end
-
-
2
attr_accessor :settings
-
-
# Send the message via SMTP.
-
# The from and to attributes are optional. If not set, they are retrieve from the Message.
-
2
def deliver!(mail)
-
smtp_from, smtp_to, message = check_delivery_params(mail)
-
-
smtp = Net::SMTP.new(settings[:address], settings[:port])
-
if settings[:tls] || settings[:ssl]
-
if smtp.respond_to?(:enable_tls)
-
smtp.enable_tls(ssl_context)
-
end
-
elsif settings[:enable_starttls_auto]
-
if smtp.respond_to?(:enable_starttls_auto)
-
smtp.enable_starttls_auto(ssl_context)
-
end
-
end
-
-
response = nil
-
smtp.start(settings[:domain], settings[:user_name], settings[:password], settings[:authentication]) do |smtp_obj|
-
response = smtp_obj.sendmail(message, smtp_from, smtp_to)
-
end
-
-
if settings[:return_response]
-
response
-
else
-
self
-
end
-
end
-
-
-
2
private
-
-
# Allow SSL context to be configured via settings, for Ruby >= 1.9
-
# Just returns openssl verify mode for Ruby 1.8.x
-
2
def ssl_context
-
openssl_verify_mode = settings[:openssl_verify_mode]
-
-
if openssl_verify_mode.kind_of?(String)
-
openssl_verify_mode = "OpenSSL::SSL::VERIFY_#{openssl_verify_mode.upcase}".constantize
-
end
-
-
context = Net::SMTP.default_ssl_context
-
context.verify_mode = openssl_verify_mode
-
context.ca_path = settings[:ca_path] if settings[:ca_path]
-
context.ca_file = settings[:ca_file] if settings[:ca_file]
-
context
-
end
-
end
-
end
-
2
require 'mail/check_delivery_params'
-
-
2
module Mail
-
# The TestMailer is a bare bones mailer that does nothing. It is useful
-
# when you are testing.
-
#
-
# It also provides a template of the minimum methods you require to implement
-
# if you want to make a custom mailer for Mail
-
2
class TestMailer
-
2
include Mail::CheckDeliveryParams
-
-
# Provides a store of all the emails sent with the TestMailer so you can check them.
-
2
def TestMailer.deliveries
-
@@deliveries ||= []
-
end
-
-
# Allows you to over write the default deliveries store from an array to some
-
# other object. If you just want to clear the store,
-
# call TestMailer.deliveries.clear.
-
#
-
# If you place another object here, please make sure it responds to:
-
#
-
# * << (message)
-
# * clear
-
# * length
-
# * size
-
# * and other common Array methods
-
2
def TestMailer.deliveries=(val)
-
6
@@deliveries = val
-
end
-
-
2
def initialize(values)
-
@settings = values.dup
-
end
-
-
2
attr_accessor :settings
-
-
2
def deliver!(mail)
-
check_delivery_params(mail)
-
Mail::TestMailer.deliveries << mail
-
end
-
-
end
-
end
-
# encoding: utf-8
-
-
2
module Mail
-
-
2
class Retriever
-
-
# Get the oldest received email(s)
-
#
-
# Possible options:
-
# count: number of emails to retrieve. The default value is 1.
-
# order: order of emails returned. Possible values are :asc or :desc. Default value is :asc.
-
#
-
2
def first(options = {}, &block)
-
options ||= {}
-
options[:what] = :first
-
options[:count] ||= 1
-
find(options, &block)
-
end
-
-
# Get the most recent received email(s)
-
#
-
# Possible options:
-
# count: number of emails to retrieve. The default value is 1.
-
# order: order of emails returned. Possible values are :asc or :desc. Default value is :asc.
-
#
-
2
def last(options = {}, &block)
-
options ||= {}
-
options[:what] = :last
-
options[:count] ||= 1
-
find(options, &block)
-
end
-
-
# Get all emails.
-
#
-
# Possible options:
-
# order: order of emails returned. Possible values are :asc or :desc. Default value is :asc.
-
#
-
2
def all(options = {}, &block)
-
options ||= {}
-
options[:count] = :all
-
find(options, &block)
-
end
-
-
# Find emails in the mailbox, and then deletes them. Without any options, the
-
# five last received emails are returned.
-
#
-
# Possible options:
-
# what: last or first emails. The default is :first.
-
# order: order of emails returned. Possible values are :asc or :desc. Default value is :asc.
-
# count: number of emails to retrieve. The default value is 10. A value of 1 returns an
-
# instance of Message, not an array of Message instances.
-
# delete_after_find: flag for whether to delete each retreived email after find. Default
-
# is true. Call #find if you would like this to default to false.
-
#
-
2
def find_and_delete(options = {}, &block)
-
options ||= {}
-
options[:delete_after_find] ||= true
-
find(options, &block)
-
end
-
-
end
-
-
end
-
# encoding: utf-8
-
2
module Mail
-
2
class Part < Message
-
-
# Creates a new empty Content-ID field and inserts it in the correct order
-
# into the Header. The ContentIdField object will automatically generate
-
# a unique content ID if you try and encode it or output it to_s without
-
# specifying a content id.
-
#
-
# It will preserve the content ID you specify if you do.
-
2
def add_content_id(content_id_val = '')
-
header['content-id'] = content_id_val
-
end
-
-
# Returns true if the part has a content ID field, the field may or may
-
# not have a value, but the field exists or not.
-
2
def has_content_id?
-
header.has_content_id?
-
end
-
-
2
def inline_content_id
-
# TODO: Deprecated in 2.2.2 - Remove in 2.3
-
STDERR.puts("Part#inline_content_id is deprecated, please call Part#cid instead")
-
cid
-
end
-
-
2
def cid
-
add_content_id unless has_content_id?
-
uri_escape(unbracket(content_id))
-
end
-
-
2
def url
-
"cid:#{cid}"
-
end
-
-
2
def inline?
-
header[:content_disposition].disposition_type == 'inline' if header[:content_disposition]
-
end
-
-
2
def add_required_fields
-
super
-
add_content_id if !has_content_id? && inline?
-
end
-
-
2
def add_required_message_fields
-
# Override so we don't add Date, MIME-Version, or Message-ID.
-
end
-
-
2
def delivery_status_report_part?
-
(main_type =~ /message/i && sub_type =~ /delivery-status/i) && body =~ /Status:/
-
end
-
-
2
def delivery_status_data
-
delivery_status_report_part? ? parse_delivery_status_report : {}
-
end
-
-
2
def bounced?
-
if action.is_a?(Array)
-
!!(action.first =~ /failed/i)
-
else
-
!!(action =~ /failed/i)
-
end
-
end
-
-
-
# Either returns the action if the message has just a single report, or an
-
# array of all the actions, one for each report
-
2
def action
-
get_return_values('action')
-
end
-
-
2
def final_recipient
-
get_return_values('final-recipient')
-
end
-
-
2
def error_status
-
get_return_values('status')
-
end
-
-
2
def diagnostic_code
-
get_return_values('diagnostic-code')
-
end
-
-
2
def remote_mta
-
get_return_values('remote-mta')
-
end
-
-
2
def retryable?
-
!(error_status =~ /^5/)
-
end
-
-
2
private
-
-
2
def get_return_values(key)
-
if delivery_status_data[key].is_a?(Array)
-
delivery_status_data[key].map { |a| a.value }
-
else
-
delivery_status_data[key].value
-
end
-
end
-
-
# A part may not have a header.... so, just init a body if no header
-
2
def parse_message
-
header_part, body_part = raw_source.split(/#{CRLF}#{WSP}*#{CRLF}/m, 2)
-
if header_part =~ HEADER_LINE
-
self.header = header_part
-
self.body = body_part
-
else
-
self.header = "Content-Type: text/plain\r\n"
-
self.body = raw_source
-
end
-
end
-
-
2
def parse_delivery_status_report
-
@delivery_status_data ||= Header.new(body.to_s.gsub("\r\n\r\n", "\r\n"))
-
end
-
-
end
-
-
end
-
2
module Mail
-
2
class PartsList < Array
-
-
2
def attachments
-
Mail::AttachmentsList.new(self)
-
end
-
-
2
def collect
-
if block_given?
-
ary = PartsList.new
-
each { |o| ary << yield(o) }
-
ary
-
else
-
to_a
-
end
-
end
-
-
2
undef :map
-
2
alias_method :map, :collect
-
-
2
def map!
-
raise NoMethodError, "#map! is not defined, please call #collect and create a new PartsList"
-
end
-
-
2
def collect!
-
raise NoMethodError, "#collect! is not defined, please call #collect and create a new PartsList"
-
end
-
-
2
def sort
-
self.class.new(super)
-
end
-
-
2
def sort!(order)
-
# stable sort should be used to maintain the relative order as the parts are added
-
i = 0;
-
sorted = self.sort_by do |a|
-
# OK, 10000 is arbitrary... if anyone actually wants to explicitly sort 10000 parts of a
-
# single email message... please show me a use case and I'll put more work into this method,
-
# in the meantime, it works :)
-
[get_order_value(a, order), i += 1]
-
end
-
self.clear
-
sorted.each { |p| self << p }
-
end
-
-
2
private
-
-
2
def get_order_value(part, order)
-
if part.respond_to?(:content_type) && !part[:content_type].nil?
-
order.index(part[:content_type].string.downcase) || 10000
-
else
-
10000
-
end
-
end
-
-
end
-
end
-
# encoding: utf-8
-
2
module Mail
-
2
module Utilities
-
2
include Constants
-
-
# Returns true if the string supplied is free from characters not allowed as an ATOM
-
2
def atom_safe?( str )
-
not ATOM_UNSAFE === str
-
end
-
-
# If the string supplied has ATOM unsafe characters in it, will return the string quoted
-
# in double quotes, otherwise returns the string unmodified
-
2
def quote_atom( str )
-
atom_safe?( str ) ? str : dquote(str)
-
end
-
-
# If the string supplied has PHRASE unsafe characters in it, will return the string quoted
-
# in double quotes, otherwise returns the string unmodified
-
2
def quote_phrase( str )
-
if RUBY_VERSION >= '1.9'
-
original_encoding = str.encoding
-
str.force_encoding('ASCII-8BIT')
-
if (PHRASE_UNSAFE === str)
-
quoted_str = dquote(str).force_encoding(original_encoding)
-
str.force_encoding(original_encoding)
-
quoted_str
-
else
-
str.force_encoding(original_encoding)
-
end
-
else
-
(PHRASE_UNSAFE === str) ? dquote(str) : str
-
end
-
end
-
-
# Returns true if the string supplied is free from characters not allowed as a TOKEN
-
2
def token_safe?( str )
-
not TOKEN_UNSAFE === str
-
end
-
-
# If the string supplied has TOKEN unsafe characters in it, will return the string quoted
-
# in double quotes, otherwise returns the string unmodified
-
2
def quote_token( str )
-
token_safe?( str ) ? str : dquote(str)
-
end
-
-
# Wraps supplied string in double quotes and applies \-escaping as necessary,
-
# unless it is already wrapped.
-
#
-
# Example:
-
#
-
# string = 'This is a string'
-
# dquote(string) #=> '"This is a string"'
-
#
-
# string = 'This is "a string"'
-
# dquote(string #=> '"This is \"a string\"'
-
2
def dquote( str )
-
'"' + unquote(str).gsub(/[\\"]/n) {|s| '\\' + s } + '"'
-
end
-
-
# Unwraps supplied string from inside double quotes and
-
# removes any \-escaping.
-
#
-
# Example:
-
#
-
# string = '"This is a string"'
-
# unquote(string) #=> 'This is a string'
-
#
-
# string = '"This is \"a string\""'
-
# unqoute(string) #=> 'This is "a string"'
-
2
def unquote( str )
-
if str =~ /^"(.*?)"$/
-
$1.gsub(/\\(.)/, '\1')
-
else
-
str
-
end
-
end
-
-
# Wraps a string in parenthesis and escapes any that are in the string itself.
-
#
-
# Example:
-
#
-
# paren( 'This is a string' ) #=> '(This is a string)'
-
2
def paren( str )
-
RubyVer.paren( str )
-
end
-
-
# Unwraps a string from being wrapped in parenthesis
-
#
-
# Example:
-
#
-
# str = '(This is a string)'
-
# unparen( str ) #=> 'This is a string'
-
2
def unparen( str )
-
match = str.match(/^\((.*?)\)$/)
-
match ? match[1] : str
-
end
-
-
# Wraps a string in angle brackets and escapes any that are in the string itself
-
#
-
# Example:
-
#
-
# bracket( 'This is a string' ) #=> '<This is a string>'
-
2
def bracket( str )
-
RubyVer.bracket( str )
-
end
-
-
# Unwraps a string from being wrapped in parenthesis
-
#
-
# Example:
-
#
-
# str = '<This is a string>'
-
# unbracket( str ) #=> 'This is a string'
-
2
def unbracket( str )
-
match = str.match(/^\<(.*?)\>$/)
-
match ? match[1] : str
-
end
-
-
# Escape parenthesies in a string
-
#
-
# Example:
-
#
-
# str = 'This is (a) string'
-
# escape_paren( str ) #=> 'This is \(a\) string'
-
2
def escape_paren( str )
-
RubyVer.escape_paren( str )
-
end
-
-
2
def uri_escape( str )
-
uri_parser.escape(str)
-
end
-
-
2
def uri_unescape( str )
-
uri_parser.unescape(str)
-
end
-
-
2
def uri_parser
-
@uri_parser ||= URI.const_defined?(:Parser) ? URI::Parser.new : URI
-
end
-
-
# Matches two objects with their to_s values case insensitively
-
#
-
# Example:
-
#
-
# obj2 = "This_is_An_object"
-
# obj1 = :this_IS_an_object
-
# match_to_s( obj1, obj2 ) #=> true
-
2
def match_to_s( obj1, obj2 )
-
obj1.to_s.casecmp(obj2.to_s) == 0
-
end
-
-
# Capitalizes a string that is joined by hyphens correctly.
-
#
-
# Example:
-
#
-
# string = 'resent-from-field'
-
# capitalize_field( string ) #=> 'Resent-From-Field'
-
2
def capitalize_field( str )
-
str.to_s.split("-").map { |v| v.capitalize }.join("-")
-
end
-
-
# Takes an underscored word and turns it into a class name
-
#
-
# Example:
-
#
-
# constantize("hello") #=> "Hello"
-
# constantize("hello-there") #=> "HelloThere"
-
# constantize("hello-there-mate") #=> "HelloThereMate"
-
2
def constantize( str )
-
str.to_s.split(/[-_]/).map { |v| v.capitalize }.to_s
-
end
-
-
# Swaps out all underscores (_) for hyphens (-) good for stringing from symbols
-
# a field name.
-
#
-
# Example:
-
#
-
# string = :resent_from_field
-
# dasherize ( string ) #=> 'resent_from_field'
-
2
def dasherize( str )
-
str.to_s.tr(UNDERSCORE, HYPHEN)
-
end
-
-
# Swaps out all hyphens (-) for underscores (_) good for stringing to symbols
-
# a field name.
-
#
-
# Example:
-
#
-
# string = :resent_from_field
-
# underscoreize ( string ) #=> 'resent_from_field'
-
2
def underscoreize( str )
-
12
str.to_s.downcase.tr(HYPHEN, UNDERSCORE)
-
end
-
-
2
if RUBY_VERSION <= '1.8.6'
-
-
def map_lines( str, &block )
-
results = []
-
str.each_line do |line|
-
results << yield(line)
-
end
-
results
-
end
-
-
def map_with_index( enum, &block )
-
results = []
-
enum.each_with_index do |token, i|
-
results[i] = yield(token, i)
-
end
-
results
-
end
-
-
else
-
-
2
def map_lines( str, &block )
-
str.each_line.map(&block)
-
end
-
-
2
def map_with_index( enum, &block )
-
enum.each_with_index.map(&block)
-
end
-
-
end
-
-
end
-
end
-
2
module Mail
-
2
module VERSION
-
-
2
MAJOR = 2
-
2
MINOR = 6
-
2
PATCH = 3
-
2
BUILD = nil
-
-
2
STRING = [MAJOR, MINOR, PATCH, BUILD].compact.join('.')
-
-
2
def self.version
-
STRING
-
end
-
-
end
-
end
-
# encoding: utf-8
-
-
2
module Mail
-
2
class Ruby19
-
2
class StrictCharsetEncoder
-
2
def encode(string, charset)
-
string.force_encoding(Mail::Ruby19.pick_encoding(charset))
-
end
-
end
-
-
2
class BestEffortCharsetEncoder
-
2
def encode(string, charset)
-
string.force_encoding(pick_encoding(charset))
-
end
-
-
2
private
-
-
2
def pick_encoding(charset)
-
charset = case charset
-
when /ansi_x3.110-1983/
-
'ISO-8859-1'
-
when /Windows-?1258/i # Windows-1258 is similar to 1252
-
"Windows-1252"
-
else
-
charset
-
end
-
Mail::Ruby19.pick_encoding(charset)
-
end
-
end
-
-
2
class << self
-
2
attr_accessor :charset_encoder
-
end
-
2
self.charset_encoder = StrictCharsetEncoder.new
-
-
# Escapes any parenthesis in a string that are unescaped this uses
-
# a Ruby 1.9.1 regexp feature of negative look behind
-
2
def Ruby19.escape_paren( str )
-
re = /(?<!\\)([\(\)])/ # Only match unescaped parens
-
str.gsub(re) { |s| '\\' + s }
-
end
-
-
2
def Ruby19.paren( str )
-
str = $1 if str =~ /^\((.*)?\)$/
-
str = escape_paren( str )
-
'(' + str + ')'
-
end
-
-
2
def Ruby19.escape_bracket( str )
-
re = /(?<!\\)([\<\>])/ # Only match unescaped brackets
-
str.gsub(re) { |s| '\\' + s }
-
end
-
-
2
def Ruby19.bracket( str )
-
str = $1 if str =~ /^\<(.*)?\>$/
-
str = escape_bracket( str )
-
'<' + str + '>'
-
end
-
-
2
def Ruby19.decode_base64(str)
-
str.unpack( 'm' ).first
-
end
-
-
2
def Ruby19.encode_base64(str)
-
[str].pack( 'm' )
-
end
-
-
2
def Ruby19.has_constant?(klass, string)
-
klass.const_defined?( string, false )
-
end
-
-
2
def Ruby19.get_constant(klass, string)
-
klass.const_get( string )
-
end
-
-
2
def Ruby19.b_value_encode(str, encoding = nil)
-
encoding = str.encoding.to_s
-
[Ruby19.encode_base64(str), encoding]
-
end
-
-
2
def Ruby19.b_value_decode(str)
-
match = str.match(/\=\?(.+)?\?[Bb]\?(.*)\?\=/m)
-
if match
-
charset = match[1]
-
str = Ruby19.decode_base64(match[2])
-
str = charset_encoder.encode(str, charset)
-
end
-
decoded = str.encode(Encoding::UTF_8, :invalid => :replace, :replace => "")
-
decoded.valid_encoding? ? decoded : decoded.encode(Encoding::UTF_16LE, :invalid => :replace, :replace => "").encode(Encoding::UTF_8)
-
rescue Encoding::UndefinedConversionError, ArgumentError, Encoding::ConverterNotFoundError
-
warn "Encoding conversion failed #{$!}"
-
str.dup.force_encoding(Encoding::UTF_8)
-
end
-
-
2
def Ruby19.q_value_encode(str, encoding = nil)
-
encoding = str.encoding.to_s
-
[Encodings::QuotedPrintable.encode(str), encoding]
-
end
-
-
2
def Ruby19.q_value_decode(str)
-
match = str.match(/\=\?(.+)?\?[Qq]\?(.*)\?\=/m)
-
if match
-
charset = match[1]
-
string = match[2].gsub(/_/, '=20')
-
# Remove trailing = if it exists in a Q encoding
-
string = string.sub(/\=$/, '')
-
str = Encodings::QuotedPrintable.decode(string)
-
str = charset_encoder.encode(str, charset)
-
# We assume that binary strings hold utf-8 directly to work around
-
# jruby/jruby#829 which subtly changes String#encode semantics.
-
str.force_encoding(Encoding::UTF_8) if str.encoding == Encoding::ASCII_8BIT
-
end
-
decoded = str.encode(Encoding::UTF_8, :invalid => :replace, :replace => "")
-
decoded.valid_encoding? ? decoded : decoded.encode(Encoding::UTF_16LE, :invalid => :replace, :replace => "").encode(Encoding::UTF_8)
-
rescue Encoding::UndefinedConversionError, ArgumentError, Encoding::ConverterNotFoundError
-
warn "Encoding conversion failed #{$!}"
-
str.dup.force_encoding(Encoding::UTF_8)
-
end
-
-
2
def Ruby19.param_decode(str, encoding)
-
str = uri_parser.unescape(str)
-
str = charset_encoder.encode(str, encoding) if encoding
-
str
-
end
-
-
2
def Ruby19.param_encode(str)
-
encoding = str.encoding.to_s.downcase
-
language = Configuration.instance.param_encode_language
-
"#{encoding}'#{language}'#{uri_parser.escape(str)}"
-
end
-
-
2
def Ruby19.uri_parser
-
@uri_parser ||= URI::Parser.new
-
end
-
-
# Pick a Ruby encoding corresponding to the message charset. Most
-
# charsets have a Ruby encoding, but some need manual aliasing here.
-
#
-
# TODO: add this as a test somewhere:
-
# Encoding.list.map { |e| [e.to_s.upcase == pick_encoding(e.to_s.downcase.gsub("-", "")), e.to_s] }.select {|a,b| !b}
-
# Encoding.list.map { |e| [e.to_s == pick_encoding(e.to_s), e.to_s] }.select {|a,b| !b}
-
2
def Ruby19.pick_encoding(charset)
-
case charset
-
-
# ISO-8859-8-I etc. http://en.wikipedia.org/wiki/ISO-8859-8-I
-
when /^iso-?8859-(\d+)(-i)?$/i
-
"ISO-8859-#{$1}"
-
-
# ISO-8859-15, ISO-2022-JP and alike
-
when /iso-?(\d{4})-?(\w{1,2})/i
-
"ISO-#{$1}-#{$2}"
-
-
# "ISO-2022-JP-KDDI" and alike
-
when /iso-?(\d{4})-?(\w{1,2})-?(\w*)/i
-
"ISO-#{$1}-#{$2}-#{$3}"
-
-
# UTF-8, UTF-32BE and alike
-
when /utf[\-_]?(\d{1,2})?(\w{1,2})/i
-
"UTF-#{$1}#{$2}".gsub(/\A(UTF-(?:16|32))\z/, '\\1BE')
-
-
# Windows-1252 and alike
-
when /Windows-?(.*)/i
-
"Windows-#{$1}"
-
-
when /^8bit$/
-
Encoding::ASCII_8BIT
-
-
# alternatives/misspellings of us-ascii seen in the wild
-
when /^iso-?646(-us)?$/i, /us=ascii/i
-
Encoding::ASCII
-
-
# Microsoft-specific alias for MACROMAN
-
when /^macintosh$/i
-
Encoding::MACROMAN
-
-
# Microsoft-specific alias for CP949 (Korean)
-
when 'ks_c_5601-1987'
-
Encoding::CP949
-
-
# Wrongly written Shift_JIS (Japanese)
-
when 'shift-jis'
-
Encoding::Shift_JIS
-
-
# GB2312 (Chinese charset) is a subset of GB18030 (its replacement)
-
when /gb2312/i
-
Encoding::GB18030
-
-
else
-
charset
-
end
-
end
-
end
-
end
-
# -*- ruby encoding: utf-8 -*-
-
-
# The definition of one MIME content-type.
-
#
-
# == Usage
-
# require 'mime/types'
-
#
-
# plaintext = MIME::Types['text/plain'].first
-
# # returns [text/plain, text/plain]
-
# text = plaintext.first
-
# print text.media_type # => 'text'
-
# print text.sub_type # => 'plain'
-
#
-
# puts text.extensions.join(" ") # => 'asc txt c cc h hh cpp'
-
#
-
# puts text.encoding # => 8bit
-
# puts text.binary? # => false
-
# puts text.ascii? # => true
-
# puts text == 'text/plain' # => true
-
# puts MIME::Type.simplified('x-appl/x-zip') # => 'appl/zip'
-
#
-
# puts MIME::Types.any? { |type|
-
# type.content_type == 'text/plain'
-
# } # => true
-
# puts MIME::Types.all?(&:registered?)
-
# # => false
-
2
class MIME::Type
-
# Reflects a MIME content-type specification that is not correctly
-
# formatted (it isn't +type+/+subtype+).
-
2
class InvalidContentType < ArgumentError
-
# :stopdoc:
-
2
def initialize(type_string)
-
@type_string = type_string
-
end
-
-
2
def to_s
-
"Invalid Content-Type #{@type_string.inspect}"
-
end
-
# :startdoc:
-
end
-
-
# Reflects an unsupported MIME encoding.
-
2
class InvalidEncoding < ArgumentError
-
# :stopdoc:
-
2
def initialize(encoding)
-
@encoding = encoding
-
end
-
-
2
def to_s
-
"Invalid Encoding #{@encoding.inspect}"
-
end
-
# :startdoc:
-
end
-
-
# The released version of the mime-types library.
-
2
VERSION = '2.99.1'
-
-
2
include Comparable
-
-
# :stopdoc:
-
2
MEDIA_TYPE_RE = %r{([-\w.+]+)/([-\w.+]*)}o
-
2
UNREGISTERED_RE = %r{[Xx]-}o
-
2
I18N_RE = %r{[^[:alnum:]]}o
-
2
PLATFORM_RE = %r{#{RUBY_PLATFORM}}o
-
-
2
DEFAULT_ENCODINGS = [ nil, :default ]
-
2
BINARY_ENCODINGS = %w(base64 8bit)
-
2
TEXT_ENCODINGS = %w(7bit quoted-printable)
-
2
VALID_ENCODINGS = DEFAULT_ENCODINGS + BINARY_ENCODINGS + TEXT_ENCODINGS
-
-
2
IANA_URL = 'http://www.iana.org/assignments/media-types/%s/%s'
-
2
RFC_URL = 'http://rfc-editor.org/rfc/rfc%s.txt'
-
2
DRAFT_URL = 'http://datatracker.ietf.org/public/idindex.cgi?command=id_details&filename=%s' # rubocop:disable Metrics/LineLength
-
2
CONTACT_URL = 'http://www.iana.org/assignments/contact-people.htm#%s'
-
# :startdoc:
-
-
2
if respond_to? :private_constant
-
2
private_constant :MEDIA_TYPE_RE, :UNREGISTERED_RE, :I18N_RE, :PLATFORM_RE,
-
:DEFAULT_ENCODINGS, :BINARY_ENCODINGS, :TEXT_ENCODINGS,
-
:VALID_ENCODINGS, :IANA_URL, :RFC_URL, :DRAFT_URL,
-
:CONTACT_URL
-
end
-
-
# Builds a MIME::Type object from the +content_type+, a MIME Content Type
-
# value (e.g., 'text/plain' or 'applicaton/x-eruby'). The constructed object
-
# is yielded to an optional block for additional configuration, such as
-
# associating extensions and encoding information.
-
#
-
# * When provided a Hash or a MIME::Type, the MIME::Type will be
-
# constructed with #init_with.
-
# * When provided an Array, the MIME::Type will be constructed only using
-
# the first two elements of the array as the content type and
-
# extensions.
-
# * Otherwise, the content_type will be used as a string.
-
#
-
# Yields the newly constructed +self+ object.
-
2
def initialize(content_type) # :yields self:
-
@friendly = {}
-
self.obsolete = false
-
self.registered = nil
-
self.use_instead = nil
-
self.signature = nil
-
-
case content_type
-
when Hash
-
init_with(content_type)
-
when Array
-
self.content_type = content_type[0]
-
self.extensions = content_type[1] || []
-
when MIME::Type
-
init_with(content_type.to_h)
-
else
-
self.content_type = content_type
-
end
-
-
self.extensions ||= []
-
self.docs ||= []
-
self.encoding ||= :default
-
self.xrefs ||= {}
-
-
yield self if block_given?
-
end
-
-
# Returns +true+ if the +other+ simplified type matches the current type.
-
2
def like?(other)
-
if other.respond_to?(:simplified)
-
@simplified == other.simplified
-
else
-
@simplified == MIME::Type.simplified(other)
-
end
-
end
-
-
# Compares the +other+ MIME::Type against the exact content type or the
-
# simplified type (the simplified type will be used if comparing against
-
# something that can be treated as a String with #to_s). In comparisons, this
-
# is done against the lowercase version of the MIME::Type.
-
2
def <=>(other)
-
7920
if other.respond_to?(:content_type)
-
108
@content_type.downcase <=> other.content_type.downcase
-
7812
elsif other.respond_to?(:to_s)
-
7812
@simplified <=> MIME::Type.simplified(other.to_s)
-
end
-
end
-
-
# Compares the +other+ MIME::Type based on how reliable it is before doing a
-
# normal <=> comparison. Used by MIME::Types#[] to sort types. The
-
# comparisons involved are:
-
#
-
# 1. self.simplified <=> other.simplified (ensures that we
-
# don't try to compare different types)
-
# 2. IANA-registered definitions < other definitions.
-
# 3. Complete definitions < incomplete definitions.
-
# 4. Current definitions < obsolete definitions.
-
# 5. Obselete with use-instead names < obsolete without.
-
# 6. Obsolete use-instead definitions are compared.
-
#
-
# While this method is public, its use is strongly discouraged by consumers
-
# of mime-types. In mime-types 3, this method is likely to see substantial
-
# revision and simplification to ensure current registered content types sort
-
# before unregistered or obsolete content types.
-
2
def priority_compare(other)
-
pc = simplified <=> other.simplified
-
if pc.zero?
-
pc = if (reg = registered?) != other.registered?
-
reg ? -1 : 1 # registered < unregistered
-
elsif (comp = complete?) != other.complete?
-
comp ? -1 : 1 # complete < incomplete
-
elsif (obs = obsolete?) != other.obsolete?
-
obs ? 1 : -1 # current < obsolete
-
elsif obs and ((ui = use_instead) != (oui = other.use_instead))
-
if ui.nil?
-
1
-
elsif oui.nil?
-
-1
-
else
-
ui <=> oui
-
end
-
else
-
0
-
end
-
end
-
-
pc
-
end
-
-
# Returns +true+ if the +other+ object is a MIME::Type and the content types
-
# match.
-
2
def eql?(other)
-
other.kind_of?(MIME::Type) and self == other
-
end
-
-
# Returns the whole MIME content-type string.
-
#
-
# The content type is a presentation value from the MIME type registry and
-
# should not be used for comparison. The case of the content type is
-
# preserved, and extension markers (<tt>x-</tt>) are kept.
-
#
-
# text/plain => text/plain
-
# x-chemical/x-pdb => x-chemical/x-pdb
-
# audio/QCELP => audio/QCELP
-
2
attr_reader :content_type
-
# A simplified form of the MIME content-type string, suitable for
-
# case-insensitive comparison, with any extension markers (<tt>x-</tt)
-
# removed and converted to lowercase.
-
#
-
# text/plain => text/plain
-
# x-chemical/x-pdb => chemical/pdb
-
# audio/QCELP => audio/qcelp
-
2
attr_reader :simplified
-
# Returns the media type of the simplified MIME::Type.
-
#
-
# text/plain => text
-
# x-chemical/x-pdb => chemical
-
2
attr_reader :media_type
-
# Returns the media type of the unmodified MIME::Type.
-
#
-
# text/plain => text
-
# x-chemical/x-pdb => x-chemical
-
2
attr_reader :raw_media_type
-
# Returns the sub-type of the simplified MIME::Type.
-
#
-
# text/plain => plain
-
# x-chemical/x-pdb => pdb
-
2
attr_reader :sub_type
-
# Returns the media type of the unmodified MIME::Type.
-
#
-
# text/plain => plain
-
# x-chemical/x-pdb => x-pdb
-
2
attr_reader :raw_sub_type
-
-
# The list of extensions which are known to be used for this MIME::Type.
-
# Non-array values will be coerced into an array with #to_a. Array values
-
# will be flattened, +nil+ values removed, and made unique.
-
2
attr_reader :extensions
-
2
def extensions=(ext) # :nodoc:
-
3906
@extensions = Array(ext).flatten.compact.uniq
-
# TODO: In mime-types 3.x, we probably want to have a clue about the
-
# container(s) we belong to so we can trigger reindexing when this is done.
-
end
-
-
# Merge the +extensions+ provided into this MIME::Type. The extensions added
-
# will be merged uniquely.
-
2
def add_extensions(*extensions)
-
self.extensions = self.extensions + extensions
-
end
-
-
##
-
# The preferred extension for this MIME type, if one is set.
-
#
-
# :attr_reader: preferred_extension
-
-
##
-
2
def preferred_extension
-
extensions.first
-
end
-
-
##
-
# The encoding (+7bit+, +8bit+, <tt>quoted-printable</tt>, or +base64+)
-
# required to transport the data of this content type safely across a
-
# network, which roughly corresponds to Content-Transfer-Encoding. A value of
-
# +nil+ or <tt>:default</tt> will reset the #encoding to the
-
# #default_encoding for the MIME::Type. Raises ArgumentError if the encoding
-
# provided is invalid.
-
#
-
# If the encoding is not provided on construction, this will be either
-
# 'quoted-printable' (for text/* media types) and 'base64' for eveything
-
# else.
-
#
-
# :attr_accessor: encoding
-
-
##
-
2
attr_reader :encoding
-
2
def encoding=(enc) # :nodoc:
-
if DEFAULT_ENCODINGS.include?(enc)
-
@encoding = default_encoding
-
elsif BINARY_ENCODINGS.include?(enc) or TEXT_ENCODINGS.include?(enc)
-
@encoding = enc
-
else
-
fail InvalidEncoding, enc
-
end
-
end
-
-
# Returns +nil+ and assignments are ignored. Prior to mime-types 2.99, this
-
# would return the regular expression for the operating system indicated if
-
# the MIME::Type is a system-specific MIME::Type,
-
#
-
# This information about MIME content types is deprecated and will be removed
-
# in mime-types 3.
-
2
def system
-
MIME::Types.deprecated(self, __method__)
-
nil
-
end
-
-
2
def system=(_os) # :nodoc:
-
MIME::Types.deprecated(self, __method__)
-
end
-
-
# Returns the default encoding for the MIME::Type based on the media type.
-
2
def default_encoding
-
(@media_type == 'text') ? 'quoted-printable' : 'base64'
-
end
-
-
##
-
# Returns the media type or types that should be used instead of this
-
# media type, if it is obsolete. If there is no replacement media type, or
-
# it is not obsolete, +nil+ will be returned.
-
#
-
# :attr_accessor: use_instead
-
-
##
-
2
def use_instead
-
return nil unless obsolete?
-
@use_instead
-
end
-
-
##
-
2
attr_writer :use_instead
-
-
# Returns +true+ if the media type is obsolete.
-
2
def obsolete?
-
!!@obsolete
-
end
-
-
2
def obsolete=(v) # :nodoc:
-
@obsolete = !!v
-
end
-
-
# The documentation for this MIME::Type.
-
2
attr_accessor :docs
-
-
# A friendly short description for this MIME::Type.
-
#
-
# call-seq:
-
# text_plain.friendly # => "Text File"
-
# text_plain.friendly('en') # => "Text File"
-
2
def friendly(lang = 'en'.freeze)
-
@friendly ||= {}
-
-
case lang
-
when String
-
@friendly[lang]
-
when Array
-
@friendly.merge!(Hash[*lang])
-
when Hash
-
@friendly.merge!(lang)
-
else
-
fail ArgumentError
-
end
-
end
-
-
# A key suitable for use as a lookup key for translations, such as with
-
# the I18n library.
-
#
-
# call-seq:
-
# text_plain.i18n_key # => "text.plain"
-
# 3gpp_xml.i18n_key # => "application.vnd-3gpp-bsf-xml"
-
# # from application/vnd.3gpp.bsf+xml
-
# x_msword.i18n_key # => "application.word"
-
# # from application/x-msword
-
2
attr_reader :i18n_key
-
-
##
-
# Returns an empty array and warns that this method has been deprecated.
-
# Assignments are ignored. Prior to mime-types 2.99, this was the encoded
-
# references URL list for this MIME::Type.
-
#
-
# This was previously called #url.
-
#
-
# #references has been deprecated and both versions (#references and #url)
-
# will be removed in mime-types 3.
-
#
-
# :attr_accessor: references
-
-
##
-
2
def references(*)
-
MIME::Types.deprecated(self, __method__)
-
[]
-
end
-
-
##
-
2
def references=(_r) # :nodoc:
-
MIME::Types.deprecated(self, __method__)
-
end
-
-
##
-
# Returns an empty array and warns that this method has been deprecated.
-
# Assignments are ignored. Prior to mime-types 2.99, this was the encoded
-
# references URL list for this MIME::Type. See #urls for more information.
-
#
-
# #url has been deprecated and both versions (#references and #url) will be
-
# removed in mime-types 3.
-
#
-
# :attr_accessor: url
-
-
##
-
2
def url
-
MIME::Types.deprecated(self, __method__)
-
[]
-
end
-
-
##
-
2
def url=(_r) # :nodoc:
-
MIME::Types.deprecated(self, __method__)
-
end
-
-
##
-
# The cross-references list for this MIME::Type.
-
#
-
# :attr_accessor: xrefs
-
-
##
-
2
attr_reader :xrefs
-
-
##
-
2
def xrefs=(x) # :nodoc:
-
@xrefs = MIME::Types::Container.new.merge(x)
-
@xrefs.each_value(&:sort!)
-
@xrefs.each_value(&:uniq!)
-
end
-
-
# Returns an empty array. Prior to mime-types 2.99, this returned the decoded
-
# URL list for this MIME::Type.
-
#
-
# The special URL value IANA was translated into:
-
# http://www.iana.org/assignments/media-types/<mediatype>/<subtype>
-
#
-
# The special URL value RFC### was translated into:
-
# http://www.rfc-editor.org/rfc/rfc###.txt
-
#
-
# The special URL value DRAFT:name was translated into:
-
# https://datatracker.ietf.org/public/idindex.cgi?
-
# command=id_detail&filename=<name>
-
#
-
# The special URL value [token] was translated into:
-
# http://www.iana.org/assignments/contact-people.htm#<token>
-
#
-
# These values were accessible through #urls, which always returns an array.
-
#
-
# This method is deprecated and will be removed in mime-types 3.
-
2
def urls
-
MIME::Types.deprecated(self, __method__)
-
[]
-
end
-
-
# The decoded cross-reference URL list for this MIME::Type.
-
2
def xref_urls
-
xrefs.flat_map { |(type, values)|
-
case type
-
when 'rfc'.freeze
-
values.map { |data| 'http://www.iana.org/go/%s'.freeze % data }
-
when 'draft'.freeze
-
values.map { |data|
-
'http://www.iana.org/go/%s'.freeze % data.sub(/\ARFC/, 'draft')
-
}
-
when 'rfc-errata'.freeze
-
values.map { |data|
-
'http://www.rfc-editor.org/errata_search.php?eid=%s'.freeze % data
-
}
-
when 'person'.freeze
-
values.map { |data|
-
'http://www.iana.org/assignments/media-types/media-types.xhtml#%s'.freeze % data # rubocop:disable Metrics/LineLength
-
}
-
when 'template'.freeze
-
values.map { |data|
-
'http://www.iana.org/assignments/media-types/%s'.freeze % data
-
}
-
else # 'uri', 'text', etc.
-
values
-
end
-
}
-
end
-
-
##
-
# Prior to BCP 178 (RFC 6648), it could be assumed that MIME content types
-
# that start with <tt>x-</tt> were unregistered MIME. Per this BCP, this
-
# assumption is no longer being made by default in this library.
-
#
-
# There are three possible registration states for a MIME::Type:
-
# - Explicitly registered, like application/x-www-url-encoded.
-
# - Explicitly not registered, like image/webp.
-
# - Unspecified, in which case the media-type and the content-type will be
-
# scanned to see if they start with <tt>x-</tt>, indicating that they
-
# are assumed unregistered.
-
#
-
# In mime-types 3, only a MIME content type that is explicitly registered
-
# will be used; there will be assumption that <tt>x-</tt> types are
-
# unregistered.
-
2
def registered?
-
if @registered.nil?
-
(@raw_media_type !~ UNREGISTERED_RE) and
-
(@raw_sub_type !~ UNREGISTERED_RE)
-
else
-
!!@registered
-
end
-
end
-
-
2
def registered=(v) # :nodoc:
-
@registered = v.nil? ? v : !!v
-
end
-
-
# MIME types can be specified to be sent across a network in particular
-
# formats. This method returns +true+ when the MIME::Type encoding is set
-
# to <tt>base64</tt>.
-
2
def binary?
-
BINARY_ENCODINGS.include?(@encoding)
-
end
-
-
# MIME types can be specified to be sent across a network in particular
-
# formats. This method returns +false+ when the MIME::Type encoding is
-
# set to <tt>base64</tt>.
-
2
def ascii?
-
!binary?
-
end
-
-
# Returns +true+ when the simplified MIME::Type is one of the known digital
-
# signature types.
-
2
def signature?
-
!!@signature
-
end
-
-
2
def signature=(v) # :nodoc:
-
@signature = !!v
-
end
-
-
# Returns +false+. Prior to mime-types 2.99, would return +true+ if the
-
# MIME::Type is specific to an operating system.
-
#
-
# This method is deprecated and will be removed in mime-types 3.
-
2
def system?(*)
-
MIME::Types.deprecated(self, __method__)
-
false
-
end
-
-
# Returns +false+. Prior to mime-types 2.99, would return +true+ if the
-
# MIME::Type is specific to the current operating system as represented by
-
# RUBY_PLATFORM.
-
#
-
# This method is deprecated and will be removed in mime-types 3.
-
2
def platform?(*)
-
MIME::Types.deprecated(self, __method__)
-
false
-
end
-
-
# Returns +true+ if the MIME::Type specifies an extension list,
-
# indicating that it is a complete MIME::Type.
-
2
def complete?
-
!@extensions.empty?
-
end
-
-
# Returns the MIME::Type as a string.
-
2
def to_s
-
content_type
-
end
-
-
# Returns the MIME::Type as a string for implicit conversions. This allows
-
# MIME::Type objects to appear on either side of a comparison.
-
#
-
# 'text/plain' == MIME::Type.new('text/plain')
-
2
def to_str
-
content_type
-
end
-
-
# Returns the MIME::Type as an array suitable for use with
-
# MIME::Type.from_array.
-
#
-
# This method is deprecated and will be removed in mime-types 3.
-
2
def to_a
-
MIME::Types.deprecated(self, __method__)
-
[ @content_type, @extensions, @encoding, nil, obsolete?, @docs, [],
-
registered? ]
-
end
-
-
# Returns the MIME::Type as an array suitable for use with
-
# MIME::Type.from_hash.
-
#
-
# This method is deprecated and will be removed in mime-types 3.
-
2
def to_hash
-
MIME::Types.deprecated(self, __method__)
-
{ 'Content-Type' => @content_type,
-
'Content-Transfer-Encoding' => @encoding,
-
'Extensions' => @extensions,
-
'System' => nil,
-
'Obsolete' => obsolete?,
-
'Docs' => @docs,
-
'URL' => [],
-
'Registered' => registered?,
-
}
-
end
-
-
# Converts the MIME::Type to a JSON string.
-
2
def to_json(*args)
-
require 'json'
-
to_h.to_json(*args)
-
end
-
-
# Converts the MIME::Type to a hash suitable for use in JSON. The output
-
# of this method can also be used to initialize a MIME::Type.
-
2
def to_h
-
encode_with({})
-
end
-
-
# Populates the +coder+ with attributes about this record for
-
# serialization. The structure of +coder+ should match the structure used
-
# with #init_with.
-
#
-
# This method should be considered a private implementation detail.
-
2
def encode_with(coder)
-
coder['content-type'] = @content_type
-
coder['docs'] = @docs unless @docs.nil? or @docs.empty?
-
coder['friendly'] = @friendly unless @friendly.empty?
-
coder['encoding'] = @encoding
-
coder['extensions'] = @extensions unless @extensions.empty?
-
if obsolete?
-
coder['obsolete'] = obsolete?
-
coder['use-instead'] = use_instead if use_instead
-
end
-
coder['xrefs'] = xrefs unless xrefs.empty?
-
coder['registered'] = registered?
-
coder['signature'] = signature? if signature?
-
coder
-
end
-
-
# Initialize an empty object from +coder+, which must contain the
-
# attributes necessary for initializing an empty object.
-
#
-
# This method should be considered a private implementation detail.
-
2
def init_with(coder)
-
self.content_type = coder['content-type']
-
self.docs = coder['docs'] || []
-
friendly(coder['friendly'] || {})
-
self.encoding = coder['encoding']
-
self.extensions = coder['extensions'] || []
-
self.obsolete = coder['obsolete']
-
self.registered = coder['registered']
-
self.signature = coder['signature']
-
self.xrefs = coder['xrefs'] || {}
-
self.use_instead = coder['use-instead']
-
end
-
-
2
class << self
-
# The MIME types main- and sub-label can both start with <tt>x-</tt>,
-
# which indicates that it is a non-registered name. Of course, after
-
# registration this flag may disappear, adds to the confusing
-
# proliferation of MIME types. The simplified +content_type+ string has the
-
# <tt>x-</tt> removed and is translated to lowercase.
-
2
def simplified(content_type)
-
11718
matchdata = case content_type
-
when MatchData
-
3906
content_type
-
else
-
7812
MEDIA_TYPE_RE.match(content_type)
-
end
-
-
11718
return unless matchdata
-
-
matchdata.captures.map { |e|
-
7812
e.downcase!
-
7812
e.gsub!(UNREGISTERED_RE, ''.freeze)
-
7812
e
-
3906
}.join('/'.freeze)
-
end
-
-
# Converts a provided +content_type+ into a translation key suitable for
-
# use with the I18n library.
-
2
def i18n_key(content_type)
-
3906
matchdata = case content_type
-
when MatchData
-
3906
content_type
-
else
-
MEDIA_TYPE_RE.match(content_type)
-
end
-
-
3906
return unless matchdata
-
-
matchdata.captures.map { |e|
-
7812
e.downcase!
-
7812
e.gsub!(UNREGISTERED_RE, ''.freeze)
-
7812
e.gsub!(I18N_RE, '-'.freeze)
-
7812
e
-
3906
}.join('.'.freeze)
-
end
-
-
# Creates a MIME::Type from an +args+ array in the form of:
-
# [ type-name, [ extensions ], encoding, system ]
-
#
-
# +extensions+, and +encoding+ are optional; +system+ is ignored.
-
#
-
# MIME::Type.from_array('application/x-ruby', %w(rb), '8bit')
-
# MIME::Type.from_array([ 'application/x-ruby', [ 'rb' ], '8bit' ])
-
#
-
# These are equivalent to:
-
#
-
# MIME::Type.new('application/x-ruby') do |t|
-
# t.extensions = %w(rb)
-
# t.encoding = '8bit'
-
# end
-
#
-
# It will yield the type (+t+) if a block is given.
-
#
-
# This method is deprecated and will be removed in mime-types 3.
-
2
def from_array(*args) # :yields t:
-
MIME::Types.deprecated(self, __method__)
-
-
# Dereferences the array one level, if necessary.
-
args = args.first if args.first.kind_of? Array
-
-
unless args.size.between?(1, 8)
-
fail ArgumentError,
-
'Array provided must contain between one and eight elements.'
-
end
-
-
MIME::Type.new(args.shift) do |t|
-
t.extensions, t.encoding, _system, t.obsolete, t.docs, _references,
-
t.registered = *args
-
yield t if block_given?
-
end
-
end
-
-
# Creates a MIME::Type from a +hash+. Keys are case-insensitive, dashes
-
# may be replaced with underscores, and the internal Symbol of the
-
# lowercase-underscore version can be used as well. That is,
-
# Content-Type can be provided as content-type, Content_Type,
-
# content_type, or :content_type.
-
#
-
# Known keys are <tt>Content-Type</tt>,
-
# <tt>Content-Transfer-Encoding</tt>, <tt>Extensions</tt>, and
-
# <tt>System</tt>. +System+ is ignored.
-
#
-
# MIME::Type.from_hash('Content-Type' => 'text/x-yaml',
-
# 'Content-Transfer-Encoding' => '8bit',
-
# 'System' => 'linux',
-
# 'Extensions' => ['yaml', 'yml'])
-
#
-
# This is equivalent to:
-
#
-
# MIME::Type.new('text/x-yaml') do |t|
-
# t.encoding = '8bit'
-
# t.system = 'linux'
-
# t.extensions = ['yaml', 'yml']
-
# end
-
#
-
# It will yield the constructed type +t+ if a block has been provided.
-
#
-
#
-
# This method is deprecated and will be removed in mime-types 3.
-
2
def from_hash(hash) # :yields t:
-
MIME::Types.deprecated(self, __method__)
-
type = {}
-
hash.each_pair do |k, v|
-
type[k.to_s.tr('A-Z', 'a-z').gsub(/-/, '_').to_sym] = v
-
end
-
-
MIME::Type.new(type[:content_type]) do |t|
-
t.extensions = type[:extensions]
-
t.encoding = type[:content_transfer_encoding]
-
t.obsolete = type[:obsolete]
-
t.docs = type[:docs]
-
t.url = type[:url]
-
t.registered = type[:registered]
-
-
yield t if block_given?
-
end
-
end
-
-
# Essentially a copy constructor for +mime_type+.
-
#
-
# MIME::Type.from_mime_type(plaintext)
-
#
-
# is equivalent to:
-
#
-
# MIME::Type.new(plaintext.content_type.dup) do |t|
-
# t.extensions = plaintext.extensions.dup
-
# t.system = plaintext.system.dup
-
# t.encoding = plaintext.encoding.dup
-
# end
-
#
-
# It will yield the type (+t+) if a block is given.
-
#
-
# This method is deprecated and will be removed in mime-types 3.
-
2
def from_mime_type(mime_type) # :yields the new MIME::Type:
-
MIME::Types.deprecated(self, __method__)
-
new(mime_type)
-
end
-
end
-
-
2
private
-
-
2
def content_type=(type_string)
-
3906
match = MEDIA_TYPE_RE.match(type_string)
-
3906
fail InvalidContentType, type_string if match.nil?
-
-
3906
@content_type = type_string
-
3906
@raw_media_type, @raw_sub_type = match.captures
-
3906
@simplified = MIME::Type.simplified(match)
-
3906
@i18n_key = MIME::Type.i18n_key(match)
-
3906
@media_type, @sub_type = MEDIA_TYPE_RE.match(@simplified).captures
-
end
-
end
-
2
require 'mime/type'
-
-
# A version of MIME::Type that works hand-in-hand with a MIME::Types::Columnar
-
# container to load data by columns.
-
#
-
# When a field is has not yet been loaded, that data will be loaded for all
-
# types in the container before forwarding the message to MIME::Type.
-
#
-
# More information can be found in MIME::Types::Columnar.
-
#
-
# MIME::Type::Columnar is *not* intended to be created except by
-
# MIME::Types::Columnar containers.
-
2
class MIME::Type::Columnar < MIME::Type
-
2
attr_writer :friendly # :nodoc:
-
-
2
def initialize(container, content_type, extensions) # :nodoc:
-
3906
@container = container
-
3906
self.content_type = content_type
-
3906
self.extensions = extensions
-
end
-
-
2
def friendly(*) # :nodoc:
-
@container.send(:load_friendly) unless defined?(@friendly)
-
super if @friendly
-
end
-
-
2
def encoding # :nodoc:
-
@container.send(:load_encoding) unless defined?(@encoding)
-
@encoding
-
end
-
-
2
def docs # :nodoc:
-
@container.send(:load_docs) unless defined?(@docs)
-
@docs
-
end
-
-
2
def obsolete? # :nodoc:
-
@container.send(:load_obsolete) unless defined?(@obsolete)
-
super
-
end
-
-
2
def registered? # :nodoc:
-
@container.send(:load_registered) unless defined?(@registered)
-
super
-
end
-
-
2
def signature? # :nodoc:
-
@container.send(:load_signature) unless defined?(@signature)
-
super
-
end
-
-
2
def xrefs # :nodoc:
-
@container.send(:load_xrefs) unless defined?(@xrefs)
-
@xrefs
-
end
-
-
2
def use_instead # :nodoc:
-
@container.send(:load_use_instead) unless defined?(@use_instead)
-
@use_instead
-
end
-
-
2
def binary? # :nodoc:
-
@container.send(:load_encoding) unless defined?(@encoding)
-
super
-
end
-
-
2
def to_a # :nodoc:
-
@container.send(:load_encoding) unless defined?(@encoding)
-
@container.send(:load_docs) unless defined?(@docs)
-
super
-
end
-
-
2
def to_hash # :nodoc:
-
@container.send(:load_encoding) unless defined?(@encoding)
-
@container.send(:load_docs) unless defined?(@docs)
-
super
-
end
-
-
2
def encode_with(coder) # :nodoc:
-
@container.send(:load_friendly) unless defined?(@friendly)
-
@container.send(:load_encoding) unless defined?(@encoding)
-
@container.send(:load_docs) unless defined?(@docs)
-
@container.send(:load_obsolete) unless defined?(@obsolete)
-
@container.send(:load_use_instead) unless defined?(@use_instead)
-
@container.send(:load_xrefs) unless defined?(@xrefs)
-
@container.send(:load_registered) unless defined?(@registered)
-
@container.send(:load_signature) unless defined?(@signature)
-
super
-
end
-
end
-
# -*- ruby encoding: utf-8 -*-
-
-
2
require 'mime/types/deprecations'
-
2
require 'mime/type'
-
2
require 'mime/types/cache'
-
2
require 'mime/types/loader'
-
-
# MIME::Types is a registry of MIME types. It is both a class (created with
-
# MIME::Types.new) and a default registry (loaded automatically or through
-
# interactions with MIME::Types.[] and MIME::Types.type_for).
-
#
-
# == The Default mime-types Registry
-
#
-
# The default mime-types registry is loaded automatically when the library
-
# is required (<tt>require 'mime/types'</tt>), but it may be lazily loaded
-
# (loaded on first use) with the use of the environment variable
-
# +RUBY_MIME_TYPES_LAZY_LOAD+ having any value other than +false+. The
-
# initial startup is about 14× faster (~10 ms vs ~140 ms), but the
-
# registry will be loaded at some point in the future.
-
#
-
# The default mime-types registry can also be loaded from a Marshal cache
-
# file specific to the version of MIME::Types being loaded. This will be
-
# handled automatically with the use of a file referred to in the
-
# environment variable +RUBY_MIME_TYPES_CACHE+. MIME::Types will attempt to
-
# load the registry from this cache file (MIME::Type::Cache.load); if it
-
# cannot be loaded (because the file does not exist, there is an error, or
-
# the data is for a different version of mime-types), the default registry
-
# will be loaded from the normal JSON version and then the cache file will
-
# be *written* to the location indicated by +RUBY_MIME_TYPES_CACHE+. Cache
-
# file loads just over 4½× faster (~30 ms vs ~140 ms).
-
# loads.
-
#
-
# Notes:
-
# * The loading of the default registry is *not* atomic; when using a
-
# multi-threaded environment, it is recommended that lazy loading is not
-
# used and mime-types is loaded as early as possible.
-
# * Cache files should be specified per application in a multiprocess
-
# environment and should be initialized during deployment or before
-
# forking to minimize the chance that the multiple processes will be
-
# trying to write to the same cache file at the same time, or that two
-
# applications that are on different versions of mime-types would be
-
# thrashing the cache.
-
# * Unless cache files are preinitialized, the application using the
-
# mime-types cache file must have read/write permission to the cache file.
-
#
-
# == Usage
-
# require 'mime/types'
-
#
-
# plaintext = MIME::Types['text/plain']
-
# print plaintext.media_type # => 'text'
-
# print plaintext.sub_type # => 'plain'
-
#
-
# puts plaintext.extensions.join(" ") # => 'asc txt c cc h hh cpp'
-
#
-
# puts plaintext.encoding # => 8bit
-
# puts plaintext.binary? # => false
-
# puts plaintext.ascii? # => true
-
# puts plaintext.obsolete? # => false
-
# puts plaintext.registered? # => true
-
# puts plaintext == 'text/plain' # => true
-
# puts MIME::Type.simplified('x-appl/x-zip') # => 'appl/zip'
-
#
-
2
class MIME::Types
-
# The release version of Ruby MIME::Types
-
2
VERSION = MIME::Type::VERSION
-
-
2
include Enumerable
-
-
# The data version.
-
2
attr_reader :data_version
-
-
# Creates a new MIME::Types registry.
-
2
def initialize
-
2
@type_variants = Container.new
-
2
@extension_index = Container.new
-
2
@data_version = VERSION.dup.freeze
-
end
-
-
# This method is deprecated and will be removed in mime-types 3.0.
-
2
def add_type_variant(mime_type) # :nodoc:
-
MIME::Types.deprecated(self, __method__, :private)
-
add_type_variant!(mime_type)
-
end
-
-
# This method is deprecated and will be removed in mime-types 3.0.
-
2
def index_extensions(mime_type) # :nodoc:
-
MIME::Types.deprecated(self, __method__, :private)
-
index_extensions!(mime_type)
-
end
-
-
# This method is deprecated and will be removed in mime-types 3.0.
-
2
def defined_types # :nodoc:
-
MIME::Types.deprecated(self, __method__)
-
@type_variants.values.flatten
-
end
-
-
# Returns the number of known type variants.
-
2
def count
-
@type_variants.values.reduce(0) { |m, o| m + o.size }
-
end
-
-
# Iterates through the type variants.
-
2
def each
-
if block_given?
-
@type_variants.each_value { |tv| tv.each { |t| yield t } }
-
else
-
enum_for(:each)
-
end
-
end
-
-
2
@__types__ = nil
-
-
# Returns a list of MIME::Type objects, which may be empty. The optional
-
# flag parameters are <tt>:complete</tt> (finds only complete MIME::Type
-
# objects) and <tt>:registered</tt> (finds only MIME::Types that are
-
# registered). It is possible for multiple matches to be returned for
-
# either type (in the example below, 'text/plain' returns two values --
-
# one for the general case, and one for VMS systems).
-
#
-
# puts "\nMIME::Types['text/plain']"
-
# MIME::Types['text/plain'].each { |t| puts t.to_a.join(", ") }
-
#
-
# puts "\nMIME::Types[/^image/, complete: true]"
-
# MIME::Types[/^image/, :complete => true].each do |t|
-
# puts t.to_a.join(", ")
-
# end
-
#
-
# If multiple type definitions are returned, returns them sorted as
-
# follows:
-
# 1. Complete definitions sort before incomplete ones;
-
# 2. IANA-registered definitions sort before LTSW-recorded
-
# definitions.
-
# 3. Current definitions sort before obsolete ones;
-
# 4. Obsolete definitions with use-instead clauses sort before those
-
# without;
-
# 5. Obsolete definitions use-instead clauses are compared.
-
# 6. Sort on name.
-
#
-
# The previously supported (but deprecated) <tt>:platform</tt> flag is now ignored.
-
2
def [](type_id, flags = {})
-
if flags.key?(:platform)
-
MIME::Types.deprecated(self, __method__, 'using the :platform flag')
-
end
-
-
matches = case type_id
-
when MIME::Type
-
@type_variants[type_id.simplified]
-
when Regexp
-
match(type_id)
-
else
-
@type_variants[MIME::Type.simplified(type_id)]
-
end
-
-
prune_matches(matches, flags).sort { |a, b| a.priority_compare(b) }
-
end
-
-
# Return the list of MIME::Types which belongs to the file based on its
-
# filename extension. If there is no extension, the filename will be used
-
# as the matching criteria on its own.
-
#
-
# This will always return a merged, flatten, priority sorted, unique array.
-
#
-
# puts MIME::Types.type_for('citydesk.xml')
-
# => [application/xml, text/xml]
-
# puts MIME::Types.type_for('citydesk.gif')
-
# => [image/gif]
-
# puts MIME::Types.type_for(%w(citydesk.xml citydesk.gif))
-
# => [application/xml, image/gif, text/xml]
-
#
-
# The deprecated +platform+ flag is ignored.
-
2
def type_for(filename, platform = :deprecated)
-
types = Array(filename).flat_map { |fn|
-
@extension_index[fn.chomp.downcase[/\.?([^.]*?)$/, 1]]
-
}.compact.sort { |a, b| a.priority_compare(b) }.uniq
-
-
unless platform == :deprecated
-
MIME::Types.deprecated(self, __method__, 'using the platform parameter')
-
end
-
types
-
end
-
2
alias_method :of, :type_for
-
-
# Add one or more MIME::Type objects to the set of known types. If the
-
# type is already known, a warning will be displayed.
-
#
-
# The last parameter may be the value <tt>:silent</tt> or +true+ which
-
# will suppress duplicate MIME type warnings.
-
2
def add(*types)
-
3906
quiet = ((types.last == :silent) or (types.last == true))
-
-
3906
types.each do |mime_type|
-
3906
case mime_type
-
when true, false, nil, Symbol
-
nil
-
when MIME::Types
-
variants = mime_type.instance_variable_get(:@type_variants)
-
add(*variants.values.flatten, quiet)
-
when Array
-
add(*mime_type, quiet)
-
else
-
3906
add_type(mime_type, quiet)
-
end
-
end
-
end
-
-
# Add a single MIME::Type object to the set of known types. If the +type+ is
-
# already known, a warning will be displayed. The +quiet+ parameter may be a
-
# truthy value to suppress that warning.
-
2
def add_type(type, quiet = false)
-
3906
if !quiet and @type_variants[type.simplified].include?(type)
-
MIME::Types.logger.warn <<-warning
-
Type #{type} is already registered as a variant of #{type.simplified}.
-
warning
-
end
-
-
3906
add_type_variant!(type)
-
3906
index_extensions!(type)
-
end
-
-
2
class << self
-
2
include Enumerable
-
-
# Load MIME::Types from a v1 file registry.
-
#
-
# This method has been deprecated and will be removed in mime-types 3.0.
-
2
def load_from_file(filename)
-
MIME::Types.deprecated(self, __method__)
-
MIME::Types::Loader.load_from_v1(filename)
-
end
-
-
# MIME::Types#[] against the default MIME::Types registry.
-
2
def [](type_id, flags = {})
-
__types__[type_id, flags]
-
end
-
-
# MIME::Types#count against the default MIME::Types registry.
-
2
def count
-
__types__.count
-
end
-
-
# MIME::Types#each against the default MIME::Types registry.
-
2
def each
-
if block_given?
-
__types__.each { |t| yield t }
-
else
-
enum_for(:each)
-
end
-
end
-
-
# MIME::Types#type_for against the default MIME::Types registry.
-
2
def type_for(filename, platform = :deprecated)
-
__types__.type_for(filename, platform)
-
end
-
2
alias_method :of, :type_for
-
-
# MIME::Types#add against the default MIME::Types registry.
-
2
def add(*types)
-
__types__.add(*types)
-
end
-
-
# Returns the currently defined cache file, if any.
-
#
-
# This method has been deprecated and will be removed in mime-types 3.0.
-
2
def cache_file
-
MIME::Types.deprecated(self, __method__)
-
ENV['RUBY_MIME_TYPES_CACHE']
-
end
-
-
2
def add_type_variant(mime_type) # :nodoc:
-
__types__.add_type_variant(mime_type)
-
end
-
-
2
def index_extensions(mime_type) # :nodoc:
-
__types__.index_extensions(mime_type)
-
end
-
-
2
private
-
-
2
def lazy_load?
-
2
(lazy = ENV['RUBY_MIME_TYPES_LAZY_LOAD']) && (lazy != 'false')
-
end
-
-
2
def __types__
-
(defined?(@__types__) and @__types__) or load_default_mime_types
-
end
-
-
2
unless private_method_defined?(:load_mode)
-
def load_mode
-
{}
-
end
-
end
-
-
2
def load_default_mime_types(mode = load_mode())
-
2
@__types__ = MIME::Types::Cache.load
-
2
unless @__types__
-
2
@__types__ = MIME::Types::Loader.load(mode)
-
2
MIME::Types::Cache.save(@__types__)
-
end
-
2
@__types__
-
end
-
end
-
-
2
private
-
-
2
def add_type_variant!(mime_type)
-
3906
@type_variants[mime_type.simplified] << mime_type
-
end
-
-
2
def index_extensions!(mime_type)
-
6534
mime_type.extensions.each { |ext| @extension_index[ext] << mime_type }
-
end
-
-
2
def prune_matches(matches, flags)
-
matches.delete_if { |e| !e.complete? } if flags[:complete]
-
matches.delete_if { |e| !e.registered? } if flags[:registered]
-
matches
-
end
-
-
2
def match(pattern)
-
@type_variants.select { |k, _| k =~ pattern }.values.flatten
-
end
-
-
2
load_default_mime_types(load_mode) unless lazy_load?
-
end
-
-
# vim: ft=ruby
-
# -*- ruby encoding: utf-8 -*-
-
-
2
class MIME::Types
-
2
Cache = Struct.new(:version, :data) # :nodoc:
-
-
# Caching of MIME::Types registries is advisable if you will be loading
-
# the default registry relatively frequently. With the class methods on
-
# MIME::Types::Cache, any MIME::Types registry can be marshaled quickly
-
# and easily.
-
#
-
# The cache is invalidated on a per-version basis; a cache file for
-
# version 2.0 will not be reused with version 2.0.1.
-
2
class Cache
-
2
class << self
-
# Attempts to load the cache from the file provided as a parameter or in
-
# the environment variable +RUBY_MIME_TYPES_CACHE+. Returns +nil+ if the
-
# file does not exist, if the file cannot be loaded, or if the data in
-
# the cache version is different than this version.
-
2
def load(cache_file = nil)
-
2
cache_file ||= ENV['RUBY_MIME_TYPES_CACHE']
-
2
return nil unless cache_file and File.exist?(cache_file)
-
-
cache = Marshal.load(File.binread(cache_file))
-
if cache.version == MIME::Types::VERSION
-
Marshal.load(cache.data)
-
else
-
MIME::Types.logger.warn <<-warning.chomp
-
Could not load MIME::Types cache: invalid version
-
warning
-
nil
-
end
-
rescue => e
-
MIME::Types.logger.warn <<-warning.chomp
-
Could not load MIME::Types cache: #{e}
-
warning
-
return nil
-
end
-
-
# Attempts to save the types provided to the cache file provided.
-
#
-
# If +types+ is not provided or is +nil+, the cache will contain the
-
# current MIME::Types default registry.
-
#
-
# If +cache_file+ is not provided or is +nil+, the cache will be written
-
# to the file specified in the environment variable
-
# +RUBY_MIME_TYPES_CACHE+. If there is no cache file specified either
-
# directly or through the environment, this method will return +nil+
-
2
def save(types = nil, cache_file = nil)
-
2
cache_file ||= ENV['RUBY_MIME_TYPES_CACHE']
-
2
return nil unless cache_file
-
-
types ||= MIME::Types.send(:__types__)
-
-
File.open(cache_file, 'wb') do |f|
-
f.write(Marshal.dump(new(types.data_version, Marshal.dump(types))))
-
end
-
end
-
end
-
end
-
-
# MIME::Types requires a container Hash with a default values for keys
-
# resulting in an empty array (<tt>[]</tt>), but this cannot be dumped
-
# through Marshal because of the presence of that default Proc. This class
-
# exists solely to satisfy that need.
-
2
class Container < Hash # :nodoc:
-
2
def initialize
-
4
super
-
6124
self.default_proc = ->(h, k) { h[k] = [] }
-
end
-
-
2
def marshal_dump
-
{}.merge(self)
-
end
-
-
2
def marshal_load(hash)
-
self.default_proc = ->(h, k) { h[k] = [] }
-
self.merge!(hash)
-
end
-
end
-
end
-
2
module MIME
-
2
class Types
-
end
-
end
-
-
2
require 'mime/type/columnar'
-
-
# MIME::Types::Columnar is used to extend a MIME::Types container to load data
-
# by columns instead of from JSON or YAML. Column loads of MIME types loaded
-
# through the columnar store are synchronized with a Mutex.
-
#
-
# MIME::Types::Columnar is not intended to be used directly, but will be added
-
# to an instance of MIME::Types when it is loaded with
-
# MIME::Types::Loader#load_columnar.
-
2
module MIME::Types::Columnar
-
2
LOAD_MUTEX = Mutex.new # :nodoc:
-
-
2
def self.extended(obj) # :nodoc:
-
2
super
-
2
obj.instance_variable_set(:@__mime_data__, [])
-
2
obj.instance_variable_set(:@__attributes__, [])
-
end
-
-
# Load the first column data file (type and extensions).
-
2
def load_base_data(path) #:nodoc:
-
2
@__root__ = path
-
-
2
each_file_line('content_type', false) do |line|
-
3906
content_type, *extensions = line.split
-
-
3906
type = MIME::Type::Columnar.new(self, content_type, extensions)
-
3906
@__mime_data__ << type
-
3906
add(type)
-
end
-
-
2
self
-
end
-
-
2
private
-
-
2
def each_file_line(name, lookup = true)
-
2
LOAD_MUTEX.synchronize do
-
2
next if @__attributes__.include?(name)
-
-
2
File.open(File.join(@__root__, "mime.#{name}.column"), 'r:UTF-8') do |f|
-
2
i = -1
-
-
2
f.each_line do |line|
-
3906
line.chomp!
-
-
3906
if lookup
-
type = @__mime_data__[i += 1] or next
-
yield type, line
-
else
-
3906
yield line
-
end
-
end
-
end
-
-
2
@__attributes__ << name
-
end
-
end
-
-
2
def load_encoding
-
pool = {}
-
each_file_line('encoding') do |type, line|
-
line.freeze
-
type.encoding = (pool[line] ||= line)
-
end
-
end
-
-
2
def load_docs
-
each_file_line('docs') do |type, line|
-
type.docs = arr(line)
-
end
-
end
-
-
2
def load_obsolete
-
each_file_line('obsolete') do |type, line|
-
type.obsolete = bool(line)
-
end
-
end
-
-
2
def load_registered
-
each_file_line('registered') do |type, line|
-
type.registered = bool(line)
-
end
-
end
-
-
2
def load_signature
-
each_file_line('signature') do |type, line|
-
type.signature = bool(line)
-
end
-
end
-
-
2
def load_xrefs
-
each_file_line('xrefs') { |type, line| type.xrefs = dict(line) }
-
end
-
-
2
def load_friendly
-
each_file_line('friendly') { |type, line|
-
v = dict(line)
-
type.friendly = v.empty? ? nil : v
-
}
-
end
-
-
2
def load_use_instead
-
each_file_line('use_instead') do |type, line|
-
type.use_instead = (line unless line == '-'.freeze)
-
end
-
end
-
-
2
def dict(line)
-
if line == '-'.freeze
-
{}
-
else
-
line.split('|'.freeze).each_with_object({}) { |l, h|
-
k, v = l.split('^'.freeze)
-
v = [ nil ] if v.empty?
-
h[k] = v
-
}
-
end
-
end
-
-
2
def arr(line)
-
if line == '-'.freeze
-
[]
-
else
-
line.split('|'.freeze).flatten.compact.uniq
-
end
-
end
-
-
2
def bool(line)
-
line == '1'.freeze ? true : false
-
end
-
end
-
-
2
unless MIME::Types.private_method_defined?(:load_mode)
-
2
class << MIME::Types
-
2
private
-
-
2
def load_mode
-
2
{ columnar: true }
-
end
-
end
-
-
2
require 'mime/types'
-
end
-
# -*- ruby encoding: utf-8 -*-
-
-
2
require 'mime/types/logger'
-
-
# The namespace for MIME applications, tools, and libraries.
-
2
module MIME
-
2
class Types
-
# Used to mark a method as deprecated in the mime-types interface.
-
2
def self.deprecated(klass, sym, message = nil, &block) # :nodoc:
-
level = case klass
-
when Class, Module
-
'.'
-
else
-
klass = klass.class
-
'#'
-
end
-
message = case message
-
when :private, :protected
-
"and will be #{message}"
-
when nil
-
'and will be removed'
-
else
-
message
-
end
-
MIME::Types.logger.warn <<-warning.chomp
-
#{caller[1]}: #{klass}#{level}#{sym} is deprecated #{message}.
-
warning
-
block.call if block
-
end
-
end
-
-
2
class << self
-
# MIME::InvalidContentType was moved to MIME::Type::InvalidContentType.
-
# Provide a single warning about this fact in the interim.
-
2
def const_missing(name) # :nodoc:
-
case name.to_s
-
when 'InvalidContentType'
-
warn_about_moved_constants(name)
-
MIME::Type.const_get(name.to_sym)
-
else
-
super
-
end
-
end
-
-
2
private
-
-
2
def warn_about_moved_constants(name)
-
MIME::Types.logger.warn <<-warning.chomp
-
#{caller[1]}: MIME::#{name} is deprecated. Use MIME::Type::#{name} instead.
-
warning
-
end
-
end
-
end
-
# -*- ruby encoding: utf-8 -*-
-
-
2
module MIME; end
-
2
class MIME::Types; end
-
-
2
require 'mime/types/loader_path'
-
-
# This class is responsible for initializing the MIME::Types registry from
-
# the data files supplied with the mime-types library.
-
#
-
# The Loader will use one of the following paths:
-
# 1. The +path+ provided in its constructor argument;
-
# 2. The value of ENV['RUBY_MIME_TYPES_DATA']; or
-
# 3. The value of MIME::Types::Loader::PATH.
-
#
-
# When #load is called, the +path+ will be searched recursively for all YAML
-
# (.yml or .yaml) files. By convention, there is one file for each media
-
# type (application.yml, audio.yml, etc.), but this is not required.
-
2
class MIME::Types::Loader
-
# The path that will be read for the MIME::Types files.
-
2
attr_reader :path
-
# The MIME::Types container instance that will be loaded. If not provided
-
# at initialization, a new MIME::Types instance will be constructed.
-
2
attr_reader :container
-
-
# Creates a Loader object that can be used to load MIME::Types registries
-
# into memory, using YAML, JSON, or v1 registry format loaders.
-
2
def initialize(path = nil, container = nil)
-
2
path = path || ENV['RUBY_MIME_TYPES_DATA'] || MIME::Types::Loader::PATH
-
2
@container = container || MIME::Types.new
-
2
@path = File.expand_path(path)
-
# begin
-
# require 'mime/lazy_types'
-
# @container.extend(MIME::LazyTypes)
-
# end
-
end
-
-
# Loads a MIME::Types registry from YAML files (<tt>*.yml</tt> or
-
# <tt>*.yaml</tt>) recursively found in +path+.
-
#
-
# It is expected that the YAML objects contained within the registry array
-
# will be tagged as <tt>!ruby/object:MIME::Type</tt>.
-
#
-
# Note that the YAML format is about 2½ times *slower* than either the v1
-
# format or the JSON format.
-
#
-
# NOTE: The purpose of this format is purely for maintenance reasons.
-
2
def load_yaml
-
Dir[yaml_path].sort.each do |f|
-
container.add(*self.class.load_from_yaml(f), :silent)
-
end
-
container
-
end
-
-
# Loads a MIME::Types registry from JSON files (<tt>*.json</tt>)
-
# recursively found in +path+.
-
#
-
# It is expected that the JSON objects will be an array of hash objects.
-
# The JSON format is the registry format for the MIME types registry
-
# shipped with the mime-types library.
-
2
def load_json
-
Dir[json_path].sort.each do |f|
-
types = self.class.load_from_json(f)
-
container.add(*types, :silent)
-
end
-
container
-
end
-
-
# Loads a MIME::Types registry from columnar files recursively found in
-
# +path+.
-
2
def load_columnar
-
2
require 'mime/types/columnar' unless defined?(MIME::Types::Columnar)
-
2
container.extend(MIME::Types::Columnar)
-
2
container.load_base_data(path)
-
-
2
container
-
end
-
-
# Loads a MIME::Types registry. Loads from JSON files by default
-
# (#load_json).
-
#
-
# This will load from columnar files (#load_columnar) if <tt>columnar:
-
# true</tt> is provided in +options+ and there are columnar files in +path+.
-
2
def load(options = { columnar: false })
-
2
if options[:columnar] && !Dir[columnar_path].empty?
-
2
load_columnar
-
else
-
load_json
-
end
-
end
-
-
# Loads a MIME::Types registry from files found in +path+ that are in the
-
# v1 data format. The file search for this will exclude both JSON
-
# (<tt>*.json</tt>) and YAML (<tt>*.yml</tt> or <tt>*.yaml</tt>) files.
-
#
-
# This method has been deprecated and will be removed from mime-types 3.0.
-
2
def load_v1
-
MIME::Types.deprecated(self.class, __method__)
-
Dir[v1_path].sort.each do |f|
-
next if f =~ /\.(?:ya?ml|json|column)$/
-
container.add(self.class.load_from_v1(f, true), true)
-
end
-
container
-
end
-
-
# Raised when a V1 format file is discovered. This exception will be removed
-
# for mime-types 3.0.
-
2
BadV1Format = Class.new(Exception)
-
-
2
class << self
-
# Loads the default MIME::Type registry.
-
2
def load(options = { columnar: false })
-
2
new.load(options)
-
end
-
-
# Build the type list from a file in the format:
-
#
-
# [*][!][os:]mt/st[<ws>@ext][<ws>:enc][<ws>'url-list][<ws>=docs]
-
#
-
# == *
-
# An unofficial MIME type. This should be used if and only if the MIME type
-
# is not properly specified (that is, not under either x-type or
-
# vnd.name.type).
-
#
-
# == !
-
# An obsolete MIME type. May be used with an unofficial MIME type.
-
#
-
# == os:
-
# Platform-specific MIME type definition.
-
#
-
# == mt
-
# The media type.
-
#
-
# == st
-
# The media subtype.
-
#
-
# == <ws>@ext
-
# The list of comma-separated extensions.
-
#
-
# == <ws>:enc
-
# The encoding.
-
#
-
# == <ws>'url-list
-
# The list of comma-separated URLs.
-
#
-
# == <ws>=docs
-
# The documentation string.
-
#
-
# That is, everything except the media type and the subtype is optional. The
-
# more information that's available, though, the richer the values that can
-
# be provided.
-
#
-
# This method has been deprecated and will be removed in mime-types 3.0.
-
2
def load_from_v1(filename, __internal__ = false)
-
MIME::Types.deprecated(self.class, __method__) unless __internal__
-
data = read_file(filename).split($/)
-
mime = MIME::Types.new
-
data.each_with_index { |line, index|
-
item = line.chomp.strip
-
next if item.empty?
-
-
m = V1_FORMAT.match(item)
-
-
unless m
-
MIME::Types.logger.warn <<-EOS
-
#{filename}:#{index + 1}: Parsing error in v1 MIME type definition.
-
=> #{line}
-
EOS
-
fail BadV1Format, line
-
end
-
-
unregistered, obsolete, _, mediatype, subtype, extensions, encoding,
-
urls, docs, _ = *m.captures
-
-
next if mediatype.nil?
-
-
extensions &&= extensions.split(/,/)
-
urls &&= urls.split(/,/)
-
-
if docs.nil?
-
use_instead = nil
-
else
-
use_instead = docs.scan(%r{use-instead:(\S+)}).flatten.first
-
docs = docs.gsub(%r{use-instead:\S+}, '').squeeze(' \t')
-
end
-
-
mime_type = MIME::Type.new("#{mediatype}/#{subtype}") do |t|
-
t.extensions = extensions
-
t.encoding = encoding
-
t.obsolete = obsolete
-
t.registered = false if unregistered
-
t.use_instead = use_instead
-
t.docs = docs
-
end
-
-
mime.add_type(mime_type, true)
-
}
-
mime
-
end
-
-
# Loads MIME::Types from a single YAML file.
-
#
-
# It is expected that the YAML objects contained within the registry
-
# array will be tagged as <tt>!ruby/object:MIME::Type</tt>.
-
#
-
# Note that the YAML format is about 2½ times *slower* than either the v1
-
# format or the JSON format.
-
#
-
# NOTE: The purpose of this format is purely for maintenance reasons.
-
2
def load_from_yaml(filename)
-
begin
-
require 'psych'
-
rescue LoadError
-
nil
-
end
-
require 'yaml'
-
YAML.load(read_file(filename))
-
end
-
-
# Loads MIME::Types from a single JSON file.
-
#
-
# It is expected that the JSON objects will be an array of hash objects.
-
# The JSON format is the registry format for the MIME types registry
-
# shipped with the mime-types library.
-
2
def load_from_json(filename)
-
require 'json'
-
JSON.parse(read_file(filename)).map { |type| MIME::Type.new(type) }
-
end
-
-
2
private
-
-
2
def read_file(filename)
-
File.open(filename, 'r:UTF-8:-') { |f| f.read }
-
end
-
end
-
-
2
private
-
-
2
def yaml_path
-
File.join(path, '*.y{,a}ml')
-
end
-
-
2
def json_path
-
File.join(path, '*.json')
-
end
-
-
2
def columnar_path
-
2
File.join(path, '*.column')
-
end
-
-
2
def v1_path
-
File.join(path, '*')
-
end
-
-
# The regular expression used to match a v1-format file-based MIME type
-
# definition.
-
#
-
# This constant has been deprecated and will be removed in mime-types 3.0.
-
2
V1_FORMAT = # :nodoc:
-
%r{\A\s*
-
([*])? # 0: Unregistered?
-
(!)? # 1: Obsolete?
-
(?:(\w+):)? # 2: Platform marker
-
([-\w.+]+)/([-\w.+]*) # 3, 4: Media Type
-
(?:\s+@(\S+))? # 5: Extensions
-
(?:\s+:(base64|7bit|8bit|quoted\-printable))? # 6: Encoding
-
(?:\s+'(\S+))? # 7: URL list
-
(?:\s+=(.+))? # 8: Documentation
-
(?:\s*([#].*)?)? # Comments
-
\s*
-
\z
-
}x
-
-
2
private_constant :V1_FORMAT if respond_to? :private_constant
-
end
-
# -*- ruby encoding: utf-8 -*-
-
-
2
class MIME::Types::Loader
-
# The path that will be used for loading the MIME::Types data. The default
-
# location is __FILE__/../../../../data, which is where the data lives
-
# in the gem installation of the mime-types library.
-
#
-
# The MIME::Types::Loader will load all JSON or columnar files contained in
-
# this path.
-
#
-
# System repackagers note: this is the constant that you would change if
-
# you repackage mime-types for your system. It is recommended that the
-
# path be something like /usr/share/ruby/mime-types/.
-
2
PATH = File.expand_path('../../../../data', __FILE__)
-
end
-
# -*- ruby encoding: utf-8 -*-
-
-
2
require 'logger'
-
-
2
module MIME
-
2
class Types
-
2
class << self
-
# Configure the MIME::Types logger. This defaults to an instance of a
-
# logger that passes messages (unformatted) through to Kernel#warn.
-
2
attr_accessor :logger
-
end
-
-
2
class WarnLogger < ::Logger #:nodoc:
-
2
class WarnLogDevice < ::Logger::LogDevice #:nodoc:
-
2
def initialize(*)
-
end
-
-
2
def write(m)
-
Kernel.warn(m)
-
end
-
-
2
def close
-
end
-
end
-
-
2
def initialize(_1, _2 = nil, _3 = nil)
-
2
super nil
-
2
@logdev = WarnLogDevice.new
-
2
@formatter = ->(_s, _d, _p, m) { m }
-
end
-
end
-
-
2
self.logger = WarnLogger.new(nil)
-
end
-
end
-
2
require 'mimemagic/tables'
-
2
require 'mimemagic/version'
-
-
# Mime type detection
-
2
class MimeMagic
-
2
attr_reader :type, :mediatype, :subtype
-
-
# Mime type by type string
-
2
def initialize(type)
-
@type = type
-
@mediatype, @subtype = type.split('/', 2)
-
end
-
-
# Add custom mime type. Arguments:
-
# * <i>type</i>: Mime type
-
# * <i>options</i>: Options hash
-
#
-
# Option keys:
-
# * <i>:extensions</i>: String list or single string of file extensions
-
# * <i>:parents</i>: String list or single string of parent mime types
-
# * <i>:magic</i>: Mime magic specification
-
# * <i>:comment</i>: Comment string
-
2
def self.add(type, options)
-
6
extensions = [options[:extensions]].flatten.compact
-
6
TYPES[type] = [extensions,
-
[options[:parents]].flatten.compact,
-
options[:comment]]
-
6
extensions.each {|ext| EXTENSIONS[ext] = type }
-
6
MAGIC.unshift [type, options[:magic]] if options[:magic]
-
end
-
-
# Removes a mime type from the dictionary. You might want to do this if
-
# you're seeing impossible conflicts (for instance, application/x-gmc-link).
-
# * <i>type</i>: The mime type to remove. All associated extensions and magic are removed too.
-
2
def self.remove(type)
-
EXTENSIONS.delete_if {|ext, t| t == type }
-
MAGIC.delete_if {|t, m| t == type }
-
TYPES.delete(type)
-
end
-
-
# Returns true if type is a text format
-
2
def text?; mediatype == 'text' || child_of?('text/plain'); end
-
-
# Mediatype shortcuts
-
2
def image?; mediatype == 'image'; end
-
2
def audio?; mediatype == 'audio'; end
-
2
def video?; mediatype == 'video'; end
-
-
# Returns true if type is child of parent type
-
2
def child_of?(parent)
-
MimeMagic.child?(type, parent)
-
end
-
-
# Get string list of file extensions
-
2
def extensions
-
TYPES.key?(type) ? TYPES[type][0] : []
-
end
-
-
# Get mime comment
-
2
def comment
-
(TYPES.key?(type) ? TYPES[type][2] : nil).to_s
-
end
-
-
# Lookup mime type by file extension
-
2
def self.by_extension(ext)
-
ext = ext.to_s.downcase
-
mime = ext[0..0] == '.' ? EXTENSIONS[ext[1..-1]] : EXTENSIONS[ext]
-
mime && new(mime)
-
end
-
-
# Lookup mime type by filename
-
2
def self.by_path(path)
-
by_extension(File.extname(path))
-
end
-
-
# Lookup mime type by magic content analysis.
-
# This is a slow operation.
-
2
def self.by_magic(io)
-
mime =
-
unless io.respond_to?(:seek) && io.respond_to?(:read)
-
str = io.respond_to?(:read) ? io.read : io.to_s
-
str = str.force_encoding(Encoding::BINARY) if str.respond_to? :force_encoding
-
MAGIC.find {|type, matches| magic_match_str(str, matches) }
-
else
-
io.binmode
-
io.set_encoding(Encoding::BINARY) if io.respond_to?(:set_encoding)
-
MAGIC.find {|type, matches| magic_match_io(io, matches) }
-
end
-
mime && new(mime[0])
-
end
-
-
# Return type as string
-
2
def to_s
-
type
-
end
-
-
# Allow comparison with string
-
2
def eql?(other)
-
type == other.to_s
-
end
-
-
2
def hash
-
type.hash
-
end
-
-
2
alias == eql?
-
-
2
def self.child?(child, parent)
-
child == parent || TYPES.key?(child) && TYPES[child][1].any? {|p| child?(p, parent) }
-
end
-
-
2
def self.magic_match_io(io, matches)
-
matches.any? do |offset, value, children|
-
match =
-
if Range === offset
-
io.seek(offset.begin)
-
x = io.read(offset.end - offset.begin + value.bytesize)
-
x && x.include?(value)
-
else
-
io.seek(offset)
-
io.read(value.bytesize) == value
-
end
-
match && (!children || magic_match_io(io, children))
-
end
-
end
-
-
2
def self.magic_match_str(str, matches)
-
matches.any? do |offset, value, children|
-
match =
-
if Range === offset
-
x = str[offset.begin, offset.end - offset.begin + value.bytesize]
-
x && x.include?(value)
-
else
-
str[offset, value.bytesize] == value
-
end
-
match && (!children || magic_match_str(str, children))
-
end
-
end
-
-
2
private_class_method :magic_match_io, :magic_match_str
-
end
-
# Extra magic
-
-
[['application/vnd.openxmlformats-officedocument.presentationml.presentation', [[0..2000, 'ppt/']]],
-
['application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', [[0..2000, 'xl/']]],
-
2
['application/vnd.openxmlformats-officedocument.wordprocessingml.document', [[0..2000, 'word/']]]].each do |magic|
-
6
MimeMagic.add(magic[0], magic: magic[1])
-
end
-
# -*- coding: binary -*-
-
# Generated from freedesktop.org.xml
-
2
class MimeMagic
-
# @private
-
# :nodoc:
-
2
EXTENSIONS = {
-
'123' => 'application/vnd.lotus-1-2-3',
-
'3ds' => 'image/x-3ds',
-
'3g2' => 'video/3gpp2',
-
'3ga' => 'video/3gpp',
-
'3gp' => 'video/3gpp',
-
'3gp2' => 'video/3gpp2',
-
'3gpp' => 'video/3gpp',
-
'3gpp2' => 'video/3gpp2',
-
'602' => 'application/x-t602',
-
'669' => 'audio/x-mod',
-
'7z' => 'application/x-7z-compressed',
-
'a' => 'application/x-archive',
-
'aac' => 'audio/aac',
-
'abw' => 'application/x-abiword',
-
'abw.crashed' => 'application/x-abiword',
-
'abw.gz' => 'application/x-abiword',
-
'ac3' => 'audio/ac3',
-
'ace' => 'application/x-ace',
-
'adb' => 'text/x-adasrc',
-
'ads' => 'text/x-adasrc',
-
'afm' => 'application/x-font-afm',
-
'ag' => 'image/x-applix-graphics',
-
'ai' => 'application/illustrator',
-
'aif' => 'audio/x-aiff',
-
'aifc' => 'audio/x-aifc',
-
'aiff' => 'audio/x-aiff',
-
'aiffc' => 'audio/x-aifc',
-
'al' => 'application/x-perl',
-
'alz' => 'application/x-alz',
-
'amr' => 'audio/AMR',
-
'amz' => 'audio/x-amzxml',
-
'ani' => 'application/x-navi-animation',
-
'anx' => 'application/annodex',
-
'ape' => 'audio/x-ape',
-
'apk' => 'application/vnd.android.package-archive',
-
'ar' => 'application/x-archive',
-
'arj' => 'application/x-arj',
-
'arw' => 'image/x-sony-arw',
-
'as' => 'application/x-applix-spreadsheet',
-
'asc' => 'application/pgp-encrypted',
-
'asf' => 'application/vnd.ms-asf',
-
'asp' => 'application/x-asp',
-
'ass' => 'text/x-ssa',
-
'asx' => 'audio/x-ms-asx',
-
'atom' => 'application/atom+xml',
-
'au' => 'audio/basic',
-
'avf' => 'video/x-msvideo',
-
'avi' => 'video/x-msvideo',
-
'aw' => 'application/x-applix-word',
-
'awb' => 'audio/AMR-WB',
-
'awk' => 'application/x-awk',
-
'axa' => 'audio/annodex',
-
'axv' => 'video/annodex',
-
'bak' => 'application/x-trash',
-
'bcpio' => 'application/x-bcpio',
-
'bdf' => 'application/x-font-bdf',
-
'bdm' => 'video/mp2t',
-
'bdmv' => 'video/mp2t',
-
'bib' => 'text/x-bibtex',
-
'bin' => 'application/octet-stream',
-
'blend' => 'application/x-blender',
-
'blender' => 'application/x-blender',
-
'bmp' => 'image/bmp',
-
'bz' => 'application/x-bzip',
-
'bz2' => 'application/x-bzip',
-
'c' => 'text/x-c++src',
-
'c++' => 'text/x-c++src',
-
'cab' => 'application/vnd.ms-cab-compressed',
-
'cap' => 'application/vnd.tcpdump.pcap',
-
'cb7' => 'application/x-cb7',
-
'cbl' => 'text/x-cobol',
-
'cbr' => 'application/x-cbr',
-
'cbt' => 'application/x-cbt',
-
'cbz' => 'application/x-cbz',
-
'cc' => 'text/x-c++src',
-
'ccmx' => 'application/x-ccmx',
-
'cdf' => 'application/x-netcdf',
-
'cdr' => 'application/vnd.corel-draw',
-
'cer' => 'application/pkix-cert',
-
'cert' => 'application/x-x509-ca-cert',
-
'cgm' => 'image/cgm',
-
'chm' => 'application/vnd.ms-htmlhelp',
-
'chrt' => 'application/x-kchart',
-
'class' => 'application/x-java',
-
'clpi' => 'video/mp2t',
-
'cls' => 'text/x-tex',
-
'cmake' => 'text/x-cmake',
-
'cob' => 'text/x-cobol',
-
'cpi' => 'video/mp2t',
-
'cpio' => 'application/x-cpio',
-
'cpio.gz' => 'application/x-cpio-compressed',
-
'cpp' => 'text/x-c++src',
-
'cr2' => 'image/x-canon-cr2',
-
'crdownload' => 'application/x-partial-download',
-
'crl' => 'application/pkix-crl',
-
'crt' => 'application/x-x509-ca-cert',
-
'crw' => 'image/x-canon-crw',
-
'cs' => 'text/x-csharp',
-
'csh' => 'application/x-csh',
-
'css' => 'text/css',
-
'csv' => 'text/csv',
-
'cue' => 'application/x-cue',
-
'cur' => 'image/x-win-bitmap',
-
'cxx' => 'text/x-c++src',
-
'd' => 'text/x-dsrc',
-
'dar' => 'application/x-dar',
-
'dbf' => 'application/x-dbf',
-
'dbk' => 'application/x-docbook+xml',
-
'dc' => 'application/x-dc-rom',
-
'dcl' => 'text/x-dcl',
-
'dcm' => 'application/dicom',
-
'dcr' => 'image/x-kodak-dcr',
-
'dds' => 'image/x-dds',
-
'deb' => 'application/vnd.debian.binary-package',
-
'der' => 'application/x-x509-ca-cert',
-
'desktop' => 'application/x-desktop',
-
'di' => 'text/x-dsrc',
-
'dia' => 'application/x-dia-diagram',
-
'diff' => 'text/x-patch',
-
'divx' => 'video/x-msvideo',
-
'djv' => 'image/vnd.djvu',
-
'djvu' => 'image/vnd.djvu',
-
'dmg' => 'application/x-apple-diskimage',
-
'dmp' => 'application/vnd.tcpdump.pcap',
-
'dng' => 'image/x-adobe-dng',
-
'doc' => 'application/msword',
-
'docbook' => 'application/x-docbook+xml',
-
'docm' => 'application/vnd.ms-word.document.macroEnabled.12',
-
'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
-
'dot' => 'application/msword-template',
-
'dotm' => 'application/vnd.ms-word.template.macroEnabled.12',
-
'dotx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.template',
-
'dsl' => 'text/x-dsl',
-
'dtd' => 'application/xml-dtd',
-
'dts' => 'audio/vnd.dts',
-
'dtshd' => 'audio/vnd.dts.hd',
-
'dtx' => 'text/x-tex',
-
'dv' => 'video/dv',
-
'dvi' => 'application/x-dvi',
-
'dvi.bz2' => 'application/x-bzdvi',
-
'dvi.gz' => 'application/x-gzdvi',
-
'dwg' => 'image/vnd.dwg',
-
'dxf' => 'image/vnd.dxf',
-
'e' => 'text/x-eiffel',
-
'egon' => 'application/x-egon',
-
'eif' => 'text/x-eiffel',
-
'el' => 'text/x-emacs-lisp',
-
'emf' => 'image/x-emf',
-
'eml' => 'message/rfc822',
-
'emp' => 'application/vnd.emusic-emusic_package',
-
'ent' => 'application/xml-external-parsed-entity',
-
'eps' => 'image/x-eps',
-
'eps.bz2' => 'image/x-bzeps',
-
'eps.gz' => 'image/x-gzeps',
-
'epsf' => 'image/x-eps',
-
'epsf.bz2' => 'image/x-bzeps',
-
'epsf.gz' => 'image/x-gzeps',
-
'epsi' => 'image/x-eps',
-
'epsi.bz2' => 'image/x-bzeps',
-
'epsi.gz' => 'image/x-gzeps',
-
'epub' => 'application/epub+zip',
-
'erl' => 'text/x-erlang',
-
'es' => 'application/ecmascript',
-
'etheme' => 'application/x-e-theme',
-
'etx' => 'text/x-setext',
-
'exe' => 'application/x-ms-dos-executable',
-
'exr' => 'image/x-exr',
-
'ez' => 'application/andrew-inset',
-
'f' => 'text/x-fortran',
-
'f4a' => 'audio/mp4',
-
'f4b' => 'audio/x-m4b',
-
'f4v' => 'video/mp4',
-
'f90' => 'text/x-fortran',
-
'f95' => 'text/x-fortran',
-
'fb2' => 'application/x-fictionbook+xml',
-
'fb2.zip' => 'application/x-zip-compressed-fb2',
-
'fig' => 'image/x-xfig',
-
'fits' => 'image/fits',
-
'fl' => 'application/x-fluid',
-
'flac' => 'audio/flac',
-
'flc' => 'video/x-flic',
-
'fli' => 'video/x-flic',
-
'flv' => 'video/x-flv',
-
'flw' => 'application/x-kivio',
-
'fo' => 'text/x-xslfo',
-
'fodg' => 'application/vnd.oasis.opendocument.graphics-flat-xml',
-
'fodp' => 'application/vnd.oasis.opendocument.presentation-flat-xml',
-
'fods' => 'application/vnd.oasis.opendocument.spreadsheet-flat-xml',
-
'fodt' => 'application/vnd.oasis.opendocument.text-flat-xml',
-
'for' => 'text/x-fortran',
-
'fxm' => 'video/x-javafx',
-
'g3' => 'image/fax-g3',
-
'gb' => 'application/x-gameboy-rom',
-
'gba' => 'application/x-gba-rom',
-
'gcrd' => 'text/vcard',
-
'ged' => 'application/x-gedcom',
-
'gedcom' => 'application/x-gedcom',
-
'gem' => 'application/x-tar',
-
'gen' => 'application/x-genesis-rom',
-
'gf' => 'application/x-tex-gf',
-
'gg' => 'application/x-sms-rom',
-
'gif' => 'image/gif',
-
'glade' => 'application/x-glade',
-
'gml' => 'application/gml+xml',
-
'gmo' => 'application/x-gettext-translation',
-
'gnc' => 'application/x-gnucash',
-
'gnd' => 'application/gnunet-directory',
-
'gnucash' => 'application/x-gnucash',
-
'gnumeric' => 'application/x-gnumeric',
-
'gnuplot' => 'application/x-gnuplot',
-
'go' => 'text/x-go',
-
'gp' => 'application/x-gnuplot',
-
'gpg' => 'application/pgp-encrypted',
-
'gplt' => 'application/x-gnuplot',
-
'gra' => 'application/x-graphite',
-
'gs' => 'text/x-genie',
-
'gsf' => 'application/x-font-type1',
-
'gsm' => 'audio/x-gsm',
-
'gtar' => 'application/x-tar',
-
'gv' => 'text/vnd.graphviz',
-
'gvp' => 'text/x-google-video-pointer',
-
'gz' => 'application/gzip',
-
'h' => 'text/x-chdr',
-
'h++' => 'text/x-c++hdr',
-
'h4' => 'application/x-hdf',
-
'h5' => 'application/x-hdf',
-
'hdf' => 'application/x-hdf',
-
'hdf4' => 'application/x-hdf',
-
'hdf5' => 'application/x-hdf',
-
'hh' => 'text/x-c++hdr',
-
'hlp' => 'application/winhlp',
-
'hp' => 'text/x-c++hdr',
-
'hpgl' => 'application/vnd.hp-hpgl',
-
'hpp' => 'text/x-c++hdr',
-
'hs' => 'text/x-haskell',
-
'htm' => 'text/html',
-
'html' => 'text/html',
-
'hwp' => 'application/x-hwp',
-
'hwt' => 'application/x-hwt',
-
'hxx' => 'text/x-c++hdr',
-
'ica' => 'application/x-ica',
-
'icb' => 'image/x-tga',
-
'icc' => 'application/vnd.iccprofile',
-
'icm' => 'application/vnd.iccprofile',
-
'icns' => 'image/x-icns',
-
'ico' => 'image/vnd.microsoft.icon',
-
'ics' => 'text/calendar',
-
'idl' => 'text/x-idl',
-
'ief' => 'image/ief',
-
'iff' => 'image/x-ilbm',
-
'ilbm' => 'image/x-ilbm',
-
'ime' => 'text/x-iMelody',
-
'img' => 'application/x-raw-disk-image',
-
'img.xz' => 'application/x-raw-disk-image-xz-compressed',
-
'imy' => 'text/x-iMelody',
-
'ins' => 'text/x-tex',
-
'iptables' => 'text/x-iptables',
-
'iso' => 'application/x-cd-image',
-
'iso9660' => 'application/x-cd-image',
-
'it' => 'audio/x-it',
-
'it87' => 'application/x-it87',
-
'jad' => 'text/vnd.sun.j2me.app-descriptor',
-
'jar' => 'application/x-java-archive',
-
'java' => 'text/x-java',
-
'jceks' => 'application/x-java-jce-keystore',
-
'jks' => 'application/x-java-keystore',
-
'jng' => 'image/x-jng',
-
'jnlp' => 'application/x-java-jnlp-file',
-
'jp2' => 'image/jp2',
-
'jpe' => 'image/jpeg',
-
'jpeg' => 'image/jpeg',
-
'jpf' => 'image/jp2',
-
'jpg' => 'image/jpeg',
-
'jpr' => 'application/x-jbuilder-project',
-
'jpx' => 'application/x-jbuilder-project',
-
'js' => 'application/javascript',
-
'jsm' => 'application/javascript',
-
'json' => 'application/json',
-
'k25' => 'image/x-kodak-k25',
-
'kar' => 'audio/midi',
-
'karbon' => 'application/x-karbon',
-
'kdc' => 'image/x-kodak-kdc',
-
'kdelnk' => 'application/x-desktop',
-
'kexi' => 'application/x-kexiproject-sqlite2',
-
'kexic' => 'application/x-kexi-connectiondata',
-
'kexis' => 'application/x-kexiproject-shortcut',
-
'key' => 'application/x-iwork-keynote-sffkey',
-
'kfo' => 'application/x-kformula',
-
'kil' => 'application/x-killustrator',
-
'kino' => 'application/smil+xml',
-
'kml' => 'application/vnd.google-earth.kml+xml',
-
'kmz' => 'application/vnd.google-earth.kmz',
-
'kon' => 'application/x-kontour',
-
'kpm' => 'application/x-kpovmodeler',
-
'kpr' => 'application/x-kpresenter',
-
'kpt' => 'application/x-kpresenter',
-
'kra' => 'application/x-krita',
-
'ks' => 'application/x-java-keystore',
-
'ksp' => 'application/x-kspread',
-
'kud' => 'application/x-kugar',
-
'kwd' => 'application/x-kword',
-
'kwt' => 'application/x-kword',
-
'la' => 'application/x-shared-library-la',
-
'latex' => 'text/x-tex',
-
'lbm' => 'image/x-ilbm',
-
'ldif' => 'text/x-ldif',
-
'lha' => 'application/x-lha',
-
'lhs' => 'text/x-literate-haskell',
-
'lhz' => 'application/x-lhz',
-
'log' => 'text/x-log',
-
'lrv' => 'video/mp4',
-
'lrz' => 'application/x-lrzip',
-
'ltx' => 'text/x-tex',
-
'lua' => 'text/x-lua',
-
'lwo' => 'image/x-lwo',
-
'lwob' => 'image/x-lwo',
-
'lwp' => 'application/vnd.lotus-wordpro',
-
'lws' => 'image/x-lws',
-
'ly' => 'text/x-lilypond',
-
'lyx' => 'application/x-lyx',
-
'lz' => 'application/x-lzip',
-
'lz4' => 'application/x-lz4',
-
'lzh' => 'application/x-lha',
-
'lzma' => 'application/x-lzma',
-
'lzo' => 'application/x-lzop',
-
'm' => 'text/x-objcsrc',
-
'm15' => 'audio/x-mod',
-
'm1u' => 'video/vnd.mpegurl',
-
'm2t' => 'video/mp2t',
-
'm2ts' => 'video/mp2t',
-
'm3u' => 'audio/x-mpegurl',
-
'm3u8' => 'audio/x-mpegurl',
-
'm4' => 'application/x-m4',
-
'm4a' => 'audio/mp4',
-
'm4b' => 'audio/x-m4b',
-
'm4u' => 'video/vnd.mpegurl',
-
'm4v' => 'video/mp4',
-
'mab' => 'application/x-markaby',
-
'mak' => 'text/x-makefile',
-
'man' => 'application/x-troff-man',
-
'manifest' => 'text/cache-manifest',
-
'markdown' => 'text/markdown',
-
'mbox' => 'application/mbox',
-
'md' => 'text/markdown',
-
'mdb' => 'application/vnd.ms-access',
-
'mdi' => 'image/vnd.ms-modi',
-
'me' => 'text/x-troff-me',
-
'med' => 'audio/x-mod',
-
'meta4' => 'application/metalink4+xml',
-
'metalink' => 'application/metalink+xml',
-
'mgp' => 'application/x-magicpoint',
-
'mht' => 'application/x-mimearchive',
-
'mhtml' => 'application/x-mimearchive',
-
'mid' => 'audio/midi',
-
'midi' => 'audio/midi',
-
'mif' => 'application/x-mif',
-
'minipsf' => 'audio/x-minipsf',
-
'mk' => 'text/x-makefile',
-
'mk3d' => 'video/x-matroska-3d',
-
'mka' => 'audio/x-matroska',
-
'mkd' => 'text/markdown',
-
'mkv' => 'video/x-matroska',
-
'ml' => 'text/x-ocaml',
-
'mli' => 'text/x-ocaml',
-
'mm' => 'text/x-troff-mm',
-
'mmf' => 'application/x-smaf',
-
'mml' => 'application/mathml+xml',
-
'mng' => 'video/x-mng',
-
'mo' => 'application/x-gettext-translation',
-
'mo3' => 'audio/x-mo3',
-
'mobi' => 'application/x-mobipocket-ebook',
-
'moc' => 'text/x-moc',
-
'mod' => 'audio/x-mod',
-
'mof' => 'text/x-mof',
-
'moov' => 'video/quicktime',
-
'mov' => 'video/quicktime',
-
'movie' => 'video/x-sgi-movie',
-
'mp+' => 'audio/x-musepack',
-
'mp2' => 'audio/mp2',
-
'mp3' => 'audio/mpeg',
-
'mp4' => 'video/mp4',
-
'mpc' => 'audio/x-musepack',
-
'mpe' => 'video/mpeg',
-
'mpeg' => 'video/mpeg',
-
'mpg' => 'video/mpeg',
-
'mpga' => 'audio/mpeg',
-
'mpl' => 'video/mp2t',
-
'mpls' => 'video/mp2t',
-
'mpp' => 'audio/x-musepack',
-
'mrl' => 'text/x-mrml',
-
'mrml' => 'text/x-mrml',
-
'mrw' => 'image/x-minolta-mrw',
-
'ms' => 'text/x-troff-ms',
-
'msi' => 'application/x-msi',
-
'msod' => 'image/x-msod',
-
'msx' => 'application/x-msx-rom',
-
'mtm' => 'audio/x-mod',
-
'mts' => 'video/mp2t',
-
'mup' => 'text/x-mup',
-
'mxf' => 'application/mxf',
-
'mxu' => 'video/vnd.mpegurl',
-
'n64' => 'application/x-n64-rom',
-
'nb' => 'application/mathematica',
-
'nc' => 'application/x-netcdf',
-
'nds' => 'application/x-nintendo-ds-rom',
-
'nef' => 'image/x-nikon-nef',
-
'nes' => 'application/x-nes-rom',
-
'nfo' => 'text/x-nfo',
-
'not' => 'text/x-mup',
-
'nsc' => 'application/x-netshow-channel',
-
'nsv' => 'video/x-nsv',
-
'nzb' => 'application/x-nzb',
-
'o' => 'application/x-object',
-
'obj' => 'application/x-tgif',
-
'ocl' => 'text/x-ocl',
-
'oda' => 'application/oda',
-
'odb' => 'application/vnd.oasis.opendocument.database',
-
'odc' => 'application/vnd.oasis.opendocument.chart',
-
'odf' => 'application/vnd.oasis.opendocument.formula',
-
'odg' => 'application/vnd.oasis.opendocument.graphics',
-
'odi' => 'application/vnd.oasis.opendocument.image',
-
'odm' => 'application/vnd.oasis.opendocument.text-master',
-
'odp' => 'application/vnd.oasis.opendocument.presentation',
-
'ods' => 'application/vnd.oasis.opendocument.spreadsheet',
-
'odt' => 'application/vnd.oasis.opendocument.text',
-
'oga' => 'audio/ogg',
-
'ogg' => 'audio/ogg',
-
'ogm' => 'video/x-ogm+ogg',
-
'ogv' => 'video/ogg',
-
'ogx' => 'application/ogg',
-
'old' => 'application/x-trash',
-
'oleo' => 'application/x-oleo',
-
'ooc' => 'text/x-ooc',
-
'opml' => 'text/x-opml+xml',
-
'oprc' => 'application/vnd.palm',
-
'opus' => 'audio/ogg',
-
'ora' => 'image/openraster',
-
'orf' => 'image/x-olympus-orf',
-
'otc' => 'application/vnd.oasis.opendocument.chart-template',
-
'otf' => 'application/vnd.oasis.opendocument.formula-template',
-
'otg' => 'application/vnd.oasis.opendocument.graphics-template',
-
'oth' => 'application/vnd.oasis.opendocument.text-web',
-
'otp' => 'application/vnd.oasis.opendocument.presentation-template',
-
'ots' => 'application/vnd.oasis.opendocument.spreadsheet-template',
-
'ott' => 'application/vnd.oasis.opendocument.text-template',
-
'owl' => 'application/rdf+xml',
-
'oxps' => 'application/oxps',
-
'oxt' => 'application/vnd.openofficeorg.extension',
-
'p' => 'text/x-pascal',
-
'p10' => 'application/pkcs10',
-
'p12' => 'application/x-pkcs12',
-
'p65' => 'application/x-pagemaker',
-
'p7b' => 'application/x-pkcs7-certificates',
-
'p7c' => 'application/pkcs7-mime',
-
'p7m' => 'application/pkcs7-mime',
-
'p7s' => 'application/pkcs7-signature',
-
'p8' => 'application/pkcs8',
-
'pack' => 'application/x-java-pack200',
-
'pak' => 'application/x-pak',
-
'par2' => 'application/x-par2',
-
'part' => 'application/x-partial-download',
-
'pas' => 'text/x-pascal',
-
'patch' => 'text/x-patch',
-
'pbm' => 'image/x-portable-bitmap',
-
'pcap' => 'application/vnd.tcpdump.pcap',
-
'pcd' => 'image/x-photo-cd',
-
'pce' => 'application/x-pc-engine-rom',
-
'pcf' => 'application/x-font-pcf',
-
'pcf.gz' => 'application/x-font-pcf',
-
'pcf.z' => 'application/x-font-pcf',
-
'pcl' => 'application/vnd.hp-pcl',
-
'pct' => 'image/x-pict',
-
'pcx' => 'image/x-pcx',
-
'pdb' => 'application/x-aportisdoc',
-
'pdc' => 'application/x-aportisdoc',
-
'pdf' => 'application/pdf',
-
'pdf.bz2' => 'application/x-bzpdf',
-
'pdf.gz' => 'application/x-gzpdf',
-
'pdf.xz' => 'application/x-xzpdf',
-
'pef' => 'image/x-pentax-pef',
-
'pem' => 'application/x-x509-ca-cert',
-
'perl' => 'application/x-perl',
-
'pfa' => 'application/x-font-type1',
-
'pfb' => 'application/x-font-type1',
-
'pfx' => 'application/x-pkcs12',
-
'pgm' => 'image/x-portable-graymap',
-
'pgn' => 'application/x-chess-pgn',
-
'pgp' => 'application/pgp-encrypted',
-
'php' => 'application/x-php',
-
'php3' => 'application/x-php',
-
'php4' => 'application/x-php',
-
'php5' => 'application/x-php',
-
'phps' => 'application/x-php',
-
'pict' => 'image/x-pict',
-
'pict1' => 'image/x-pict',
-
'pict2' => 'image/x-pict',
-
'pk' => 'application/x-tex-pk',
-
'pkipath' => 'application/pkix-pkipath',
-
'pkr' => 'application/pgp-keys',
-
'pl' => 'application/x-perl',
-
'pla' => 'audio/x-iriver-pla',
-
'pln' => 'application/x-planperfect',
-
'pls' => 'audio/x-scpls',
-
'pm' => 'application/x-perl',
-
'pm6' => 'application/x-pagemaker',
-
'pmd' => 'application/x-pagemaker',
-
'png' => 'image/png',
-
'pnm' => 'image/x-portable-anymap',
-
'pntg' => 'image/x-macpaint',
-
'po' => 'text/x-gettext-translation',
-
'pod' => 'application/x-perl',
-
'por' => 'application/x-spss-por',
-
'pot' => 'application/vnd.ms-powerpoint',
-
'potm' => 'application/vnd.ms-powerpoint.template.macroEnabled.12',
-
'potx' => 'application/vnd.openxmlformats-officedocument.presentationml.template',
-
'ppam' => 'application/vnd.ms-powerpoint.addin.macroEnabled.12',
-
'ppm' => 'image/x-portable-pixmap',
-
'pps' => 'application/vnd.ms-powerpoint',
-
'ppsm' => 'application/vnd.ms-powerpoint.slideshow.macroEnabled.12',
-
'ppsx' => 'application/vnd.openxmlformats-officedocument.presentationml.slideshow',
-
'ppt' => 'application/vnd.ms-powerpoint',
-
'pptm' => 'application/vnd.ms-powerpoint.presentation.macroEnabled.12',
-
'pptx' => 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
-
'ppz' => 'application/vnd.ms-powerpoint',
-
'pqa' => 'application/vnd.palm',
-
'prc' => 'application/x-mobipocket-ebook',
-
'ps' => 'application/postscript',
-
'ps.bz2' => 'application/x-bzpostscript',
-
'ps.gz' => 'application/x-gzpostscript',
-
'psd' => 'image/vnd.adobe.photoshop',
-
'psf' => 'application/x-font-linux-psf',
-
'psf.gz' => 'application/x-gz-font-linux-psf',
-
'psflib' => 'audio/x-psflib',
-
'psid' => 'audio/prs.sid',
-
'psw' => 'application/x-pocket-word',
-
'pub' => 'application/vnd.ms-publisher',
-
'pw' => 'application/x-pw',
-
'py' => 'text/x-python',
-
'pyc' => 'application/x-python-bytecode',
-
'pyo' => 'application/x-python-bytecode',
-
'pyx' => 'text/x-python',
-
'qif' => 'application/x-qw',
-
'qml' => 'text/x-qml',
-
'qmlproject' => 'text/x-qml',
-
'qmltypes' => 'text/x-qml',
-
'qp' => 'application/x-qpress',
-
'qt' => 'video/quicktime',
-
'qti' => 'application/x-qtiplot',
-
'qti.gz' => 'application/x-qtiplot',
-
'qtif' => 'image/x-quicktime',
-
'qtl' => 'application/x-quicktime-media-link',
-
'qtvr' => 'video/quicktime',
-
'ra' => 'audio/vnd.rn-realaudio',
-
'raf' => 'image/x-fuji-raf',
-
'ram' => 'application/ram',
-
'rar' => 'application/x-rar',
-
'ras' => 'image/x-cmu-raster',
-
'raw' => 'image/x-panasonic-raw',
-
'raw-disk-image' => 'application/x-raw-disk-image',
-
'raw-disk-image.xz' => 'application/x-raw-disk-image-xz-compressed',
-
'rax' => 'audio/vnd.rn-realaudio',
-
'rb' => 'application/x-ruby',
-
'rdf' => 'application/rdf+xml',
-
'rdfs' => 'application/rdf+xml',
-
'reg' => 'text/x-ms-regedit',
-
'rej' => 'text/x-reject',
-
'rgb' => 'image/x-rgb',
-
'rle' => 'image/rle',
-
'rm' => 'application/vnd.rn-realmedia',
-
'rmj' => 'application/vnd.rn-realmedia',
-
'rmm' => 'application/vnd.rn-realmedia',
-
'rms' => 'application/vnd.rn-realmedia',
-
'rmvb' => 'application/vnd.rn-realmedia',
-
'rmx' => 'application/vnd.rn-realmedia',
-
'rnc' => 'application/relax-ng-compact-syntax',
-
'rng' => 'application/xml',
-
'roff' => 'text/troff',
-
'rp' => 'image/vnd.rn-realpix',
-
'rpm' => 'application/x-rpm',
-
'rss' => 'application/rss+xml',
-
'rt' => 'text/vnd.rn-realtext',
-
'rtf' => 'application/rtf',
-
'rtx' => 'text/richtext',
-
'rv' => 'video/vnd.rn-realvideo',
-
'rvx' => 'video/vnd.rn-realvideo',
-
'rw2' => 'image/x-panasonic-raw2',
-
's3m' => 'audio/x-s3m',
-
'sam' => 'application/x-amipro',
-
'sami' => 'application/x-sami',
-
'sav' => 'application/x-spss-sav',
-
'scala' => 'text/x-scala',
-
'scm' => 'text/x-scheme',
-
'sda' => 'application/vnd.stardivision.draw',
-
'sdc' => 'application/vnd.stardivision.calc',
-
'sdd' => 'application/vnd.stardivision.impress',
-
'sdp' => 'application/vnd.stardivision.impress',
-
'sds' => 'application/vnd.stardivision.chart',
-
'sdw' => 'application/vnd.stardivision.writer',
-
'sfc' => 'application/vnd.nintendo.snes.rom',
-
'sgf' => 'application/x-go-sgf',
-
'sgi' => 'image/x-sgi',
-
'sgl' => 'application/vnd.stardivision.writer',
-
'sgm' => 'text/sgml',
-
'sgml' => 'text/sgml',
-
'sh' => 'application/x-shellscript',
-
'shape' => 'application/x-dia-shape',
-
'shar' => 'application/x-shar',
-
'shn' => 'application/x-shorten',
-
'siag' => 'application/x-siag',
-
'sid' => 'audio/prs.sid',
-
'sig' => 'application/pgp-signature',
-
'sik' => 'application/x-trash',
-
'sis' => 'application/vnd.symbian.install',
-
'sisx' => 'x-epoc/x-sisx-app',
-
'sit' => 'application/x-stuffit',
-
'siv' => 'application/sieve',
-
'sk' => 'image/x-skencil',
-
'sk1' => 'image/x-skencil',
-
'skr' => 'application/pgp-keys',
-
'sldm' => 'application/vnd.ms-powerpoint.slide.macroEnabled.12',
-
'sldx' => 'application/vnd.openxmlformats-officedocument.presentationml.slide',
-
'slk' => 'text/spreadsheet',
-
'smaf' => 'application/x-smaf',
-
'smc' => 'application/vnd.nintendo.snes.rom',
-
'smd' => 'application/vnd.stardivision.mail',
-
'smf' => 'application/vnd.stardivision.math',
-
'smi' => 'application/smil+xml',
-
'smil' => 'application/smil+xml',
-
'sml' => 'application/smil+xml',
-
'sms' => 'application/x-sms-rom',
-
'snd' => 'audio/basic',
-
'so' => 'application/x-sharedlib',
-
'spc' => 'application/x-pkcs7-certificates',
-
'spd' => 'application/x-font-speedo',
-
'spec' => 'text/x-rpm-spec',
-
'spl' => 'application/vnd.adobe.flash.movie',
-
'spm' => 'application/x-source-rpm',
-
'spx' => 'audio/x-speex',
-
'sql' => 'application/sql',
-
'sr2' => 'image/x-sony-sr2',
-
'src' => 'application/x-wais-source',
-
'src.rpm' => 'application/x-source-rpm',
-
'srf' => 'image/x-sony-srf',
-
'srt' => 'application/x-subrip',
-
'ss' => 'text/x-scheme',
-
'ssa' => 'text/x-ssa',
-
'stc' => 'application/vnd.sun.xml.calc.template',
-
'std' => 'application/vnd.sun.xml.draw.template',
-
'sti' => 'application/vnd.sun.xml.impress.template',
-
'stm' => 'audio/x-stm',
-
'stw' => 'application/vnd.sun.xml.writer.template',
-
'sty' => 'text/x-tex',
-
'sub' => 'text/x-microdvd',
-
'sun' => 'image/x-sun-raster',
-
'sv' => 'text/x-svsrc',
-
'sv4cpio' => 'application/x-sv4cpio',
-
'sv4crc' => 'application/x-sv4crc',
-
'svg' => 'image/svg+xml',
-
'svgz' => 'image/svg+xml-compressed',
-
'svh' => 'text/x-svhdr',
-
'swf' => 'application/vnd.adobe.flash.movie',
-
'swm' => 'application/x-ms-wim',
-
'sxc' => 'application/vnd.sun.xml.calc',
-
'sxd' => 'application/vnd.sun.xml.draw',
-
'sxg' => 'application/vnd.sun.xml.writer.global',
-
'sxi' => 'application/vnd.sun.xml.impress',
-
'sxm' => 'application/vnd.sun.xml.math',
-
'sxw' => 'application/vnd.sun.xml.writer',
-
'sylk' => 'text/spreadsheet',
-
't' => 'application/x-perl',
-
't2t' => 'text/x-txt2tags',
-
'tar' => 'application/x-tar',
-
'tar.bz' => 'application/x-bzip-compressed-tar',
-
'tar.bz2' => 'application/x-bzip-compressed-tar',
-
'tar.gz' => 'application/x-compressed-tar',
-
'tar.lrz' => 'application/x-lrzip-compressed-tar',
-
'tar.lzma' => 'application/x-lzma-compressed-tar',
-
'tar.lzo' => 'application/x-tzo',
-
'tar.xz' => 'application/x-xz-compressed-tar',
-
'tar.z' => 'application/x-tarz',
-
'taz' => 'application/x-tarz',
-
'tb2' => 'application/x-bzip-compressed-tar',
-
'tbz' => 'application/x-bzip-compressed-tar',
-
'tbz2' => 'application/x-bzip-compressed-tar',
-
'tcl' => 'text/x-tcl',
-
'tex' => 'text/x-tex',
-
'texi' => 'text/x-texinfo',
-
'texinfo' => 'text/x-texinfo',
-
'tga' => 'image/x-tga',
-
'tgz' => 'application/x-compressed-tar',
-
'theme' => 'application/x-theme',
-
'themepack' => 'application/x-windows-themepack',
-
'tif' => 'image/tiff',
-
'tiff' => 'image/tiff',
-
'tk' => 'text/x-tcl',
-
'tlrz' => 'application/x-lrzip-compressed-tar',
-
'tlz' => 'application/x-lzma-compressed-tar',
-
'tnef' => 'application/vnd.ms-tnef',
-
'tnf' => 'application/vnd.ms-tnef',
-
'toc' => 'application/x-cdrdao-toc',
-
'torrent' => 'application/x-bittorrent',
-
'tpic' => 'image/x-tga',
-
'tr' => 'text/troff',
-
'trig' => 'application/x-trig',
-
'ts' => 'text/vnd.trolltech.linguist',
-
'tsv' => 'text/tab-separated-values',
-
'tta' => 'audio/x-tta',
-
'ttc' => 'application/x-font-ttf',
-
'ttf' => 'application/x-font-ttf',
-
'ttx' => 'application/x-font-ttx',
-
'txt' => 'text/plain',
-
'txz' => 'application/x-xz-compressed-tar',
-
'tzo' => 'application/x-tzo',
-
'udeb' => 'application/vnd.debian.binary-package',
-
'ufraw' => 'application/x-ufraw',
-
'ui' => 'application/x-designer',
-
'uil' => 'text/x-uil',
-
'ult' => 'audio/x-mod',
-
'uni' => 'audio/x-mod',
-
'url' => 'application/x-mswinurl',
-
'ustar' => 'application/x-ustar',
-
'uue' => 'text/x-uuencode',
-
'v' => 'text/x-verilog',
-
'v64' => 'application/x-n64-rom',
-
'vala' => 'text/x-vala',
-
'vapi' => 'text/x-vala',
-
'vcard' => 'text/vcard',
-
'vcf' => 'text/vcard',
-
'vcs' => 'text/calendar',
-
'vct' => 'text/vcard',
-
'vda' => 'image/x-tga',
-
'vhd' => 'text/x-vhdl',
-
'vhdl' => 'text/x-vhdl',
-
'viv' => 'video/vnd.vivo',
-
'vivo' => 'video/vnd.vivo',
-
'vlc' => 'audio/x-mpegurl',
-
'vob' => 'video/mpeg',
-
'voc' => 'audio/x-voc',
-
'vor' => 'application/vnd.stardivision.writer',
-
'vrm' => 'model/vrml',
-
'vrml' => 'model/vrml',
-
'vsd' => 'application/vnd.visio',
-
'vss' => 'application/vnd.visio',
-
'vst' => 'application/vnd.visio',
-
'vsw' => 'application/vnd.visio',
-
'vtt' => 'text/vtt',
-
'wav' => 'audio/x-wav',
-
'wax' => 'audio/x-ms-asx',
-
'wb1' => 'application/x-quattropro',
-
'wb2' => 'application/x-quattropro',
-
'wb3' => 'application/x-quattropro',
-
'wbmp' => 'image/vnd.wap.wbmp',
-
'wcm' => 'application/vnd.ms-works',
-
'wdb' => 'application/vnd.ms-works',
-
'webm' => 'video/webm',
-
'webp' => 'image/webp',
-
'wim' => 'application/x-ms-wim',
-
'wk1' => 'application/vnd.lotus-1-2-3',
-
'wk3' => 'application/vnd.lotus-1-2-3',
-
'wk4' => 'application/vnd.lotus-1-2-3',
-
'wkdownload' => 'application/x-partial-download',
-
'wks' => 'application/vnd.lotus-1-2-3',
-
'wma' => 'audio/x-ms-wma',
-
'wmf' => 'image/x-wmf',
-
'wml' => 'text/vnd.wap.wml',
-
'wmls' => 'text/vnd.wap.wmlscript',
-
'wmv' => 'video/x-ms-wmv',
-
'wmx' => 'audio/x-ms-asx',
-
'woff' => 'application/font-woff',
-
'wp' => 'application/vnd.wordperfect',
-
'wp4' => 'application/vnd.wordperfect',
-
'wp5' => 'application/vnd.wordperfect',
-
'wp6' => 'application/vnd.wordperfect',
-
'wpd' => 'application/vnd.wordperfect',
-
'wpg' => 'application/x-wpg',
-
'wpl' => 'application/vnd.ms-wpl',
-
'wpp' => 'application/vnd.wordperfect',
-
'wps' => 'application/vnd.ms-works',
-
'wri' => 'application/x-mswrite',
-
'wrl' => 'model/vrml',
-
'wsgi' => 'text/x-python',
-
'wv' => 'audio/x-wavpack',
-
'wvc' => 'audio/x-wavpack-correction',
-
'wvp' => 'audio/x-wavpack',
-
'wvx' => 'audio/x-ms-asx',
-
'wwf' => 'application/x-wwf',
-
'x3f' => 'image/x-sigma-x3f',
-
'xac' => 'application/x-gnucash',
-
'xbel' => 'application/x-xbel',
-
'xbl' => 'application/xml',
-
'xbm' => 'image/x-xbitmap',
-
'xcf' => 'image/x-xcf',
-
'xcf.bz2' => 'image/x-compressed-xcf',
-
'xcf.gz' => 'image/x-compressed-xcf',
-
'xhtml' => 'application/xhtml+xml',
-
'xi' => 'audio/x-xi',
-
'xla' => 'application/vnd.ms-excel',
-
'xlam' => 'application/vnd.ms-excel.addin.macroEnabled.12',
-
'xlc' => 'application/vnd.ms-excel',
-
'xld' => 'application/vnd.ms-excel',
-
'xlf' => 'application/x-xliff',
-
'xliff' => 'application/x-xliff',
-
'xll' => 'application/vnd.ms-excel',
-
'xlm' => 'application/vnd.ms-excel',
-
'xlr' => 'application/vnd.ms-works',
-
'xls' => 'application/vnd.ms-excel',
-
'xlsb' => 'application/vnd.ms-excel.sheet.binary.macroEnabled.12',
-
'xlsm' => 'application/vnd.ms-excel.sheet.macroEnabled.12',
-
'xlsx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
-
'xlt' => 'application/vnd.ms-excel',
-
'xltm' => 'application/vnd.ms-excel.template.macroEnabled.12',
-
'xltx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.template',
-
'xlw' => 'application/vnd.ms-excel',
-
'xm' => 'audio/x-xm',
-
'xmf' => 'audio/x-xmf',
-
'xmi' => 'text/x-xmi',
-
'xml' => 'application/xml',
-
'xpi' => 'application/x-xpinstall',
-
'xpm' => 'image/x-xpixmap',
-
'xps' => 'application/oxps',
-
'xsd' => 'application/xml',
-
'xsl' => 'application/xslt+xml',
-
'xslfo' => 'text/x-xslfo',
-
'xslt' => 'application/xslt+xml',
-
'xspf' => 'application/xspf+xml',
-
'xul' => 'application/vnd.mozilla.xul+xml',
-
'xwd' => 'image/x-xwindowdump',
-
'xz' => 'application/x-xz',
-
'yaml' => 'application/x-yaml',
-
'yml' => 'application/x-yaml',
-
'z' => 'application/x-compress',
-
'z64' => 'application/x-n64-rom',
-
'zabw' => 'application/x-abiword',
-
'zip' => 'application/zip',
-
'zoo' => 'application/x-zoo',
-
'zsav' => 'application/x-spss-sav',
-
'zz' => 'application/zlib',
-
}
-
# @private
-
# :nodoc:
-
2
TYPES = {
-
'application/andrew-inset' => [%w(ez), %w(), 'ATK inset'],
-
'application/annodex' => [%w(anx), %w(), 'Annodex exchange format'],
-
'application/atom+xml' => [%w(atom), %w(application/xml), 'Atom syndication feed'],
-
'application/dicom' => [%w(dcm), %w(), 'DICOM image'],
-
'application/ecmascript' => [%w(es), %w(text/plain), 'ECMAScript program'],
-
'application/epub+zip' => [%w(epub), %w(application/zip), 'electronic book document'],
-
'application/font-woff' => [%w(woff), %w(), 'WOFF font'],
-
'application/gml+xml' => [%w(gml), %w(application/xml), 'GML document'],
-
'application/gnunet-directory' => [%w(gnd), %w(), 'GNUnet search file'],
-
'application/gzip' => [%w(gz), %w(), 'Gzip archive'],
-
'application/illustrator' => [%w(ai), %w(), 'Adobe Illustrator document'],
-
'application/javascript' => [%w(js jsm), %w(application/ecmascript), 'JavaScript program'],
-
'application/json' => [%w(json), %w(application/javascript), 'JSON document'],
-
'application/mathematica' => [%w(nb), %w(text/plain), 'Mathematica Notebook'],
-
'application/mathml+xml' => [%w(mml), %w(application/xml), 'MathML document'],
-
'application/mbox' => [%w(mbox), %w(text/plain), 'mailbox file'],
-
'application/metalink+xml' => [%w(metalink), %w(application/xml), 'Metalink file'],
-
'application/metalink4+xml' => [%w(meta4), %w(application/xml), 'Metalink file'],
-
'application/msword' => [%w(doc), %w(application/x-ole-storage), 'Word document'],
-
'application/msword-template' => [%w(dot), %w(application/msword), 'Word template'],
-
'application/mxf' => [%w(mxf), %w(), 'MXF video'],
-
'application/octet-stream' => [%w(bin), %w(), 'unknown'],
-
'application/oda' => [%w(oda), %w(), 'ODA document'],
-
'application/ogg' => [%w(ogx), %w(), 'Ogg multimedia file'],
-
'application/oxps' => [%w(oxps xps), %w(application/zip), 'XPS document'],
-
'application/pdf' => [%w(pdf), %w(), 'PDF document'],
-
'application/pgp-encrypted' => [%w(asc gpg pgp), %w(text/plain), 'PGP/MIME-encrypted message header'],
-
'application/pgp-keys' => [%w(asc gpg pgp pkr skr), %w(text/plain), 'PGP keys'],
-
'application/pgp-signature' => [%w(asc gpg pgp sig), %w(text/plain), 'detached OpenPGP signature'],
-
'application/pkcs10' => [%w(p10), %w(), 'PKCS#10 certification request'],
-
'application/pkcs7-mime' => [%w(p7c p7m), %w(), 'PKCS#7 Message or Certificate'],
-
'application/pkcs7-signature' => [%w(p7s), %w(text/plain), 'detached S/MIME signature'],
-
'application/pkcs8' => [%w(p8), %w(), 'PKCS#8 private key'],
-
'application/pkix-cert' => [%w(cer), %w(), 'X.509 certificate'],
-
'application/pkix-crl' => [%w(crl), %w(), 'Certificate revocation list'],
-
'application/pkix-pkipath' => [%w(pkipath), %w(), 'PkiPath certification path'],
-
'application/postscript' => [%w(ps), %w(text/plain), 'PS document'],
-
'application/ram' => [%w(ram), %w(), 'RealMedia Metafile'],
-
'application/rdf+xml' => [%w(owl rdf rdfs), %w(application/xml), 'RDF file'],
-
'application/relax-ng-compact-syntax' => [%w(rnc), %w(text/plain), 'RELAX NG XML schema'],
-
'application/rss+xml' => [%w(rss), %w(application/xml), 'RSS summary'],
-
'application/rtf' => [%w(rtf), %w(text/plain), 'RTF document'],
-
'application/sdp' => [%w(sdp), %w(), 'SDP multicast stream file'],
-
'application/sieve' => [%w(siv), %w(application/xml), 'Sieve mail filter script'],
-
'application/smil+xml' => [%w(kino smi smil sml), %w(application/xml), 'SMIL document'],
-
'application/sql' => [%w(sql), %w(text/plain), 'SQL code'],
-
'application/vnd.adobe.flash.movie' => [%w(spl swf), %w(), 'Shockwave Flash file'],
-
'application/vnd.android.package-archive' => [%w(apk), %w(application/x-java-archive), 'Android package'],
-
'application/vnd.apple.mpegurl' => [%w(m3u m3u8), %w(), 'HTTP Live Streaming playlist'],
-
'application/vnd.corel-draw' => [%w(cdr), %w(), 'Corel Draw drawing'],
-
'application/vnd.debian.binary-package' => [%w(deb udeb), %w(), 'Debian package'],
-
'application/vnd.emusic-emusic_package' => [%w(emp), %w(), 'eMusic download package'],
-
'application/vnd.google-earth.kml+xml' => [%w(kml), %w(application/xml), 'KML geographic data'],
-
'application/vnd.google-earth.kmz' => [%w(kmz), %w(application/zip), 'KML geographic compressed data'],
-
'application/vnd.hp-hpgl' => [%w(hpgl), %w(), 'HPGL file'],
-
'application/vnd.hp-pcl' => [%w(pcl), %w(), 'PCL file'],
-
'application/vnd.iccprofile' => [%w(icc icm), %w(), 'ICC profile'],
-
'application/vnd.lotus-1-2-3' => [%w(123 wk1 wk3 wk4 wks), %w(), 'Lotus 1-2-3 spreadsheet'],
-
'application/vnd.lotus-wordpro' => [%w(lwp), %w(), 'Lotus Word Pro'],
-
'application/vnd.mozilla.xul+xml' => [%w(xul), %w(application/xml), 'XUL interface document'],
-
'application/vnd.ms-access' => [%w(mdb), %w(), 'JET database'],
-
'application/vnd.ms-asf' => [%w(asf), %w(), 'ASF video'],
-
'application/vnd.ms-cab-compressed' => [%w(cab), %w(), 'Microsoft Cabinet archive'],
-
'application/vnd.ms-excel' => [%w(xla xlc xld xll xlm xls xlt xlw), %w(), 'Excel spreadsheet'],
-
'application/vnd.ms-excel.addin.macroEnabled.12' => [%w(xlam), %w(application/vnd.openxmlformats-officedocument.spreadsheetml.sheet), 'Excel add-in'],
-
'application/vnd.ms-excel.sheet.binary.macroEnabled.12' => [%w(xlsb), %w(application/vnd.openxmlformats-officedocument.spreadsheetml.sheet), 'Excel 2007 binary spreadsheet'],
-
'application/vnd.ms-excel.sheet.macroEnabled.12' => [%w(xlsm), %w(application/vnd.openxmlformats-officedocument.spreadsheetml.sheet), 'Excel macro-enabled spreadsheet'],
-
'application/vnd.ms-excel.template.macroEnabled.12' => [%w(xltm), %w(application/vnd.openxmlformats-officedocument.spreadsheetml.template), 'Excel macro-enabled spreadsheet template'],
-
'application/vnd.ms-htmlhelp' => [%w(chm), %w(), 'CHM document'],
-
'application/vnd.ms-powerpoint' => [%w(pot pps ppt ppz), %w(), 'PowerPoint presentation'],
-
'application/vnd.ms-powerpoint.addin.macroEnabled.12' => [%w(ppam), %w(), 'PowerPoint add-in'],
-
'application/vnd.ms-powerpoint.presentation.macroEnabled.12' => [%w(pptm), %w(application/vnd.openxmlformats-officedocument.presentationml.presentation), 'PowerPoint macro-enabled presentation'],
-
'application/vnd.ms-powerpoint.slide.macroEnabled.12' => [%w(sldm), %w(application/vnd.openxmlformats-officedocument.presentationml.slide), 'PowerPoint macro-enabled slide'],
-
'application/vnd.ms-powerpoint.slideshow.macroEnabled.12' => [%w(ppsm), %w(application/vnd.openxmlformats-officedocument.presentationml.slideshow), 'PowerPoint macro-enabled presentation'],
-
'application/vnd.ms-powerpoint.template.macroEnabled.12' => [%w(potm), %w(application/vnd.openxmlformats-officedocument.presentationml.template), 'PowerPoint macro-enabled presentation template'],
-
'application/vnd.ms-publisher' => [%w(pub), %w(application/x-ole-storage), 'Microsoft Publisher document'],
-
'application/vnd.ms-tnef' => [%w(tnef tnf), %w(), 'TNEF message'],
-
'application/vnd.ms-word.document.macroEnabled.12' => [%w(docm), %w(application/vnd.openxmlformats-officedocument.wordprocessingml.document), 'Word macro-enabled document'],
-
'application/vnd.ms-word.template.macroEnabled.12' => [%w(dotm), %w(application/vnd.openxmlformats-officedocument.wordprocessingml.template), 'Word macro-enabled document template'],
-
'application/vnd.ms-works' => [%w(wcm wdb wks wps xlr), %w(application/x-ole-storage), 'Microsoft Works document'],
-
'application/vnd.ms-wpl' => [%w(wpl), %w(), 'WPL playlist'],
-
'application/vnd.nintendo.snes.rom' => [%w(sfc smc), %w(), 'Super NES ROM'],
-
'application/vnd.oasis.opendocument.chart' => [%w(odc), %w(application/zip), 'ODC chart'],
-
'application/vnd.oasis.opendocument.chart-template' => [%w(otc), %w(application/zip), 'ODC template'],
-
'application/vnd.oasis.opendocument.database' => [%w(odb), %w(application/zip), 'ODB database'],
-
'application/vnd.oasis.opendocument.formula' => [%w(odf), %w(application/zip), 'ODF formula'],
-
'application/vnd.oasis.opendocument.formula-template' => [%w(otf), %w(application/zip), 'ODF template'],
-
'application/vnd.oasis.opendocument.graphics' => [%w(odg), %w(application/zip), 'ODG drawing'],
-
'application/vnd.oasis.opendocument.graphics-flat-xml' => [%w(fodg), %w(application/xml), 'ODG drawing (Flat XML)'],
-
'application/vnd.oasis.opendocument.graphics-template' => [%w(otg), %w(application/zip), 'ODG template'],
-
'application/vnd.oasis.opendocument.image' => [%w(odi), %w(application/zip), 'ODI image'],
-
'application/vnd.oasis.opendocument.presentation' => [%w(odp), %w(application/zip), 'ODP presentation'],
-
'application/vnd.oasis.opendocument.presentation-flat-xml' => [%w(fodp), %w(application/xml), 'ODP presentation (Flat XML)'],
-
'application/vnd.oasis.opendocument.presentation-template' => [%w(otp), %w(application/zip), 'ODP template'],
-
'application/vnd.oasis.opendocument.spreadsheet' => [%w(ods), %w(application/zip), 'ODS spreadsheet'],
-
'application/vnd.oasis.opendocument.spreadsheet-flat-xml' => [%w(fods), %w(application/xml), 'ODS spreadsheet (Flat XML)'],
-
'application/vnd.oasis.opendocument.spreadsheet-template' => [%w(ots), %w(application/zip), 'ODS template'],
-
'application/vnd.oasis.opendocument.text' => [%w(odt), %w(application/zip), 'ODT document'],
-
'application/vnd.oasis.opendocument.text-flat-xml' => [%w(fodt), %w(application/xml), 'ODT document (Flat XML)'],
-
'application/vnd.oasis.opendocument.text-master' => [%w(odm), %w(application/zip), 'ODM document'],
-
'application/vnd.oasis.opendocument.text-template' => [%w(ott), %w(application/zip), 'ODT template'],
-
'application/vnd.oasis.opendocument.text-web' => [%w(oth), %w(application/zip), 'OTH template'],
-
'application/vnd.openofficeorg.extension' => [%w(oxt), %w(application/zip), 'OpenOffice.org extension'],
-
'application/vnd.openxmlformats-officedocument.presentationml.presentation' => [%w(pptx), %w(application/zip), 'PowerPoint 2007 presentation'],
-
'application/vnd.openxmlformats-officedocument.presentationml.slide' => [%w(sldx), %w(application/zip), 'PowerPoint 2007 slide'],
-
'application/vnd.openxmlformats-officedocument.presentationml.slideshow' => [%w(ppsx), %w(application/zip), 'PowerPoint 2007 show'],
-
'application/vnd.openxmlformats-officedocument.presentationml.template' => [%w(potx), %w(application/zip), 'PowerPoint 2007 presentation template'],
-
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' => [%w(xlsx), %w(application/zip), 'Excel 2007 spreadsheet'],
-
'application/vnd.openxmlformats-officedocument.spreadsheetml.template' => [%w(xltx), %w(application/zip), 'Excel 2007 spreadsheet template'],
-
'application/vnd.openxmlformats-officedocument.wordprocessingml.document' => [%w(docx), %w(application/zip), 'Word 2007 document'],
-
'application/vnd.openxmlformats-officedocument.wordprocessingml.template' => [%w(dotx), %w(application/zip), 'Word 2007 document template'],
-
'application/vnd.palm' => [%w(oprc pdb pqa prc), %w(), 'Palm OS database'],
-
'application/vnd.rn-realmedia' => [%w(rm rmj rmm rms rmvb rmx), %w(), 'RealMedia document'],
-
'application/vnd.stardivision.calc' => [%w(sdc), %w(), 'StarCalc spreadsheet'],
-
'application/vnd.stardivision.chart' => [%w(sds), %w(), 'StarChart chart'],
-
'application/vnd.stardivision.draw' => [%w(sda), %w(), 'StarDraw drawing'],
-
'application/vnd.stardivision.impress' => [%w(sdd sdp), %w(), 'StarImpress presentation'],
-
'application/vnd.stardivision.mail' => [%w(smd), %w(), 'StarMail email'],
-
'application/vnd.stardivision.math' => [%w(smf), %w(), 'StarMath formula'],
-
'application/vnd.stardivision.writer' => [%w(sdw sgl vor), %w(), 'StarWriter document'],
-
'application/vnd.sun.xml.calc' => [%w(sxc), %w(application/zip), 'OpenOffice Calc spreadsheet'],
-
'application/vnd.sun.xml.calc.template' => [%w(stc), %w(application/zip), 'OpenOffice Calc template'],
-
'application/vnd.sun.xml.draw' => [%w(sxd), %w(application/zip), 'OpenOffice Draw drawing'],
-
'application/vnd.sun.xml.draw.template' => [%w(std), %w(application/zip), 'OpenOffice Draw template'],
-
'application/vnd.sun.xml.impress' => [%w(sxi), %w(application/zip), 'OpenOffice Impress presentation'],
-
'application/vnd.sun.xml.impress.template' => [%w(sti), %w(application/zip), 'OpenOffice Impress template'],
-
'application/vnd.sun.xml.math' => [%w(sxm), %w(application/zip), 'OpenOffice Math formula'],
-
'application/vnd.sun.xml.writer' => [%w(sxw), %w(application/zip), 'OpenOffice Writer document'],
-
'application/vnd.sun.xml.writer.global' => [%w(sxg), %w(application/zip), 'OpenOffice Writer global document'],
-
'application/vnd.sun.xml.writer.template' => [%w(stw), %w(application/zip), 'OpenOffice Writer template'],
-
'application/vnd.symbian.install' => [%w(sis), %w(), 'SIS package'],
-
'application/vnd.tcpdump.pcap' => [%w(cap dmp pcap), %w(), 'Network Packet Capture'],
-
'application/vnd.visio' => [%w(vsd vss vst vsw), %w(application/x-ole-storage), 'Microsoft Visio document'],
-
'application/vnd.wordperfect' => [%w(wp wp4 wp5 wp6 wpd wpp), %w(), 'WordPerfect document'],
-
'application/winhlp' => [%w(hlp), %w(), 'WinHelp help file'],
-
'application/x-7z-compressed' => [%w(7z), %w(), '7-zip archive'],
-
'application/x-abiword' => [%w(abw abw.crashed abw.gz zabw), %w(application/xml), 'AbiWord document'],
-
'application/x-ace' => [%w(ace), %w(), 'ACE archive'],
-
'application/x-alz' => [%w(alz), %w(), 'Alzip archive'],
-
'application/x-amipro' => [%w(sam), %w(), 'Lotus AmiPro document'],
-
'application/x-aportisdoc' => [%w(pdb pdc), %w(application/x-palm-database), 'AportisDoc document'],
-
'application/x-apple-diskimage' => [%w(dmg), %w(), 'Apple disk image'],
-
'application/x-applix-spreadsheet' => [%w(as), %w(), 'Applix Spreadsheets spreadsheet'],
-
'application/x-applix-word' => [%w(aw), %w(), 'Applix Words document'],
-
'application/x-archive' => [%w(a ar), %w(), 'AR archive'],
-
'application/x-arj' => [%w(arj), %w(), 'ARJ archive'],
-
'application/x-asp' => [%w(asp), %w(text/plain), 'ASP page'],
-
'application/x-awk' => [%w(awk), %w(application/x-executable text/plain), 'AWK script'],
-
'application/x-bcpio' => [%w(bcpio), %w(), 'BCPIO document'],
-
'application/x-bittorrent' => [%w(torrent), %w(), 'BitTorrent seed file'],
-
'application/x-blender' => [%w(blend blend blender), %w(), 'Blender scene'],
-
'application/x-bzdvi' => [%w(dvi.bz2), %w(application/x-bzip), 'TeX DVI document (bzip-compressed)'],
-
'application/x-bzip' => [%w(bz bz2), %w(), 'Bzip archive'],
-
'application/x-bzip-compressed-tar' => [%w(tar.bz tar.bz2 tb2 tbz tbz2), %w(application/x-bzip), 'Tar archive (bzip-compressed)'],
-
'application/x-bzpdf' => [%w(pdf.bz2), %w(application/x-bzip), 'PDF document (bzip-compressed)'],
-
'application/x-bzpostscript' => [%w(ps.bz2), %w(application/x-bzip), 'PostScript document (bzip-compressed)'],
-
'application/x-cb7' => [%w(cb7), %w(application/x-7z-compressed), 'comic book archive'],
-
'application/x-cbr' => [%w(cbr), %w(application/x-rar), 'comic book archive'],
-
'application/x-cbt' => [%w(cbt), %w(application/x-tar), 'comic book archive'],
-
'application/x-cbz' => [%w(cbz), %w(application/zip), 'comic book archive'],
-
'application/x-ccmx' => [%w(ccmx), %w(text/plain), 'CCMX color correction file'],
-
'application/x-cd-image' => [%w(iso iso9660), %w(application/x-raw-disk-image), 'raw CD image'],
-
'application/x-cdrdao-toc' => [%w(toc), %w(text/plain), 'CD Table Of Contents'],
-
'application/x-chess-pgn' => [%w(pgn), %w(text/plain), 'PGN chess game notation'],
-
'application/x-cisco-vpn-settings' => [%w(pcf), %w(), 'Cisco VPN Settings'],
-
'application/x-compress' => [%w(z), %w(), 'UNIX-compressed file'],
-
'application/x-compressed-tar' => [%w(tar.gz tgz), %w(application/gzip), 'Tar archive (gzip-compressed)'],
-
'application/x-cpio' => [%w(cpio), %w(), 'CPIO archive'],
-
'application/x-cpio-compressed' => [%w(cpio.gz), %w(application/gzip), 'CPIO archive (gzip-compressed)'],
-
'application/x-csh' => [%w(csh), %w(application/x-shellscript text/plain), 'C shell script'],
-
'application/x-cue' => [%w(cue), %w(text/plain), 'CD image cuesheet'],
-
'application/x-dar' => [%w(dar), %w(), 'DAR archive'],
-
'application/x-dbf' => [%w(dbf), %w(), 'Xbase document'],
-
'application/x-dc-rom' => [%w(dc), %w(), 'Dreamcast ROM'],
-
'application/x-designer' => [%w(ui), %w(application/xml), 'Qt Designer file'],
-
'application/x-desktop' => [%w(desktop kdelnk), %w(text/plain), 'desktop configuration file'],
-
'application/x-dia-diagram' => [%w(dia), %w(application/xml), 'Dia diagram'],
-
'application/x-dia-shape' => [%w(shape), %w(application/xml), 'Dia shape'],
-
'application/x-docbook+xml' => [%w(dbk docbook), %w(application/xml), 'DocBook document'],
-
'application/x-dvi' => [%w(dvi), %w(), 'TeX DVI document'],
-
'application/x-e-theme' => [%w(etheme), %w(), 'Enlightenment theme'],
-
'application/x-egon' => [%w(egon), %w(), 'Egon Animator animation'],
-
'application/x-fictionbook+xml' => [%w(fb2), %w(application/xml), 'FictionBook document'],
-
'application/x-fluid' => [%w(fl), %w(text/plain), 'FLTK Fluid file'],
-
'application/x-font-afm' => [%w(afm), %w(), 'Adobe font metrics'],
-
'application/x-font-bdf' => [%w(bdf), %w(), 'BDF font'],
-
'application/x-font-linux-psf' => [%w(psf), %w(), 'Linux PSF console font'],
-
'application/x-font-otf' => [%w(otf), %w(application/x-font-ttf), 'OpenType font'],
-
'application/x-font-pcf' => [%w(pcf pcf.gz pcf.z), %w(), 'PCF font'],
-
'application/x-font-speedo' => [%w(spd), %w(), 'Speedo font'],
-
'application/x-font-ttf' => [%w(ttc ttf), %w(), 'TrueType font'],
-
'application/x-font-ttx' => [%w(ttx), %w(text/xml), 'TrueType XML font'],
-
'application/x-font-type1' => [%w(gsf pfa pfb), %w(application/postscript), 'Postscript type-1 font'],
-
'application/x-gameboy-rom' => [%w(gb), %w(), 'Game Boy ROM'],
-
'application/x-gamecube-rom' => [%w(iso), %w(), 'GameCube disc image'],
-
'application/x-gba-rom' => [%w(gba), %w(), 'Game Boy Advance ROM'],
-
'application/x-gedcom' => [%w(ged gedcom), %w(), 'GEDCOM family history'],
-
'application/x-genesis-rom' => [%w(gen), %w(), 'Genesis ROM'],
-
'application/x-gettext-translation' => [%w(gmo mo), %w(), 'translated messages (machine-readable)'],
-
'application/x-glade' => [%w(glade), %w(application/xml), 'Glade project'],
-
'application/x-gnucash' => [%w(gnc gnucash xac), %w(), 'GnuCash financial data'],
-
'application/x-gnumeric' => [%w(gnumeric), %w(), 'Gnumeric spreadsheet'],
-
'application/x-gnuplot' => [%w(gnuplot gp gplt), %w(text/plain), 'Gnuplot document'],
-
'application/x-go-sgf' => [%w(sgf), %w(text/plain), 'SGF record'],
-
'application/x-graphite' => [%w(gra), %w(), 'Graphite scientific graph'],
-
'application/x-gtk-builder' => [%w(ui), %w(application/xml), 'GTK+ Builder'],
-
'application/x-gz-font-linux-psf' => [%w(psf.gz), %w(application/gzip), 'Linux PSF console font (gzip-compressed)'],
-
'application/x-gzdvi' => [%w(dvi.gz), %w(application/gzip), 'TeX DVI document (gzip-compressed)'],
-
'application/x-gzpdf' => [%w(pdf.gz), %w(application/gzip), 'PDF document (gzip-compressed)'],
-
'application/x-gzpostscript' => [%w(ps.gz), %w(application/gzip), 'PostScript document (gzip-compressed)'],
-
'application/x-hdf' => [%w(h4 h5 hdf hdf4 hdf5), %w(), 'HDF document'],
-
'application/x-hwp' => [%w(hwp), %w(), 'Haansoft Hangul document'],
-
'application/x-hwt' => [%w(hwt), %w(), 'Haansoft Hangul document template'],
-
'application/x-ica' => [%w(ica), %w(text/plain), 'Citrix ICA settings file'],
-
'application/x-it87' => [%w(it87), %w(text/plain), 'IT 8.7 color calibration file'],
-
'application/x-iwork-keynote-sffkey' => [%w(key), %w(application/zip), 'Apple Keynote 5 presentation'],
-
'application/x-java' => [%w(class), %w(), 'Java class'],
-
'application/x-java-archive' => [%w(jar), %w(application/zip), 'Java archive'],
-
'application/x-java-jce-keystore' => [%w(jceks), %w(), 'Java JCE keystore'],
-
'application/x-java-jnlp-file' => [%w(jnlp), %w(application/xml), 'JNLP file'],
-
'application/x-java-keystore' => [%w(jks ks), %w(), 'Java keystore'],
-
'application/x-java-pack200' => [%w(pack), %w(), 'Pack200 Java archive'],
-
'application/x-jbuilder-project' => [%w(jpr jpx), %w(), 'JBuilder project'],
-
'application/x-karbon' => [%w(karbon), %w(), 'Karbon14 drawing'],
-
'application/x-kchart' => [%w(chrt), %w(), 'KChart chart'],
-
'application/x-kexi-connectiondata' => [%w(kexic), %w(), 'Kexi settings for database server connection'],
-
'application/x-kexiproject-shortcut' => [%w(kexis), %w(), 'shortcut to Kexi project on database server'],
-
'application/x-kexiproject-sqlite2' => [%w(kexi), %w(application/x-sqlite2), 'Kexi database file-based project'],
-
'application/x-kexiproject-sqlite3' => [%w(kexi), %w(application/x-sqlite3), 'Kexi database file-based project'],
-
'application/x-kformula' => [%w(kfo), %w(), 'KFormula formula'],
-
'application/x-killustrator' => [%w(kil), %w(), 'KIllustrator drawing'],
-
'application/x-kivio' => [%w(flw), %w(), 'Kivio flowchart'],
-
'application/x-kontour' => [%w(kon), %w(), 'Kontour drawing'],
-
'application/x-kpovmodeler' => [%w(kpm), %w(), 'KPovModeler scene'],
-
'application/x-kpresenter' => [%w(kpr kpt), %w(), 'KPresenter presentation'],
-
'application/x-krita' => [%w(kra), %w(), 'Krita document'],
-
'application/x-kspread' => [%w(ksp), %w(), 'KSpread spreadsheet'],
-
'application/x-kugar' => [%w(kud), %w(), 'Kugar document'],
-
'application/x-kword' => [%w(kwd kwt), %w(), 'KWord document'],
-
'application/x-lha' => [%w(lha lzh), %w(), 'LHA archive'],
-
'application/x-lhz' => [%w(lhz), %w(), 'LHZ archive'],
-
'application/x-lrzip' => [%w(lrz), %w(), 'Lrzip archive'],
-
'application/x-lrzip-compressed-tar' => [%w(tar.lrz tlrz), %w(application/x-lrzip), 'Tar archive (lrzip-compressed)'],
-
'application/x-lyx' => [%w(lyx), %w(text/plain), 'LyX document'],
-
'application/x-lz4' => [%w(lz4), %w(), 'LZ4 archive'],
-
'application/x-lzip' => [%w(lz), %w(), 'Lzip archive'],
-
'application/x-lzma' => [%w(lzma), %w(), 'LZMA archive'],
-
'application/x-lzma-compressed-tar' => [%w(tar.lzma tlz), %w(application/x-lzma), 'Tar archive (LZMA-compressed)'],
-
'application/x-lzop' => [%w(lzo), %w(), 'LZO archive'],
-
'application/x-m4' => [%w(m4), %w(text/plain), 'M4 macro'],
-
'application/x-magicpoint' => [%w(mgp), %w(text/plain), 'MagicPoint presentation'],
-
'application/x-markaby' => [%w(mab), %w(application/x-ruby), 'Markaby script'],
-
'application/x-mif' => [%w(mif), %w(), 'Adobe FrameMaker MIF document'],
-
'application/x-mimearchive' => [%w(mht mhtml), %w(multipart/related), 'MHTML web archive'],
-
'application/x-mobipocket-ebook' => [%w(mobi prc), %w(application/x-palm-database), 'Mobipocket e-book'],
-
'application/x-ms-dos-executable' => [%w(exe), %w(), 'DOS/Windows executable'],
-
'application/x-ms-wim' => [%w(swm wim), %w(), 'Windows Imaging Format Disk Image'],
-
'application/x-msi' => [%w(msi), %w(application/x-ole-storage), 'Windows Installer package'],
-
'application/x-mswinurl' => [%w(url), %w(), 'Internet shortcut'],
-
'application/x-mswrite' => [%w(wri), %w(), 'WRI document'],
-
'application/x-msx-rom' => [%w(msx), %w(), 'MSX ROM'],
-
'application/x-n64-rom' => [%w(n64 v64 z64), %w(), 'Nintendo64 ROM'],
-
'application/x-navi-animation' => [%w(ani), %w(), 'Windows animated cursor'],
-
'application/x-nes-rom' => [%w(nes), %w(), 'NES ROM'],
-
'application/x-netcdf' => [%w(cdf nc), %w(), 'Unidata NetCDF document'],
-
'application/x-netshow-channel' => [%w(nsc), %w(application/vnd.ms-asf), 'Windows Media Station file'],
-
'application/x-nintendo-ds-rom' => [%w(nds), %w(), 'Nintendo DS ROM'],
-
'application/x-nzb' => [%w(nzb), %w(application/xml), 'NewzBin usenet index'],
-
'application/x-object' => [%w(o), %w(), 'object code'],
-
'application/x-oleo' => [%w(oleo), %w(), 'GNU Oleo spreadsheet'],
-
'application/x-pagemaker' => [%w(p65 pm pm6 pmd), %w(application/x-ole-storage), 'Adobe PageMaker'],
-
'application/x-pak' => [%w(pak), %w(), 'PAK archive'],
-
'application/x-par2' => [%w(par2 par2), %w(), 'Parchive archive'],
-
'application/x-partial-download' => [%w(crdownload part wkdownload), %w(), 'Partially downloaded file'],
-
'application/x-pc-engine-rom' => [%w(pce), %w(), 'PC Engine ROM'],
-
'application/x-perl' => [%w(al perl pl pl pm pod t), %w(application/x-executable text/plain), 'Perl script'],
-
'application/x-php' => [%w(php php3 php4 php5 phps), %w(text/plain), 'PHP script'],
-
'application/x-pkcs12' => [%w(p12 pfx), %w(), 'PKCS#12 certificate bundle'],
-
'application/x-pkcs7-certificates' => [%w(p7b spc), %w(), 'PKCS#7 certificate bundle'],
-
'application/x-planperfect' => [%w(pln), %w(), 'PlanPerfect spreadsheet'],
-
'application/x-pocket-word' => [%w(psw), %w(), 'Pocket Word document'],
-
'application/x-pw' => [%w(pw), %w(), 'Pathetic Writer document'],
-
'application/x-python-bytecode' => [%w(pyc pyo), %w(), 'Python bytecode'],
-
'application/x-qpress' => [%w(qp), %w(), 'Qpress archive'],
-
'application/x-qtiplot' => [%w(qti qti.gz), %w(text/plain), 'QtiPlot document'],
-
'application/x-quattropro' => [%w(wb1 wb2 wb3), %w(), 'Quattro Pro spreadsheet'],
-
'application/x-quicktime-media-link' => [%w(qtl), %w(video/quicktime), 'QuickTime metalink playlist'],
-
'application/x-qw' => [%w(qif), %w(), 'Quicken document'],
-
'application/x-rar' => [%w(rar), %w(), 'RAR archive'],
-
'application/x-raw-disk-image' => [%w(img raw-disk-image), %w(), 'Raw disk image'],
-
'application/x-raw-disk-image-xz-compressed' => [%w(img.xz raw-disk-image.xz), %w(application/x-xz), 'Raw disk image (XZ-compressed)'],
-
'application/x-rpm' => [%w(rpm), %w(), 'RPM package'],
-
'application/x-ruby' => [%w(rb), %w(application/x-executable text/plain), 'Ruby script'],
-
'application/x-sami' => [%w(sami smi), %w(text/plain), 'SAMI subtitles'],
-
'application/x-shar' => [%w(shar), %w(), 'shell archive'],
-
'application/x-shared-library-la' => [%w(la), %w(text/plain), 'libtool shared library'],
-
'application/x-sharedlib' => [%w(so), %w(), 'shared library'],
-
'application/x-shellscript' => [%w(sh), %w(application/x-executable text/plain), 'shell script'],
-
'application/x-shorten' => [%w(shn), %w(), 'Shorten audio'],
-
'application/x-siag' => [%w(siag), %w(), 'Siag spreadsheet'],
-
'application/x-smaf' => [%w(mmf smaf), %w(), 'SMAF audio'],
-
'application/x-sms-rom' => [%w(gg sms), %w(), 'Sega Master System/Game Gear ROM'],
-
'application/x-source-rpm' => [%w(spm src.rpm), %w(application/x-rpm), 'Source RPM package'],
-
'application/x-spss-por' => [%w(por), %w(), 'SPSS Portable Data File'],
-
'application/x-spss-sav' => [%w(sav zsav), %w(), 'SPSS Data File'],
-
'application/x-stuffit' => [%w(sit), %w(), 'StuffIt archive'],
-
'application/x-subrip' => [%w(srt), %w(text/plain), 'SubRip subtitles'],
-
'application/x-sv4cpio' => [%w(sv4cpio), %w(), 'SV4 CPIO archive'],
-
'application/x-sv4crc' => [%w(sv4crc), %w(), 'SV4 CPIO archive (with CRC)'],
-
'application/x-t602' => [%w(602), %w(), 'T602 document'],
-
'application/x-tar' => [%w(gem gtar tar), %w(), 'Tar archive'],
-
'application/x-tarz' => [%w(tar.z taz), %w(application/x-compress), 'Tar archive (compressed)'],
-
'application/x-tex-gf' => [%w(gf), %w(), 'generic font file'],
-
'application/x-tex-pk' => [%w(pk), %w(), 'packed font file'],
-
'application/x-tgif' => [%w(obj), %w(), 'TGIF document'],
-
'application/x-theme' => [%w(theme), %w(application/x-desktop), 'theme'],
-
'application/x-trash' => [%w(bak old sik), %w(), 'backup file'],
-
'application/x-trig' => [%w(trig), %w(text/plain), 'TriG RDF document'],
-
'application/x-troff-man' => [%w(man), %w(text/plain), 'Troff document (with manpage macros)'],
-
'application/x-tzo' => [%w(tar.lzo tzo), %w(application/x-lzop), 'Tar archive (LZO-compressed)'],
-
'application/x-ufraw' => [%w(ufraw), %w(text/xml), 'UFRaw ID image'],
-
'application/x-ustar' => [%w(ustar), %w(), 'Ustar archive'],
-
'application/x-wais-source' => [%w(src), %w(text/plain), 'WAIS source code'],
-
'application/x-wii-rom' => [%w(iso), %w(), 'Wii disc image'],
-
'application/x-windows-themepack' => [%w(themepack), %w(application/vnd.ms-cab-compressed), 'Microsoft Windows theme pack'],
-
'application/x-wpg' => [%w(wpg), %w(), 'WordPerfect/Drawperfect image'],
-
'application/x-wwf' => [%w(wwf), %w(application/pdf), 'WWF document'],
-
'application/x-x509-ca-cert' => [%w(cert crt der pem), %w(), 'DER/PEM/Netscape-encoded X.509 certificate'],
-
'application/x-xbel' => [%w(xbel), %w(application/xml), 'XBEL bookmarks'],
-
'application/x-xliff' => [%w(xlf xliff), %w(application/xml), 'XLIFF translation file'],
-
'application/x-xpinstall' => [%w(xpi), %w(application/zip), 'XPInstall installer module'],
-
'application/x-xz' => [%w(xz), %w(), 'XZ archive'],
-
'application/x-xz-compressed-tar' => [%w(tar.xz txz), %w(application/x-xz), 'Tar archive (XZ-compressed)'],
-
'application/x-xzpdf' => [%w(pdf.xz), %w(application/x-xz), 'PDF document (XZ-compressed)'],
-
'application/x-yaml' => [%w(yaml yml), %w(text/plain), 'YAML document'],
-
'application/x-zip-compressed-fb2' => [%w(fb2.zip), %w(application/zip), 'Compressed FictionBook document'],
-
'application/x-zoo' => [%w(zoo), %w(), 'Zoo archive'],
-
'application/xhtml+xml' => [%w(xhtml), %w(application/xml), 'XHTML page'],
-
'application/xml' => [%w(rng xbl xml xsd), %w(text/plain), 'XML document'],
-
'application/xml-dtd' => [%w(dtd), %w(text/plain), 'DTD file'],
-
'application/xml-external-parsed-entity' => [%w(ent), %w(application/xml), 'XML entities document'],
-
'application/xslt+xml' => [%w(xsl xslt), %w(application/xml), 'XSLT stylesheet'],
-
'application/xspf+xml' => [%w(xspf), %w(application/xml), 'XSPF playlist'],
-
'application/zip' => [%w(zip), %w(), 'Zip archive'],
-
'application/zlib' => [%w(zz), %w(), 'Zlib archive'],
-
'audio/AMR' => [%w(amr), %w(), 'AMR audio'],
-
'audio/AMR-WB' => [%w(awb), %w(), 'AMR-WB audio'],
-
'audio/aac' => [%w(aac), %w(), 'AAC audio'],
-
'audio/ac3' => [%w(ac3), %w(), 'Dolby Digital audio'],
-
'audio/annodex' => [%w(axa), %w(application/annodex), 'Annodex Audio'],
-
'audio/basic' => [%w(au snd), %w(), 'ULAW (Sun) audio'],
-
'audio/flac' => [%w(flac), %w(), 'FLAC audio'],
-
'audio/midi' => [%w(kar mid midi), %w(), 'MIDI audio'],
-
'audio/mp2' => [%w(mp2), %w(), 'MP2 audio'],
-
'audio/mp4' => [%w(f4a m4a), %w(), 'MPEG-4 audio'],
-
'audio/mpeg' => [%w(mp3 mpga), %w(), 'MP3 audio'],
-
'audio/ogg' => [%w(oga ogg opus), %w(application/ogg), 'Ogg Audio'],
-
'audio/prs.sid' => [%w(psid sid), %w(), 'Commodore 64 audio'],
-
'audio/vnd.dts' => [%w(dts), %w(), 'DTS audio'],
-
'audio/vnd.dts.hd' => [%w(dtshd), %w(audio/vnd.dts), 'DTSHD audio'],
-
'audio/vnd.rn-realaudio' => [%w(ra rax), %w(), 'RealAudio document'],
-
'audio/x-aifc' => [%w(aifc aiffc), %w(application/x-iff), 'AIFC audio'],
-
'audio/x-aiff' => [%w(aif aiff), %w(application/x-iff), 'AIFF/Amiga/Mac audio'],
-
'audio/x-amzxml' => [%w(amz), %w(), 'AmazonMP3 download file'],
-
'audio/x-ape' => [%w(ape), %w(), "Monkey's audio"],
-
'audio/x-flac+ogg' => [%w(oga ogg), %w(audio/ogg), 'Ogg FLAC audio'],
-
'audio/x-gsm' => [%w(gsm), %w(), 'GSM 06.10 audio'],
-
'audio/x-iriver-pla' => [%w(pla), %w(), 'iRiver Playlist'],
-
'audio/x-it' => [%w(it), %w(), 'Impulse Tracker audio'],
-
'audio/x-m4b' => [%w(f4b m4b), %w(audio/mp4), 'MPEG-4 audio book'],
-
'audio/x-matroska' => [%w(mka), %w(application/x-matroska), 'Matroska audio'],
-
'audio/x-minipsf' => [%w(minipsf), %w(audio/x-psf), 'MiniPSF audio'],
-
'audio/x-mo3' => [%w(mo3), %w(), 'compressed Tracker audio'],
-
'audio/x-mod' => [%w(669 m15 med mod mtm ult uni), %w(), 'Amiga SoundTracker audio'],
-
'audio/x-mpegurl' => [%w(m3u m3u8 vlc), %w(text/plain), 'MP3 audio (streamed)'],
-
'audio/x-ms-asx' => [%w(asx wax wmx wvx), %w(), 'Microsoft ASX playlist'],
-
'audio/x-ms-wma' => [%w(wma), %w(application/vnd.ms-asf), 'Windows Media audio'],
-
'audio/x-musepack' => [%w(mp+ mpc mpp), %w(), 'Musepack audio'],
-
'audio/x-opus+ogg' => [%w(opus), %w(audio/ogg), 'Opus audio'],
-
'audio/x-psf' => [%w(psf), %w(), 'PSF audio'],
-
'audio/x-psflib' => [%w(psflib), %w(audio/x-psf), 'PSFlib audio library'],
-
'audio/x-s3m' => [%w(s3m), %w(), 'Scream Tracker 3 audio'],
-
'audio/x-scpls' => [%w(pls), %w(), 'MP3 ShoutCast playlist'],
-
'audio/x-speex' => [%w(spx), %w(), 'Speex audio'],
-
'audio/x-speex+ogg' => [%w(oga ogg), %w(audio/ogg), 'Ogg Speex audio'],
-
'audio/x-stm' => [%w(stm), %w(), 'Scream Tracker audio'],
-
'audio/x-tta' => [%w(tta), %w(), 'TrueAudio audio'],
-
'audio/x-voc' => [%w(voc), %w(), 'VOC audio'],
-
'audio/x-vorbis+ogg' => [%w(oga ogg), %w(audio/ogg), 'Ogg Vorbis audio'],
-
'audio/x-wav' => [%w(wav), %w(), 'WAV audio'],
-
'audio/x-wavpack' => [%w(wv wvp), %w(), 'WavPack audio'],
-
'audio/x-wavpack-correction' => [%w(wvc), %w(), 'WavPack audio correction file'],
-
'audio/x-xi' => [%w(xi), %w(), 'Scream Tracker instrument'],
-
'audio/x-xm' => [%w(xm), %w(), 'FastTracker II audio'],
-
'audio/x-xmf' => [%w(xmf), %w(), 'XMF audio'],
-
'image/bmp' => [%w(bmp), %w(), 'Windows BMP image'],
-
'image/cgm' => [%w(cgm), %w(), 'Computer Graphics Metafile'],
-
'image/fax-g3' => [%w(g3), %w(), 'CCITT G3 fax'],
-
'image/fits' => [%w(fits), %w(), 'FITS document'],
-
'image/gif' => [%w(gif), %w(), 'GIF image'],
-
'image/ief' => [%w(ief), %w(), 'IEF image'],
-
'image/jp2' => [%w(jp2 jpf jpx), %w(), 'JPEG-2000 image'],
-
'image/jpeg' => [%w(jpe jpeg jpg), %w(), 'JPEG image'],
-
'image/openraster' => [%w(ora), %w(), 'OpenRaster archiving image'],
-
'image/png' => [%w(png), %w(), 'PNG image'],
-
'image/rle' => [%w(rle), %w(), 'Run Length Encoded bitmap image'],
-
'image/svg+xml' => [%w(svg), %w(application/xml), 'SVG image'],
-
'image/svg+xml-compressed' => [%w(svgz), %w(application/gzip), 'compressed SVG image'],
-
'image/tiff' => [%w(tif tiff), %w(), 'TIFF image'],
-
'image/vnd.adobe.photoshop' => [%w(psd), %w(), 'Photoshop image'],
-
'image/vnd.djvu' => [%w(djv djvu), %w(), 'DjVu image'],
-
'image/vnd.dwg' => [%w(dwg), %w(), 'AutoCAD image'],
-
'image/vnd.dxf' => [%w(dxf), %w(), 'DXF vector image'],
-
'image/vnd.microsoft.icon' => [%w(ico), %w(), 'Windows icon'],
-
'image/vnd.ms-modi' => [%w(mdi), %w(), 'Microsoft Document Imaging format'],
-
'image/vnd.rn-realpix' => [%w(rp), %w(), 'RealPix document'],
-
'image/vnd.wap.wbmp' => [%w(wbmp), %w(), 'WBMP image'],
-
'image/webp' => [%w(webp), %w(), 'WebP image'],
-
'image/x-3ds' => [%w(3ds), %w(), '3D Studio image'],
-
'image/x-adobe-dng' => [%w(dng), %w(image/tiff image/x-dcraw), 'Adobe DNG negative'],
-
'image/x-applix-graphics' => [%w(ag), %w(), 'Applix Graphics image'],
-
'image/x-bzeps' => [%w(eps.bz2 epsf.bz2 epsi.bz2), %w(application/x-bzip), 'EPS image (bzip-compressed)'],
-
'image/x-canon-cr2' => [%w(cr2), %w(image/tiff image/x-dcraw), 'Canon CR2 raw image'],
-
'image/x-canon-crw' => [%w(crw), %w(image/x-dcraw), 'Canon CRW raw image'],
-
'image/x-cmu-raster' => [%w(ras), %w(), 'CMU raster image'],
-
'image/x-compressed-xcf' => [%w(xcf.bz2 xcf.gz), %w(), 'compressed GIMP image'],
-
'image/x-dds' => [%w(dds), %w(), 'DirectDraw surface'],
-
'image/x-emf' => [%w(emf), %w(), 'EMF image'],
-
'image/x-eps' => [%w(eps epsf epsi), %w(application/postscript), 'EPS image'],
-
'image/x-exr' => [%w(exr), %w(), 'EXR image'],
-
'image/x-fuji-raf' => [%w(raf), %w(image/x-dcraw), 'Fuji RAF raw image'],
-
'image/x-gzeps' => [%w(eps.gz epsf.gz epsi.gz), %w(application/gzip), 'EPS image (gzip-compressed)'],
-
'image/x-icns' => [%w(icns), %w(), 'MacOS X icon'],
-
'image/x-ilbm' => [%w(iff ilbm lbm), %w(application/x-iff), 'ILBM image'],
-
'image/x-jng' => [%w(jng), %w(), 'JNG image'],
-
'image/x-kodak-dcr' => [%w(dcr), %w(image/tiff image/x-dcraw), 'Kodak DCR raw image'],
-
'image/x-kodak-k25' => [%w(k25), %w(image/tiff image/x-dcraw), 'Kodak K25 raw image'],
-
'image/x-kodak-kdc' => [%w(kdc), %w(image/tiff image/x-dcraw), 'Kodak KDC raw image'],
-
'image/x-lwo' => [%w(lwo lwob), %w(), 'LightWave object'],
-
'image/x-lws' => [%w(lws), %w(), 'LightWave scene'],
-
'image/x-macpaint' => [%w(pntg), %w(), 'MacPaint Bitmap image'],
-
'image/x-minolta-mrw' => [%w(mrw), %w(image/x-dcraw), 'Minolta MRW raw image'],
-
'image/x-msod' => [%w(msod), %w(), 'Office drawing'],
-
'image/x-nikon-nef' => [%w(nef), %w(image/tiff image/x-dcraw), 'Nikon NEF raw image'],
-
'image/x-olympus-orf' => [%w(orf), %w(image/x-dcraw), 'Olympus ORF raw image'],
-
'image/x-panasonic-raw' => [%w(raw), %w(image/x-dcraw), 'Panasonic raw image'],
-
'image/x-panasonic-raw2' => [%w(rw2), %w(image/x-dcraw), 'Panasonic raw2 image'],
-
'image/x-pcx' => [%w(pcx), %w(), 'PCX image'],
-
'image/x-pentax-pef' => [%w(pef), %w(image/tiff image/x-dcraw), 'Pentax PEF raw image'],
-
'image/x-photo-cd' => [%w(pcd), %w(), 'PCD image'],
-
'image/x-pict' => [%w(pct pict pict1 pict2), %w(), 'Macintosh Quickdraw/PICT drawing'],
-
'image/x-portable-anymap' => [%w(pnm), %w(), 'PNM image'],
-
'image/x-portable-bitmap' => [%w(pbm), %w(image/x-portable-anymap), 'PBM image'],
-
'image/x-portable-graymap' => [%w(pgm), %w(image/x-portable-anymap), 'PGM image'],
-
'image/x-portable-pixmap' => [%w(ppm), %w(image/x-portable-anymap), 'PPM image'],
-
'image/x-quicktime' => [%w(qif qtif), %w(), 'QuickTime image'],
-
'image/x-rgb' => [%w(rgb), %w(), 'RGB image'],
-
'image/x-sgi' => [%w(sgi), %w(), 'SGI image'],
-
'image/x-sigma-x3f' => [%w(x3f), %w(image/x-dcraw), 'Sigma X3F raw image'],
-
'image/x-skencil' => [%w(sk sk1), %w(), 'Skencil document'],
-
'image/x-sony-arw' => [%w(arw), %w(image/tiff image/x-dcraw), 'Sony ARW raw image'],
-
'image/x-sony-sr2' => [%w(sr2), %w(image/tiff image/x-dcraw), 'Sony SR2 raw image'],
-
'image/x-sony-srf' => [%w(srf), %w(image/tiff image/x-dcraw), 'Sony SRF raw image'],
-
'image/x-sun-raster' => [%w(sun), %w(), 'Sun raster image'],
-
'image/x-tga' => [%w(icb tga tpic vda vst), %w(), 'TGA image'],
-
'image/x-win-bitmap' => [%w(cur), %w(), 'Windows cursor'],
-
'image/x-wmf' => [%w(wmf), %w(), 'WMF image'],
-
'image/x-xbitmap' => [%w(xbm), %w(), 'XBM image'],
-
'image/x-xcf' => [%w(xcf), %w(), 'GIMP image'],
-
'image/x-xfig' => [%w(fig), %w(), 'XFig image'],
-
'image/x-xpixmap' => [%w(xpm), %w(), 'XPM image'],
-
'image/x-xwindowdump' => [%w(xwd), %w(), 'X window image'],
-
'message/rfc822' => [%w(eml), %w(text/plain), 'email message'],
-
'model/vrml' => [%w(vrm vrml wrl), %w(text/plain), 'VRML document'],
-
'text/cache-manifest' => [%w(manifest), %w(text/plain), 'Web application cache manifest'],
-
'text/calendar' => [%w(ics vcs), %w(text/plain), 'VCS/ICS calendar'],
-
'text/css' => [%w(css), %w(text/plain), 'CSS stylesheet'],
-
'text/csv' => [%w(csv), %w(text/plain), 'CSV document'],
-
'text/html' => [%w(htm html), %w(text/plain), 'HTML document'],
-
'text/markdown' => [%w(markdown md mkd), %w(text/plain), 'Markdown document'],
-
'text/plain' => [%w(asc txt), %w(), 'plain text document'],
-
'text/richtext' => [%w(rtx), %w(text/plain), 'rich text document'],
-
'text/sgml' => [%w(sgm sgml), %w(text/plain), 'SGML document'],
-
'text/spreadsheet' => [%w(slk sylk), %w(text/plain), 'spreadsheet interchange document'],
-
'text/tab-separated-values' => [%w(tsv), %w(text/plain), 'TSV document'],
-
'text/troff' => [%w(roff t tr), %w(text/plain), 'Troff document'],
-
'text/vcard' => [%w(gcrd vcard vcf vct), %w(text/plain), 'electronic business card'],
-
'text/vnd.graphviz' => [%w(dot gv), %w(), 'Graphviz DOT graph'],
-
'text/vnd.rn-realtext' => [%w(rt), %w(), 'RealText document'],
-
'text/vnd.sun.j2me.app-descriptor' => [%w(jad), %w(), 'JAD document'],
-
'text/vnd.trolltech.linguist' => [%w(ts), %w(application/xml), 'message catalog'],
-
'text/vnd.wap.wml' => [%w(wml), %w(application/xml), 'WML document'],
-
'text/vnd.wap.wmlscript' => [%w(wmls), %w(), 'WMLScript program'],
-
'text/vtt' => [%w(vtt), %w(text/plain), 'WebVTT subtitles'],
-
'text/x-adasrc' => [%w(adb ads), %w(text/plain), 'Ada source code'],
-
'text/x-bibtex' => [%w(bib), %w(text/plain), 'BibTeX document'],
-
'text/x-c++hdr' => [%w(h++ hh hp hpp hxx), %w(text/x-chdr), 'C++ header'],
-
'text/x-c++src' => [%w(c c++ cc cpp cxx), %w(text/x-csrc), 'C++ source code'],
-
'text/x-chdr' => [%w(h), %w(text/x-csrc), 'C header'],
-
'text/x-cmake' => [%w(cmake), %w(text/plain), 'CMake source code'],
-
'text/x-cobol' => [%w(cbl cob), %w(text/plain), 'COBOL source file'],
-
'text/x-csharp' => [%w(cs), %w(text/x-csrc), 'C# source code'],
-
'text/x-csrc' => [%w(c), %w(text/plain), 'C source code'],
-
'text/x-dcl' => [%w(dcl), %w(text/plain), 'DCL script'],
-
'text/x-dsl' => [%w(dsl), %w(text/plain), 'DSSSL document'],
-
'text/x-dsrc' => [%w(d di), %w(text/x-csrc), 'D source code'],
-
'text/x-eiffel' => [%w(e eif), %w(text/plain), 'Eiffel source code'],
-
'text/x-emacs-lisp' => [%w(el), %w(text/plain), 'Emacs Lisp source code'],
-
'text/x-erlang' => [%w(erl), %w(text/plain), 'Erlang source code'],
-
'text/x-fortran' => [%w(f f90 f95 for), %w(text/plain), 'Fortran source code'],
-
'text/x-genie' => [%w(gs), %w(text/plain), 'Genie source code'],
-
'text/x-gettext-translation' => [%w(po), %w(text/plain), 'translation file'],
-
'text/x-gettext-translation-template' => [%w(pot), %w(text/plain), 'translation template'],
-
'text/x-go' => [%w(go), %w(text/plain), 'Go source code'],
-
'text/x-google-video-pointer' => [%w(gvp), %w(), 'Google Video Pointer'],
-
'text/x-haskell' => [%w(hs), %w(text/plain), 'Haskell source code'],
-
'text/x-iMelody' => [%w(ime imy), %w(), 'iMelody ringtone'],
-
'text/x-idl' => [%w(idl), %w(text/plain), 'IDL document'],
-
'text/x-iptables' => [%w(iptables), %w(text/plain), 'iptables configuration file'],
-
'text/x-java' => [%w(java), %w(text/x-csrc), 'Java source code'],
-
'text/x-ldif' => [%w(ldif), %w(text/plain), 'LDIF address book'],
-
'text/x-lilypond' => [%w(ly), %w(text/plain), 'Lilypond music sheet'],
-
'text/x-literate-haskell' => [%w(lhs), %w(text/plain), 'LHS source code'],
-
'text/x-log' => [%w(log), %w(text/plain), 'application log'],
-
'text/x-lua' => [%w(lua), %w(application/x-executable text/plain), 'Lua script'],
-
'text/x-makefile' => [%w(mak mk), %w(text/plain), 'Makefile'],
-
'text/x-matlab' => [%w(m), %w(text/plain), 'MATLAB script/function'],
-
'text/x-microdvd' => [%w(sub), %w(text/plain), 'MicroDVD subtitles'],
-
'text/x-moc' => [%w(moc), %w(text/plain), 'Qt MOC file'],
-
'text/x-modelica' => [%w(mo), %w(text/plain), 'Modelica model'],
-
'text/x-mof' => [%w(mof), %w(text/x-csrc), 'Managed Object Format'],
-
'text/x-mpsub' => [%w(sub), %w(text/plain), 'MPSub subtitles'],
-
'text/x-mrml' => [%w(mrl mrml), %w(), 'MRML playlist'],
-
'text/x-ms-regedit' => [%w(reg), %w(text/plain), 'Windows Registry extract'],
-
'text/x-mup' => [%w(mup not), %w(text/plain), 'Mup publication'],
-
'text/x-nfo' => [%w(nfo), %w(text/x-readme), 'NFO document'],
-
'text/x-objcsrc' => [%w(m), %w(text/x-csrc), 'Objective-C source code'],
-
'text/x-ocaml' => [%w(ml mli), %w(), 'OCaml source code'],
-
'text/x-ocl' => [%w(ocl), %w(text/plain), 'OCL file'],
-
'text/x-ooc' => [%w(ooc), %w(text/x-csrc), 'OOC source code'],
-
'text/x-opml+xml' => [%w(opml), %w(application/xml), 'OPML syndication feed'],
-
'text/x-pascal' => [%w(p pas), %w(text/plain), 'Pascal source code'],
-
'text/x-patch' => [%w(diff patch), %w(text/plain), 'differences between files'],
-
'text/x-python' => [%w(py pyx wsgi), %w(application/x-executable text/plain), 'Python script'],
-
'text/x-qml' => [%w(qml qmlproject qmltypes), %w(), 'Qt Markup Language file'],
-
'text/x-reject' => [%w(rej), %w(text/plain), 'rejected patch'],
-
'text/x-rpm-spec' => [%w(spec), %w(text/plain), 'RPM spec file'],
-
'text/x-scala' => [%w(scala), %w(text/plain), 'Scala source code'],
-
'text/x-scheme' => [%w(scm ss), %w(text/plain), 'Scheme source code'],
-
'text/x-setext' => [%w(etx), %w(text/plain), 'Setext document'],
-
'text/x-ssa' => [%w(ass ssa), %w(text/plain), 'SSA subtitles'],
-
'text/x-subviewer' => [%w(sub), %w(text/plain), 'SubViewer subtitles'],
-
'text/x-svhdr' => [%w(svh), %w(text/x-verilog), 'SystemVerilog header'],
-
'text/x-svsrc' => [%w(sv), %w(text/x-verilog), 'SystemVerilog source code'],
-
'text/x-tcl' => [%w(tcl tk), %w(text/plain), 'Tcl script'],
-
'text/x-tex' => [%w(cls dtx ins latex ltx sty tex), %w(text/plain), 'TeX document'],
-
'text/x-texinfo' => [%w(texi texinfo), %w(text/plain), 'TeXInfo document'],
-
'text/x-troff-me' => [%w(me), %w(text/plain), 'Troff ME input document'],
-
'text/x-troff-mm' => [%w(mm), %w(text/plain), 'Troff MM input document'],
-
'text/x-troff-ms' => [%w(ms), %w(text/plain), 'Troff MS input document'],
-
'text/x-txt2tags' => [%w(t2t), %w(text/plain), 'txt2tags document'],
-
'text/x-uil' => [%w(uil), %w(text/plain), 'X-Motif UIL table'],
-
'text/x-uuencode' => [%w(uue), %w(text/plain), 'uuencoded file'],
-
'text/x-vala' => [%w(vala vapi), %w(text/x-csrc), 'Vala source code'],
-
'text/x-verilog' => [%w(v), %w(text/plain), 'Verilog source code'],
-
'text/x-vhdl' => [%w(vhd vhdl), %w(text/plain), 'VHDL source code'],
-
'text/x-xmi' => [%w(xmi), %w(application/xml), 'XMI file'],
-
'text/x-xslfo' => [%w(fo xslfo), %w(application/xml), 'XSL FO file'],
-
'video/3gpp' => [%w(3ga 3gp 3gpp), %w(video/mp4), '3GPP multimedia file'],
-
'video/3gpp2' => [%w(3g2 3gp2 3gpp2), %w(video/mp4), '3GPP2 multimedia file'],
-
'video/annodex' => [%w(axv), %w(application/annodex), 'Annodex Video'],
-
'video/dv' => [%w(dv), %w(), 'DV video'],
-
'video/mp2t' => [%w(bdm bdmv clpi cpi m2t m2ts mpl mpls mts ts), %w(), 'MPEG-2 transport stream'],
-
'video/mp4' => [%w(f4v lrv m4v mp4), %w(), 'MPEG-4 video'],
-
'video/mpeg' => [%w(mp2 mpe mpeg mpg vob), %w(), 'MPEG video'],
-
'video/ogg' => [%w(ogg ogv), %w(application/ogg), 'Ogg Video'],
-
'video/quicktime' => [%w(moov mov qt qtvr), %w(), 'QuickTime video'],
-
'video/vnd.mpegurl' => [%w(m1u m4u mxu), %w(text/plain), 'MPEG video (streamed)'],
-
'video/vnd.rn-realvideo' => [%w(rv rvx), %w(), 'RealVideo document'],
-
'video/vnd.vivo' => [%w(viv vivo), %w(), 'Vivo video'],
-
'video/webm' => [%w(webm), %w(), 'WebM video'],
-
'video/x-flic' => [%w(flc fli), %w(), 'FLIC animation'],
-
'video/x-flv' => [%w(flv), %w(), 'Flash video'],
-
'video/x-javafx' => [%w(fxm), %w(video/x-flv), 'JavaFX video'],
-
'video/x-matroska' => [%w(mkv), %w(application/x-matroska), 'Matroska video'],
-
'video/x-matroska-3d' => [%w(mk3d), %w(application/x-matroska), 'Matroska 3D video'],
-
'video/x-mng' => [%w(mng), %w(), 'MNG animation'],
-
'video/x-ms-wmv' => [%w(wmv), %w(application/vnd.ms-asf), 'Windows Media video'],
-
'video/x-msvideo' => [%w(avf avi divx), %w(), 'AVI video'],
-
'video/x-nsv' => [%w(nsv), %w(), 'NullSoft video'],
-
'video/x-ogm+ogg' => [%w(ogm), %w(video/ogg), 'OGM video'],
-
'video/x-sgi-movie' => [%w(movie), %w(), 'SGI video'],
-
'video/x-theora+ogg' => [%w(ogg), %w(video/ogg), 'Ogg Theora video'],
-
'x-epoc/x-sisx-app' => [%w(sisx), %w(), 'SISX package'],
-
}
-
# @private
-
# :nodoc:
-
2
MAGIC = [
-
['application/vnd.stardivision.writer', [[2089, 'StarWriter']]],
-
['application/x-docbook+xml', [[0, '<?xml', [[0..100, '-//OASIS//DTD DocBook XML'], [0..100, '-//KDE//DTD DocBook XML']]]]],
-
['image/x-eps', [[0, '%!', [[15, 'EPS']]], [0, "\004%!", [[16, 'EPS']]], [0, "\305\320\323\306"]]],
-
['application/prs.plucker', [[60, 'DataPlkr']]],
-
['application/vnd.corel-draw', []],
-
['application/x-fictionbook+xml', [[0..256, '<FictionBook']]],
-
['application/x-mobipocket-ebook', [[60, 'BOOKMOBI']]],
-
['application/x-mozilla-bookmarks', [[0..64, '<!DOCTYPE NETSCAPE-Bookmark-file-1>']]],
-
['application/x-nzb', [[0..256, '<nzb']]],
-
['application/x-pak', [[0, 'PACK']]],
-
['application/x-php', [[0..64, '<?php']]],
-
['application/x-xliff', [[0..256, '<xliff']]],
-
['application/x-zip-compressed-fb2', [[0, "PK\003\004", [[30..256, '.fb2']]]]],
-
['audio/x-flac+ogg', [[0, 'OggS', [[28, 'fLaC']]], [0, 'OggS', [[28, "\177FLAC"]]]]],
-
['audio/x-opus+ogg', [[0, 'OggS', [[28, 'OpusHead']]]]],
-
['audio/x-speex+ogg', [[0, 'OggS', [[28, 'Speex ']]]]],
-
['audio/x-vorbis+ogg', [[0, 'OggS', [[28, "\001vorbis"]]]]],
-
['image/svg+xml', [[0..256, '<!DOCTYPE svg'], [0..256, '<svg']]],
-
['image/x-kodak-kdc', [[242, 'EASTMAN KODAK COMPANY']]],
-
['image/x-niff', [[0, 'IIN1']]],
-
['text/x-qml', [[0..256, 'import Qt ']]],
-
['video/x-ogm+ogg', [[0, 'OggS', [[29, 'video']]]]],
-
['video/x-theora+ogg', [[0, 'OggS', [[28, "\200theora"]]]]],
-
['application/atom+xml', [[0..256, '<feed ']]],
-
['application/rss+xml', [[0..256, '<rss '], [0..256, '<RSS ']]],
-
['application/vnd.apple.mpegurl', [[0, '#EXTM3U', [[0..128, '#EXT-X-TARGETDURATION'], [0..128, '#EXT-X-STREAM-INF']]]]],
-
['text/x-opml+xml', [[0..256, '<opml ']]],
-
['application/msword', [[0, "1\276\000\000"], [0, 'PO^Q`'], [0, "\3767\000#"], [0, "\333\245-\000\000\000"], [2112, 'MSWordDoc'], [2108, 'MSWordDoc'], [2112, 'Microsoft Word document data'], [546, 'bjbj'], [546, 'jbjb']]],
-
['application/vnd.ms-wpl', [[0..256, '<?wpl']]],
-
['application/x-font-type1', [[0, 'LWFN'], [65, 'LWFN'], [0, '%!PS-AdobeFont-1.'], [6, '%!PS-AdobeFont-1.'], [0, '%!FontType1-1.'], [6, '%!FontType1-1.']]],
-
['application/x-karbon', [[0, "\037\213", [[10, 'KOffice', [[18, "application/x-karbon\004\006"]]]]], [0, "PK\003\004", [[30, 'mimetype', [[38, 'application/x-karbon']]]]]]],
-
['application/x-kchart', [[0, "\037\213", [[10, 'KOffice', [[18, "application/x-kchart\004\006"]]]]], [0, "PK\003\004", [[30, 'mimetype', [[38, 'application/x-kchart']]]]]]],
-
['application/x-kformula', [[0, "\037\213", [[10, 'KOffice', [[18, "application/x-kformula\004\006"]]]]], [0, "PK\003\004", [[30, 'mimetype', [[38, 'application/x-kformula']]]]]]],
-
['application/x-killustrator', [[0, "\037\213", [[10, 'KOffice', [[18, "application/x-killustrator\004\006"]]]]]]],
-
['application/x-kivio', [[0, "\037\213", [[10, 'KOffice', [[18, "application/x-kivio\004\006"]]]]], [0, "PK\003\004", [[30, 'mimetype', [[38, 'application/x-kivio']]]]]]],
-
['application/x-kontour', [[0, "\037\213", [[10, 'KOffice', [[18, "application/x-kontour\004\006"]]]]], [0, "PK\003\004", [[30, 'mimetype', [[38, 'application/x-kontour']]]]]]],
-
['application/x-kpresenter', [[0, "\037\213", [[10, 'KOffice', [[18, "application/x-kpresenter\004\006"]]]]], [0, "PK\003\004", [[30, 'mimetype', [[38, 'application/x-kpresenter']]]]]]],
-
['application/x-krita', [[0, "\037\213", [[10, 'KOffice', [[18, "application/x-krita\004\006"]]]]], [0, "PK\003\004", [[30, 'mimetype', [[38, 'application/x-krita']]]]]]],
-
['application/x-kspread', [[0, "\037\213", [[10, 'KOffice', [[18, "application/x-kspread\004\006"]]]]], [0, "PK\003\004", [[30, 'mimetype', [[38, 'application/x-kspread']]]]]]],
-
['application/x-kword', [[0, "\037\213", [[10, 'KOffice', [[18, "application/x-kword\004\006"]]]]], [0, "PK\003\004", [[30, 'mimetype', [[38, 'application/x-kword']]]]]]],
-
['application/x-quicktime-media-link', [[0, '<?xml', [[0..64, '<?quicktime']]], [0, 'RTSPtext'], [0, 'rtsptext'], [0, 'SMILtext']]],
-
['audio/vnd.dts.hd', [[0..18725, 'dX %']]],
-
['text/x-txt2tags', [[0, '%!postproc'], [0, '%!encoding']]],
-
['application/smil+xml', [[0..256, '<smil']]],
-
['audio/x-ms-asx', [[0, 'ASF '], [0..64, '<ASX'], [0..64, '<asx'], [0..64, '<Asx']]],
-
['application/annodex', [[0, 'OggS', [[28, "fishead\000", [[56..512, "CMML\000\000\000\000"]]]]]]],
-
['application/dicom', [[128, 'DICM']]],
-
['application/epub+zip', [[0, "PK\003\004", [[30, 'mimetype', [[38, 'application/epub+zip'], [43, 'application/epub+zip']]]]]]],
-
['application/font-woff', [[0, 'wOFF']]],
-
['application/gnunet-directory', [[0, "\211GND\r\n\032\n"]]],
-
['application/gzip', [[0, "\037\213"]]],
-
['application/mac-binhex40', [[11, 'must be converted with BinHex']]],
-
['application/mathematica', [[0, '(************** Content-type: application/mathematica'], [100..256, 'This notebook can be used on any computer system with Mathematica'], [10..256, 'This is a Mathematica Notebook file. It contains ASCII text']]],
-
['application/metalink+xml', [[0..256, "<metalink version=\"3.0\""]]],
-
['application/metalink4+xml', [[0..256, "<metalink xmlns=\"urn"]]],
-
['application/mxf', [[0..256, "\006\016+4\002\005\001\001\r\001\002\001\001\002"]]],
-
['application/ogg', [[0, 'OggS']]],
-
['application/pdf', [[0..1024, '%PDF-']]],
-
['application/pgp-encrypted', [[0, '-----BEGIN PGP MESSAGE-----']]],
-
['application/pgp-keys', [[0, '-----BEGIN PGP PUBLIC KEY BLOCK-----'], [0, '-----BEGIN PGP PRIVATE KEY BLOCK-----'], [0, "\225\001"], [0, "\225\000"], [0, "\231\000"], [0, "\231\001"]]],
-
['application/pgp-signature', [[0, '-----BEGIN PGP SIGNATURE-----']]],
-
['application/postscript', [[0, "\004%!"], [0, '%!']]],
-
['application/rtf', [[0, "{\\rtf"]]],
-
['application/sdp', [[0, 'v=', [[0..256, 's=']]]]],
-
['application/vnd.adobe.flash.movie', [[0, 'FWS'], [0, 'CWS']]],
-
['application/vnd.debian.binary-package', [[0, '!<arch>', [[8, 'debian']]]]],
-
['application/vnd.emusic-emusic_package', [[0, 'nF7YLao']]],
-
['application/vnd.iccprofile', [[36, 'acsp']]],
-
['application/vnd.lotus-1-2-3', [[0, "\000\000\002\000\006\004\006\000\b\000\000\000\000\000"]]],
-
['application/vnd.lotus-wordpro', [[0, 'WordPro']]],
-
['application/vnd.ms-access', [[0, "\000\001\000\000Standard Jet DB"]]],
-
['application/vnd.ms-asf', [[0, "0&\262u"], [0, '[Reference]']]],
-
['application/vnd.ms-cab-compressed', [[0, "MSCF\000\000\000\000"]]],
-
['application/vnd.ms-excel', [[2080, 'Microsoft Excel 5.0 Worksheet']]],
-
['application/vnd.ms-tnef', [[0, "x\237>\""]]],
-
['application/vnd.oasis.opendocument.chart', [[0, "PK\003\004", [[30, 'mimetype', [[38, 'application/vnd.oasis.opendocument.chart']]]]]]],
-
['application/vnd.oasis.opendocument.chart-template', [[0, "PK\003\004", [[30, 'mimetype', [[38, 'application/vnd.oasis.opendocument.chart-template']]]]]]],
-
['application/vnd.oasis.opendocument.database', [[0, "PK\003\004", [[30, 'mimetype', [[38, 'application/vnd.oasis.opendocument.base']]]]]]],
-
['application/vnd.oasis.opendocument.formula', [[0, "PK\003\004", [[30, 'mimetype', [[38, 'application/vnd.oasis.opendocument.formula']]]]]]],
-
['application/vnd.oasis.opendocument.formula-template', [[0, "PK\003\004", [[30, 'mimetype', [[38, 'application/vnd.oasis.opendocument.formula-template']]]]]]],
-
['application/vnd.oasis.opendocument.graphics', [[0, "PK\003\004", [[30, 'mimetype', [[38, 'application/vnd.oasis.opendocument.graphics']]]]]]],
-
['application/vnd.oasis.opendocument.graphics-template', [[0, "PK\003\004", [[30, 'mimetype', [[38, 'application/vnd.oasis.opendocument.graphics-template']]]]]]],
-
['application/vnd.oasis.opendocument.image', [[0, "PK\003\004", [[30, 'mimetype', [[38, 'application/vnd.oasis.opendocument.image']]]]]]],
-
['application/vnd.oasis.opendocument.presentation', [[0, "PK\003\004", [[30, 'mimetype', [[38, 'application/vnd.oasis.opendocument.presentation']]]]]]],
-
['application/vnd.oasis.opendocument.presentation-template', [[0, "PK\003\004", [[30, 'mimetype', [[38, 'application/vnd.oasis.opendocument.presentation-template']]]]]]],
-
['application/vnd.oasis.opendocument.spreadsheet', [[0, "PK\003\004", [[30, 'mimetype', [[38, 'application/vnd.oasis.opendocument.spreadsheet']]]]]]],
-
['application/vnd.oasis.opendocument.spreadsheet-template', [[0, "PK\003\004", [[30, 'mimetype', [[38, 'application/vnd.oasis.opendocument.spreadsheet-template']]]]]]],
-
['application/vnd.oasis.opendocument.text', [[0, "PK\003\004", [[30, 'mimetype', [[38, 'application/vnd.oasis.opendocument.text']]]]]]],
-
['application/vnd.oasis.opendocument.text-master', [[0, "PK\003\004", [[30, 'mimetype', [[38, 'application/vnd.oasis.opendocument.text-master']]]]]]],
-
['application/vnd.oasis.opendocument.text-template', [[0, "PK\003\004", [[30, 'mimetype', [[38, 'application/vnd.oasis.opendocument.text-template']]]]]]],
-
['application/vnd.oasis.opendocument.text-web', [[0, "PK\003\004", [[30, 'mimetype', [[38, 'application/vnd.oasis.opendocument.text-web']]]]]]],
-
['application/vnd.rn-realmedia', [[0, '.RMF']]],
-
['application/vnd.symbian.install', [[8, "\031\004\000\020"]]],
-
['application/vnd.tcpdump.pcap', [[0, "\324\303\262\241"], [0, "\241\262\303\324"]]],
-
['application/vnd.wordperfect', [[1, 'WPC']]],
-
['application/winhlp', [[0, "?_\003\000"]]],
-
['application/x-7z-compressed', [[0, "7z\274\257'\034"]]],
-
['application/x-abiword', [[0..256, '<abiword'], [0..256, '<!DOCTYPE abiword']]],
-
['application/x-ace', [[7, '**ACE**']]],
-
['application/x-alz', [[0, 'ALZ']]],
-
['application/x-aportisdoc', [[60, 'TEXtREAd'], [60, 'TEXtTlDc']]],
-
['application/x-applix-spreadsheet', [[0, '*BEGIN SPREADSHEETS'], [0, '*BEGIN', [[7, 'SPREADSHEETS']]]]],
-
['application/x-applix-word', [[0, '*BEGIN', [[7, 'WORDS']]]]],
-
['application/x-arc', []],
-
['application/x-arj', [[0, "`\352"]]],
-
['application/x-awk', [[0, '#!/bin/gawk'], [0, '#! /bin/gawk'], [0, '#!/usr/bin/gawk'], [0, '#! /usr/bin/gawk'], [0, '#!/usr/local/bin/gawk'], [0, '#! /usr/local/bin/gawk'], [0, '#!/bin/awk'], [0, '#! /bin/awk'], [0, '#!/usr/bin/awk'], [0, '#! /usr/bin/awk']]],
-
['application/x-bittorrent', [[0, 'd8:announce']]],
-
['application/x-blender', [[0, 'BLENDER']]],
-
['application/x-bzip', [[0, 'BZh']]],
-
['application/x-ccmx', [[0, 'CCMX']]],
-
['application/x-cdrdao-toc', [[0, "CD_ROM\n"], [0, "CD_DA\n"], [0, "CD_ROM_XA\n"], [0, 'CD_TEXT '], [0, "CATALOG \"", [[22, "\""]]]]],
-
['application/x-chess-pgn', [[0, '[Event ']]],
-
['application/x-cisco-vpn-settings', [[0, '[main]', [[0..256, 'AuthType=']]]]],
-
['application/x-compress', [[0, "\037\235"]]],
-
['application/x-core', [[0, "\177ELF", [[5, "\001", [[16, "\004\000"]]]]], [0, "\177ELF", [[5, "\002", [[16, "\000\004"]]]]], [0, "Core\001"], [0, "Core\002"]]],
-
['application/x-cpio', [[0, "\307q"], [0, '070701'], [0, '070702'], [0, "q\307"]]],
-
['application/x-desktop', [[0..32, '[Desktop Entry]'], [0, '[Desktop Action'], [0, '[KDE Desktop Entry]'], [0, '# Config File'], [0, '# KDE Config File']]],
-
['application/x-dia-diagram', [[5..100, '<dia:']]],
-
['application/x-dia-shape', [[5..100, '<shape']]],
-
['application/x-dvi', [[0, "\367\002"]]],
-
['application/x-fluid', [[0, '# data file for the Fltk']]],
-
['application/x-font-bdf', [[0, 'STARTFONT ']]],
-
['application/x-font-dos', [[0, "\377FON"], [7, "\000EGA"], [7, "\000VID"]]],
-
['application/x-font-framemaker', [[0, '<MakerScreenFont']]],
-
['application/x-font-libgrx', [[0, "\024\002Y\031"]]],
-
['application/x-font-linux-psf', [[0, "6\004"]]],
-
['application/x-font-otf', [[0, 'OTTO']]],
-
['application/x-font-pcf', [[0, "\001fcp"]]],
-
['application/x-font-speedo', [[0, "D1.0\r"]]],
-
['application/x-font-sunos-news', [[0, 'StartFont'], [0, "\023z)"], [8, "\023z+"]]],
-
['application/x-font-tex', [[0, "\367\203"], [0, "\367Y"], [0, "\367\312"]]],
-
['application/x-font-tex-tfm', [[2, "\000\021"], [2, "\000\022"]]],
-
['application/x-font-ttf', [[0, 'FFIL'], [65, 'FFIL'], [0, "\000\001\000\000\000"]]],
-
['application/x-font-ttx', [[0..256, "<ttFont sfntVersion=\"\\000\\001\\000\\000\" ttLibVersion=\""]]],
-
['application/x-font-vfont', [[0, 'FONT']]],
-
['application/x-frame', [[0, '<MakerFile'], [0, '<MIFFile'], [0, '<MakerDictionary'], [0, '<MakerScreenFon'], [0, '<MML'], [0, '<Book'], [0, '<Maker']]],
-
['application/x-gamecube-rom', [[28, "\3023\237="]]],
-
['application/x-gdbm', [[0, "\023W\232\316"], [0, "\316\232W\023"], [0, 'GDBM']]],
-
['application/x-gedcom', [[0, '0 HEAD']]],
-
['application/x-genesis-rom', [[256, 'SEGA'], [640, 'EAGN'], [640, 'EAMG']]],
-
['application/x-gettext-translation', [[0, "\336\022\004\225"], [0, "\225\004\022\336"]]],
-
['application/x-glade', [[0..256, '<glade-interface']]],
-
['application/x-gnumeric', [[0..64, 'gmr:Workbook'], [0..64, 'gnm:Workbook']]],
-
['application/x-go-sgf', [[0, '(;FF[3]'], [0, '(;FF[4]']]],
-
['application/x-gtk-builder', [[0..256, '<interface']]],
-
['application/x-gtktalog', [[4, 'gtktalog ']]],
-
['application/x-hdf', [[0, "\211HDF\r\n\032\n"], [0, "\016\003\023\001"]]],
-
['application/x-hwp', [[0, 'HWP Document File']]],
-
['application/x-ipod-firmware', [[0, 'S T O P']]],
-
['application/x-it87', [[0, 'IT8.7']]],
-
['application/x-iwork-keynote-sffkey', [[0, "PK\003\004", [[30, 'index.apxl']]]]],
-
['application/x-java', [[0, "\312\376\272\276"]]],
-
['application/x-java-jce-keystore', [[0, "\316\316\316\316"]]],
-
['application/x-java-jnlp-file', [[0..256, '<jnlp']]],
-
['application/x-java-keystore', [[0, "\355\376\355\376"]]],
-
['application/x-java-pack200', [[0, "\312\376\320\r"]]],
-
['application/x-kspread-crypt', [[0, "\r\032'\002"]]],
-
['application/x-ksysv-package', [[4, 'KSysV', [[15, "\001"]]]]],
-
['application/x-kword-crypt', [[0, "\r\032'\001"]]],
-
['application/x-lha', [[2, '-lh -'], [2, '-lh0-'], [2, '-lh1-'], [2, '-lh2-'], [2, '-lh3-'], [2, '-lh4-'], [2, '-lh5-'], [2, '-lh40-'], [2, '-lhd-'], [2, '-lz4-'], [2, '-lz5-'], [2, '-lzs-']]],
-
['application/x-lrzip', [[0, 'LRZI']]],
-
['application/x-lyx', [[0, '#LyX']]],
-
['application/x-lz4', [[0, "\004\"M\030"], [0, "\002!L\030"]]],
-
['application/x-lzip', [[0, 'LZIP']]],
-
['application/x-lzop', [[0, "\211LZO\000\r\n\032\n"]]],
-
['application/x-macbinary', [[102, 'mBIN']]],
-
['application/x-matroska', [[0, "\032E\337\243", [[5..65, "B\202", [[8..75, 'matroska']]]]]]],
-
['application/x-ms-dos-executable', [[0, 'MZ']]],
-
['application/x-mswinurl', [[1, 'InternetShortcut'], [1, 'DEFAULT', [[11, 'BASEURL=']]]]],
-
['application/x-nautilus-link', [[0..32, '<nautilus_object nautilus_link']]],
-
['application/x-navi-animation', [[0, 'RIFF', [[8, 'ACON']]]]],
-
['application/x-netshow-channel', [[0, '[Address]']]],
-
['application/x-object', [[0, "\177ELF", [[5, "\001", [[16, "\001\000"]]]]], [0, "\177ELF", [[5, "\002", [[16, "\000\001"]]]]]]],
-
['application/x-ole-storage', [[0, "\320\317\021\340\241\261\032\341"], [0, "\320\317\021\340"]]],
-
['application/x-oleo', [[31, 'Oleo']]],
-
['application/x-par2', [[0, 'PAR2']]],
-
['application/x-pef-executable', [[0, 'Joy!']]],
-
['application/x-perl', [[0, "eval \"exec /usr/local/bin/perl"], [2..16, '/bin/perl'], [2..16, '/bin/env perl'], [0..256, 'use strict'], [0..256, 'use warnings'], [0..256, 'use diagnostics'], [0..256, 'use Test::'], [0..256, 'BEGIN {']]],
-
['application/x-pocket-word', [[0, "{\\pwi"]]],
-
['application/x-python-bytecode', [[0, "\231N\r\n"]]],
-
['application/x-qpress', [[0, 'qpress10']]],
-
['application/x-qtiplot', [[0, 'QtiPlot']]],
-
['application/x-rar', [[0, 'Rar!']]],
-
['application/x-rpm', [[0, "\355\253\356\333"]]],
-
['application/x-sami', [[0..256, '<SAMI>']]],
-
['application/x-sc', [[38, 'Spreadsheet']]],
-
['application/x-sharedlib', [[0, "\177ELF", [[5, "\001", [[16, "\003\000"]]]]], [0, "\177ELF", [[5, "\002", [[16, "\000\003"]]]]], [0, "\203\001"]]],
-
['application/x-shellscript', [[10, '# This is a shell archive'], [2..16, '/bin/bash'], [2..16, '/bin/nawk'], [2..16, '/bin/zsh'], [2..16, '/bin/sh'], [2..16, '/bin/ksh'], [2..16, '/bin/dash'], [2..16, '/bin/env sh'], [2..16, '/bin/env bash'], [2..16, '/bin/env zsh'], [2..16, '/bin/env ksh']]],
-
['application/x-shorten', [[0, 'ajkg']]],
-
['application/x-smaf', [[0, 'MMMD']]],
-
['application/x-spss-por', [[40, 'ASCII SPSS PORT FILE']]],
-
['application/x-spss-sav', [[0, '$FL2'], [0, '$FL3']]],
-
['application/x-stuffit', [[0, 'StuffIt '], [0, 'SIT!']]],
-
['application/x-subrip', [[0, '1', [[0..256, ' --> ']]]]],
-
['application/x-t602', [[0, '@CT 0'], [0, '@CT 1'], [0, '@CT 2']]],
-
['application/x-tar', [[257, "ustar\000"], [257, "ustar \000"]]],
-
['application/x-tgif', [[0, '%TGIF']]],
-
['application/x-wii-rom', [[24, "]\034\236\243"], [0, 'WBFS'], [0, "WII\001DISC"]]],
-
['application/x-xbel', [[0..256, '<!DOCTYPE xbel']]],
-
['application/x-xz', [[0, "\3757zXZ\000"]]],
-
['application/x-zoo', [[20, "\334\247\304\375"]]],
-
['application/xslt+xml', [[0..256, '<xsl:stylesheet']]],
-
['application/xspf+xml', [[0..64, "<playlist version=\"1"], [0..64, "<playlist version='1"]]],
-
['audio/AMR', [[0, "#!AMR\n"], [0, "#!AMR_MC1.0\n"]]],
-
['audio/AMR-WB', [[0, "#!AMR-WB\n"], [0, "#!AMR-WB_MC1.0\n"]]],
-
['audio/aac', [[0, 'ADIF']]],
-
['audio/ac3', [[0, "\vw"]]],
-
['audio/annodex', [[0, 'OggS', [[28, "fishead\000", [[56..512, "CMML\000\000\000\000"]]]]]]],
-
['audio/flac', [[0, 'fLaC']]],
-
['audio/midi', [[0, 'MThd']]],
-
['audio/mp4', [[4, 'ftypM4A']]],
-
['audio/mpeg', [[0, "\377\373"], [0, 'ID3']]],
-
['audio/ogg', [[0, 'OggS']]],
-
['audio/prs.sid', [[0, 'PSID']]],
-
['audio/vnd.dts', [[0, "\177\376\200\001"], [0, "\200\001\177\376"], [0, "\037\377\350\000"], [0, "\350\000\037\377"]]],
-
['audio/x-adpcm', [[0, '.snd', [[12, "\000\000\000\027"]]], [0, ".sd\000", [[12, "\001\000\000\000"], [12, "\002\000\000\000"], [12, "\003\000\000\000"], [12, "\004\000\000\000"], [12, "\005\000\000\000"], [12, "\006\000\000\000"], [12, "\a\000\000\000"], [12, "\027\000\000\000"]]]]],
-
['audio/x-aifc', [[8, 'AIFC']]],
-
['audio/x-aiff', [[8, 'AIFF'], [8, '8SVX']]],
-
['audio/x-ape', [[0, 'MAC ']]],
-
['audio/x-iriver-pla', [[4, 'iriver UMS PLA']]],
-
['audio/x-it', [[0, 'IMPM']]],
-
['audio/x-m4b', [[4, 'ftypM4B']]],
-
['audio/x-mo3', [[0, 'MO3']]],
-
['audio/x-mpegurl', [[0, '#EXTM3U']]],
-
['audio/x-musepack', [[0, 'MP+']]],
-
['audio/x-psf', [[0, 'PSF']]],
-
['audio/x-s3m', [[44, 'SCRM']]],
-
['audio/x-scpls', [[0, '[playlist]'], [0, '[Playlist]'], [0, '[PLAYLIST]']]],
-
['audio/x-speex', [[0, 'Speex']]],
-
['audio/x-tta', [[0, 'TTA1']]],
-
['audio/x-wav', [[8, 'WAVE'], [8, 'WAV ']]],
-
['audio/x-wavpack', [[0, 'wvpk']]],
-
['audio/x-wavpack-correction', [[0, 'wvpk']]],
-
['audio/x-xi', [[0, 'Extended Instrument:']]],
-
['audio/x-xm', [[0, 'Extended Module:']]],
-
['audio/x-xmf', [[0, 'XMF_'], [0, "XMF_2.00\000\000\000\002"]]],
-
['image/bmp', [[0, 'BM', [[14, "\f"], [14, '@'], [14, '(']]]]],
-
['image/dpx', [[0, 'SDPX']]],
-
['image/fits', [[0, 'SIMPLE =']]],
-
['image/gif', [[0, 'GIF8']]],
-
['image/jp2', [[0, "\377O\377Q\000"], [3, "\fjP "], [20, 'jp2']]],
-
['image/jpeg', [[0, "\377\330\377"], [0, "\377\330"]]],
-
['image/openraster', [[0, "PK\003\004", [[30, 'mimetype', [[38, 'image/openraster']]]]]]],
-
['image/png', [[0, "\211PNG"]]],
-
['image/tiff', [[0, "MM\000*"], [0, "II*\000"]]],
-
['image/vnd.adobe.photoshop', []],
-
['image/vnd.djvu', [[0, 'AT&TFORM', [[12, 'DJVM'], [12, 'DJVU']]], [0, 'FORM', [[8, 'DJVM'], [8, 'DJVU']]]]],
-
['image/vnd.dxf', [[0..64, "\nHEADER\n"], [0..64, "\r\nHEADER\r\n"]]],
-
['image/vnd.microsoft.icon', [[0, "\000\000\001\000", [[5, "\000"]]]]],
-
['image/vnd.ms-modi', [[0, "EP*\000"]]],
-
['image/webp', [[0, 'RIFF', [[8, 'WEBP']]]]],
-
['image/x-applix-graphics', [[0, '*BEGIN', [[7, 'GRAPHICS']]]]],
-
['image/x-canon-crw', [[0, "II\032\000\000\000HEAPCCDR"]]],
-
['image/x-dds', [[0, 'DDS']]],
-
['image/x-dib', [[0, "(\000\000\000"]]],
-
['image/x-emf', [[0, "\001\000\000\000", [[40, ' EMF', [[44, "\000\000\001\000", [[58, "\000\000"]]]]]]]]],
-
['image/x-exr', [[0, "v/1\001"]]],
-
['image/x-fpx', [[0, 'FPix']]],
-
['image/x-fuji-raf', [[0, 'FUJIFILMCCD-RAW ']]],
-
['image/x-icns', [[0, 'icns']]],
-
['image/x-ilbm', [[8, 'ILBM'], [8, 'PBM ']]],
-
['image/x-minolta-mrw', [[0, "\000MRM"]]],
-
['image/x-olympus-orf', [[0, "IIRO\b\000\000\000"]]],
-
['image/x-panasonic-raw', [[0, "IIU\000\b\000\000\000"]]],
-
['image/x-panasonic-raw2', [[0, "IIU\000\030\000\000\000"]]],
-
['image/x-pcx', [[0, "\n", [[1, "\000"], [1, "\002"], [1, "\003"], [1, "\005"]]]]],
-
['image/x-pict', [[10, "\000\021", [[12, "\002\377", [[14, "\f\000", [[16, "\377\376"]]]]]]]]],
-
['image/x-pict', [[522, "\000\021", [[524, "\002\377", [[526, "\f\000", [[528, "\377\376"]]]]]]]]],
-
['image/x-portable-bitmap', [[0, 'P1', [[2, "\n"], [2, ' '], [2, "\t"], [2, "\r"]]], [0, 'P4', [[2, "\n"], [2, ' '], [2, "\t"], [2, "\r"]]]]],
-
['image/x-portable-graymap', [[0, 'P2', [[2, "\n"], [2, ' '], [2, "\t"], [2, "\r"]]], [0, 'P5', [[2, "\n"], [2, ' '], [2, "\t"], [2, "\r"]]]]],
-
['image/x-portable-pixmap', [[0, 'P3', [[2, "\n"], [2, ' '], [2, "\t"], [2, "\r"]]], [0, 'P6', [[2, "\n"], [2, ' '], [2, "\t"], [2, "\r"]]]]],
-
['image/x-quicktime', [[4, 'idat']]],
-
['image/x-sigma-x3f', [[0, 'FOVb']]],
-
['image/x-skencil', [[0, '##Sketch']]],
-
['image/x-sun-raster', [[0, "Y\246j\225"]]],
-
['image/x-tga', [[1, "\000\002", [[16, "\b"], [16, "\020"], [16, "\030"], [16, ' ']]]]],
-
['image/x-win-bitmap', [[0, "\000\000\002\000", [[5, "\000"]]]]],
-
['image/x-wmf', [[0, "\327\315\306\232", [[22, "\001\000", [[24, "\t\000"]]]]], [0, "\001\000", [[2, "\t\000"]]]]],
-
['image/x-xcf', [[0, 'gimp xcf file'], [0, 'gimp xcf v001'], [0, 'gimp xcf v002']]],
-
['image/x-xcursor', [[0, 'Xcur']]],
-
['image/x-xfig', [[0, '#FIG']]],
-
['image/x-xpixmap', [[0, '/* XPM']]],
-
['message/news', [[0, 'Article'], [0, 'Path:'], [0, 'Xref:']]],
-
['message/rfc822', [[0, '#! rnews'], [0, 'Forward to'], [0, 'From:'], [0, 'N#! rnews'], [0, 'Pipe to'], [0, 'Received:'], [0, 'Relay-Version:'], [0, 'Return-Path:'], [0, 'Return-path:'], [0, 'Subject: ']]],
-
['text/calendar', [[0, 'BEGIN:VCALENDAR'], [0, 'begin:vcalendar']]],
-
['text/html', [[0..256, '<!DOCTYPE HTML'], [0..256, '<!doctype html'], [0..256, '<HEAD'], [0..256, '<head'], [0..256, '<TITLE'], [0..256, '<title'], [0..256, '<HTML'], [0..256, '<html'], [0..256, '<SCRIPT'], [0..256, '<script'], [0, '<BODY'], [0, '<body'], [0, '<!--'], [0, '<h1'], [0, '<H1'], [0, '<!doctype HTML'], [0, '<!DOCTYPE html']]],
-
['text/plain', [[0, 'This is TeX,'], [0, 'This is METAFONT,']]],
-
['text/spreadsheet', [[0, 'ID;']]],
-
['text/troff', [[0, ".\\\""], [0, "'\\\""], [0, "'.\\\""], [0, "\\\""]]],
-
['text/vcard', [[0, 'BEGIN:VCARD'], [0, 'begin:vcard']]],
-
['text/vnd.graphviz', [[0, 'digraph '], [0, 'strict digraph '], [0, 'graph '], [0, 'strict graph ']]],
-
['text/vnd.sun.j2me.app-descriptor', [[0, 'MIDlet-']]],
-
['text/vtt', [[0, 'WEBVTT']]],
-
['text/x-emacs-lisp', [[0, "\n("], [0, ";ELC\023\000\000\000"]]],
-
['text/x-gettext-translation-template', [[0..256, "#, fuzzy\nmsgid \"\"\nmsgstr \"\"\n\"Project-Id-Version:"]]],
-
['text/x-google-video-pointer', [[0, '#.download.the.free.Google.Video.Player'], [0, '# download the free Google Video Player']]],
-
['text/x-iMelody', [[0, 'BEGIN:IMELODY']]],
-
['text/x-iptables', [[0..256, '/etc/sysconfig/iptables'], [0..256, '*filter', [[0..256, ':INPUT', [[0..256, ':FORWARD', [[0..256, ':OUTPUT']]]]]]], [0..256, '-A INPUT', [[0..256, '-A FORWARD', [[0..256, '-A OUTPUT']]]]], [0..256, '-P INPUT', [[0..256, '-P FORWARD', [[0..256, '-P OUTPUT']]]]]]],
-
['text/x-ldif', [[0, 'dn: cn='], [0, 'dn: mail=']]],
-
['text/x-lua', [[2..16, '/bin/lua'], [2..16, '/bin/luajit'], [2..16, '/bin/env lua'], [2..16, '/bin/env luajit']]],
-
['text/x-makefile', [[0, '#!/usr/bin/make'], [0, '#! /usr/bin/make']]],
-
['text/x-matlab', [[0, 'function']]],
-
['text/x-microdvd', [[0, '{1}'], [0, '{0}'], [0..6, '}{']]],
-
['text/x-modelica', [[0, 'class']]],
-
['text/x-modelica', [[0, 'model']]],
-
['text/x-modelica', [[0, 'function']]],
-
['text/x-modelica', [[0, 'record']]],
-
['text/x-mpsub', [[0..256, 'FORMAT=']]],
-
['text/x-mrml', [[0, '<mrml ']]],
-
['text/x-ms-regedit', [[0, 'REGEDIT'], [0, 'Windows Registry Editor Version 5.00'], [0, "\377\376W\000i\000n\000d\000o\000w\000s\000 \000R\000e\000g\000i\000s\000t\000r\000y\000 \000E\000d\000i\000t\000o\000r\000"]]],
-
['text/x-mup', [[0, '//!Mup']]],
-
['text/x-patch', [[0, "diff\t"], [0, 'diff '], [0, "***\t"], [0, '*** '], [0, '=== '], [0, '--- '], [0, "Only in\t"], [0, 'Only in '], [0, 'Common subdirectories: '], [0, 'Index:']]],
-
['text/x-python', [[0, '#!/bin/python'], [0, '#! /bin/python'], [0, "eval \"exec /bin/python"], [0, '#!/usr/bin/python'], [0, '#! /usr/bin/python'], [0, "eval \"exec /usr/bin/python"], [0, '#!/usr/local/bin/python'], [0, '#! /usr/local/bin/python'], [0, "eval \"exec /usr/local/bin/python"], [2..16, '/bin/env python']]],
-
['text/x-rpm-spec', [[0, 'Summary: '], [0, '%define ']]],
-
['text/x-ssa', [[0..256, '[Script Info]'], [0..256, 'Dialogue: ']]],
-
['text/x-subviewer', [[0, '[INFORMATION]']]],
-
['text/x-tex', [[1, 'documentclass']]],
-
['text/x-uuencode', [[0, 'begin ']]],
-
['text/xmcd', [[0, '# xmcd']]],
-
['video/3gpp', [[4, 'ftyp3ge'], [4, 'ftyp3gg'], [4, 'ftyp3gp'], [4, 'ftyp3gs']]],
-
['video/3gpp2', [[4, 'ftyp3g2']]],
-
['video/annodex', [[0, 'OggS', [[28, "fishead\000", [[56..512, "CMML\000\000\000\000"]]]]]]],
-
['video/dv', []],
-
['video/mp2t', []],
-
['video/mp4', [[4, 'ftypisom'], [4, 'ftypmp42'], [4, 'ftypMSNV'], [4, 'ftypM4V '], [4, 'ftypf4v ']]],
-
['video/mpeg', [[0, "G?\377\020"], [0, "\000\000\001\263"], [0, "\000\000\001\272"]]],
-
['video/ogg', [[0, 'OggS']]],
-
['video/quicktime', [[12, 'mdat'], [4, 'mdat'], [4, 'moov'], [4, 'ftypqt']]],
-
['video/vnd.mpegurl', [[0, '#EXTM4U']]],
-
['video/webm', [[0, "\032E\337\243", [[5..65, "B\202", [[8..75, 'webm']]]]]]],
-
['video/x-flic', [[0, "\021\257"], [0, "\022\257"]]],
-
['video/x-flv', [[0, 'FLV']]],
-
['video/x-mng', [[0, "\212MNG\r\n\032\n"]]],
-
['video/x-msvideo', [[0, 'RIFF', [[8, 'AVI ']]], [0, 'AVF0', [[8, 'AVI ']]]]],
-
['video/x-nsv', [[0, 'NSVf']]],
-
['video/x-sgi-movie', [[0, 'MOVI']]],
-
['x-epoc/x-sisx-app', [[0, "z\032 \020"]]],
-
['application/x-archive', [[0, '<ar>'], [0, '!<arch>']]],
-
['application/x-riff', [[0, 'RIFF']]],
-
['application/x-executable', [[0, "\177ELF", [[5, "\001", [[16, "\002\000"]]]]], [0, "\177ELF", [[5, "\002", [[16, "\000\002"]]]]], [0, 'MZ'], [0, "\034R"], [0, "\020\001"], [0, "\021\001"], [0, "\203\001"]]],
-
['application/x-iff', [[0, 'FORM']]],
-
['application/x-perl', [[0..256, "\n=pod"], [0..256, "\n=head1 NAME"], [0..256, "\n=head1 DESCRIPTION"]]],
-
['application/xml', [[0, '<?xml'], [0, '<!--']]],
-
['application/zip', [[0, "PK\003\004"]]],
-
['audio/basic', [[0, '.snd']]],
-
['video/x-javafx', [[0, 'FLV']]],
-
['application/x-mobipocket-ebook', [[60, 'TEXtREAd']]],
-
['text/x-csrc', [[0, '/*'], [0, '//'], [0, '#include']]],
-
['text/x-objcsrc', [[0, '#import']]],
-
['application/mbox', [[0, 'From ']]],
-
['image/x-tga', [[1, "\001\001"], [1, "\0019"], [1, "\000\003"], [1, "\000\n"], [1, "\000\v"]]],
-
['text/x-matlab', [[0, '%']]],
-
['text/x-matlab', [[0, '##']]],
-
['text/x-modelica', [[0, '//']]],
-
['text/x-tex', [[0, '%']]],
-
['application/vnd.sun.xml.calc', [[0, "PK\003\004", [[30, 'mimetype', [[38, 'application/vnd.sun.xml.calc']]]]]]],
-
['application/vnd.sun.xml.calc.template', [[0, "PK\003\004", [[30, 'mimetype', [[38, 'application/vnd.sun.xml.calc']]]]]]],
-
['application/vnd.sun.xml.draw', [[0, "PK\003\004", [[30, 'mimetype', [[38, 'application/vnd.sun.xml.draw']]]]]]],
-
['application/vnd.sun.xml.draw.template', [[0, "PK\003\004", [[30, 'mimetype', [[38, 'application/vnd.sun.xml.draw']]]]]]],
-
['application/vnd.sun.xml.impress', [[0, "PK\003\004", [[30, 'mimetype', [[38, 'application/vnd.sun.xml.impress']]]]]]],
-
['application/vnd.sun.xml.impress.template', [[0, "PK\003\004", [[30, 'mimetype', [[38, 'application/vnd.sun.xml.impress']]]]]]],
-
['application/vnd.sun.xml.math', [[0, "PK\003\004", [[30, 'mimetype', [[38, 'application/vnd.sun.xml.math']]]]]]],
-
['application/vnd.sun.xml.writer', [[0, "PK\003\004", [[30, 'mimetype', [[38, 'application/vnd.sun.xml.writer']]]]]]],
-
['application/vnd.sun.xml.writer.global', [[0, "PK\003\004", [[30, 'mimetype', [[38, 'application/vnd.sun.xml.writer']]]]]]],
-
['application/vnd.sun.xml.writer.template', [[0, "PK\003\004", [[30, 'mimetype', [[38, 'application/vnd.sun.xml.writer']]]]]]],
-
['application/x-csh', [[2..16, '/bin/tcsh'], [2..16, '/bin/csh'], [2..16, '/bin/env csh'], [2..16, '/bin/env tcsh']]],
-
['application/x-dar', [[0, "\000\000\000{"]]],
-
['application/x-designer', [[0..256, '<ui '], [0..256, '<UI ']]],
-
['application/x-ms-wim', [[0, "MSWIM\000\000\000"]]],
-
['application/x-n64-rom', [[0, "\2007\022@"], [0, "7\200@\022"], [0, "@\0227\200"]]],
-
['application/x-ruby', [[2..16, '/bin/env ruby'], [2..16, '/bin/ruby']]],
-
['application/x-sqlite2', [[0, '** This file contains an SQLite']]],
-
['application/x-sqlite3', [[0, 'SQLite format 3']]],
-
['application/x-yaml', [[0, '%YAML']]],
-
['audio/x-stm', [[20, "!Scream!\032"], [20, "!SCREAM!\032"], [20, "BMOD2STM\032"]]],
-
['text/cache-manifest', [[0, 'CACHE MANIFEST', [[14, ' '], [14, "\t"], [14, "\n"], [14, "\r"]]]]],
-
['text/vnd.trolltech.linguist', [[0..256, '<TS']]],
-
['text/x-bibtex', [[0, '% This file was created with JabRef']]],
-
]
-
end
-
2
class MimeMagic
-
# MimeMagic version string
-
# @api public
-
2
VERSION = '0.3.0'
-
end
-
2
require 'rails/backtrace_cleaner'
-
2
require 'minitest/unit'
-
2
require 'mini_backtrace/unit'
-
2
module MiniTest
-
-
2
def self.filter_backtrace_with_rails(bt)
-
filter_backtrace_without_rails(Rails.backtrace_cleaner.clean(bt))
-
end
-
-
2
class << self
-
2
alias :filter_backtrace_without_rails :filter_backtrace
-
2
alias :filter_backtrace :filter_backtrace_with_rails
-
end
-
-
-
end
-
2
require "optparse"
-
2
require "thread"
-
2
require "mutex_m"
-
2
require "minitest/parallel"
-
-
##
-
# :include: README.rdoc
-
-
2
module Minitest
-
2
VERSION = "5.8.4" # :nodoc:
-
2
ENCS = "".respond_to? :encoding # :nodoc:
-
-
2
@@installed_at_exit ||= false
-
2
@@after_run = []
-
2
@extensions = []
-
-
4
mc = (class << self; self; end)
-
-
##
-
# Parallel test executor
-
-
2
mc.send :attr_accessor, :parallel_executor
-
2
self.parallel_executor = Parallel::Executor.new((ENV["N"] || 2).to_i)
-
-
##
-
# Filter object for backtraces.
-
-
2
mc.send :attr_accessor, :backtrace_filter
-
-
##
-
# Reporter object to be used for all runs.
-
#
-
# NOTE: This accessor is only available during setup, not during runs.
-
-
2
mc.send :attr_accessor, :reporter
-
-
##
-
# Names of known extension plugins.
-
-
2
mc.send :attr_accessor, :extensions
-
-
##
-
# Registers Minitest to run at process exit
-
-
2
def self.autorun
-
at_exit {
-
1
next if $! and not ($!.kind_of? SystemExit and $!.success?)
-
-
1
exit_code = nil
-
-
1
at_exit {
-
1
@@after_run.reverse_each(&:call)
-
1
exit exit_code || false
-
}
-
-
1
exit_code = Minitest.run ARGV
-
1
} unless @@installed_at_exit
-
1
@@installed_at_exit = true
-
end
-
-
##
-
# A simple hook allowing you to run a block of code after everything
-
# is done running. Eg:
-
#
-
# Minitest.after_run { p $debugging_info }
-
-
2
def self.after_run &block
-
@@after_run << block
-
end
-
-
2
def self.init_plugins options # :nodoc:
-
self.extensions.each do |name|
-
msg = "plugin_#{name}_init"
-
send msg, options if self.respond_to? msg
-
end
-
end
-
-
2
def self.load_plugins # :nodoc:
-
return unless self.extensions.empty?
-
-
seen = {}
-
-
require "rubygems" unless defined? Gem
-
-
Gem.find_files("minitest/*_plugin.rb").each do |plugin_path|
-
name = File.basename plugin_path, "_plugin.rb"
-
-
next if seen[name]
-
seen[name] = true
-
-
require plugin_path
-
self.extensions << name
-
end
-
end
-
-
##
-
# This is the top-level run method. Everything starts from here. It
-
# tells each Runnable sub-class to run, and each of those are
-
# responsible for doing whatever they do.
-
#
-
# The overall structure of a run looks like this:
-
#
-
# Minitest.autorun
-
# Minitest.run(args)
-
# Minitest.__run(reporter, options)
-
# Runnable.runnables.each
-
# runnable.run(reporter, options)
-
# self.runnable_methods.each
-
# self.run_one_method(self, runnable_method, reporter)
-
# Minitest.run_one_method(klass, runnable_method)
-
# klass.new(runnable_method).run
-
-
2
def self.run args = []
-
self.load_plugins
-
-
options = process_args args
-
-
reporter = CompositeReporter.new
-
reporter << SummaryReporter.new(options[:io], options)
-
reporter << ProgressReporter.new(options[:io], options)
-
-
self.reporter = reporter # this makes it available to plugins
-
self.init_plugins options
-
self.reporter = nil # runnables shouldn't depend on the reporter, ever
-
-
self.parallel_executor.start if parallel_executor.respond_to?(:start)
-
reporter.start
-
begin
-
__run reporter, options
-
rescue Interrupt
-
warn "Interrupted. Exiting..."
-
end
-
self.parallel_executor.shutdown
-
reporter.report
-
-
reporter.passed?
-
end
-
-
##
-
# Internal run method. Responsible for telling all Runnable
-
# sub-classes to run.
-
-
2
def self.__run reporter, options
-
suites = Runnable.runnables.shuffle
-
parallel, serial = suites.partition { |s| s.test_order == :parallel }
-
-
# If we run the parallel tests before the serial tests, the parallel tests
-
# could run in parallel with the serial tests. This would be bad because
-
# the serial tests won't lock around Reporter#record. Run the serial tests
-
# first, so that after they complete, the parallel tests will lock when
-
# recording results.
-
serial.map { |suite| suite.run reporter, options } +
-
parallel.map { |suite| suite.run reporter, options }
-
end
-
-
2
def self.process_args args = [] # :nodoc:
-
options = {
-
:io => $stdout,
-
}
-
orig_args = args.dup
-
-
OptionParser.new do |opts|
-
opts.banner = "minitest options:"
-
opts.version = Minitest::VERSION
-
-
opts.on "-h", "--help", "Display this help." do
-
puts opts
-
exit
-
end
-
-
desc = "Sets random seed. Also via env. Eg: SEED=n rake"
-
opts.on "-s", "--seed SEED", Integer, desc do |m|
-
options[:seed] = m.to_i
-
end
-
-
opts.on "-v", "--verbose", "Verbose. Show progress processing files." do
-
options[:verbose] = true
-
end
-
-
opts.on "-n", "--name PATTERN", "Filter run on /regexp/ or string." do |a|
-
options[:filter] = a
-
end
-
-
unless extensions.empty?
-
opts.separator ""
-
opts.separator "Known extensions: #{extensions.join(", ")}"
-
-
extensions.each do |meth|
-
msg = "plugin_#{meth}_options"
-
send msg, opts, options if self.respond_to?(msg)
-
end
-
end
-
-
begin
-
opts.parse! args
-
rescue OptionParser::InvalidOption => e
-
puts
-
puts e
-
puts
-
puts opts
-
exit 1
-
end
-
-
orig_args -= args
-
end
-
-
unless options[:seed] then
-
srand
-
options[:seed] = (ENV["SEED"] || srand).to_i % 0xFFFF
-
orig_args << "--seed" << options[:seed].to_s
-
end
-
-
srand options[:seed]
-
-
options[:args] = orig_args.map { |s|
-
s =~ /[\s|&<>$()]/ ? s.inspect : s
-
}.join " "
-
-
options
-
end
-
-
2
def self.filter_backtrace bt # :nodoc:
-
backtrace_filter.filter bt
-
end
-
-
##
-
# Represents anything "runnable", like Test, Spec, Benchmark, or
-
# whatever you can dream up.
-
#
-
# Subclasses of this are automatically registered and available in
-
# Runnable.runnables.
-
-
2
class Runnable
-
##
-
# Number of assertions executed in this run.
-
-
2
attr_accessor :assertions
-
-
##
-
# An assertion raised during the run, if any.
-
-
2
attr_accessor :failures
-
-
##
-
# Name of the run.
-
-
2
def name
-
@NAME
-
end
-
-
##
-
# Set the name of the run.
-
-
2
def name= o
-
@NAME = o
-
end
-
-
2
def self.inherited klass # :nodoc:
-
14
self.runnables << klass
-
14
super
-
end
-
-
##
-
# Returns all instance methods matching the pattern +re+.
-
-
2
def self.methods_matching re
-
public_instance_methods(true).grep(re).map(&:to_s)
-
end
-
-
2
def self.reset # :nodoc:
-
2
@@runnables = []
-
end
-
-
2
reset
-
-
##
-
# Responsible for running all runnable methods in a given class,
-
# each in its own instance. Each instance is passed to the
-
# reporter to record.
-
-
2
def self.run reporter, options = {}
-
filter = options[:filter] || "/./"
-
filter = Regexp.new $1 if filter =~ %r%/(.*)/%
-
-
filtered_methods = self.runnable_methods.find_all { |m|
-
filter === m || filter === "#{self}##{m}"
-
}
-
-
return if filtered_methods.empty?
-
-
with_info_handler reporter do
-
filtered_methods.each do |method_name|
-
run_one_method self, method_name, reporter
-
end
-
end
-
end
-
-
##
-
# Runs a single method and has the reporter record the result.
-
# This was considered internal API but is factored out of run so
-
# that subclasses can specialize the running of an individual
-
# test. See Minitest::ParallelTest::ClassMethods for an example.
-
-
2
def self.run_one_method klass, method_name, reporter
-
reporter.record Minitest.run_one_method(klass, method_name)
-
end
-
-
2
def self.with_info_handler reporter, &block # :nodoc:
-
handler = lambda do
-
unless reporter.passed? then
-
warn "Current results:"
-
warn ""
-
warn reporter.reporters.first
-
warn ""
-
end
-
end
-
-
on_signal "INFO", handler, &block
-
end
-
-
2
SIGNALS = Signal.list # :nodoc:
-
-
2
def self.on_signal name, action # :nodoc:
-
supported = SIGNALS[name]
-
-
old_trap = trap name do
-
old_trap.call if old_trap.respond_to? :call
-
action.call
-
end if supported
-
-
yield
-
ensure
-
trap name, old_trap if supported
-
end
-
-
##
-
# Each subclass of Runnable is responsible for overriding this
-
# method to return all runnable methods. See #methods_matching.
-
-
2
def self.runnable_methods
-
raise NotImplementedError, "subclass responsibility"
-
end
-
-
##
-
# Returns all subclasses of Runnable.
-
-
2
def self.runnables
-
14
@@runnables
-
end
-
-
2
def marshal_dump # :nodoc:
-
[self.name, self.failures, self.assertions]
-
end
-
-
2
def marshal_load ary # :nodoc:
-
self.name, self.failures, self.assertions = ary
-
end
-
-
2
def failure # :nodoc:
-
self.failures.first
-
end
-
-
2
def initialize name # :nodoc:
-
self.name = name
-
self.failures = []
-
self.assertions = 0
-
end
-
-
##
-
# Runs a single method. Needs to return self.
-
-
2
def run
-
raise NotImplementedError, "subclass responsibility"
-
end
-
-
##
-
# Did this run pass?
-
#
-
# Note: skipped runs are not considered passing, but they don't
-
# cause the process to exit non-zero.
-
-
2
def passed?
-
raise NotImplementedError, "subclass responsibility"
-
end
-
-
##
-
# Returns a single character string to print based on the result
-
# of the run. Eg ".", "F", or "E".
-
-
2
def result_code
-
raise NotImplementedError, "subclass responsibility"
-
end
-
-
##
-
# Was this run skipped? See #passed? for more information.
-
-
2
def skipped?
-
raise NotImplementedError, "subclass responsibility"
-
end
-
end
-
-
##
-
# Defines the API for Reporters. Subclass this and override whatever
-
# you want. Go nuts.
-
-
2
class AbstractReporter
-
2
include Mutex_m
-
-
##
-
# Starts reporting on the run.
-
-
2
def start
-
end
-
-
##
-
# Record a result and output the Runnable#result_code. Stores the
-
# result of the run if the run did not pass.
-
-
2
def record result
-
end
-
-
##
-
# Outputs the summary of the run.
-
-
2
def report
-
end
-
-
##
-
# Did this run pass?
-
-
2
def passed?
-
true
-
end
-
end
-
-
2
class Reporter < AbstractReporter # :nodoc:
-
##
-
# The IO used to report.
-
-
2
attr_accessor :io
-
-
##
-
# Command-line options for this run.
-
-
2
attr_accessor :options
-
-
2
def initialize io = $stdout, options = {} # :nodoc:
-
super()
-
self.io = io
-
self.options = options
-
end
-
end
-
-
##
-
# A very simple reporter that prints the "dots" during the run.
-
#
-
# This is added to the top-level CompositeReporter at the start of
-
# the run. If you want to change the output of minitest via a
-
# plugin, pull this out of the composite and replace it with your
-
# own.
-
-
2
class ProgressReporter < Reporter
-
2
def record result # :nodoc:
-
io.print "%s#%s = %.2f s = " % [result.class, result.name, result.time] if
-
options[:verbose]
-
io.print result.result_code
-
io.puts if options[:verbose]
-
end
-
end
-
-
##
-
# A reporter that gathers statistics about a test run. Does not do
-
# any IO because meant to be used as a parent class for a reporter
-
# that does.
-
#
-
# If you want to create an entirely different type of output (eg,
-
# CI, HTML, etc), this is the place to start.
-
-
2
class StatisticsReporter < Reporter
-
# :stopdoc:
-
2
attr_accessor :assertions
-
2
attr_accessor :count
-
2
attr_accessor :results
-
2
attr_accessor :start_time
-
2
attr_accessor :total_time
-
2
attr_accessor :failures
-
2
attr_accessor :errors
-
2
attr_accessor :skips
-
# :startdoc:
-
-
2
def initialize io = $stdout, options = {} # :nodoc:
-
super
-
-
self.assertions = 0
-
self.count = 0
-
self.results = []
-
self.start_time = nil
-
self.total_time = nil
-
self.failures = nil
-
self.errors = nil
-
self.skips = nil
-
end
-
-
2
def passed? # :nodoc:
-
results.all?(&:skipped?)
-
end
-
-
2
def start # :nodoc:
-
self.start_time = Minitest.clock_time
-
end
-
-
2
def record result # :nodoc:
-
self.count += 1
-
self.assertions += result.assertions
-
-
results << result if not result.passed? or result.skipped?
-
end
-
-
2
def report # :nodoc:
-
aggregate = results.group_by { |r| r.failure.class }
-
aggregate.default = [] # dumb. group_by should provide this
-
-
self.total_time = Minitest.clock_time - start_time
-
self.failures = aggregate[Assertion].size
-
self.errors = aggregate[UnexpectedError].size
-
self.skips = aggregate[Skip].size
-
end
-
end
-
-
##
-
# A reporter that prints the header, summary, and failure details at
-
# the end of the run.
-
#
-
# This is added to the top-level CompositeReporter at the start of
-
# the run. If you want to change the output of minitest via a
-
# plugin, pull this out of the composite and replace it with your
-
# own.
-
-
2
class SummaryReporter < StatisticsReporter
-
# :stopdoc:
-
2
attr_accessor :sync
-
2
attr_accessor :old_sync
-
# :startdoc:
-
-
2
def start # :nodoc:
-
super
-
-
io.puts "Run options: #{options[:args]}"
-
io.puts
-
io.puts "# Running:"
-
io.puts
-
-
self.sync = io.respond_to? :"sync=" # stupid emacs
-
self.old_sync, io.sync = io.sync, true if self.sync
-
end
-
-
2
def report # :nodoc:
-
super
-
-
io.sync = self.old_sync
-
-
io.puts unless options[:verbose] # finish the dots
-
io.puts
-
io.puts statistics
-
io.puts aggregated_results
-
io.puts summary
-
end
-
-
2
def statistics # :nodoc:
-
"Finished in %.6fs, %.4f runs/s, %.4f assertions/s." %
-
[total_time, count / total_time, assertions / total_time]
-
end
-
-
2
def aggregated_results # :nodoc:
-
filtered_results = results.dup
-
filtered_results.reject!(&:skipped?) unless options[:verbose]
-
-
s = filtered_results.each_with_index.map { |result, i|
-
"\n%3d) %s" % [i+1, result]
-
}.join("\n") + "\n"
-
-
s.force_encoding(io.external_encoding) if
-
ENCS and io.external_encoding and s.encoding != io.external_encoding
-
-
s
-
end
-
-
2
alias to_s aggregated_results
-
-
2
def summary # :nodoc:
-
extra = ""
-
-
extra = "\n\nYou have skipped tests. Run with --verbose for details." if
-
results.any?(&:skipped?) unless options[:verbose] or ENV["MT_NO_SKIP_MSG"]
-
-
"%d runs, %d assertions, %d failures, %d errors, %d skips%s" %
-
[count, assertions, failures, errors, skips, extra]
-
end
-
end
-
-
##
-
# Dispatch to multiple reporters as one.
-
-
2
class CompositeReporter < AbstractReporter
-
##
-
# The list of reporters to dispatch to.
-
-
2
attr_accessor :reporters
-
-
2
def initialize *reporters # :nodoc:
-
super()
-
self.reporters = reporters
-
end
-
-
##
-
# Add another reporter to the mix.
-
-
2
def << reporter
-
self.reporters << reporter
-
end
-
-
2
def passed? # :nodoc:
-
self.reporters.all?(&:passed?)
-
end
-
-
2
def start # :nodoc:
-
self.reporters.each(&:start)
-
end
-
-
2
def record result # :nodoc:
-
self.reporters.each do |reporter|
-
reporter.record result
-
end
-
end
-
-
2
def report # :nodoc:
-
self.reporters.each(&:report)
-
end
-
end
-
-
##
-
# Represents run failures.
-
-
2
class Assertion < Exception
-
2
def error # :nodoc:
-
self
-
end
-
-
##
-
# Where was this run before an assertion was raised?
-
-
2
def location
-
last_before_assertion = ""
-
self.backtrace.reverse_each do |s|
-
break if s =~ /in .(assert|refute|flunk|pass|fail|raise|must|wont)/
-
last_before_assertion = s
-
end
-
last_before_assertion.sub(/:in .*$/, "")
-
end
-
-
2
def result_code # :nodoc:
-
result_label[0, 1]
-
end
-
-
2
def result_label # :nodoc:
-
"Failure"
-
end
-
end
-
-
##
-
# Assertion raised when skipping a run.
-
-
2
class Skip < Assertion
-
2
def result_label # :nodoc:
-
"Skipped"
-
end
-
end
-
-
##
-
# Assertion wrapping an unexpected error that was raised during a run.
-
-
2
class UnexpectedError < Assertion
-
2
attr_accessor :exception # :nodoc:
-
-
2
def initialize exception # :nodoc:
-
super "Unexpected exception"
-
self.exception = exception
-
end
-
-
2
def backtrace # :nodoc:
-
self.exception.backtrace
-
end
-
-
2
def error # :nodoc:
-
self.exception
-
end
-
-
2
def message # :nodoc:
-
bt = Minitest.filter_backtrace(self.backtrace).join "\n "
-
"#{self.exception.class}: #{self.exception.message}\n #{bt}"
-
end
-
-
2
def result_label # :nodoc:
-
"Error"
-
end
-
end
-
-
##
-
# Provides a simple set of guards that you can use in your tests
-
# to skip execution if it is not applicable. These methods are
-
# mixed into Test as both instance and class methods so you
-
# can use them inside or outside of the test methods.
-
#
-
# def test_something_for_mri
-
# skip "bug 1234" if jruby?
-
# # ...
-
# end
-
#
-
# if windows? then
-
# # ... lots of test methods ...
-
# end
-
-
2
module Guard
-
-
##
-
# Is this running on jruby?
-
-
2
def jruby? platform = RUBY_PLATFORM
-
"java" == platform
-
end
-
-
##
-
# Is this running on maglev?
-
-
2
def maglev? platform = defined?(RUBY_ENGINE) && RUBY_ENGINE
-
"maglev" == platform
-
end
-
-
##
-
# Is this running on mri?
-
-
2
def mri? platform = RUBY_DESCRIPTION
-
/^ruby/ =~ platform
-
end
-
-
##
-
# Is this running on rubinius?
-
-
2
def rubinius? platform = defined?(RUBY_ENGINE) && RUBY_ENGINE
-
"rbx" == platform
-
end
-
-
##
-
# Is this running on windows?
-
-
2
def windows? platform = RUBY_PLATFORM
-
/mswin|mingw/ =~ platform
-
end
-
end
-
-
2
class BacktraceFilter # :nodoc:
-
2
def filter bt
-
return ["No backtrace"] unless bt
-
-
return bt.dup if $DEBUG
-
-
new_bt = bt.take_while { |line| line !~ /lib\/minitest/ }
-
new_bt = bt.select { |line| line !~ /lib\/minitest/ } if new_bt.empty?
-
new_bt = bt.dup if new_bt.empty?
-
-
new_bt
-
end
-
end
-
-
2
self.backtrace_filter = BacktraceFilter.new
-
-
2
def self.run_one_method klass, method_name # :nodoc:
-
result = klass.new(method_name).run
-
raise "#{klass}#run _must_ return self" unless klass === result
-
result
-
end
-
-
2
if defined? Process::CLOCK_MONOTONIC
-
2
def self.clock_time
-
Process.clock_gettime Process::CLOCK_MONOTONIC
-
end
-
else
-
def self.clock_time
-
Time.now
-
end
-
end
-
end
-
-
2
require "minitest/test"
-
2
require "rbconfig"
-
2
require "tempfile"
-
2
require "stringio"
-
-
2
module Minitest
-
##
-
# Minitest Assertions. All assertion methods accept a +msg+ which is
-
# printed if the assertion fails.
-
#
-
# Protocol: Nearly everything here boils up to +assert+, which
-
# expects to be able to increment an instance accessor named
-
# +assertions+. This is not provided by Assertions and must be
-
# provided by the thing including Assertions. See Minitest::Runnable
-
# for an example.
-
-
2
module Assertions
-
2
UNDEFINED = Object.new # :nodoc:
-
-
2
def UNDEFINED.inspect # :nodoc:
-
"UNDEFINED" # again with the rdoc bugs... :(
-
end
-
-
##
-
# Returns the diff command to use in #diff. Tries to intelligently
-
# figure out what diff to use.
-
-
2
def self.diff
-
@diff = if (RbConfig::CONFIG["host_os"] =~ /mswin|mingw/ &&
-
system("diff.exe", __FILE__, __FILE__)) then
-
"diff.exe -u"
-
elsif Minitest::Test.maglev? then
-
"diff -u"
-
elsif system("gdiff", __FILE__, __FILE__)
-
"gdiff -u" # solaris and kin suck
-
elsif system("diff", __FILE__, __FILE__)
-
"diff -u"
-
else
-
nil
-
end unless defined? @diff
-
-
@diff
-
end
-
-
##
-
# Set the diff command to use in #diff.
-
-
2
def self.diff= o
-
@diff = o
-
end
-
-
##
-
# Returns a diff between +exp+ and +act+. If there is no known
-
# diff command or if it doesn't make sense to diff the output
-
# (single line, short output), then it simply returns a basic
-
# comparison between the two.
-
-
2
def diff exp, act
-
expect = mu_pp_for_diff exp
-
butwas = mu_pp_for_diff act
-
result = nil
-
-
need_to_diff =
-
(expect.include?("\n") ||
-
butwas.include?("\n") ||
-
expect.size > 30 ||
-
butwas.size > 30 ||
-
expect == butwas) &&
-
Minitest::Assertions.diff
-
-
return "Expected: #{mu_pp exp}\n Actual: #{mu_pp act}" unless
-
need_to_diff
-
-
Tempfile.open("expect") do |a|
-
a.puts expect
-
a.flush
-
-
Tempfile.open("butwas") do |b|
-
b.puts butwas
-
b.flush
-
-
result = `#{Minitest::Assertions.diff} #{a.path} #{b.path}`
-
result.sub!(/^\-\-\- .+/, "--- expected")
-
result.sub!(/^\+\+\+ .+/, "+++ actual")
-
-
if result.empty? then
-
klass = exp.class
-
result = [
-
"No visible difference in the #{klass}#inspect output.\n",
-
"You should look at the implementation of #== on ",
-
"#{klass} or its members.\n",
-
expect,
-
].join
-
end
-
end
-
end
-
-
result
-
end
-
-
##
-
# This returns a human-readable version of +obj+. By default
-
# #inspect is called. You can override this to use #pretty_print
-
# if you want.
-
-
2
def mu_pp obj
-
s = obj.inspect
-
s = s.encode Encoding.default_external if defined? Encoding
-
s
-
end
-
-
##
-
# This returns a diff-able human-readable version of +obj+. This
-
# differs from the regular mu_pp because it expands escaped
-
# newlines and makes hex-values generic (like object_ids). This
-
# uses mu_pp to do the first pass and then cleans it up.
-
-
2
def mu_pp_for_diff obj
-
mu_pp(obj).gsub(/\\n/, "\n").gsub(/:0x[a-fA-F0-9]{4,}/m, ":0xXXXXXX")
-
end
-
-
##
-
# Fails unless +test+ is truthy.
-
-
2
def assert test, msg = nil
-
4
self.assertions += 1
-
4
unless test then
-
msg ||= "Failed assertion, no message given."
-
msg = msg.call if Proc === msg
-
raise Minitest::Assertion, msg
-
end
-
4
true
-
end
-
-
2
def _synchronize # :nodoc:
-
yield
-
end
-
-
##
-
# Fails unless +obj+ is empty.
-
-
2
def assert_empty obj, msg = nil
-
msg = message(msg) { "Expected #{mu_pp(obj)} to be empty" }
-
assert_respond_to obj, :empty?
-
assert obj.empty?, msg
-
end
-
-
2
E = "" # :nodoc:
-
-
##
-
# Fails unless <tt>exp == act</tt> printing the difference between
-
# the two, if possible.
-
#
-
# If there is no visible difference but the assertion fails, you
-
# should suspect that your #== is buggy, or your inspect output is
-
# missing crucial details.
-
#
-
# For floats use assert_in_delta.
-
#
-
# See also: Minitest::Assertions.diff
-
-
2
def assert_equal exp, act, msg = nil
-
msg = message(msg, E) { diff exp, act }
-
assert exp == act, msg
-
end
-
-
##
-
# For comparing Floats. Fails unless +exp+ and +act+ are within +delta+
-
# of each other.
-
#
-
# assert_in_delta Math::PI, (22.0 / 7.0), 0.01
-
-
2
def assert_in_delta exp, act, delta = 0.001, msg = nil
-
n = (exp - act).abs
-
msg = message(msg) {
-
"Expected |#{exp} - #{act}| (#{n}) to be <= #{delta}"
-
}
-
assert delta >= n, msg
-
end
-
-
##
-
# For comparing Floats. Fails unless +exp+ and +act+ have a relative
-
# error less than +epsilon+.
-
-
2
def assert_in_epsilon a, b, epsilon = 0.001, msg = nil
-
assert_in_delta a, b, [a.abs, b.abs].min * epsilon, msg
-
end
-
-
##
-
# Fails unless +collection+ includes +obj+.
-
-
2
def assert_includes collection, obj, msg = nil
-
msg = message(msg) {
-
"Expected #{mu_pp(collection)} to include #{mu_pp(obj)}"
-
}
-
assert_respond_to collection, :include?
-
assert collection.include?(obj), msg
-
end
-
-
##
-
# Fails unless +obj+ is an instance of +cls+.
-
-
2
def assert_instance_of cls, obj, msg = nil
-
msg = message(msg) {
-
"Expected #{mu_pp(obj)} to be an instance of #{cls}, not #{obj.class}"
-
}
-
-
assert obj.instance_of?(cls), msg
-
end
-
-
##
-
# Fails unless +obj+ is a kind of +cls+.
-
-
2
def assert_kind_of cls, obj, msg = nil
-
msg = message(msg) {
-
"Expected #{mu_pp(obj)} to be a kind of #{cls}, not #{obj.class}" }
-
-
assert obj.kind_of?(cls), msg
-
end
-
-
##
-
# Fails unless +matcher+ <tt>=~</tt> +obj+.
-
-
2
def assert_match matcher, obj, msg = nil
-
msg = message(msg) { "Expected #{mu_pp matcher} to match #{mu_pp obj}" }
-
assert_respond_to matcher, :"=~"
-
matcher = Regexp.new Regexp.escape matcher if String === matcher
-
assert matcher =~ obj, msg
-
end
-
-
##
-
# Fails unless +obj+ is nil
-
-
2
def assert_nil obj, msg = nil
-
msg = message(msg) { "Expected #{mu_pp(obj)} to be nil" }
-
assert obj.nil?, msg
-
end
-
-
##
-
# For testing with binary operators. Eg:
-
#
-
# assert_operator 5, :<=, 4
-
-
2
def assert_operator o1, op, o2 = UNDEFINED, msg = nil
-
return assert_predicate o1, op, msg if UNDEFINED == o2
-
msg = message(msg) { "Expected #{mu_pp(o1)} to be #{op} #{mu_pp(o2)}" }
-
assert o1.__send__(op, o2), msg
-
end
-
-
##
-
# Fails if stdout or stderr do not output the expected results.
-
# Pass in nil if you don't care about that streams output. Pass in
-
# "" if you require it to be silent. Pass in a regexp if you want
-
# to pattern match.
-
#
-
# NOTE: this uses #capture_io, not #capture_subprocess_io.
-
#
-
# See also: #assert_silent
-
-
2
def assert_output stdout = nil, stderr = nil
-
out, err = capture_io do
-
yield
-
end
-
-
err_msg = Regexp === stderr ? :assert_match : :assert_equal if stderr
-
out_msg = Regexp === stdout ? :assert_match : :assert_equal if stdout
-
-
y = send err_msg, stderr, err, "In stderr" if err_msg
-
x = send out_msg, stdout, out, "In stdout" if out_msg
-
-
(!stdout || x) && (!stderr || y)
-
end
-
-
##
-
# For testing with predicates. Eg:
-
#
-
# assert_predicate str, :empty?
-
#
-
# This is really meant for specs and is front-ended by assert_operator:
-
#
-
# str.must_be :empty?
-
-
2
def assert_predicate o1, op, msg = nil
-
msg = message(msg) { "Expected #{mu_pp(o1)} to be #{op}" }
-
assert o1.__send__(op), msg
-
end
-
-
##
-
# Fails unless the block raises one of +exp+. Returns the
-
# exception matched so you can check the message, attributes, etc.
-
#
-
# +exp+ takes an optional message on the end to help explain
-
# failures and defaults to StandardError if no exception class is
-
# passed.
-
-
2
def assert_raises *exp
-
msg = "#{exp.pop}.\n" if String === exp.last
-
exp << StandardError if exp.empty?
-
-
begin
-
yield
-
rescue *exp => e
-
pass # count assertion
-
return e
-
rescue Minitest::Skip, Minitest::Assertion
-
# don't count assertion
-
raise
-
rescue SignalException, SystemExit
-
raise
-
rescue Exception => e
-
flunk proc {
-
exception_details(e, "#{msg}#{mu_pp(exp)} exception expected, not")
-
}
-
end
-
-
exp = exp.first if exp.size == 1
-
-
flunk "#{msg}#{mu_pp(exp)} expected but nothing was raised."
-
end
-
-
##
-
# Fails unless +obj+ responds to +meth+.
-
-
2
def assert_respond_to obj, meth, msg = nil
-
msg = message(msg) {
-
"Expected #{mu_pp(obj)} (#{obj.class}) to respond to ##{meth}"
-
}
-
assert obj.respond_to?(meth), msg
-
end
-
-
##
-
# Fails unless +exp+ and +act+ are #equal?
-
-
2
def assert_same exp, act, msg = nil
-
msg = message(msg) {
-
data = [mu_pp(act), act.object_id, mu_pp(exp), exp.object_id]
-
"Expected %s (oid=%d) to be the same as %s (oid=%d)" % data
-
}
-
assert exp.equal?(act), msg
-
end
-
-
##
-
# +send_ary+ is a receiver, message and arguments.
-
#
-
# Fails unless the call returns a true value
-
-
2
def assert_send send_ary, m = nil
-
recv, msg, *args = send_ary
-
m = message(m) {
-
"Expected #{mu_pp(recv)}.#{msg}(*#{mu_pp(args)}) to return true" }
-
assert recv.__send__(msg, *args), m
-
end
-
-
##
-
# Fails if the block outputs anything to stderr or stdout.
-
#
-
# See also: #assert_output
-
-
2
def assert_silent
-
assert_output "", "" do
-
yield
-
end
-
end
-
-
##
-
# Fails unless the block throws +sym+
-
-
2
def assert_throws sym, msg = nil
-
default = "Expected #{mu_pp(sym)} to have been thrown"
-
caught = true
-
catch(sym) do
-
begin
-
yield
-
rescue ThreadError => e # wtf?!? 1.8 + threads == suck
-
default += ", not \:#{e.message[/uncaught throw \`(\w+?)\'/, 1]}"
-
rescue ArgumentError => e # 1.9 exception
-
default += ", not #{e.message.split(/ /).last}"
-
rescue NameError => e # 1.8 exception
-
default += ", not #{e.name.inspect}"
-
end
-
caught = false
-
end
-
-
assert caught, message(msg) { default }
-
end
-
-
##
-
# Captures $stdout and $stderr into strings:
-
#
-
# out, err = capture_io do
-
# puts "Some info"
-
# warn "You did a bad thing"
-
# end
-
#
-
# assert_match %r%info%, out
-
# assert_match %r%bad%, err
-
#
-
# NOTE: For efficiency, this method uses StringIO and does not
-
# capture IO for subprocesses. Use #capture_subprocess_io for
-
# that.
-
-
2
def capture_io
-
_synchronize do
-
begin
-
captured_stdout, captured_stderr = StringIO.new, StringIO.new
-
-
orig_stdout, orig_stderr = $stdout, $stderr
-
$stdout, $stderr = captured_stdout, captured_stderr
-
-
yield
-
-
return captured_stdout.string, captured_stderr.string
-
ensure
-
$stdout = orig_stdout
-
$stderr = orig_stderr
-
end
-
end
-
end
-
-
##
-
# Captures $stdout and $stderr into strings, using Tempfile to
-
# ensure that subprocess IO is captured as well.
-
#
-
# out, err = capture_subprocess_io do
-
# system "echo Some info"
-
# system "echo You did a bad thing 1>&2"
-
# end
-
#
-
# assert_match %r%info%, out
-
# assert_match %r%bad%, err
-
#
-
# NOTE: This method is approximately 10x slower than #capture_io so
-
# only use it when you need to test the output of a subprocess.
-
-
2
def capture_subprocess_io
-
_synchronize do
-
begin
-
require "tempfile"
-
-
captured_stdout, captured_stderr = Tempfile.new("out"), Tempfile.new("err")
-
-
orig_stdout, orig_stderr = $stdout.dup, $stderr.dup
-
$stdout.reopen captured_stdout
-
$stderr.reopen captured_stderr
-
-
yield
-
-
$stdout.rewind
-
$stderr.rewind
-
-
return captured_stdout.read, captured_stderr.read
-
ensure
-
captured_stdout.unlink
-
captured_stderr.unlink
-
$stdout.reopen orig_stdout
-
$stderr.reopen orig_stderr
-
end
-
end
-
end
-
-
##
-
# Returns details for exception +e+
-
-
2
def exception_details e, msg
-
[
-
"#{msg}",
-
"Class: <#{e.class}>",
-
"Message: <#{e.message.inspect}>",
-
"---Backtrace---",
-
"#{Minitest.filter_backtrace(e.backtrace).join("\n")}",
-
"---------------",
-
].join "\n"
-
end
-
-
##
-
# Fails with +msg+
-
-
2
def flunk msg = nil
-
msg ||= "Epic Fail!"
-
assert false, msg
-
end
-
-
##
-
# Returns a proc that will output +msg+ along with the default message.
-
-
2
def message msg = nil, ending = nil, &default
-
proc {
-
msg = msg.call.chomp(".") if Proc === msg
-
custom_message = "#{msg}.\n" unless msg.nil? or msg.to_s.empty?
-
"#{custom_message}#{default.call}#{ending || "."}"
-
}
-
end
-
-
##
-
# used for counting assertions
-
-
2
def pass _msg = nil
-
assert true
-
end
-
-
##
-
# Fails if +test+ is truthy.
-
-
2
def refute test, msg = nil
-
msg ||= "Failed refutation, no message given"
-
not assert !test, msg
-
end
-
-
##
-
# Fails if +obj+ is empty.
-
-
2
def refute_empty obj, msg = nil
-
msg = message(msg) { "Expected #{mu_pp(obj)} to not be empty" }
-
assert_respond_to obj, :empty?
-
refute obj.empty?, msg
-
end
-
-
##
-
# Fails if <tt>exp == act</tt>.
-
#
-
# For floats use refute_in_delta.
-
-
2
def refute_equal exp, act, msg = nil
-
msg = message(msg) {
-
"Expected #{mu_pp(act)} to not be equal to #{mu_pp(exp)}"
-
}
-
refute exp == act, msg
-
end
-
-
##
-
# For comparing Floats. Fails if +exp+ is within +delta+ of +act+.
-
#
-
# refute_in_delta Math::PI, (22.0 / 7.0)
-
-
2
def refute_in_delta exp, act, delta = 0.001, msg = nil
-
n = (exp - act).abs
-
msg = message(msg) {
-
"Expected |#{exp} - #{act}| (#{n}) to not be <= #{delta}"
-
}
-
refute delta >= n, msg
-
end
-
-
##
-
# For comparing Floats. Fails if +exp+ and +act+ have a relative error
-
# less than +epsilon+.
-
-
2
def refute_in_epsilon a, b, epsilon = 0.001, msg = nil
-
refute_in_delta a, b, a * epsilon, msg
-
end
-
-
##
-
# Fails if +collection+ includes +obj+.
-
-
2
def refute_includes collection, obj, msg = nil
-
msg = message(msg) {
-
"Expected #{mu_pp(collection)} to not include #{mu_pp(obj)}"
-
}
-
assert_respond_to collection, :include?
-
refute collection.include?(obj), msg
-
end
-
-
##
-
# Fails if +obj+ is an instance of +cls+.
-
-
2
def refute_instance_of cls, obj, msg = nil
-
msg = message(msg) {
-
"Expected #{mu_pp(obj)} to not be an instance of #{cls}"
-
}
-
refute obj.instance_of?(cls), msg
-
end
-
-
##
-
# Fails if +obj+ is a kind of +cls+.
-
-
2
def refute_kind_of cls, obj, msg = nil
-
msg = message(msg) { "Expected #{mu_pp(obj)} to not be a kind of #{cls}" }
-
refute obj.kind_of?(cls), msg
-
end
-
-
##
-
# Fails if +matcher+ <tt>=~</tt> +obj+.
-
-
2
def refute_match matcher, obj, msg = nil
-
msg = message(msg) { "Expected #{mu_pp matcher} to not match #{mu_pp obj}" }
-
assert_respond_to matcher, :"=~"
-
matcher = Regexp.new Regexp.escape matcher if String === matcher
-
refute matcher =~ obj, msg
-
end
-
-
##
-
# Fails if +obj+ is nil.
-
-
2
def refute_nil obj, msg = nil
-
msg = message(msg) { "Expected #{mu_pp(obj)} to not be nil" }
-
refute obj.nil?, msg
-
end
-
-
##
-
# Fails if +o1+ is not +op+ +o2+. Eg:
-
#
-
# refute_operator 1, :>, 2 #=> pass
-
# refute_operator 1, :<, 2 #=> fail
-
-
2
def refute_operator o1, op, o2 = UNDEFINED, msg = nil
-
return refute_predicate o1, op, msg if UNDEFINED == o2
-
msg = message(msg) { "Expected #{mu_pp(o1)} to not be #{op} #{mu_pp(o2)}" }
-
refute o1.__send__(op, o2), msg
-
end
-
-
##
-
# For testing with predicates.
-
#
-
# refute_predicate str, :empty?
-
#
-
# This is really meant for specs and is front-ended by refute_operator:
-
#
-
# str.wont_be :empty?
-
-
2
def refute_predicate o1, op, msg = nil
-
msg = message(msg) { "Expected #{mu_pp(o1)} to not be #{op}" }
-
refute o1.__send__(op), msg
-
end
-
-
##
-
# Fails if +obj+ responds to the message +meth+.
-
-
2
def refute_respond_to obj, meth, msg = nil
-
msg = message(msg) { "Expected #{mu_pp(obj)} to not respond to #{meth}" }
-
-
refute obj.respond_to?(meth), msg
-
end
-
-
##
-
# Fails if +exp+ is the same (by object identity) as +act+.
-
-
2
def refute_same exp, act, msg = nil
-
msg = message(msg) {
-
data = [mu_pp(act), act.object_id, mu_pp(exp), exp.object_id]
-
"Expected %s (oid=%d) to not be the same as %s (oid=%d)" % data
-
}
-
refute exp.equal?(act), msg
-
end
-
-
##
-
# Skips the current run. If run in verbose-mode, the skipped run
-
# gets listed at the end of the run but doesn't cause a failure
-
# exit code.
-
-
2
def skip msg = nil, bt = caller
-
msg ||= "Skipped, no message given"
-
@skip = true
-
raise Minitest::Skip, msg, bt
-
end
-
-
##
-
# Was this testcase skipped? Meant for #teardown.
-
-
2
def skipped?
-
defined?(@skip) and @skip
-
end
-
end
-
end
-
2
module Minitest
-
2
module Parallel
-
-
##
-
# The engine used to run multiple tests in parallel.
-
-
2
class Executor
-
-
##
-
# The size of the pool of workers.
-
-
2
attr_reader :size
-
-
##
-
# Create a parallel test executor of with +size+ workers.
-
-
2
def initialize size
-
2
@size = size
-
2
@queue = Queue.new
-
2
@pool = nil
-
end
-
-
##
-
# Start the executor
-
-
2
def start
-
@pool = size.times.map {
-
Thread.new(@queue) do |queue|
-
Thread.current.abort_on_exception = true
-
while (job = queue.pop)
-
klass, method, reporter = job
-
result = Minitest.run_one_method klass, method
-
reporter.synchronize { reporter.record result }
-
end
-
end
-
}
-
end
-
-
##
-
# Add a job to the queue
-
-
2
def << work; @queue << work; end
-
-
##
-
# Shuts down the pool of workers by signalling them to quit and
-
# waiting for them all to finish what they're currently working
-
# on.
-
-
2
def shutdown
-
size.times { @queue << nil }
-
@pool.each(&:join)
-
end
-
end
-
-
2
module Test
-
2
def _synchronize; Minitest::Test.io_lock.synchronize { yield }; end # :nodoc:
-
-
2
module ClassMethods # :nodoc:
-
2
def run_one_method klass, method_name, reporter
-
Minitest.parallel_executor << [klass, method_name, reporter]
-
end
-
-
2
def test_order
-
:parallel
-
end
-
end
-
end
-
end
-
end
-
2
require "minitest" unless defined? Minitest::Runnable
-
-
2
module Minitest
-
##
-
# Subclass Test to create your own tests. Typically you'll want a
-
# Test subclass per implementation class.
-
#
-
# See Minitest::Assertions
-
-
2
class Test < Runnable
-
2
require "minitest/assertions"
-
2
include Minitest::Assertions
-
-
2
PASSTHROUGH_EXCEPTIONS = [NoMemoryError, SignalException, # :nodoc:
-
Interrupt, SystemExit]
-
-
4
class << self; attr_accessor :io_lock; end # :nodoc:
-
2
self.io_lock = Mutex.new
-
-
##
-
# Call this at the top of your tests when you absolutely
-
# positively need to have ordered tests. In doing so, you're
-
# admitting that you suck and your tests are weak.
-
-
2
def self.i_suck_and_my_tests_are_order_dependent!
-
2
class << self
-
2
undef_method :test_order if method_defined? :test_order
-
2
define_method :test_order do :alpha end
-
end
-
end
-
-
##
-
# Make diffs for this Test use #pretty_inspect so that diff
-
# in assert_equal can have more details. NOTE: this is much slower
-
# than the regular inspect but much more usable for complex
-
# objects.
-
-
2
def self.make_my_diffs_pretty!
-
require "pp"
-
-
define_method :mu_pp do |o|
-
o.pretty_inspect
-
end
-
end
-
-
##
-
# Call this at the top of your tests when you want to run your
-
# tests in parallel. In doing so, you're admitting that you rule
-
# and your tests are awesome.
-
-
2
def self.parallelize_me!
-
include Minitest::Parallel::Test
-
extend Minitest::Parallel::Test::ClassMethods
-
end
-
-
##
-
# Returns all instance methods starting with "test_". Based on
-
# #test_order, the methods are either sorted, randomized
-
# (default), or run in parallel.
-
-
2
def self.runnable_methods
-
methods = methods_matching(/^test_/)
-
-
case self.test_order
-
when :random, :parallel then
-
max = methods.size
-
methods.sort.sort_by { rand max }
-
when :alpha, :sorted then
-
methods.sort
-
else
-
raise "Unknown test_order: #{self.test_order.inspect}"
-
end
-
end
-
-
##
-
# Defines the order to run tests (:random by default). Override
-
# this or use a convenience method to change it for your tests.
-
-
2
def self.test_order
-
:random
-
end
-
-
##
-
# The time it took to run this test.
-
-
2
attr_accessor :time
-
-
2
def marshal_dump # :nodoc:
-
super << self.time
-
end
-
-
2
def marshal_load ary # :nodoc:
-
self.time = ary.pop
-
super
-
end
-
-
2
TEARDOWN_METHODS = %w[ before_teardown teardown after_teardown ] # :nodoc:
-
-
##
-
# Runs a single test with setup/teardown hooks.
-
-
2
def run
-
with_info_handler do
-
time_it do
-
capture_exceptions do
-
before_setup; setup; after_setup
-
-
self.send self.name
-
end
-
-
TEARDOWN_METHODS.each do |hook|
-
capture_exceptions do
-
self.send hook
-
end
-
end
-
end
-
end
-
-
self # per contract
-
end
-
-
##
-
# Provides before/after hooks for setup and teardown. These are
-
# meant for library writers, NOT for regular test authors. See
-
# #before_setup for an example.
-
-
2
module LifecycleHooks
-
-
##
-
# Runs before every test, before setup. This hook is meant for
-
# libraries to extend minitest. It is not meant to be used by
-
# test developers.
-
#
-
# As a simplistic example:
-
#
-
# module MyMinitestPlugin
-
# def before_setup
-
# super
-
# # ... stuff to do before setup is run
-
# end
-
#
-
# def after_setup
-
# # ... stuff to do after setup is run
-
# super
-
# end
-
#
-
# def before_teardown
-
# super
-
# # ... stuff to do before teardown is run
-
# end
-
#
-
# def after_teardown
-
# # ... stuff to do after teardown is run
-
# super
-
# end
-
# end
-
#
-
# class MiniTest::Test
-
# include MyMinitestPlugin
-
# end
-
-
2
def before_setup; end
-
-
##
-
# Runs before every test. Use this to set up before each test
-
# run.
-
-
2
def setup; end
-
-
##
-
# Runs before every test, after setup. This hook is meant for
-
# libraries to extend minitest. It is not meant to be used by
-
# test developers.
-
#
-
# See #before_setup for an example.
-
-
2
def after_setup; end
-
-
##
-
# Runs after every test, before teardown. This hook is meant for
-
# libraries to extend minitest. It is not meant to be used by
-
# test developers.
-
#
-
# See #before_setup for an example.
-
-
2
def before_teardown; end
-
-
##
-
# Runs after every test. Use this to clean up after each test
-
# run.
-
-
2
def teardown; end
-
-
##
-
# Runs after every test, after teardown. This hook is meant for
-
# libraries to extend minitest. It is not meant to be used by
-
# test developers.
-
#
-
# See #before_setup for an example.
-
-
2
def after_teardown; end
-
end # LifecycleHooks
-
-
2
def capture_exceptions # :nodoc:
-
yield
-
rescue *PASSTHROUGH_EXCEPTIONS
-
raise
-
rescue Assertion => e
-
self.failures << e
-
rescue Exception => e
-
self.failures << UnexpectedError.new(e)
-
end
-
-
##
-
# Did this run error?
-
-
2
def error?
-
self.failures.any? { |f| UnexpectedError === f }
-
end
-
-
##
-
# The location identifier of this test.
-
-
2
def location
-
loc = " [#{self.failure.location}]" unless passed? or error?
-
"#{self.class}##{self.name}#{loc}"
-
end
-
-
##
-
# Did this run pass?
-
#
-
# Note: skipped runs are not considered passing, but they don't
-
# cause the process to exit non-zero.
-
-
2
def passed?
-
not self.failure
-
end
-
-
##
-
# Returns ".", "F", or "E" based on the result of the run.
-
-
2
def result_code
-
self.failure and self.failure.result_code or "."
-
end
-
-
##
-
# Was this run skipped?
-
-
2
def skipped?
-
self.failure and Skip === self.failure
-
end
-
-
2
def time_it # :nodoc:
-
t0 = Minitest.clock_time
-
-
yield
-
ensure
-
self.time = Minitest.clock_time - t0
-
end
-
-
2
def to_s # :nodoc:
-
return location if passed? and not skipped?
-
-
failures.map { |failure|
-
"#{failure.result_label}:\n#{self.location}:\n#{failure.message}\n"
-
}.join "\n"
-
end
-
-
2
def with_info_handler &block # :nodoc:
-
t0 = Minitest.clock_time
-
-
handler = lambda do
-
warn "\nCurrent: %s#%s %.2fs" % [self.class, self.name, Minitest.clock_time - t0]
-
end
-
-
self.class.on_signal "INFO", handler, &block
-
end
-
-
2
include LifecycleHooks
-
2
include Guard
-
2
extend Guard
-
end # Test
-
end
-
-
2
require "minitest/unit" unless defined?(MiniTest) # compatibility layer only
-
# :stopdoc:
-
-
2
unless defined?(Minitest) then
-
# all of this crap is just to avoid circular requires and is only
-
# needed if a user requires "minitest/unit" directly instead of
-
# "minitest/autorun", so we also warn
-
-
from = caller.reject { |s| s =~ /rubygems/ }.join("\n ")
-
warn "Warning: you should require 'minitest/autorun' instead."
-
warn %(Warning: or add 'gem "minitest"' before 'require "minitest/autorun"')
-
warn "From:\n #{from}"
-
-
module Minitest; end
-
MiniTest = Minitest # prevents minitest.rb from requiring back to us
-
require "minitest"
-
end
-
-
2
MiniTest = Minitest unless defined?(MiniTest)
-
-
2
module Minitest
-
2
class Unit
-
2
VERSION = Minitest::VERSION
-
2
class TestCase < Minitest::Test
-
2
def self.inherited klass # :nodoc:
-
from = caller.first
-
warn "MiniTest::Unit::TestCase is now Minitest::Test. From #{from}"
-
super
-
end
-
end
-
-
2
def self.autorun # :nodoc:
-
from = caller.first
-
warn "MiniTest::Unit.autorun is now Minitest.autorun. From #{from}"
-
Minitest.autorun
-
end
-
-
2
def self.after_tests(&b)
-
from = caller.first
-
warn "MiniTest::Unit.after_tests is now Minitest.after_run. From #{from}"
-
Minitest.after_run(&b)
-
end
-
end
-
end
-
-
# :startdoc:
-
2
module Minitest
-
# Filters backtraces of exceptions that may arise when running tests.
-
2
class ExtensibleBacktraceFilter
-
# Returns the default filter.
-
#
-
# The default filter will filter out all Minitest and minitest-reporters
-
# lines.
-
#
-
# @return [Minitest::ExtensibleBacktraceFilter]
-
2
def self.default_filter
-
unless defined? @default_filter
-
filter = self.new
-
filter.add_filter(/lib\/minitest/)
-
@default_filter = filter
-
end
-
-
@default_filter
-
end
-
-
# Creates a new backtrace filter.
-
2
def initialize
-
@filters = []
-
end
-
-
# Adds a filter.
-
#
-
# @param [Regex] regex the filter
-
2
def add_filter(regex)
-
@filters << regex
-
end
-
-
# Determines if the string would be filtered.
-
#
-
# @param [String] str
-
# @return [Boolean]
-
2
def filters?(str)
-
@filters.any? { |filter| str =~ filter }
-
end
-
-
# Filters a backtrace.
-
#
-
# This will add new lines to the new backtrace until a filtered line is
-
# encountered. If there were lines added to the new backtrace, it returns
-
# those lines. However, if the first line in the backtrace was filtered,
-
# resulting in an empty backtrace, it returns all lines that would have
-
# been unfiltered. If that in turn does not contain any lines, it returns
-
# the original backtrace.
-
#
-
# @param [Array] backtrace the backtrace to filter
-
# @return [Array] the filtered backtrace
-
# @note This logic is based off of Minitest's #filter_backtrace.
-
2
def filter(backtrace)
-
result = []
-
return result unless backtrace
-
-
backtrace.each do |line|
-
break if filters?(line)
-
result << line
-
end
-
-
result = backtrace.reject { |line| filters?(line) } if result.empty?
-
result = backtrace.dup if result.empty?
-
-
result
-
end
-
end
-
end
-
2
module Minitest
-
2
module RelativePosition
-
2
TEST_PADDING = 2
-
2
TEST_SIZE = 63
-
2
MARK_SIZE = 5
-
2
INFO_PADDING = 8
-
-
2
private
-
-
2
def print_with_info_padding(line)
-
puts pad(line, INFO_PADDING)
-
end
-
-
2
def pad(str, size = INFO_PADDING)
-
' ' * size + str
-
end
-
-
2
def pad_mark(str)
-
"%#{MARK_SIZE}s" % str
-
end
-
-
2
def pad_test(str)
-
pad("%-#{TEST_SIZE}s" % str, TEST_PADDING)
-
end
-
end
-
end
-
2
require 'minitest'
-
-
2
module Minitest
-
2
require "minitest/relative_position"
-
2
require "minitest/extensible_backtrace_filter"
-
-
2
module Reporters
-
2
require "minitest/reporters/version"
-
-
2
autoload :ANSI, "minitest/reporters/ansi"
-
2
autoload :BaseReporter, "minitest/reporters/base_reporter"
-
2
autoload :DefaultReporter, "minitest/reporters/default_reporter"
-
2
autoload :SpecReporter, "minitest/reporters/spec_reporter"
-
2
autoload :ProgressReporter, "minitest/reporters/progress_reporter"
-
2
autoload :RubyMateReporter, "minitest/reporters/ruby_mate_reporter"
-
2
autoload :RubyMineReporter, "minitest/reporters/rubymine_reporter"
-
2
autoload :JUnitReporter, "minitest/reporters/junit_reporter"
-
2
autoload :HtmlReporter, "minitest/reporters/html_reporter"
-
2
autoload :MeanTimeReporter, "minitest/reporters/mean_time_reporter"
-
-
2
class << self
-
2
attr_accessor :reporters
-
end
-
-
2
def self.use!(console_reporters = ProgressReporter.new, env = ENV, backtrace_filter = nil)
-
use_runner!(console_reporters, env)
-
if backtrace_filter.nil? && !defined?(::Rails)
-
backtrace_filter = ExtensibleBacktraceFilter.default_filter
-
end
-
Minitest.backtrace_filter = backtrace_filter unless backtrace_filter.nil?
-
-
unless defined?(@@loaded)
-
use_around_test_hooks!
-
use_old_activesupport_fix!
-
@@loaded = true
-
end
-
end
-
-
2
def self.use_runner!(console_reporters, env)
-
self.reporters = choose_reporters(console_reporters, env)
-
end
-
-
2
def self.use_around_test_hooks!
-
Minitest::Test.class_eval do
-
def run_with_hooks(*args)
-
if defined?(Minitest::Reporters) && (reporters = Minitest::Reporters.reporters)
-
reporters.each { |r| r.before_test(self) }
-
result = run_without_hooks(*args)
-
reporters.each { |r| r.after_test(self) }
-
result
-
else
-
run_without_hooks(*args)
-
end
-
end
-
-
alias_method :run_without_hooks, :run
-
alias_method :run, :run_with_hooks
-
end
-
end
-
-
2
def self.choose_reporters(console_reporters, env)
-
if env["TM_PID"]
-
[RubyMateReporter.new]
-
elsif env["RM_INFO"] || env["TEAMCITY_VERSION"]
-
[RubyMineReporter.new]
-
elsif !env["VIM"]
-
Array(console_reporters)
-
end
-
end
-
-
2
def self.clock_time
-
if minitest_version >= 561
-
Minitest.clock_time
-
else
-
Time.now
-
end
-
end
-
-
2
def self.minitest_version
-
Minitest::VERSION.gsub('.', '').to_i
-
end
-
-
2
def self.use_old_activesupport_fix!
-
if defined?(ActiveSupport::VERSION) && ActiveSupport::VERSION::MAJOR < 4
-
require "minitest/old_activesupport_fix"
-
end
-
end
-
end
-
end
-
2
module Minitest
-
2
module Reporters
-
2
VERSION = '1.1.8'
-
end
-
end
-
1
require 'multi_json/options'
-
1
require 'multi_json/version'
-
1
require 'multi_json/adapter_error'
-
1
require 'multi_json/parse_error'
-
-
1
module MultiJson
-
1
include Options
-
1
extend self
-
-
1
def default_options=(value)
-
Kernel.warn "MultiJson.default_options setter is deprecated\n" +
-
"Use MultiJson.load_options and MultiJson.dump_options instead"
-
-
self.load_options = self.dump_options = value
-
end
-
-
1
def default_options
-
Kernel.warn "MultiJson.default_options is deprecated\n" +
-
"Use MultiJson.load_options or MultiJson.dump_options instead"
-
-
self.load_options
-
end
-
-
1
%w[cached_options reset_cached_options!].each do |method_name|
-
2
define_method method_name do |*|
-
Kernel.warn "MultiJson.#{method_name} method is deprecated and no longer used."
-
end
-
end
-
-
1
ALIASES = { 'jrjackson' => 'jr_jackson' }
-
-
1
REQUIREMENT_MAP = [
-
['oj', :oj],
-
['yajl', :yajl],
-
['jrjackson', :jr_jackson],
-
['json/ext', :json_gem],
-
['gson', :gson],
-
['json/pure', :json_pure]
-
]
-
-
# The default adapter based on what you currently
-
# have loaded and installed. First checks to see
-
# if any adapters are already loaded, then checks
-
# to see which are installed if none are loaded.
-
1
def default_adapter
-
return :oj if defined?(::Oj)
-
return :yajl if defined?(::Yajl)
-
return :jr_jackson if defined?(::JrJackson)
-
return :json_gem if defined?(::JSON::JSON_LOADED)
-
return :gson if defined?(::Gson)
-
-
REQUIREMENT_MAP.each do |library, adapter|
-
begin
-
require library
-
return adapter
-
rescue ::LoadError
-
next
-
end
-
end
-
-
Kernel.warn '[WARNING] MultiJson is using the default adapter (ok_json).' +
-
'We recommend loading a different JSON library to improve performance.'
-
-
:ok_json
-
end
-
1
alias default_engine default_adapter
-
-
# Get the current adapter class.
-
1
def adapter
-
return @adapter if defined?(@adapter) && @adapter
-
-
self.use nil # load default adapter
-
-
@adapter
-
end
-
1
alias engine adapter
-
-
# Set the JSON parser utilizing a symbol, string, or class.
-
# Supported by default are:
-
#
-
# * <tt>:oj</tt>
-
# * <tt>:json_gem</tt>
-
# * <tt>:json_pure</tt>
-
# * <tt>:ok_json</tt>
-
# * <tt>:yajl</tt>
-
# * <tt>:nsjsonserialization</tt> (MacRuby only)
-
# * <tt>:gson</tt> (JRuby only)
-
# * <tt>:jr_jackson</tt> (JRuby only)
-
1
def use(new_adapter)
-
@adapter = load_adapter(new_adapter)
-
end
-
1
alias adapter= use
-
1
alias engine= use
-
-
1
def load_adapter(new_adapter)
-
case new_adapter
-
when String, Symbol
-
load_adapter_from_string_name new_adapter.to_s
-
when NilClass, FalseClass
-
load_adapter default_adapter
-
when Class, Module
-
new_adapter
-
else
-
raise ::LoadError, new_adapter
-
end
-
rescue ::LoadError => exception
-
raise AdapterError.build(exception)
-
end
-
-
# Decode a JSON string into Ruby.
-
#
-
# <b>Options</b>
-
#
-
# <tt>:symbolize_keys</tt> :: If true, will use symbols instead of strings for the keys.
-
# <tt>:adapter</tt> :: If set, the selected adapter will be used for this call.
-
1
def load(string, options={})
-
adapter = current_adapter(options)
-
begin
-
adapter.load(string, options)
-
rescue adapter::ParseError => exception
-
raise ParseError.build(exception, string)
-
end
-
end
-
1
alias decode load
-
-
1
def current_adapter(options={})
-
if new_adapter = options[:adapter]
-
load_adapter(new_adapter)
-
else
-
adapter
-
end
-
end
-
-
# Encodes a Ruby object as JSON.
-
1
def dump(object, options={})
-
current_adapter(options).dump(object, options)
-
end
-
1
alias encode dump
-
-
# Executes passed block using specified adapter.
-
1
def with_adapter(new_adapter)
-
old_adapter, self.adapter = adapter, new_adapter
-
yield
-
ensure
-
self.adapter = old_adapter
-
end
-
1
alias with_engine with_adapter
-
-
1
private
-
-
1
def load_adapter_from_string_name(name)
-
name = ALIASES.fetch(name, name)
-
require "multi_json/adapters/#{name.downcase}"
-
klass_name = name.to_s.split('_').map(&:capitalize) * ''
-
MultiJson::Adapters.const_get(klass_name)
-
end
-
-
end
-
1
module MultiJson
-
1
class AdapterError < ArgumentError
-
1
attr_reader :cause
-
-
1
def self.build(original_exception)
-
message = "Did not recognize your adapter specification (#{original_exception.message})."
-
new(message).tap do |exception|
-
exception.instance_eval do
-
@cause = original_exception
-
set_backtrace original_exception.backtrace
-
end
-
end
-
end
-
end
-
end
-
1
module MultiJson
-
1
module Options
-
-
1
def load_options=(options)
-
@load_options = options
-
end
-
-
1
def dump_options=(options)
-
@dump_options = options
-
end
-
-
1
def load_options(*args)
-
defined?(@load_options) && get_options(@load_options, *args) || default_load_options
-
end
-
-
1
def dump_options(*args)
-
defined?(@dump_options) && get_options(@dump_options, *args) || default_dump_options
-
end
-
-
1
def default_load_options
-
@default_load_options ||= {}
-
end
-
-
1
def default_dump_options
-
@default_dump_options ||= {}
-
end
-
-
1
private
-
-
1
def get_options(options, *args)
-
if options.respond_to?(:call) and options.arity
-
options.arity == 0 ? options[] : options[*args]
-
elsif Hash === options or options.respond_to?(:to_hash)
-
options.to_hash
-
end
-
end
-
end
-
end
-
1
module MultiJson
-
1
class ParseError < StandardError
-
1
attr_reader :data, :cause
-
-
1
def self.build(original_exception, data)
-
new(original_exception.message).tap do |exception|
-
exception.instance_eval do
-
@cause = original_exception
-
set_backtrace original_exception.backtrace
-
@data = data
-
end
-
end
-
end
-
end
-
-
1
DecodeError = LoadError = ParseError # Legacy support
-
end
-
1
module MultiJson
-
1
class Version
-
1
MAJOR = 1 unless defined? MultiJson::Version::MAJOR
-
1
MINOR = 11 unless defined? MultiJson::Version::MINOR
-
1
PATCH = 2 unless defined? MultiJson::Version::PATCH
-
1
PRE = nil unless defined? MultiJson::Version::PRE
-
-
1
class << self
-
-
# @return [String]
-
1
def to_s
-
1
[MAJOR, MINOR, PATCH, PRE].compact.join('.')
-
end
-
-
end
-
-
end
-
-
1
VERSION = Version.to_s.freeze
-
end
-
2
require 'nenv/version'
-
-
2
require 'nenv/autoenvironment'
-
2
require 'nenv/builder'
-
-
2
def Nenv(namespace = nil)
-
Nenv::AutoEnvironment.new(namespace).tap do |env|
-
yield env if block_given?
-
end
-
end
-
-
2
module Nenv
-
2
class << self
-
2
def respond_to?(meth)
-
instance.respond_to?(meth)
-
end
-
-
2
def method_missing(meth, *args)
-
instance.send(meth, *args)
-
end
-
-
2
def reset
-
@instance = nil
-
end
-
-
2
def instance
-
@instance ||= Nenv::AutoEnvironment.new
-
end
-
end
-
end
-
2
require 'nenv/environment'
-
2
module Nenv
-
2
class AutoEnvironment < Nenv::Environment
-
2
def method_missing(meth, *args)
-
create_method(meth) unless respond_to?(meth)
-
send(meth, *args)
-
end
-
end
-
end
-
2
require 'nenv/environment'
-
-
2
module Nenv
-
2
module Builder
-
2
def self.build(&block)
-
6
Class.new(Nenv::Environment, &block)
-
end
-
end
-
end
-
2
require 'nenv/environment/dumper'
-
2
require 'nenv/environment/loader'
-
-
2
module Nenv
-
2
class Environment
-
2
class Error < ArgumentError
-
end
-
-
2
class MethodError < Error
-
2
def initialize(meth)
-
@meth = meth
-
end
-
end
-
-
2
class AlreadyExistsError < MethodError
-
2
def message
-
format('Method %s already exists', @meth.inspect)
-
end
-
end
-
-
2
def initialize(namespace = nil)
-
24
@namespace = (namespace ? namespace.upcase : nil)
-
end
-
-
2
def create_method(meth, &block)
-
self.class._create_env_accessor(singleton_class, meth, &block)
-
end
-
-
2
private
-
-
2
def _sanitize(meth)
-
2
meth.to_s[/^([^=?]*)[=?]?$/, 1].upcase
-
end
-
-
2
def _namespaced_sanitize(meth)
-
2
[@namespace, _sanitize(meth)].compact.join('_')
-
end
-
-
2
class << self
-
2
def create_method(meth, &block)
-
18
_create_env_accessor(self, meth, &block)
-
end
-
-
2
def _create_env_accessor(klass, meth, &block)
-
18
_fail_if_accessor_exists(klass, meth)
-
-
18
if meth.to_s.end_with? '='
-
6
_create_env_writer(klass, meth, &block)
-
else
-
12
_create_env_reader(klass, meth, &block)
-
end
-
end
-
-
2
private
-
-
2
def _create_env_writer(klass, meth, &block)
-
6
env_name = nil
-
6
dumper = nil
-
6
klass.send(:define_method, meth) do |raw_value|
-
env_name ||= _namespaced_sanitize(meth)
-
dumper ||= Dumper.setup(&block)
-
ENV[env_name] = dumper.(raw_value)
-
end
-
end
-
-
2
def _create_env_reader(klass, meth, &block)
-
12
env_name = nil
-
12
loader = nil
-
12
klass.send(:define_method, meth) do
-
24
env_name ||= _namespaced_sanitize(meth)
-
24
loader ||= Loader.setup(meth, &block)
-
24
loader.(ENV[env_name])
-
end
-
end
-
-
2
def _fail_if_accessor_exists(klass, meth)
-
18
fail(AlreadyExistsError, meth) if klass.method_defined?(meth)
-
end
-
end
-
end
-
end
-
2
module Nenv
-
2
class Environment
-
2
module Dumper
-
2
require 'nenv/environment/dumper/default'
-
-
2
def self.setup(&callback)
-
if callback
-
callback
-
else
-
Default
-
end
-
end
-
end
-
end
-
end
-
2
module Nenv
-
2
class Environment
-
2
module Dumper::Default
-
2
def self.call(raw_value)
-
raw_value.nil? ? nil : raw_value.to_s
-
end
-
end
-
end
-
end
-
2
module Nenv
-
2
class Environment
-
2
module Loader
-
2
require 'nenv/environment/loader/predicate'
-
2
require 'nenv/environment/loader/default'
-
-
2
def self.setup(meth, &callback)
-
2
if callback
-
callback
-
else
-
2
if meth.to_s.end_with? '?'
-
2
Predicate
-
else
-
Default
-
end
-
end
-
end
-
end
-
end
-
end
-
2
module Nenv
-
2
class Environment
-
2
module Loader::Default
-
2
def self.call(raw_value)
-
raw_value
-
end
-
end
-
end
-
end
-
2
module Nenv
-
2
class Environment
-
2
module Loader::Predicate
-
2
def self.call(raw_value)
-
24
case raw_value
-
when nil
-
nil
-
when ''
-
fail ArgumentError, "Can't convert empty string into Bool"
-
when '0', 'false', 'n', 'no', 'NO', 'FALSE'
-
false
-
else
-
true
-
end
-
end
-
end
-
end
-
end
-
2
module Nenv
-
2
VERSION = '0.3.0'
-
end
-
# -*- coding: utf-8 -*-
-
# Modify the PATH on windows so that the external DLLs will get loaded.
-
-
2
require 'rbconfig'
-
-
2
if defined?(RUBY_ENGINE) && RUBY_ENGINE == "jruby"
-
# The line below caused a problem on non-GAE rack environment.
-
# unless defined?(JRuby::Rack::VERSION) || defined?(AppEngine::ApiProxy)
-
#
-
# However, simply cutting defined?(JRuby::Rack::VERSION) off resulted in
-
# an unable-to-load-nokogiri problem. Thus, now, Nokogiri checks the presense
-
# of appengine-rack.jar in $LOAD_PATH. If Nokogiri is on GAE, Nokogiri
-
# should skip loading xml jars. This is because those are in WEB-INF/lib and
-
# already set in the classpath.
-
unless $LOAD_PATH.to_s.include?("appengine-rack")
-
require 'stringio'
-
require 'isorelax.jar'
-
require 'jing.jar'
-
require 'nekohtml.jar'
-
require 'nekodtd.jar'
-
require 'xercesImpl.jar'
-
end
-
end
-
-
2
begin
-
2
RUBY_VERSION =~ /(\d+.\d+)/
-
2
require "nokogiri/#{$1}/nokogiri"
-
rescue LoadError
-
2
require 'nokogiri/nokogiri'
-
end
-
2
require 'nokogiri/version'
-
2
require 'nokogiri/syntax_error'
-
2
require 'nokogiri/xml'
-
2
require 'nokogiri/xslt'
-
2
require 'nokogiri/html'
-
2
require 'nokogiri/decorators/slop'
-
2
require 'nokogiri/css'
-
2
require 'nokogiri/html/builder'
-
-
# Nokogiri parses and searches XML/HTML very quickly, and also has
-
# correctly implemented CSS3 selector support as well as XPath 1.0
-
# support.
-
#
-
# Parsing a document returns either a Nokogiri::XML::Document, or a
-
# Nokogiri::HTML::Document depending on the kind of document you parse.
-
#
-
# Here is an example:
-
#
-
# require 'nokogiri'
-
# require 'open-uri'
-
#
-
# # Get a Nokogiri::HTML:Document for the page we’re interested in...
-
#
-
# doc = Nokogiri::HTML(open('http://www.google.com/search?q=tenderlove'))
-
#
-
# # Do funky things with it using Nokogiri::XML::Node methods...
-
#
-
# ####
-
# # Search for nodes by css
-
# doc.css('h3.r a.l').each do |link|
-
# puts link.content
-
# end
-
#
-
# See Nokogiri::XML::Searchable#css for more information about CSS searching.
-
# See Nokogiri::XML::Searchable#xpath for more information about XPath searching.
-
2
module Nokogiri
-
2
class << self
-
###
-
# Parse an HTML or XML document. +string+ contains the document.
-
2
def parse string, url = nil, encoding = nil, options = nil
-
if string.respond_to?(:read) ||
-
/^\s*<(?:!DOCTYPE\s+)?html[\s>]/i === string[0, 512]
-
# Expect an HTML indicator to appear within the first 512
-
# characters of a document. (<?xml ?> + <?xml-stylesheet ?>
-
# shouldn't be that long)
-
Nokogiri.HTML(string, url, encoding,
-
options || XML::ParseOptions::DEFAULT_HTML)
-
else
-
Nokogiri.XML(string, url, encoding,
-
options || XML::ParseOptions::DEFAULT_XML)
-
end.tap { |doc|
-
yield doc if block_given?
-
}
-
end
-
-
###
-
# Create a new Nokogiri::XML::DocumentFragment
-
2
def make input = nil, opts = {}, &blk
-
if input
-
Nokogiri::HTML.fragment(input).children.first
-
else
-
Nokogiri(&blk)
-
end
-
end
-
-
###
-
# Parse a document and add the Slop decorator. The Slop decorator
-
# implements method_missing such that methods may be used instead of CSS
-
# or XPath. For example:
-
#
-
# doc = Nokogiri::Slop(<<-eohtml)
-
# <html>
-
# <body>
-
# <p>first</p>
-
# <p>second</p>
-
# </body>
-
# </html>
-
# eohtml
-
# assert_equal('second', doc.html.body.p[1].text)
-
#
-
2
def Slop(*args, &block)
-
Nokogiri(*args, &block).slop!
-
end
-
end
-
-
# Make sure to support some popular encoding aliases not known by
-
# all iconv implementations.
-
{
-
'Windows-31J' => 'CP932', # Windows-31J is the IANA registered name of CP932.
-
2
}.each { |alias_name, name|
-
2
EncodingHandler.alias(name, alias_name) if EncodingHandler[alias_name].nil?
-
}
-
end
-
-
###
-
# Parser a document contained in +args+. Nokogiri will try to guess what
-
# type of document you are attempting to parse. For more information, see
-
# Nokogiri.parse
-
#
-
# To specify the type of document, use Nokogiri.XML or Nokogiri.HTML.
-
2
def Nokogiri(*args, &block)
-
if block_given?
-
Nokogiri::HTML::Builder.new(&block).doc.root
-
else
-
Nokogiri.parse(*args)
-
end
-
end
-
2
require 'nokogiri/css/node'
-
2
require 'nokogiri/css/xpath_visitor'
-
2
x = $-w
-
2
$-w = false
-
2
require 'nokogiri/css/parser'
-
2
$-w = x
-
-
2
require 'nokogiri/css/tokenizer'
-
2
require 'nokogiri/css/syntax_error'
-
-
2
module Nokogiri
-
2
module CSS
-
2
class << self
-
###
-
# Parse this CSS selector in +selector+. Returns an AST.
-
2
def parse selector
-
Parser.new.parse selector
-
end
-
-
###
-
# Get the XPath for +selector+.
-
2
def xpath_for selector, options={}
-
34
Parser.new(options[:ns] || {}).xpath_for selector, options
-
end
-
end
-
end
-
end
-
2
module Nokogiri
-
2
module CSS
-
2
class Node
-
2
ALLOW_COMBINATOR_ON_SELF = [:DIRECT_ADJACENT_SELECTOR, :FOLLOWING_SELECTOR, :CHILD_SELECTOR]
-
-
# Get the type of this node
-
2
attr_accessor :type
-
# Get the value of this node
-
2
attr_accessor :value
-
-
# Create a new Node with +type+ and +value+
-
2
def initialize type, value
-
1
@type = type
-
1
@value = value
-
end
-
-
# Accept +visitor+
-
2
def accept visitor
-
1
visitor.send(:"visit_#{type.to_s.downcase}", self)
-
end
-
-
###
-
# Convert this CSS node to xpath with +prefix+ using +visitor+
-
2
def to_xpath prefix = '//', visitor = XPathVisitor.new
-
1
prefix = '.' if ALLOW_COMBINATOR_ON_SELF.include?(type) && value.first.nil?
-
1
prefix + visitor.accept(self)
-
end
-
-
# Find a node by type using +types+
-
2
def find_by_type types
-
matches = []
-
matches << self if to_type == types
-
@value.each do |v|
-
matches += v.find_by_type(types) if v.respond_to?(:find_by_type)
-
end
-
matches
-
end
-
-
# Convert to_type
-
2
def to_type
-
[@type] + @value.map { |n|
-
n.to_type if n.respond_to?(:to_type)
-
}.compact
-
end
-
-
# Convert to array
-
2
def to_a
-
[@type] + @value.map { |n| n.respond_to?(:to_a) ? n.to_a : [n] }
-
end
-
end
-
end
-
end
-
#
-
# DO NOT MODIFY!!!!
-
# This file is automatically generated by Racc 1.4.12
-
# from Racc grammer file "".
-
#
-
-
2
require 'racc/parser.rb'
-
-
-
2
require 'nokogiri/css/parser_extras'
-
2
module Nokogiri
-
2
module CSS
-
2
class Parser < Racc::Parser
-
##### State transition tables begin ###
-
-
2
racc_action_table = [
-
24, 93, 56, 57, 33, 55, 94, 23, 24, 22,
-
12, 93, 33, 27, 35, 52, 88, 22, -23, 25,
-
92, 98, 23, 33, 26, 18, 20, 25, 27, 86,
-
23, 24, 26, 18, 20, 33, 27, 11, 39, 24,
-
22, 23, 89, 33, 18, 101, 100, 27, 22, 12,
-
25, 24, 95, 23, 90, 26, 18, 20, 25, 27,
-
66, 23, 24, 26, 18, 20, 33, 27, 91, 90,
-
51, 22, 96, 85, 33, 26, 33, -23, 33, 56,
-
87, 25, 60, 99, 23, 74, 26, 18, 20, 39,
-
27, 39, 23, 39, 23, 18, 23, 18, 27, 18,
-
27, 33, 27, 33, 56, 87, 22, 60, 56, 87,
-
102, 60, 56, 87, 33, 60, 39, 24, 39, 23,
-
103, 23, 18, 20, 18, 27, 46, 27, 49, 39,
-
93, 44, 23, 105, 33, 18, 51, 45, 27, 33,
-
-23, 26, 108, 56, 58, 109, 60, nil, nil, 39,
-
nil, nil, 23, nil, 39, 18, nil, 23, 27, nil,
-
18, 20, nil, 27, 82, 83, nil, nil, nil, 82,
-
83, nil, nil, nil, nil, 78, 79, 80, nil, 81,
-
78, 79, 80, 77, 81, 4, 5, 10, 77, 4,
-
5, 43, nil, nil, nil, 6, nil, 8, 7, 6,
-
nil, 8, 7, 4, 5, 10, nil, nil, nil, nil,
-
nil, nil, nil, 6, nil, 8, 7 ]
-
-
2
racc_action_check = [
-
42, 58, 24, 24, 42, 24, 57, 15, 43, 42,
-
64, 57, 43, 15, 11, 24, 53, 43, 58, 42,
-
56, 64, 42, 14, 42, 42, 42, 43, 42, 50,
-
43, 3, 43, 43, 43, 3, 43, 1, 14, 9,
-
3, 14, 54, 9, 14, 76, 76, 14, 9, 1,
-
3, 27, 59, 3, 60, 3, 3, 3, 9, 3,
-
27, 9, 12, 9, 9, 9, 12, 9, 55, 55,
-
27, 12, 61, 49, 28, 27, 62, 46, 30, 92,
-
92, 12, 92, 75, 12, 45, 12, 12, 12, 28,
-
12, 62, 28, 30, 62, 28, 30, 62, 28, 30,
-
62, 39, 30, 32, 90, 90, 39, 90, 51, 51,
-
84, 51, 93, 93, 31, 93, 39, 23, 32, 39,
-
86, 32, 39, 39, 32, 39, 23, 32, 23, 31,
-
87, 18, 31, 91, 29, 31, 23, 21, 31, 25,
-
22, 23, 94, 25, 25, 105, 25, nil, nil, 29,
-
nil, nil, 29, nil, 25, 29, nil, 25, 29, nil,
-
25, 25, nil, 25, 48, 48, nil, nil, nil, 47,
-
47, nil, nil, nil, nil, 48, 48, 48, nil, 48,
-
47, 47, 47, 48, 47, 0, 0, 0, 47, 17,
-
17, 17, nil, nil, nil, 0, nil, 0, 0, 17,
-
nil, 17, 17, 26, 26, 26, nil, nil, nil, nil,
-
nil, nil, nil, 26, nil, 26, 26 ]
-
-
2
racc_action_pointer = [
-
178, 37, nil, 29, nil, nil, nil, nil, nil, 37,
-
nil, 14, 60, nil, 17, -17, nil, 182, 120, nil,
-
nil, 108, 111, 115, -8, 133, 196, 49, 68, 128,
-
72, 108, 97, nil, nil, nil, nil, nil, nil, 95,
-
nil, nil, -2, 6, nil, 74, 48, 166, 161, 48,
-
0, 98, nil, -7, 19, 57, 8, -1, -11, 29,
-
42, 49, 70, nil, -2, nil, nil, nil, nil, nil,
-
nil, nil, nil, nil, nil, 58, 35, nil, nil, nil,
-
nil, nil, nil, nil, 85, nil, 109, 118, nil, nil,
-
94, 126, 69, 102, 129, nil, nil, nil, nil, nil,
-
nil, nil, nil, nil, nil, 132, nil, nil, nil, nil ]
-
-
2
racc_action_default = [
-
-74, -75, -2, -24, -4, -5, -6, -7, -8, -24,
-
-73, -75, -24, -3, -47, -10, -13, -17, -75, -19,
-
-20, -75, -22, -24, -75, -24, -74, -75, -53, -54,
-
-55, -56, -57, -58, -14, 110, -1, -9, -46, -24,
-
-11, -12, -24, -24, -18, -75, -29, -61, -61, -75,
-
-75, -75, -30, -75, -75, -38, -39, -40, -22, -75,
-
-38, -75, -70, -72, -75, -44, -45, -48, -49, -50,
-
-51, -52, -15, -16, -21, -75, -75, -62, -63, -64,
-
-65, -66, -67, -68, -75, -27, -75, -40, -31, -32,
-
-75, -43, -75, -75, -75, -33, -69, -71, -34, -25,
-
-59, -60, -26, -28, -35, -75, -36, -37, -42, -41 ]
-
-
2
racc_goto_table = [
-
53, 38, 13, 1, 41, 48, 62, 40, 34, 65,
-
50, 36, 63, 75, 84, 67, 68, 69, 70, 71,
-
62, 47, 37, 42, 54, nil, 63, nil, nil, 64,
-
nil, nil, nil, nil, nil, nil, nil, nil, nil, nil,
-
nil, 72, 73, nil, nil, nil, nil, nil, nil, 97,
-
nil, nil, nil, nil, nil, nil, nil, nil, nil, nil,
-
nil, nil, nil, nil, nil, nil, 104, nil, 106, 107 ]
-
-
2
racc_goto_check = [
-
18, 12, 2, 1, 11, 9, 7, 10, 2, 9,
-
15, 2, 12, 17, 17, 12, 12, 12, 12, 12,
-
7, 16, 8, 5, 19, nil, 12, nil, nil, 1,
-
nil, nil, nil, nil, nil, nil, nil, nil, nil, nil,
-
nil, 2, 2, nil, nil, nil, nil, nil, nil, 12,
-
nil, nil, nil, nil, nil, nil, nil, nil, nil, nil,
-
nil, nil, nil, nil, nil, nil, 18, nil, 18, 18 ]
-
-
2
racc_goto_pointer = [
-
nil, 3, -1, nil, nil, 6, nil, -19, 8, -18,
-
-8, -11, -13, nil, nil, -13, -2, -34, -24, 0,
-
nil, nil, nil, nil ]
-
-
2
racc_goto_default = [
-
nil, nil, nil, 2, 3, 9, 17, 14, nil, 15,
-
31, 30, 16, 29, 19, 21, nil, nil, 59, nil,
-
28, 32, 76, 61 ]
-
-
2
racc_reduce_table = [
-
0, 0, :racc_error,
-
3, 32, :_reduce_1,
-
1, 32, :_reduce_2,
-
2, 32, :_reduce_3,
-
1, 36, :_reduce_4,
-
1, 36, :_reduce_5,
-
1, 36, :_reduce_6,
-
1, 36, :_reduce_7,
-
1, 36, :_reduce_8,
-
2, 37, :_reduce_9,
-
1, 37, :_reduce_none,
-
2, 37, :_reduce_11,
-
2, 37, :_reduce_12,
-
1, 37, :_reduce_13,
-
2, 34, :_reduce_14,
-
3, 33, :_reduce_15,
-
3, 33, :_reduce_16,
-
1, 33, :_reduce_none,
-
2, 44, :_reduce_18,
-
1, 38, :_reduce_none,
-
1, 38, :_reduce_20,
-
3, 45, :_reduce_21,
-
1, 45, :_reduce_22,
-
1, 46, :_reduce_23,
-
0, 46, :_reduce_none,
-
4, 42, :_reduce_25,
-
4, 42, :_reduce_26,
-
3, 42, :_reduce_27,
-
3, 47, :_reduce_28,
-
1, 47, :_reduce_29,
-
2, 40, :_reduce_30,
-
3, 40, :_reduce_31,
-
3, 40, :_reduce_32,
-
3, 40, :_reduce_33,
-
3, 40, :_reduce_34,
-
3, 49, :_reduce_35,
-
3, 49, :_reduce_36,
-
3, 49, :_reduce_37,
-
1, 49, :_reduce_none,
-
1, 49, :_reduce_none,
-
1, 49, :_reduce_40,
-
4, 50, :_reduce_41,
-
3, 50, :_reduce_42,
-
2, 50, :_reduce_43,
-
2, 41, :_reduce_44,
-
2, 41, :_reduce_45,
-
1, 39, :_reduce_none,
-
0, 39, :_reduce_none,
-
2, 43, :_reduce_48,
-
2, 43, :_reduce_49,
-
2, 43, :_reduce_50,
-
2, 43, :_reduce_51,
-
2, 43, :_reduce_52,
-
1, 43, :_reduce_none,
-
1, 43, :_reduce_none,
-
1, 43, :_reduce_none,
-
1, 43, :_reduce_none,
-
1, 43, :_reduce_none,
-
1, 51, :_reduce_58,
-
2, 48, :_reduce_59,
-
2, 48, :_reduce_60,
-
0, 48, :_reduce_none,
-
1, 53, :_reduce_62,
-
1, 53, :_reduce_63,
-
1, 53, :_reduce_64,
-
1, 53, :_reduce_65,
-
1, 53, :_reduce_66,
-
1, 53, :_reduce_67,
-
1, 53, :_reduce_68,
-
3, 52, :_reduce_69,
-
1, 54, :_reduce_none,
-
2, 54, :_reduce_none,
-
1, 54, :_reduce_none,
-
1, 35, :_reduce_none,
-
0, 35, :_reduce_none ]
-
-
2
racc_reduce_n = 75
-
-
2
racc_shift_n = 110
-
-
2
racc_token_table = {
-
false => 0,
-
:error => 1,
-
:FUNCTION => 2,
-
:INCLUDES => 3,
-
:DASHMATCH => 4,
-
:LBRACE => 5,
-
:HASH => 6,
-
:PLUS => 7,
-
:GREATER => 8,
-
:S => 9,
-
:STRING => 10,
-
:IDENT => 11,
-
:COMMA => 12,
-
:NUMBER => 13,
-
:PREFIXMATCH => 14,
-
:SUFFIXMATCH => 15,
-
:SUBSTRINGMATCH => 16,
-
:TILDE => 17,
-
:NOT_EQUAL => 18,
-
:SLASH => 19,
-
:DOUBLESLASH => 20,
-
:NOT => 21,
-
:EQUAL => 22,
-
:RPAREN => 23,
-
:LSQUARE => 24,
-
:RSQUARE => 25,
-
:HAS => 26,
-
"." => 27,
-
"*" => 28,
-
"|" => 29,
-
":" => 30 }
-
-
2
racc_nt_base = 31
-
-
2
racc_use_result_var = true
-
-
2
Racc_arg = [
-
racc_action_table,
-
racc_action_check,
-
racc_action_default,
-
racc_action_pointer,
-
racc_goto_table,
-
racc_goto_check,
-
racc_goto_default,
-
racc_goto_pointer,
-
racc_nt_base,
-
racc_reduce_table,
-
racc_token_table,
-
racc_shift_n,
-
racc_reduce_n,
-
racc_use_result_var ]
-
-
2
Racc_token_to_s_table = [
-
"$end",
-
"error",
-
"FUNCTION",
-
"INCLUDES",
-
"DASHMATCH",
-
"LBRACE",
-
"HASH",
-
"PLUS",
-
"GREATER",
-
"S",
-
"STRING",
-
"IDENT",
-
"COMMA",
-
"NUMBER",
-
"PREFIXMATCH",
-
"SUFFIXMATCH",
-
"SUBSTRINGMATCH",
-
"TILDE",
-
"NOT_EQUAL",
-
"SLASH",
-
"DOUBLESLASH",
-
"NOT",
-
"EQUAL",
-
"RPAREN",
-
"LSQUARE",
-
"RSQUARE",
-
"HAS",
-
"\".\"",
-
"\"*\"",
-
"\"|\"",
-
"\":\"",
-
"$start",
-
"selector",
-
"simple_selector_1toN",
-
"prefixless_combinator_selector",
-
"optional_S",
-
"combinator",
-
"simple_selector",
-
"element_name",
-
"hcap_0toN",
-
"function",
-
"pseudo",
-
"attrib",
-
"hcap_1toN",
-
"class",
-
"namespaced_ident",
-
"namespace",
-
"attrib_name",
-
"attrib_val_0or1",
-
"expr",
-
"nth",
-
"attribute_id",
-
"negation",
-
"eql_incl_dash",
-
"negation_arg" ]
-
-
2
Racc_debug_parser = false
-
-
##### State transition tables end #####
-
-
# reduce 0 omitted
-
-
2
def _reduce_1(val, _values, result)
-
result = [val.first, val.last].flatten
-
-
result
-
end
-
-
2
def _reduce_2(val, _values, result)
-
result = val.flatten
-
result
-
end
-
-
2
def _reduce_3(val, _values, result)
-
1
result = [val.last].flatten
-
1
result
-
end
-
-
2
def _reduce_4(val, _values, result)
-
result = :DIRECT_ADJACENT_SELECTOR
-
result
-
end
-
-
2
def _reduce_5(val, _values, result)
-
result = :CHILD_SELECTOR
-
result
-
end
-
-
2
def _reduce_6(val, _values, result)
-
result = :FOLLOWING_SELECTOR
-
result
-
end
-
-
2
def _reduce_7(val, _values, result)
-
result = :DESCENDANT_SELECTOR
-
result
-
end
-
-
2
def _reduce_8(val, _values, result)
-
result = :CHILD_SELECTOR
-
result
-
end
-
-
2
def _reduce_9(val, _values, result)
-
1
result = if val[1].nil?
-
1
val.first
-
else
-
Node.new(:CONDITIONAL_SELECTOR, [val.first, val[1]])
-
end
-
-
1
result
-
end
-
-
# reduce 10 omitted
-
-
2
def _reduce_11(val, _values, result)
-
result = Node.new(:CONDITIONAL_SELECTOR, val)
-
-
result
-
end
-
-
2
def _reduce_12(val, _values, result)
-
result = Node.new(:CONDITIONAL_SELECTOR, val)
-
-
result
-
end
-
-
2
def _reduce_13(val, _values, result)
-
result = Node.new(:CONDITIONAL_SELECTOR,
-
[Node.new(:ELEMENT_NAME, ['*']), val.first]
-
)
-
-
result
-
end
-
-
2
def _reduce_14(val, _values, result)
-
result = Node.new(val.first, [nil, val.last])
-
-
result
-
end
-
-
2
def _reduce_15(val, _values, result)
-
result = Node.new(val[1], [val.first, val.last])
-
-
result
-
end
-
-
2
def _reduce_16(val, _values, result)
-
result = Node.new(:DESCENDANT_SELECTOR, [val.first, val.last])
-
-
result
-
end
-
-
# reduce 17 omitted
-
-
2
def _reduce_18(val, _values, result)
-
result = Node.new(:CLASS_CONDITION, [val[1]])
-
result
-
end
-
-
# reduce 19 omitted
-
-
2
def _reduce_20(val, _values, result)
-
result = Node.new(:ELEMENT_NAME, val)
-
result
-
end
-
-
2
def _reduce_21(val, _values, result)
-
result = Node.new(:ELEMENT_NAME,
-
[[val.first, val.last].compact.join(':')]
-
)
-
-
result
-
end
-
-
2
def _reduce_22(val, _values, result)
-
1
name = @namespaces.key?('xmlns') ? "xmlns:#{val.first}" : val.first
-
1
result = Node.new(:ELEMENT_NAME, [name])
-
-
1
result
-
end
-
-
2
def _reduce_23(val, _values, result)
-
result = val[0]
-
result
-
end
-
-
# reduce 24 omitted
-
-
2
def _reduce_25(val, _values, result)
-
result = Node.new(:ATTRIBUTE_CONDITION,
-
[val[1]] + (val[2] || [])
-
)
-
-
result
-
end
-
-
2
def _reduce_26(val, _values, result)
-
result = Node.new(:ATTRIBUTE_CONDITION,
-
[val[1]] + (val[2] || [])
-
)
-
-
result
-
end
-
-
2
def _reduce_27(val, _values, result)
-
# Non standard, but hpricot supports it.
-
result = Node.new(:PSEUDO_CLASS,
-
[Node.new(:FUNCTION, ['nth-child(', val[1]])]
-
)
-
-
result
-
end
-
-
2
def _reduce_28(val, _values, result)
-
result = Node.new(:ELEMENT_NAME,
-
[[val.first, val.last].compact.join(':')]
-
)
-
-
result
-
end
-
-
2
def _reduce_29(val, _values, result)
-
# Default namespace is not applied to attributes.
-
# So we don't add prefix "xmlns:" as in namespaced_ident.
-
result = Node.new(:ELEMENT_NAME, [val.first])
-
-
result
-
end
-
-
2
def _reduce_30(val, _values, result)
-
result = Node.new(:FUNCTION, [val.first.strip])
-
-
result
-
end
-
-
2
def _reduce_31(val, _values, result)
-
result = Node.new(:FUNCTION, [val.first.strip, val[1]].flatten)
-
-
result
-
end
-
-
2
def _reduce_32(val, _values, result)
-
result = Node.new(:FUNCTION, [val.first.strip, val[1]].flatten)
-
-
result
-
end
-
-
2
def _reduce_33(val, _values, result)
-
result = Node.new(:FUNCTION, [val.first.strip, val[1]].flatten)
-
-
result
-
end
-
-
2
def _reduce_34(val, _values, result)
-
result = Node.new(:FUNCTION, [val.first.strip, val[1]].flatten)
-
-
result
-
end
-
-
2
def _reduce_35(val, _values, result)
-
result = [val.first, val.last]
-
result
-
end
-
-
2
def _reduce_36(val, _values, result)
-
result = [val.first, val.last]
-
result
-
end
-
-
2
def _reduce_37(val, _values, result)
-
result = [val.first, val.last]
-
result
-
end
-
-
# reduce 38 omitted
-
-
# reduce 39 omitted
-
-
2
def _reduce_40(val, _values, result)
-
case val[0]
-
when 'even'
-
result = Node.new(:NTH, ['2','n','+','0'])
-
when 'odd'
-
result = Node.new(:NTH, ['2','n','+','1'])
-
when 'n'
-
result = Node.new(:NTH, ['1','n','+','0'])
-
else
-
# This is not CSS standard. It allows us to support this:
-
# assert_xpath("//a[foo(., @href)]", @parser.parse('a:foo(@href)'))
-
# assert_xpath("//a[foo(., @a, b)]", @parser.parse('a:foo(@a, b)'))
-
# assert_xpath("//a[foo(., a, 10)]", @parser.parse('a:foo(a, 10)'))
-
result = val
-
end
-
-
result
-
end
-
-
2
def _reduce_41(val, _values, result)
-
if val[1] == 'n'
-
result = Node.new(:NTH, val)
-
else
-
raise Racc::ParseError, "parse error on IDENT '#{val[1]}'"
-
end
-
-
result
-
end
-
-
2
def _reduce_42(val, _values, result)
-
# n+3, -n+3
-
if val[0] == 'n'
-
val.unshift("1")
-
result = Node.new(:NTH, val)
-
elsif val[0] == '-n'
-
val[0] = 'n'
-
val.unshift("-1")
-
result = Node.new(:NTH, val)
-
else
-
raise Racc::ParseError, "parse error on IDENT '#{val[1]}'"
-
end
-
-
result
-
end
-
-
2
def _reduce_43(val, _values, result)
-
# 5n, -5n, 10n-1
-
n = val[1]
-
if n[0, 2] == 'n-'
-
val[1] = 'n'
-
val << "-"
-
# b is contained in n as n is the string "n-b"
-
val << n[2, n.size]
-
result = Node.new(:NTH, val)
-
elsif n == 'n'
-
val << "+"
-
val << "0"
-
result = Node.new(:NTH, val)
-
else
-
raise Racc::ParseError, "parse error on IDENT '#{val[1]}'"
-
end
-
-
result
-
end
-
-
2
def _reduce_44(val, _values, result)
-
result = Node.new(:PSEUDO_CLASS, [val[1]])
-
-
result
-
end
-
-
2
def _reduce_45(val, _values, result)
-
result = Node.new(:PSEUDO_CLASS, [val[1]])
-
result
-
end
-
-
# reduce 46 omitted
-
-
# reduce 47 omitted
-
-
2
def _reduce_48(val, _values, result)
-
result = Node.new(:COMBINATOR, val)
-
-
result
-
end
-
-
2
def _reduce_49(val, _values, result)
-
result = Node.new(:COMBINATOR, val)
-
-
result
-
end
-
-
2
def _reduce_50(val, _values, result)
-
result = Node.new(:COMBINATOR, val)
-
-
result
-
end
-
-
2
def _reduce_51(val, _values, result)
-
result = Node.new(:COMBINATOR, val)
-
-
result
-
end
-
-
2
def _reduce_52(val, _values, result)
-
result = Node.new(:COMBINATOR, val)
-
-
result
-
end
-
-
# reduce 53 omitted
-
-
# reduce 54 omitted
-
-
# reduce 55 omitted
-
-
# reduce 56 omitted
-
-
# reduce 57 omitted
-
-
2
def _reduce_58(val, _values, result)
-
result = Node.new(:ID, val)
-
result
-
end
-
-
2
def _reduce_59(val, _values, result)
-
result = [val.first, val[1]]
-
result
-
end
-
-
2
def _reduce_60(val, _values, result)
-
result = [val.first, val[1]]
-
result
-
end
-
-
# reduce 61 omitted
-
-
2
def _reduce_62(val, _values, result)
-
result = :equal
-
result
-
end
-
-
2
def _reduce_63(val, _values, result)
-
result = :prefix_match
-
result
-
end
-
-
2
def _reduce_64(val, _values, result)
-
result = :suffix_match
-
result
-
end
-
-
2
def _reduce_65(val, _values, result)
-
result = :substring_match
-
result
-
end
-
-
2
def _reduce_66(val, _values, result)
-
result = :not_equal
-
result
-
end
-
-
2
def _reduce_67(val, _values, result)
-
result = :includes
-
result
-
end
-
-
2
def _reduce_68(val, _values, result)
-
result = :dash_match
-
result
-
end
-
-
2
def _reduce_69(val, _values, result)
-
result = Node.new(:NOT, [val[1]])
-
-
result
-
end
-
-
# reduce 70 omitted
-
-
# reduce 71 omitted
-
-
# reduce 72 omitted
-
-
# reduce 73 omitted
-
-
# reduce 74 omitted
-
-
2
def _reduce_none(val, _values, result)
-
val[0]
-
end
-
-
end # class Parser
-
end # module CSS
-
end # module Nokogiri
-
2
require 'thread'
-
-
2
module Nokogiri
-
2
module CSS
-
2
class Parser < Racc::Parser
-
2
@cache_on = true
-
2
@cache = {}
-
2
@mutex = Mutex.new
-
-
2
class << self
-
# Turn on CSS parse caching
-
2
attr_accessor :cache_on
-
2
alias :cache_on? :cache_on
-
2
alias :set_cache :cache_on=
-
-
# Get the css selector in +string+ from the cache
-
2
def [] string
-
34
return unless @cache_on
-
68
@mutex.synchronize { @cache[string] }
-
end
-
-
# Set the css selector in +string+ in the cache to +value+
-
2
def []= string, value
-
1
return value unless @cache_on
-
2
@mutex.synchronize { @cache[string] = value }
-
end
-
-
# Clear the cache
-
2
def clear_cache
-
@mutex.synchronize { @cache = {} }
-
end
-
-
# Execute +block+ without cache
-
2
def without_cache &block
-
tmp = @cache_on
-
@cache_on = false
-
block.call
-
@cache_on = tmp
-
end
-
-
###
-
# Parse this CSS selector in +selector+. Returns an AST.
-
2
def parse selector
-
@warned ||= false
-
unless @warned
-
$stderr.puts('Nokogiri::CSS::Parser.parse is deprecated, call Nokogiri::CSS.parse(), this will be removed August 1st or version 1.4.0 (whichever is first)')
-
@warned = true
-
end
-
new.parse selector
-
end
-
end
-
-
# Create a new CSS parser with respect to +namespaces+
-
2
def initialize namespaces = {}
-
34
@tokenizer = Tokenizer.new
-
34
@namespaces = namespaces
-
34
super()
-
end
-
-
2
def parse string
-
1
@tokenizer.scan_setup string
-
1
do_parse
-
end
-
-
2
def next_token
-
2
@tokenizer.next_token
-
end
-
-
# Get the xpath for +string+ using +options+
-
2
def xpath_for string, options={}
-
34
key = "#{string}#{options[:ns]}#{options[:prefix]}"
-
34
v = self.class[key]
-
34
return v if v
-
-
1
args = [
-
options[:prefix] || '//',
-
options[:visitor] || XPathVisitor.new
-
]
-
1
self.class[key] = parse(string).map { |ast|
-
1
ast.to_xpath(*args)
-
}
-
end
-
-
# On CSS parser error, raise an exception
-
2
def on_error error_token_id, error_value, value_stack
-
after = value_stack.compact.last
-
raise SyntaxError.new("unexpected '#{error_value}' after '#{after}'")
-
end
-
end
-
end
-
end
-
2
require 'nokogiri/syntax_error'
-
2
module Nokogiri
-
2
module CSS
-
2
class SyntaxError < ::Nokogiri::SyntaxError
-
end
-
end
-
end
-
#--
-
# DO NOT MODIFY!!!!
-
# This file is automatically generated by rex 1.0.5
-
# from lexical definition file "lib/nokogiri/css/tokenizer.rex".
-
#++
-
-
2
module Nokogiri
-
2
module CSS
-
2
class Tokenizer # :nodoc:
-
2
require 'strscan'
-
-
2
class ScanError < StandardError ; end
-
-
2
attr_reader :lineno
-
2
attr_reader :filename
-
2
attr_accessor :state
-
-
2
def scan_setup(str)
-
1
@ss = StringScanner.new(str)
-
1
@lineno = 1
-
1
@state = nil
-
end
-
-
2
def action
-
1
yield
-
end
-
-
2
def scan_str(str)
-
scan_setup(str)
-
do_parse
-
end
-
2
alias :scan :scan_str
-
-
2
def load_file( filename )
-
@filename = filename
-
open(filename, "r") do |f|
-
scan_setup(f.read)
-
end
-
end
-
-
2
def scan_file( filename )
-
load_file(filename)
-
do_parse
-
end
-
-
-
2
def next_token
-
2
return if @ss.eos?
-
-
# skips empty actions
-
1
until token = _next_token or @ss.eos?; end
-
1
token
-
end
-
-
2
def _next_token
-
1
text = @ss.peek(1)
-
1
@lineno += 1 if text == "\n"
-
1
token = case @state
-
when nil
-
case
-
1
when (text = @ss.scan(/has\([\s]*/))
-
action { [:HAS, text] }
-
-
1
when (text = @ss.scan(/[-@]?([_A-Za-z]|[^\0-\177]|\\[0-9A-Fa-f]{1,6}(\r\n|[\s])?|\\[^\n\r\f0-9A-Fa-f])([_A-Za-z0-9-]|[^\0-\177]|\\[0-9A-Fa-f]{1,6}(\r\n|[\s])?|\\[^\n\r\f0-9A-Fa-f])*\([\s]*/))
-
action { [:FUNCTION, text] }
-
-
1
when (text = @ss.scan(/[-@]?([_A-Za-z]|[^\0-\177]|\\[0-9A-Fa-f]{1,6}(\r\n|[\s])?|\\[^\n\r\f0-9A-Fa-f])([_A-Za-z0-9-]|[^\0-\177]|\\[0-9A-Fa-f]{1,6}(\r\n|[\s])?|\\[^\n\r\f0-9A-Fa-f])*/))
-
2
action { [:IDENT, text] }
-
-
when (text = @ss.scan(/\#([_A-Za-z0-9-]|[^\0-\177]|\\[0-9A-Fa-f]{1,6}(\r\n|[\s])?|\\[^\n\r\f0-9A-Fa-f])+/))
-
action { [:HASH, text] }
-
-
when (text = @ss.scan(/[\s]*~=[\s]*/))
-
action { [:INCLUDES, text] }
-
-
when (text = @ss.scan(/[\s]*\|=[\s]*/))
-
action { [:DASHMATCH, text] }
-
-
when (text = @ss.scan(/[\s]*\^=[\s]*/))
-
action { [:PREFIXMATCH, text] }
-
-
when (text = @ss.scan(/[\s]*\$=[\s]*/))
-
action { [:SUFFIXMATCH, text] }
-
-
when (text = @ss.scan(/[\s]*\*=[\s]*/))
-
action { [:SUBSTRINGMATCH, text] }
-
-
when (text = @ss.scan(/[\s]*!=[\s]*/))
-
action { [:NOT_EQUAL, text] }
-
-
when (text = @ss.scan(/[\s]*=[\s]*/))
-
action { [:EQUAL, text] }
-
-
when (text = @ss.scan(/[\s]*\)/))
-
action { [:RPAREN, text] }
-
-
when (text = @ss.scan(/\[[\s]*/))
-
action { [:LSQUARE, text] }
-
-
when (text = @ss.scan(/[\s]*\]/))
-
action { [:RSQUARE, text] }
-
-
when (text = @ss.scan(/[\s]*\+[\s]*/))
-
action { [:PLUS, text] }
-
-
when (text = @ss.scan(/[\s]*>[\s]*/))
-
action { [:GREATER, text] }
-
-
when (text = @ss.scan(/[\s]*,[\s]*/))
-
action { [:COMMA, text] }
-
-
when (text = @ss.scan(/[\s]*~[\s]*/))
-
action { [:TILDE, text] }
-
-
when (text = @ss.scan(/\:not\([\s]*/))
-
action { [:NOT, text] }
-
-
when (text = @ss.scan(/-?([0-9]+|[0-9]*\.[0-9]+)/))
-
action { [:NUMBER, text] }
-
-
when (text = @ss.scan(/[\s]*\/\/[\s]*/))
-
action { [:DOUBLESLASH, text] }
-
-
when (text = @ss.scan(/[\s]*\/[\s]*/))
-
action { [:SLASH, text] }
-
-
when (text = @ss.scan(/U\+[0-9a-f?]{1,6}(-[0-9a-f]{1,6})?/))
-
action {[:UNICODE_RANGE, text] }
-
-
when (text = @ss.scan(/[\s]+/))
-
action { [:S, text] }
-
-
when (text = @ss.scan(/"([^\n\r\f"]|\n|\r\n|\r|\f|[^\0-\177]|\\[0-9A-Fa-f]{1,6}(\r\n|[\s])?|\\[^\n\r\f0-9A-Fa-f])*"|'([^\n\r\f']|\n|\r\n|\r|\f|[^\0-\177]|\\[0-9A-Fa-f]{1,6}(\r\n|[\s])?|\\[^\n\r\f0-9A-Fa-f])*'/))
-
action { [:STRING, text] }
-
-
when (text = @ss.scan(/./))
-
action { [text, text] }
-
-
else
-
text = @ss.string[@ss.pos .. -1]
-
raise ScanError, "can not match: '" + text + "'"
-
1
end # if
-
-
else
-
raise ScanError, "undefined state: '" + state.to_s + "'"
-
end # case state
-
1
token
-
end # def _next_token
-
-
end # class
-
end
-
end
-
2
module Nokogiri
-
2
module CSS
-
2
class XPathVisitor # :nodoc:
-
2
def visit_function node
-
-
msg = :"visit_function_#{node.value.first.gsub(/[(]/, '')}"
-
return self.send(msg, node) if self.respond_to?(msg)
-
-
case node.value.first
-
when /^text\(/
-
'child::text()'
-
when /^self\(/
-
"self::#{node.value[1]}"
-
when /^eq\(/
-
"position() = #{node.value[1]}"
-
when /^(nth|nth-of-type)\(/
-
if node.value[1].is_a?(Nokogiri::CSS::Node) and node.value[1].type == :NTH
-
nth(node.value[1])
-
else
-
"position() = #{node.value[1]}"
-
end
-
when /^nth-child\(/
-
if node.value[1].is_a?(Nokogiri::CSS::Node) and node.value[1].type == :NTH
-
nth(node.value[1], :child => true)
-
else
-
"count(preceding-sibling::*) = #{node.value[1].to_i-1}"
-
end
-
when /^nth-last-of-type\(/
-
if node.value[1].is_a?(Nokogiri::CSS::Node) and node.value[1].type == :NTH
-
nth(node.value[1], :last => true)
-
else
-
index = node.value[1].to_i - 1
-
index == 0 ? "position() = last()" : "position() = last() - #{index}"
-
end
-
when /^nth-last-child\(/
-
if node.value[1].is_a?(Nokogiri::CSS::Node) and node.value[1].type == :NTH
-
nth(node.value[1], :last => true, :child => true)
-
else
-
"count(following-sibling::*) = #{node.value[1].to_i-1}"
-
end
-
when /^(first|first-of-type)\(/
-
"position() = 1"
-
when /^(last|last-of-type)\(/
-
"position() = last()"
-
when /^contains\(/
-
"contains(., #{node.value[1]})"
-
when /^gt\(/
-
"position() > #{node.value[1]}"
-
when /^only-child\(/
-
"last() = 1"
-
when /^comment\(/
-
"comment()"
-
when /^has\(/
-
node.value[1].accept(self)
-
else
-
args = ['.'] + node.value[1..-1]
-
"#{node.value.first}#{args.join(', ')})"
-
end
-
end
-
-
2
def visit_not node
-
child = node.value.first
-
if :ELEMENT_NAME == child.type
-
"not(self::#{child.accept(self)})"
-
else
-
"not(#{child.accept(self)})"
-
end
-
end
-
-
2
def visit_id node
-
node.value.first =~ /^#(.*)$/
-
"@id = '#{$1}'"
-
end
-
-
2
def visit_attribute_condition node
-
attribute = if (node.value.first.type == :FUNCTION) or (node.value.first.value.first =~ /::/)
-
''
-
else
-
'@'
-
end
-
attribute += node.value.first.accept(self)
-
-
# Support non-standard css
-
attribute.gsub!(/^@@/, '@')
-
-
return attribute unless node.value.length == 3
-
-
value = node.value.last
-
value = "'#{value}'" if value !~ /^['"]/
-
-
case node.value[1]
-
when :equal
-
attribute + " = " + "#{value}"
-
when :not_equal
-
attribute + " != " + "#{value}"
-
when :substring_match
-
"contains(#{attribute}, #{value})"
-
when :prefix_match
-
"starts-with(#{attribute}, #{value})"
-
when :dash_match
-
"#{attribute} = #{value} or starts-with(#{attribute}, concat(#{value}, '-'))"
-
when :includes
-
"contains(concat(\" \", #{attribute}, \" \"),concat(\" \", #{value}, \" \"))"
-
when :suffix_match
-
"substring(#{attribute}, string-length(#{attribute}) - " +
-
"string-length(#{value}) + 1, string-length(#{value})) = #{value}"
-
else
-
attribute + " #{node.value[1]} " + "#{value}"
-
end
-
end
-
-
2
def visit_pseudo_class node
-
if node.value.first.is_a?(Nokogiri::CSS::Node) and node.value.first.type == :FUNCTION
-
node.value.first.accept(self)
-
else
-
msg = :"visit_pseudo_class_#{node.value.first.gsub(/[(]/, '')}"
-
return self.send(msg, node) if self.respond_to?(msg)
-
-
case node.value.first
-
when "first" then "position() = 1"
-
when "first-child" then "count(preceding-sibling::*) = 0"
-
when "last" then "position() = last()"
-
when "last-child" then "count(following-sibling::*) = 0"
-
when "first-of-type" then "position() = 1"
-
when "last-of-type" then "position() = last()"
-
when "only-child" then "count(preceding-sibling::*) = 0 and count(following-sibling::*) = 0"
-
when "only-of-type" then "last() = 1"
-
when "empty" then "not(node())"
-
when "parent" then "node()"
-
when "root" then "not(parent::*)"
-
else
-
node.value.first + "(.)"
-
end
-
end
-
end
-
-
2
def visit_class_condition node
-
"contains(concat(' ', normalize-space(@class), ' '), ' #{node.value.first} ')"
-
end
-
-
2
def visit_combinator node
-
if is_of_type_pseudo_class?(node.value.last)
-
"#{node.value.first.accept(self) if node.value.first}][#{node.value.last.accept(self)}"
-
else
-
"#{node.value.first.accept(self) if node.value.first} and #{node.value.last.accept(self)}"
-
end
-
end
-
-
{
-
'direct_adjacent_selector' => "/following-sibling::*[1]/self::",
-
'following_selector' => "/following-sibling::",
-
'descendant_selector' => '//',
-
'child_selector' => '/',
-
2
}.each do |k,v|
-
8
class_eval %{
-
def visit_#{k} node
-
"\#{node.value.first.accept(self) if node.value.first}#{v}\#{node.value.last.accept(self)}"
-
end
-
}
-
end
-
-
2
def visit_conditional_selector node
-
node.value.first.accept(self) + '[' +
-
node.value.last.accept(self) + ']'
-
end
-
-
2
def visit_element_name node
-
1
node.value.first
-
end
-
-
2
def accept node
-
1
node.accept(self)
-
end
-
-
2
private
-
2
def nth node, options={}
-
raise ArgumentError, "expected an+b node to contain 4 tokens, but is #{node.value.inspect}" unless node.value.size == 4
-
-
a, b = read_a_and_positive_b node.value
-
position = if options[:child]
-
options[:last] ? "(count(following-sibling::*) + 1)" : "(count(preceding-sibling::*) + 1)"
-
else
-
options[:last] ? "(last()-position()+1)" : "position()"
-
end
-
-
if b.zero?
-
"(#{position} mod #{a}) = 0"
-
else
-
compare = a < 0 ? "<=" : ">="
-
if a.abs == 1
-
"#{position} #{compare} #{b}"
-
else
-
"(#{position} #{compare} #{b}) and (((#{position}-#{b}) mod #{a.abs}) = 0)"
-
end
-
end
-
end
-
-
2
def read_a_and_positive_b values
-
op = values[2]
-
if op == "+"
-
a = values[0].to_i
-
b = values[3].to_i
-
elsif op == "-"
-
a = values[0].to_i
-
b = a - (values[3].to_i % a)
-
else
-
raise ArgumentError, "expected an+b node to have either + or - as the operator, but is #{op.inspect}"
-
end
-
[a, b]
-
end
-
-
2
def is_of_type_pseudo_class? node
-
if node.type==:PSEUDO_CLASS
-
if node.value[0].is_a?(Nokogiri::CSS::Node) and node.value[0].type == :FUNCTION
-
node.value[0].value[0]
-
else
-
node.value[0]
-
end =~ /(nth|first|last|only)-of-type(\()?/
-
end
-
end
-
end
-
end
-
end
-
2
module Nokogiri
-
2
module Decorators
-
###
-
# The Slop decorator implements method missing such that a methods may be
-
# used instead of XPath or CSS. See Nokogiri.Slop
-
2
module Slop
-
# The default XPath search context for Slop
-
2
XPATH_PREFIX = "./"
-
-
###
-
# look for node with +name+. See Nokogiri.Slop
-
2
def method_missing name, *args, &block
-
if args.empty?
-
list = xpath("#{XPATH_PREFIX}#{name.to_s.sub(/^_/, '')}")
-
elsif args.first.is_a? Hash
-
hash = args.first
-
if hash[:css]
-
list = css("#{name}#{hash[:css]}")
-
elsif hash[:xpath]
-
conds = Array(hash[:xpath]).join(' and ')
-
list = xpath("#{XPATH_PREFIX}#{name}[#{conds}]")
-
end
-
else
-
CSS::Parser.without_cache do
-
list = xpath(
-
*CSS.xpath_for("#{name}#{args.first}", :prefix => XPATH_PREFIX)
-
)
-
end
-
end
-
-
super if list.empty?
-
list.length == 1 ? list.first : list
-
end
-
-
2
def respond_to_missing? name, include_private = false
-
list = xpath("#{XPATH_PREFIX}#{name.to_s.sub(/^_/, '')}")
-
-
!list.empty?
-
end
-
end
-
end
-
end
-
2
require 'nokogiri/html/entity_lookup'
-
2
require 'nokogiri/html/document'
-
2
require 'nokogiri/html/document_fragment'
-
2
require 'nokogiri/html/sax/parser_context'
-
2
require 'nokogiri/html/sax/parser'
-
2
require 'nokogiri/html/sax/push_parser'
-
2
require 'nokogiri/html/element_description'
-
2
require 'nokogiri/html/element_description_defaults'
-
-
2
module Nokogiri
-
2
class << self
-
###
-
# Parse HTML. Convenience method for Nokogiri::HTML::Document.parse
-
2
def HTML thing, url = nil, encoding = nil, options = XML::ParseOptions::DEFAULT_HTML, &block
-
7
Nokogiri::HTML::Document.parse(thing, url, encoding, options, &block)
-
end
-
end
-
-
2
module HTML
-
2
class << self
-
###
-
# Parse HTML. Convenience method for Nokogiri::HTML::Document.parse
-
2
def parse thing, url = nil, encoding = nil, options = XML::ParseOptions::DEFAULT_HTML, &block
-
Document.parse(thing, url, encoding, options, &block)
-
end
-
-
####
-
# Parse a fragment from +string+ in to a NodeSet.
-
2
def fragment string, encoding = nil
-
HTML::DocumentFragment.parse string, encoding
-
end
-
end
-
-
# Instance of Nokogiri::HTML::EntityLookup
-
2
NamedCharacters = EntityLookup.new
-
end
-
end
-
2
module Nokogiri
-
2
module HTML
-
###
-
# Nokogiri HTML builder is used for building HTML documents. It is very
-
# similar to the Nokogiri::XML::Builder. In fact, you should go read the
-
# documentation for Nokogiri::XML::Builder before reading this
-
# documentation.
-
#
-
# == Synopsis:
-
#
-
# Create an HTML document with a body that has an onload attribute, and a
-
# span tag with a class of "bold" that has content of "Hello world".
-
#
-
# builder = Nokogiri::HTML::Builder.new do |doc|
-
# doc.html {
-
# doc.body(:onload => 'some_func();') {
-
# doc.span.bold {
-
# doc.text "Hello world"
-
# }
-
# }
-
# }
-
# end
-
# puts builder.to_html
-
#
-
# The HTML builder inherits from the XML builder, so make sure to read the
-
# Nokogiri::XML::Builder documentation.
-
2
class Builder < Nokogiri::XML::Builder
-
###
-
# Convert the builder to HTML
-
2
def to_html
-
@doc.to_html
-
end
-
end
-
end
-
end
-
2
module Nokogiri
-
2
module HTML
-
2
class Document < Nokogiri::XML::Document
-
###
-
# Get the meta tag encoding for this document. If there is no meta tag,
-
# then nil is returned.
-
2
def meta_encoding
-
case
-
when meta = at('//meta[@charset]')
-
meta[:charset]
-
when meta = meta_content_type
-
meta['content'][/charset\s*=\s*([\w-]+)/i, 1]
-
end
-
end
-
-
###
-
# Set the meta tag encoding for this document.
-
#
-
# If an meta encoding tag is already present, its content is
-
# replaced with the given text.
-
#
-
# Otherwise, this method tries to create one at an appropriate
-
# place supplying head and/or html elements as necessary, which
-
# is inside a head element if any, and before any text node or
-
# content element (typically <body>) if any.
-
#
-
# The result when trying to set an encoding that is different
-
# from the document encoding is undefined.
-
#
-
# Beware in CRuby, that libxml2 automatically inserts a meta tag
-
# into a head element.
-
2
def meta_encoding= encoding
-
case
-
when meta = meta_content_type
-
meta['content'] = 'text/html; charset=%s' % encoding
-
encoding
-
when meta = at('//meta[@charset]')
-
meta['charset'] = encoding
-
else
-
meta = XML::Node.new('meta', self)
-
if dtd = internal_subset and dtd.html5_dtd?
-
meta['charset'] = encoding
-
else
-
meta['http-equiv'] = 'Content-Type'
-
meta['content'] = 'text/html; charset=%s' % encoding
-
end
-
-
case
-
when head = at('//head')
-
head.prepend_child(meta)
-
else
-
set_metadata_element(meta)
-
end
-
encoding
-
end
-
end
-
-
2
def meta_content_type
-
xpath('//meta[@http-equiv and boolean(@content)]').find { |node|
-
node['http-equiv'] =~ /\AContent-Type\z/i
-
}
-
end
-
2
private :meta_content_type
-
-
###
-
# Get the title string of this document. Return nil if there is
-
# no title tag.
-
2
def title
-
title = at('//title') and title.inner_text
-
end
-
-
###
-
# Set the title string of this document.
-
#
-
# If a title element is already present, its content is replaced
-
# with the given text.
-
#
-
# Otherwise, this method tries to create one at an appropriate
-
# place supplying head and/or html elements as necessary, which
-
# is inside a head element if any, right after a meta
-
# encoding/charset tag if any, and before any text node or
-
# content element (typically <body>) if any.
-
2
def title=(text)
-
tnode = XML::Text.new(text, self)
-
if title = at('//title')
-
title.children = tnode
-
return text
-
end
-
-
title = XML::Node.new('title', self) << tnode
-
case
-
when head = at('//head')
-
head << title
-
when meta = at('//meta[@charset]') || meta_content_type
-
# better put after charset declaration
-
meta.add_next_sibling(title)
-
else
-
set_metadata_element(title)
-
end
-
text
-
end
-
-
2
def set_metadata_element(element)
-
case
-
when head = at('//head')
-
head << element
-
when html = at('//html')
-
head = html.prepend_child(XML::Node.new('head', self))
-
head.prepend_child(element)
-
when first = children.find { |node|
-
case node
-
when XML::Element, XML::Text
-
true
-
end
-
}
-
# We reach here only if the underlying document model
-
# allows <html>/<head> elements to be omitted and does not
-
# automatically supply them.
-
first.add_previous_sibling(element)
-
else
-
html = add_child(XML::Node.new('html', self))
-
head = html.add_child(XML::Node.new('head', self))
-
head.prepend_child(element)
-
end
-
end
-
2
private :set_metadata_element
-
-
####
-
# Serialize Node using +options+. Save options can also be set using a
-
# block. See SaveOptions.
-
#
-
# These two statements are equivalent:
-
#
-
# node.serialize(:encoding => 'UTF-8', :save_with => FORMAT | AS_XML)
-
#
-
# or
-
#
-
# node.serialize(:encoding => 'UTF-8') do |config|
-
# config.format.as_xml
-
# end
-
#
-
2
def serialize options = {}
-
options[:save_with] ||= XML::Node::SaveOptions::DEFAULT_HTML
-
super
-
end
-
-
####
-
# Create a Nokogiri::XML::DocumentFragment from +tags+
-
2
def fragment tags = nil
-
DocumentFragment.new(self, tags, self.root)
-
end
-
-
2
class << self
-
###
-
# Parse HTML. +string_or_io+ may be a String, or any object that
-
# responds to _read_ and _close_ such as an IO, or StringIO.
-
# +url+ is resource where this document is located. +encoding+ is the
-
# encoding that should be used when processing the document. +options+
-
# is a number that sets options in the parser, such as
-
# Nokogiri::XML::ParseOptions::RECOVER. See the constants in
-
# Nokogiri::XML::ParseOptions.
-
2
def parse string_or_io, url = nil, encoding = nil, options = XML::ParseOptions::DEFAULT_HTML
-
-
7
options = Nokogiri::XML::ParseOptions.new(options) if Fixnum === options
-
# Give the options to the user
-
7
yield options if block_given?
-
-
7
if string_or_io.respond_to?(:encoding)
-
7
unless string_or_io.encoding.name == "ASCII-8BIT"
-
7
encoding ||= string_or_io.encoding.name
-
end
-
end
-
-
7
if string_or_io.respond_to?(:read)
-
url ||= string_or_io.respond_to?(:path) ? string_or_io.path : nil
-
if !encoding
-
# Libxml2's parser has poor support for encoding
-
# detection. First, it does not recognize the HTML5
-
# style meta charset declaration. Secondly, even if it
-
# successfully detects an encoding hint, it does not
-
# re-decode or re-parse the preceding part which may be
-
# garbled.
-
#
-
# EncodingReader aims to perform advanced encoding
-
# detection beyond what Libxml2 does, and to emulate
-
# rewinding of a stream and make Libxml2 redo parsing
-
# from the start when an encoding hint is found.
-
string_or_io = EncodingReader.new(string_or_io)
-
begin
-
return read_io(string_or_io, url, encoding, options.to_i)
-
rescue EncodingFound => e
-
encoding = e.found_encoding
-
end
-
end
-
return read_io(string_or_io, url, encoding, options.to_i)
-
end
-
-
# read_memory pukes on empty docs
-
7
return new if string_or_io.nil? or string_or_io.empty?
-
-
7
encoding ||= EncodingReader.detect_encoding(string_or_io)
-
-
7
read_memory(string_or_io, url, encoding, options.to_i)
-
end
-
end
-
-
2
class EncodingFound < StandardError # :nodoc:
-
2
attr_reader :found_encoding
-
-
2
def initialize(encoding)
-
@found_encoding = encoding
-
super("encoding found: %s" % encoding)
-
end
-
end
-
-
2
class EncodingReader # :nodoc:
-
2
class SAXHandler < Nokogiri::XML::SAX::Document # :nodoc:
-
2
attr_reader :encoding
-
-
2
def initialize
-
@encoding = nil
-
super()
-
end
-
-
2
def start_element(name, attrs = [])
-
return unless name == 'meta'
-
attr = Hash[attrs]
-
charset = attr['charset'] and
-
@encoding = charset
-
http_equiv = attr['http-equiv'] and
-
http_equiv.match(/\AContent-Type\z/i) and
-
content = attr['content'] and
-
m = content.match(/;\s*charset\s*=\s*([\w-]+)/) and
-
@encoding = m[1]
-
end
-
end
-
-
2
class JumpSAXHandler < SAXHandler
-
2
def initialize(jumptag)
-
@jumptag = jumptag
-
super()
-
end
-
-
2
def start_element(name, attrs = [])
-
super
-
throw @jumptag, @encoding if @encoding
-
throw @jumptag, nil if name =~ /\A(?:div|h1|img|p|br)\z/
-
end
-
end
-
-
2
def self.detect_encoding(chunk)
-
if Nokogiri.jruby? && EncodingReader.is_jruby_without_fix?
-
return EncodingReader.detect_encoding_for_jruby_without_fix(chunk)
-
end
-
m = chunk.match(/\A(<\?xml[ \t\r\n]+[^>]*>)/) and
-
return Nokogiri.XML(m[1]).encoding
-
-
if Nokogiri.jruby?
-
m = chunk.match(/(<meta\s)(.*)(charset\s*=\s*([\w-]+))(.*)/i) and
-
return m[4]
-
catch(:encoding_found) {
-
Nokogiri::HTML::SAX::Parser.new(JumpSAXHandler.new(:encoding_found)).parse(chunk)
-
nil
-
}
-
else
-
handler = SAXHandler.new
-
parser = Nokogiri::HTML::SAX::PushParser.new(handler)
-
parser << chunk rescue Nokogiri::SyntaxError
-
handler.encoding
-
end
-
end
-
-
2
def self.is_jruby_without_fix?
-
JRUBY_VERSION.split('.').join.to_i < 165
-
end
-
-
2
def self.detect_encoding_for_jruby_without_fix(chunk)
-
m = chunk.match(/\A(<\?xml[ \t\r\n]+[^>]*>)/) and
-
return Nokogiri.XML(m[1]).encoding
-
-
m = chunk.match(/(<meta\s)(.*)(charset\s*=\s*([\w-]+))(.*)/i) and
-
return m[4]
-
-
catch(:encoding_found) {
-
Nokogiri::HTML::SAX::Parser.new(JumpSAXHandler.new(:encoding_found.to_s)).parse(chunk)
-
nil
-
}
-
rescue Nokogiri::SyntaxError, RuntimeError
-
# Ignore parser errors that nokogiri may raise
-
nil
-
end
-
-
2
def initialize(io)
-
@io = io
-
@firstchunk = nil
-
@encoding_found = nil
-
end
-
-
# This method is used by the C extension so that
-
# Nokogiri::HTML::Document#read_io() does not leak memory when
-
# EncodingFound is raised.
-
2
attr_reader :encoding_found
-
-
2
def read(len)
-
# no support for a call without len
-
-
if !@firstchunk
-
@firstchunk = @io.read(len) or return nil
-
-
# This implementation expects that the first call from
-
# htmlReadIO() is made with a length long enough (~1KB) to
-
# achieve advanced encoding detection.
-
if encoding = EncodingReader.detect_encoding(@firstchunk)
-
# The first chunk is stored for the next read in retry.
-
raise @encoding_found = EncodingFound.new(encoding)
-
end
-
end
-
@encoding_found = nil
-
-
ret = @firstchunk.slice!(0, len)
-
if (len -= ret.length) > 0
-
rest = @io.read(len) and ret << rest
-
end
-
if ret.empty?
-
nil
-
else
-
ret
-
end
-
end
-
end
-
end
-
end
-
end
-
2
module Nokogiri
-
2
module HTML
-
2
class DocumentFragment < Nokogiri::XML::DocumentFragment
-
####
-
# Create a Nokogiri::XML::DocumentFragment from +tags+, using +encoding+
-
2
def self.parse tags, encoding = nil
-
doc = HTML::Document.new
-
-
encoding ||= tags.respond_to?(:encoding) ? tags.encoding.name : 'UTF-8'
-
doc.encoding = encoding
-
-
new(doc, tags)
-
end
-
-
2
def initialize document, tags = nil, ctx = nil
-
return self unless tags
-
-
if ctx
-
preexisting_errors = document.errors.dup
-
node_set = ctx.parse("<div>#{tags}</div>")
-
node_set.first.children.each { |child| child.parent = self } unless node_set.empty?
-
self.errors = document.errors - preexisting_errors
-
else
-
# This is a horrible hack, but I don't care
-
if tags.strip =~ /^<body/i
-
path = "/html/body"
-
else
-
path = "/html/body/node()"
-
end
-
-
temp_doc = HTML::Document.parse "<html><body>#{tags}", nil, document.encoding
-
temp_doc.xpath(path).each { |child| child.parent = self }
-
self.errors = temp_doc.errors
-
end
-
children
-
end
-
end
-
end
-
end
-
2
module Nokogiri
-
2
module HTML
-
2
class ElementDescription
-
###
-
# Is this element a block element?
-
2
def block?
-
!inline?
-
end
-
-
###
-
# Convert this description to a string
-
2
def to_s
-
"#{name}: #{description}"
-
end
-
-
###
-
# Inspection information
-
2
def inspect
-
"#<#{self.class.name}: #{name} #{description}>"
-
end
-
end
-
end
-
end
-
2
module Nokogiri
-
2
module HTML
-
2
class ElementDescription
-
-
# Methods are defined protected by method_defined? because at
-
# this point the C-library or Java library is already loaded,
-
# and we don't want to clobber any methods that have been
-
# defined there.
-
-
2
Desc = Struct.new("HTMLElementDescription", :name,
-
:startTag, :endTag, :saveEndTag,
-
:empty, :depr, :dtd, :isinline,
-
:desc,
-
:subelts, :defaultsubelt,
-
:attrs_opt, :attrs_depr, :attrs_req)
-
-
# This is filled in down below.
-
2
DefaultDescriptions = Hash.new()
-
-
2
def default_desc
-
DefaultDescriptions[name.downcase]
-
end
-
2
private :default_desc
-
-
2
unless method_defined? :implied_start_tag?
-
def implied_start_tag?
-
d = default_desc
-
d ? d.startTag : nil
-
end
-
end
-
-
2
unless method_defined? :implied_end_tag?
-
def implied_end_tag?
-
d = default_desc
-
d ? d.endTag : nil
-
end
-
end
-
-
2
unless method_defined? :save_end_tag?
-
def save_end_tag?
-
d = default_desc
-
d ? d.saveEndTag : nil
-
end
-
end
-
-
2
unless method_defined? :deprecated?
-
def deprecated?
-
d = default_desc
-
d ? d.depr : nil
-
end
-
end
-
-
2
unless method_defined? :description
-
def description
-
d = default_desc
-
d ? d.desc : nil
-
end
-
end
-
-
2
unless method_defined? :default_sub_element
-
def default_sub_element
-
d = default_desc
-
d ? d.defaultsubelt : nil
-
end
-
end
-
-
2
unless method_defined? :optional_attributes
-
def optional_attributes
-
d = default_desc
-
d ? d.attrs_opt : []
-
end
-
end
-
-
2
unless method_defined? :deprecated_attributes
-
def deprecated_attributes
-
d = default_desc
-
d ? d.attrs_depr : []
-
end
-
end
-
-
2
unless method_defined? :required_attributes
-
def required_attributes
-
d = default_desc
-
d ? d.attrs_req : []
-
end
-
end
-
-
###
-
# Default Element Descriptions (HTML 4.0) copied from
-
# libxml2/HTMLparser.c and libxml2/include/libxml/HTMLparser.h
-
#
-
# The copyright notice for those files and the following list of
-
# element and attribute descriptions is reproduced here:
-
#
-
# Except where otherwise noted in the source code (e.g. the
-
# files hash.c, list.c and the trio files, which are covered by
-
# a similar licence but with different Copyright notices) all
-
# the files are:
-
#
-
# Copyright (C) 1998-2003 Daniel Veillard. All Rights Reserved.
-
#
-
# Permission is hereby granted, free of charge, to any person
-
# obtaining a copy of this software and associated documentation
-
# files (the "Software"), to deal in the Software without
-
# restriction, including without limitation the rights to use,
-
# copy, modify, merge, publish, distribute, sublicense, and/or
-
# sell copies of the Software, and to permit persons to whom the
-
# Software is fur- nished to do so, subject to the following
-
# conditions:
-
-
# The above copyright notice and this permission notice shall be
-
# included in all copies or substantial portions of the
-
# Software.
-
-
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
-
# KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
-
# WARRANTIES OF MERCHANTABILITY, FIT- NESS FOR A PARTICULAR
-
# PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE DANIEL
-
# VEILLARD BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
-
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
-
# FROM, OUT OF OR IN CON- NECTION WITH THE SOFTWARE OR THE USE
-
# OR OTHER DEALINGS IN THE SOFTWARE.
-
-
# Except as contained in this notice, the name of Daniel
-
# Veillard shall not be used in advertising or otherwise to
-
# promote the sale, use or other deal- ings in this Software
-
# without prior written authorization from him.
-
-
# Attributes defined and categorized
-
2
FONTSTYLE = ["tt", "i", "b", "u", "s", "strike", "big", "small"]
-
2
PHRASE = ['em', 'strong', 'dfn', 'code', 'samp',
-
'kbd', 'var', 'cite', 'abbr', 'acronym']
-
2
SPECIAL = ['a', 'img', 'applet', 'embed', 'object', 'font','basefont',
-
'br', 'script', 'map', 'q', 'sub', 'sup', 'span', 'bdo',
-
'iframe']
-
2
PCDATA = []
-
2
HEADING = ['h1', 'h2', 'h3', 'h4', 'h5', 'h6']
-
2
LIST = ['ul', 'ol', 'dir', 'menu']
-
2
FORMCTRL = ['input', 'select', 'textarea', 'label', 'button']
-
2
BLOCK = [HEADING, LIST, 'pre', 'p', 'dl', 'div', 'center', 'noscript',
-
'noframes', 'blockquote', 'form', 'isindex', 'hr', 'table',
-
'fieldset', 'address']
-
2
INLINE = [PCDATA, FONTSTYLE, PHRASE, SPECIAL, FORMCTRL]
-
2
FLOW = [BLOCK, INLINE]
-
2
MODIFIER = []
-
2
EMPTY = []
-
-
2
HTML_FLOW = FLOW
-
2
HTML_INLINE = INLINE
-
2
HTML_PCDATA = PCDATA
-
2
HTML_CDATA = HTML_PCDATA
-
-
2
COREATTRS = ['id', 'class', 'style', 'title']
-
2
I18N = ['lang', 'dir']
-
2
EVENTS = ['onclick', 'ondblclick', 'onmousedown', 'onmouseup',
-
'onmouseover', 'onmouseout', 'onkeypress', 'onkeydown',
-
'onkeyup']
-
2
ATTRS = [COREATTRS, I18N,EVENTS]
-
2
CELLHALIGN = ['align', 'char', 'charoff']
-
2
CELLVALIGN = ['valign']
-
-
2
HTML_ATTRS = ATTRS
-
2
CORE_I18N_ATTRS = [COREATTRS, I18N]
-
2
CORE_ATTRS = COREATTRS
-
2
I18N_ATTRS = I18N
-
-
-
2
A_ATTRS = [ATTRS, 'charset', 'type', 'name',
-
'href', 'hreflang', 'rel', 'rev', 'accesskey', 'shape',
-
'coords', 'tabindex', 'onfocus', 'onblur']
-
2
TARGET_ATTR = ['target']
-
2
ROWS_COLS_ATTR = ['rows', 'cols']
-
2
ALT_ATTR = ['alt']
-
2
SRC_ALT_ATTRS = ['src', 'alt']
-
2
HREF_ATTRS = ['href']
-
2
CLEAR_ATTRS = ['clear']
-
2
INLINE_P = [INLINE, 'p']
-
-
2
FLOW_PARAM = [FLOW, 'param']
-
2
APPLET_ATTRS = [COREATTRS , 'codebase',
-
'archive', 'alt', 'name', 'height', 'width', 'align',
-
'hspace', 'vspace']
-
2
AREA_ATTRS = ['shape', 'coords', 'href', 'nohref',
-
'tabindex', 'accesskey', 'onfocus', 'onblur']
-
2
BASEFONT_ATTRS = ['id', 'size', 'color', 'face']
-
2
QUOTE_ATTRS = [ATTRS, 'cite']
-
2
BODY_CONTENTS = [FLOW, 'ins', 'del']
-
2
BODY_ATTRS = [ATTRS, 'onload', 'onunload']
-
2
BODY_DEPR = ['background', 'bgcolor', 'text',
-
'link', 'vlink', 'alink']
-
2
BUTTON_ATTRS = [ATTRS, 'name', 'value', 'type',
-
'disabled', 'tabindex', 'accesskey', 'onfocus', 'onblur']
-
-
-
2
COL_ATTRS = [ATTRS, 'span', 'width', CELLHALIGN, CELLVALIGN]
-
2
COL_ELT = ['col']
-
2
EDIT_ATTRS = [ATTRS, 'datetime', 'cite']
-
2
COMPACT_ATTRS = [ATTRS, 'compact']
-
2
DL_CONTENTS = ['dt', 'dd']
-
2
COMPACT_ATTR = ['compact']
-
2
LABEL_ATTR = ['label']
-
2
FIELDSET_CONTENTS = [FLOW, 'legend' ]
-
2
FONT_ATTRS = [COREATTRS, I18N, 'size', 'color', 'face' ]
-
2
FORM_CONTENTS = [HEADING, LIST, INLINE, 'pre', 'p', 'div', 'center',
-
'noscript', 'noframes', 'blockquote', 'isindex', 'hr',
-
'table', 'fieldset', 'address']
-
2
FORM_ATTRS = [ATTRS, 'method', 'enctype', 'accept', 'name', 'onsubmit',
-
'onreset', 'accept-charset']
-
2
FRAME_ATTRS = [COREATTRS, 'longdesc', 'name', 'src', 'frameborder',
-
'marginwidth', 'marginheight', 'noresize', 'scrolling' ]
-
2
FRAMESET_ATTRS = [COREATTRS, 'rows', 'cols', 'onload', 'onunload']
-
2
FRAMESET_CONTENTS = ['frameset', 'frame', 'noframes']
-
2
HEAD_ATTRS = [I18N, 'profile']
-
2
HEAD_CONTENTS = ['title', 'isindex', 'base', 'script', 'style', 'meta',
-
'link', 'object']
-
2
HR_DEPR = ['align', 'noshade', 'size', 'width']
-
2
VERSION_ATTR = ['version']
-
2
HTML_CONTENT = ['head', 'body', 'frameset']
-
2
IFRAME_ATTRS = [COREATTRS, 'longdesc', 'name', 'src', 'frameborder',
-
'marginwidth', 'marginheight', 'scrolling', 'align',
-
'height', 'width']
-
2
IMG_ATTRS = [ATTRS, 'longdesc', 'name', 'height', 'width', 'usemap',
-
'ismap']
-
2
EMBED_ATTRS = [COREATTRS, 'align', 'alt', 'border', 'code', 'codebase',
-
'frameborder', 'height', 'hidden', 'hspace', 'name',
-
'palette', 'pluginspace', 'pluginurl', 'src', 'type',
-
'units', 'vspace', 'width']
-
2
INPUT_ATTRS = [ATTRS, 'type', 'name', 'value', 'checked', 'disabled',
-
'readonly', 'size', 'maxlength', 'src', 'alt', 'usemap',
-
'ismap', 'tabindex', 'accesskey', 'onfocus', 'onblur',
-
'onselect', 'onchange', 'accept']
-
2
PROMPT_ATTRS = [COREATTRS, I18N, 'prompt']
-
2
LABEL_ATTRS = [ATTRS, 'for', 'accesskey', 'onfocus', 'onblur']
-
2
LEGEND_ATTRS = [ATTRS, 'accesskey']
-
2
ALIGN_ATTR = ['align']
-
2
LINK_ATTRS = [ATTRS, 'charset', 'href', 'hreflang', 'type', 'rel', 'rev',
-
'media']
-
2
MAP_CONTENTS = [BLOCK, 'area']
-
2
NAME_ATTR = ['name']
-
2
ACTION_ATTR = ['action']
-
2
BLOCKLI_ELT = [BLOCK, 'li']
-
2
META_ATTRS = [I18N, 'http-equiv', 'name', 'scheme']
-
2
CONTENT_ATTR = ['content']
-
2
TYPE_ATTR = ['type']
-
2
NOFRAMES_CONTENT = ['body', FLOW, MODIFIER]
-
2
OBJECT_CONTENTS = [FLOW, 'param']
-
2
OBJECT_ATTRS = [ATTRS, 'declare', 'classid', 'codebase', 'data', 'type',
-
'codetype', 'archive', 'standby', 'height', 'width',
-
'usemap', 'name', 'tabindex']
-
2
OBJECT_DEPR = ['align', 'border', 'hspace', 'vspace']
-
2
OL_ATTRS = ['type', 'compact', 'start']
-
2
OPTION_ELT = ['option']
-
2
OPTGROUP_ATTRS = [ATTRS, 'disabled']
-
2
OPTION_ATTRS = [ATTRS, 'disabled', 'label', 'selected', 'value']
-
2
PARAM_ATTRS = ['id', 'value', 'valuetype', 'type']
-
2
WIDTH_ATTR = ['width']
-
2
PRE_CONTENT = [PHRASE, 'tt', 'i', 'b', 'u', 's', 'strike', 'a', 'br',
-
'script', 'map', 'q', 'span', 'bdo', 'iframe']
-
2
SCRIPT_ATTRS = ['charset', 'src', 'defer', 'event', 'for']
-
2
LANGUAGE_ATTR = ['language']
-
2
SELECT_CONTENT = ['optgroup', 'option']
-
2
SELECT_ATTRS = [ATTRS, 'name', 'size', 'multiple', 'disabled', 'tabindex',
-
'onfocus', 'onblur', 'onchange']
-
2
STYLE_ATTRS = [I18N, 'media', 'title']
-
2
TABLE_ATTRS = [ATTRS, 'summary', 'width', 'border', 'frame', 'rules',
-
'cellspacing', 'cellpadding', 'datapagesize']
-
2
TABLE_DEPR = ['align', 'bgcolor']
-
2
TABLE_CONTENTS = ['caption', 'col', 'colgroup', 'thead', 'tfoot', 'tbody',
-
'tr']
-
2
TR_ELT = ['tr']
-
2
TALIGN_ATTRS = [ATTRS, CELLHALIGN, CELLVALIGN]
-
2
TH_TD_DEPR = ['nowrap', 'bgcolor', 'width', 'height']
-
2
TH_TD_ATTR = [ATTRS, 'abbr', 'axis', 'headers', 'scope', 'rowspan',
-
'colspan', CELLHALIGN, CELLVALIGN]
-
2
TEXTAREA_ATTRS = [ATTRS, 'name', 'disabled', 'readonly', 'tabindex',
-
'accesskey', 'onfocus', 'onblur', 'onselect',
-
'onchange']
-
2
TR_CONTENTS = ['th', 'td']
-
2
BGCOLOR_ATTR = ['bgcolor']
-
2
LI_ELT = ['li']
-
2
UL_DEPR = ['type', 'compact']
-
2
DIR_ATTR = ['dir']
-
-
[
-
['a', false, false, false, false, false, :any, true,
-
'anchor ',
-
HTML_INLINE, nil, A_ATTRS, TARGET_ATTR, []
-
],
-
['abbr', false, false, false, false, false, :any, true,
-
'abbreviated form',
-
HTML_INLINE, nil, HTML_ATTRS, [], []
-
],
-
['acronym', false, false, false, false, false, :any, true, '',
-
HTML_INLINE, nil, HTML_ATTRS, [], []
-
],
-
['address', false, false, false, false, false, :any, false,
-
'information on author',
-
INLINE_P , nil, HTML_ATTRS, [], []
-
],
-
['applet', false, false, false, false, true, :loose, true,
-
'java applet ',
-
FLOW_PARAM, nil, [], APPLET_ATTRS, []
-
],
-
['area', false, true, true, true, false, :any, false,
-
'client-side image map area ',
-
EMPTY, nil, AREA_ATTRS, TARGET_ATTR, ALT_ATTR
-
],
-
['b', false, true, false, false, false, :any, true,
-
'bold text style',
-
HTML_INLINE, nil, HTML_ATTRS, [], []
-
],
-
['base', false, true, true, true, false, :any, false,
-
'document base uri ',
-
EMPTY, nil, [], TARGET_ATTR, HREF_ATTRS
-
],
-
['basefont', false, true, true, true, true, :loose, true,
-
'base font size ',
-
EMPTY, nil, [], BASEFONT_ATTRS, []
-
],
-
['bdo', false, false, false, false, false, :any, true,
-
'i18n bidi over-ride ',
-
HTML_INLINE, nil, CORE_I18N_ATTRS, [], DIR_ATTR
-
],
-
['big', false, true, false, false, false, :any, true,
-
'large text style',
-
HTML_INLINE, nil, HTML_ATTRS, [], []
-
],
-
['blockquote', false, false, false, false, false, :any, false,
-
'long quotation ',
-
HTML_FLOW, nil, QUOTE_ATTRS, [], []
-
],
-
['body', true, true, false, false, false, :any, false,
-
'document body ',
-
BODY_CONTENTS, 'div', BODY_ATTRS, BODY_DEPR, []
-
],
-
['br', false, true, true, true, false, :any, true,
-
'forced line break ',
-
EMPTY, nil, CORE_ATTRS, CLEAR_ATTRS, []
-
],
-
['button', false, false, false, false, false, :any, true,
-
'push button ',
-
[HTML_FLOW, MODIFIER], nil, BUTTON_ATTRS, [], []
-
],
-
['caption', false, false, false, false, false, :any, false,
-
'table caption ',
-
HTML_INLINE, nil, HTML_ATTRS, [], []
-
],
-
['center', false, true, false, false, true, :loose, false,
-
'shorthand for div align=center ',
-
HTML_FLOW, nil, [], HTML_ATTRS, []
-
],
-
['cite', false, false, false, false, false, :any, true, 'citation',
-
HTML_INLINE, nil, HTML_ATTRS, [], []
-
],
-
['code', false, false, false, false, false, :any, true,
-
'computer code fragment',
-
HTML_INLINE, nil, HTML_ATTRS, [], []
-
],
-
['col', false, true, true, true, false, :any, false, 'table column ',
-
EMPTY, nil, COL_ATTRS, [], []
-
],
-
['colgroup', false, true, false, false, false, :any, false,
-
'table column group ',
-
COL_ELT, 'col', COL_ATTRS, [], []
-
],
-
['dd', false, true, false, false, false, :any, false,
-
'definition description ',
-
HTML_FLOW, nil, HTML_ATTRS, [], []
-
],
-
['del', false, false, false, false, false, :any, true,
-
'deleted text ',
-
HTML_FLOW, nil, EDIT_ATTRS, [], []
-
],
-
['dfn', false, false, false, false, false, :any, true,
-
'instance definition',
-
HTML_INLINE, nil, HTML_ATTRS, [], []
-
],
-
['dir', false, false, false, false, true, :loose, false,
-
'directory list',
-
BLOCKLI_ELT, 'li', [], COMPACT_ATTRS, []
-
],
-
['div', false, false, false, false, false, :any, false,
-
'generic language/style container',
-
HTML_FLOW, nil, HTML_ATTRS, ALIGN_ATTR, []
-
],
-
['dl', false, false, false, false, false, :any, false,
-
'definition list ',
-
DL_CONTENTS, 'dd', HTML_ATTRS, COMPACT_ATTR, []
-
],
-
['dt', false, true, false, false, false, :any, false,
-
'definition term ',
-
HTML_INLINE, nil, HTML_ATTRS, [], []
-
],
-
['em', false, true, false, false, false, :any, true,
-
'emphasis',
-
HTML_INLINE, nil, HTML_ATTRS, [], []
-
],
-
['embed', false, true, false, false, true, :loose, true,
-
'generic embedded object ',
-
EMPTY, nil, EMBED_ATTRS, [], []
-
],
-
['fieldset', false, false, false, false, false, :any, false,
-
'form control group ',
-
FIELDSET_CONTENTS, nil, HTML_ATTRS, [], []
-
],
-
['font', false, true, false, false, true, :loose, true,
-
'local change to font ',
-
HTML_INLINE, nil, [], FONT_ATTRS, []
-
],
-
['form', false, false, false, false, false, :any, false,
-
'interactive form ',
-
FORM_CONTENTS, 'fieldset', FORM_ATTRS, TARGET_ATTR, ACTION_ATTR
-
],
-
['frame', false, true, true, true, false, :frameset, false,
-
'subwindow ',
-
EMPTY, nil, [], FRAME_ATTRS, []
-
],
-
['frameset', false, false, false, false, false, :frameset, false,
-
'window subdivision',
-
FRAMESET_CONTENTS, 'noframes', [], FRAMESET_ATTRS, []
-
],
-
['htrue', false, false, false, false, false, :any, false,
-
'heading ',
-
HTML_INLINE, nil, HTML_ATTRS, ALIGN_ATTR, []
-
],
-
['htrue', false, false, false, false, false, :any, false,
-
'heading ',
-
HTML_INLINE, nil, HTML_ATTRS, ALIGN_ATTR, []
-
],
-
['htrue', false, false, false, false, false, :any, false,
-
'heading ',
-
HTML_INLINE, nil, HTML_ATTRS, ALIGN_ATTR, []
-
],
-
['h4', false, false, false, false, false, :any, false,
-
'heading ',
-
HTML_INLINE, nil, HTML_ATTRS, ALIGN_ATTR, []
-
],
-
['h5', false, false, false, false, false, :any, false,
-
'heading ',
-
HTML_INLINE, nil, HTML_ATTRS, ALIGN_ATTR, []
-
],
-
['h6', false, false, false, false, false, :any, false,
-
'heading ',
-
HTML_INLINE, nil, HTML_ATTRS, ALIGN_ATTR, []
-
],
-
['head', true, true, false, false, false, :any, false,
-
'document head ',
-
HEAD_CONTENTS, nil, HEAD_ATTRS, [], []
-
],
-
['hr', false, true, true, true, false, :any, false,
-
'horizontal rule ',
-
EMPTY, nil, HTML_ATTRS, HR_DEPR, []
-
],
-
['html', true, true, false, false, false, :any, false,
-
'document root element ',
-
HTML_CONTENT, nil, I18N_ATTRS, VERSION_ATTR, []
-
],
-
['i', false, true, false, false, false, :any, true,
-
'italic text style',
-
HTML_INLINE, nil, HTML_ATTRS, [], []
-
],
-
['iframe', false, false, false, false, false, :any, true,
-
'inline subwindow ',
-
HTML_FLOW, nil, [], IFRAME_ATTRS, []
-
],
-
['img', false, true, true, true, false, :any, true,
-
'embedded image ',
-
EMPTY, nil, IMG_ATTRS, ALIGN_ATTR, SRC_ALT_ATTRS
-
],
-
['input', false, true, true, true, false, :any, true,
-
'form control ',
-
EMPTY, nil, INPUT_ATTRS, ALIGN_ATTR, []
-
],
-
['ins', false, false, false, false, false, :any, true,
-
'inserted text',
-
HTML_FLOW, nil, EDIT_ATTRS, [], []
-
],
-
['isindex', false, true, true, true, true, :loose, false,
-
'single line prompt ',
-
EMPTY, nil, [], PROMPT_ATTRS, []
-
],
-
['kbd', false, false, false, false, false, :any, true,
-
'text to be entered by the user',
-
HTML_INLINE, nil, HTML_ATTRS, [], []
-
],
-
['label', false, false, false, false, false, :any, true,
-
'form field label text ',
-
[HTML_INLINE, MODIFIER], nil, LABEL_ATTRS, [], []
-
],
-
['legend', false, false, false, false, false, :any, false,
-
'fieldset legend ',
-
HTML_INLINE, nil, LEGEND_ATTRS, ALIGN_ATTR, []
-
],
-
['li', false, true, true, false, false, :any, false,
-
'list item ',
-
HTML_FLOW, nil, HTML_ATTRS, [], []
-
],
-
['link', false, true, true, true, false, :any, false,
-
'a media-independent link ',
-
EMPTY, nil, LINK_ATTRS, TARGET_ATTR, []
-
],
-
['map', false, false, false, false, false, :any, true,
-
'client-side image map ',
-
MAP_CONTENTS, nil, HTML_ATTRS, [], NAME_ATTR
-
],
-
['menu', false, false, false, false, true, :loose, false,
-
'menu list ',
-
BLOCKLI_ELT, nil, [], COMPACT_ATTRS, []
-
],
-
['meta', false, true, true, true, false, :any, false,
-
'generic metainformation ',
-
EMPTY, nil, META_ATTRS, [], CONTENT_ATTR
-
],
-
['noframes', false, false, false, false, false, :frameset, false,
-
'alternate content container for non frame-based rendering ',
-
NOFRAMES_CONTENT, 'body', HTML_ATTRS, [], []
-
],
-
['noscript', false, false, false, false, false, :any, false,
-
'alternate content container for non script-based rendering ',
-
HTML_FLOW, 'div', HTML_ATTRS, [], []
-
],
-
['object', false, false, false, false, false, :any, true,
-
'generic embedded object ',
-
OBJECT_CONTENTS, 'div', OBJECT_ATTRS, OBJECT_DEPR, []
-
],
-
['ol', false, false, false, false, false, :any, false,
-
'ordered list ',
-
LI_ELT, 'li', HTML_ATTRS, OL_ATTRS, []
-
],
-
['optgroup', false, false, false, false, false, :any, false,
-
'option group ',
-
OPTION_ELT, 'option', OPTGROUP_ATTRS, [], LABEL_ATTR
-
],
-
['option', false, true, false, false, false, :any, false,
-
'selectable choice ',
-
HTML_PCDATA, nil, OPTION_ATTRS, [], []
-
],
-
['p', false, true, false, false, false, :any, false,
-
'paragraph ',
-
HTML_INLINE, nil, HTML_ATTRS, ALIGN_ATTR, []
-
],
-
['param', false, true, true, true, false, :any, false,
-
'named property value ',
-
EMPTY, nil, PARAM_ATTRS, [], NAME_ATTR
-
],
-
['pre', false, false, false, false, false, :any, false,
-
'preformatted text ',
-
PRE_CONTENT, nil, HTML_ATTRS, WIDTH_ATTR, []
-
],
-
['q', false, false, false, false, false, :any, true,
-
'short inline quotation ',
-
HTML_INLINE, nil, QUOTE_ATTRS, [], []
-
],
-
['s', false, true, false, false, true, :loose, true,
-
'strike-through text style',
-
HTML_INLINE, nil, [], HTML_ATTRS, []
-
],
-
['samp', false, false, false, false, false, :any, true,
-
'sample program output, scripts, etc.',
-
HTML_INLINE, nil, HTML_ATTRS, [], []
-
],
-
['script', false, false, false, false, false, :any, true,
-
'script statements ',
-
HTML_CDATA, nil, SCRIPT_ATTRS, LANGUAGE_ATTR, TYPE_ATTR
-
],
-
['select', false, false, false, false, false, :any, true,
-
'option selector ',
-
SELECT_CONTENT, nil, SELECT_ATTRS, [], []
-
],
-
['small', false, true, false, false, false, :any, true,
-
'small text style',
-
HTML_INLINE, nil, HTML_ATTRS, [], []
-
],
-
['span', false, false, false, false, false, :any, true,
-
'generic language/style container ',
-
HTML_INLINE, nil, HTML_ATTRS, [], []
-
],
-
['strike', false, true, false, false, true, :loose, true,
-
'strike-through text',
-
HTML_INLINE, nil, [], HTML_ATTRS, []
-
],
-
['strong', false, true, false, false, false, :any, true,
-
'strong emphasis',
-
HTML_INLINE, nil, HTML_ATTRS, [], []
-
],
-
['style', false, false, false, false, false, :any, false,
-
'style info ',
-
HTML_CDATA, nil, STYLE_ATTRS, [], TYPE_ATTR
-
],
-
['sub', false, true, false, false, false, :any, true,
-
'subscript',
-
HTML_INLINE, nil, HTML_ATTRS, [], []
-
],
-
['sup', false, true, false, false, false, :any, true,
-
'superscript ',
-
HTML_INLINE, nil, HTML_ATTRS, [], []
-
],
-
['table', false, false, false, false, false, :any, false,
-
'',
-
TABLE_CONTENTS, 'tr', TABLE_ATTRS, TABLE_DEPR, []
-
],
-
['tbody', true, false, false, false, false, :any, false,
-
'table body ',
-
TR_ELT, 'tr', TALIGN_ATTRS, [], []
-
],
-
['td', false, false, false, false, false, :any, false,
-
'table data cell',
-
HTML_FLOW, nil, TH_TD_ATTR, TH_TD_DEPR, []
-
],
-
['textarea', false, false, false, false, false, :any, true,
-
'multi-line text field ',
-
HTML_PCDATA, nil, TEXTAREA_ATTRS, [], ROWS_COLS_ATTR
-
],
-
['tfoot', false, true, false, false, false, :any, false,
-
'table footer ',
-
TR_ELT, 'tr', TALIGN_ATTRS, [], []
-
],
-
['th', false, true, false, false, false, :any, false,
-
'table header cell',
-
HTML_FLOW, nil, TH_TD_ATTR, TH_TD_DEPR, []
-
],
-
['thead', false, true, false, false, false, :any, false,
-
'table header ',
-
TR_ELT, 'tr', TALIGN_ATTRS, [], []
-
],
-
['title', false, false, false, false, false, :any, false,
-
'document title ',
-
HTML_PCDATA, nil, I18N_ATTRS, [], []
-
],
-
['tr', false, false, false, false, false, :any, false,
-
'table row ',
-
TR_CONTENTS, 'td', TALIGN_ATTRS, BGCOLOR_ATTR, []
-
],
-
['tt', false, true, false, false, false, :any, true,
-
'teletype or monospaced text style',
-
HTML_INLINE, nil, HTML_ATTRS, [], []
-
],
-
['u', false, true, false, false, true, :loose, true,
-
'underlined text style',
-
HTML_INLINE, nil, [], HTML_ATTRS, []
-
],
-
['ul', false, false, false, false, false, :any, false,
-
'unordered list ',
-
LI_ELT, 'li', HTML_ATTRS, UL_DEPR, []
-
],
-
['var', false, false, false, false, false, :any, true,
-
'instance of a variable or program argument',
-
HTML_INLINE, nil, HTML_ATTRS, [], []
-
]
-
2
].each do |descriptor|
-
184
name = descriptor[0]
-
-
184
begin
-
184
d = Desc.new(*descriptor)
-
-
# flatten all the attribute lists (Ruby1.9, *[a,b,c] can be
-
# used to flatten a literal list, but not in Ruby1.8).
-
184
d[:subelts] = d[:subelts].flatten
-
184
d[:attrs_opt] = d[:attrs_opt].flatten
-
184
d[:attrs_depr] = d[:attrs_depr].flatten
-
184
d[:attrs_req] = d[:attrs_req].flatten
-
rescue => e
-
p name
-
raise e
-
end
-
-
184
DefaultDescriptions[name] = d
-
end
-
end
-
end
-
end
-
2
module Nokogiri
-
2
module HTML
-
2
class EntityDescription < Struct.new(:value, :name, :description); end
-
-
2
class EntityLookup
-
###
-
# Look up entity with +name+
-
2
def [] name
-
(val = get(name)) && val.value
-
end
-
end
-
end
-
end
-
2
module Nokogiri
-
2
module HTML
-
###
-
# Nokogiri lets you write a SAX parser to process HTML but get HTML
-
# correction features.
-
#
-
# See Nokogiri::HTML::SAX::Parser for a basic example of using a
-
# SAX parser with HTML.
-
#
-
# For more information on SAX parsers, see Nokogiri::XML::SAX
-
2
module SAX
-
###
-
# This class lets you perform SAX style parsing on HTML with HTML
-
# error correction.
-
#
-
# Here is a basic usage example:
-
#
-
# class MyDoc < Nokogiri::XML::SAX::Document
-
# def start_element name, attributes = []
-
# puts "found a #{name}"
-
# end
-
# end
-
#
-
# parser = Nokogiri::HTML::SAX::Parser.new(MyDoc.new)
-
# parser.parse(File.read(ARGV[0], mode: 'rb'))
-
#
-
# For more information on SAX parsers, see Nokogiri::XML::SAX
-
2
class Parser < Nokogiri::XML::SAX::Parser
-
###
-
# Parse html stored in +data+ using +encoding+
-
2
def parse_memory data, encoding = 'UTF-8'
-
raise ArgumentError unless data
-
return unless data.length > 0
-
ctx = ParserContext.memory(data, encoding)
-
yield ctx if block_given?
-
ctx.parse_with self
-
end
-
-
###
-
# Parse a file with +filename+
-
2
def parse_file filename, encoding = 'UTF-8'
-
raise ArgumentError unless filename
-
raise Errno::ENOENT unless File.exist?(filename)
-
raise Errno::EISDIR if File.directory?(filename)
-
ctx = ParserContext.file(filename, encoding)
-
yield ctx if block_given?
-
ctx.parse_with self
-
end
-
end
-
end
-
end
-
end
-
2
module Nokogiri
-
2
module HTML
-
2
module SAX
-
###
-
# Context for HTML SAX parsers. This class is usually not instantiated
-
# by the user. Instead, you should be looking at
-
# Nokogiri::HTML::SAX::Parser
-
2
class ParserContext < Nokogiri::XML::SAX::ParserContext
-
2
def self.new thing, encoding = 'UTF-8'
-
[:read, :close].all? { |x| thing.respond_to?(x) } ? super :
-
memory(thing, encoding)
-
end
-
end
-
end
-
end
-
end
-
2
module Nokogiri
-
2
module HTML
-
2
module SAX
-
2
class PushParser
-
-
# The Nokogiri::HTML::SAX::Document on which the PushParser will be
-
# operating
-
2
attr_accessor :document
-
-
2
def initialize(doc = HTML::SAX::Document.new, file_name = nil, encoding = 'UTF-8')
-
@document = doc
-
@encoding = encoding
-
@sax_parser = HTML::SAX::Parser.new(doc, @encoding)
-
-
## Create our push parser context
-
initialize_native(@sax_parser, file_name, encoding)
-
end
-
-
###
-
# Write a +chunk+ of HTML to the PushParser. Any callback methods
-
# that can be called will be called immediately.
-
2
def write chunk, last_chunk = false
-
native_write(chunk, last_chunk)
-
end
-
2
alias :<< :write
-
-
###
-
# Finish the parsing. This method is only necessary for
-
# Nokogiri::HTML::SAX::Document#end_document to be called.
-
2
def finish
-
write '', true
-
end
-
end
-
end
-
end
-
end
-
2
module Nokogiri
-
2
class SyntaxError < ::StandardError
-
end
-
end
-
2
require 'nokogiri/xml/pp'
-
2
require 'nokogiri/xml/parse_options'
-
2
require 'nokogiri/xml/sax'
-
2
require 'nokogiri/xml/searchable'
-
2
require 'nokogiri/xml/node'
-
2
require 'nokogiri/xml/attribute_decl'
-
2
require 'nokogiri/xml/element_decl'
-
2
require 'nokogiri/xml/element_content'
-
2
require 'nokogiri/xml/character_data'
-
2
require 'nokogiri/xml/namespace'
-
2
require 'nokogiri/xml/attr'
-
2
require 'nokogiri/xml/dtd'
-
2
require 'nokogiri/xml/cdata'
-
2
require 'nokogiri/xml/text'
-
2
require 'nokogiri/xml/document'
-
2
require 'nokogiri/xml/document_fragment'
-
2
require 'nokogiri/xml/processing_instruction'
-
2
require 'nokogiri/xml/node_set'
-
2
require 'nokogiri/xml/syntax_error'
-
2
require 'nokogiri/xml/xpath'
-
2
require 'nokogiri/xml/xpath_context'
-
2
require 'nokogiri/xml/builder'
-
2
require 'nokogiri/xml/reader'
-
2
require 'nokogiri/xml/notation'
-
2
require 'nokogiri/xml/entity_decl'
-
2
require 'nokogiri/xml/schema'
-
2
require 'nokogiri/xml/relax_ng'
-
-
2
module Nokogiri
-
2
class << self
-
###
-
# Parse XML. Convenience method for Nokogiri::XML::Document.parse
-
2
def XML thing, url = nil, encoding = nil, options = XML::ParseOptions::DEFAULT_XML, &block
-
Nokogiri::XML::Document.parse(thing, url, encoding, options, &block)
-
end
-
end
-
-
2
module XML
-
# Original C14N 1.0 spec canonicalization
-
2
XML_C14N_1_0 = 0
-
# Exclusive C14N 1.0 spec canonicalization
-
2
XML_C14N_EXCLUSIVE_1_0 = 1
-
# C14N 1.1 spec canonicalization
-
2
XML_C14N_1_1 = 2
-
2
class << self
-
###
-
# Parse an XML document using the Nokogiri::XML::Reader API. See
-
# Nokogiri::XML::Reader for mor information
-
2
def Reader string_or_io, url = nil, encoding = nil, options = ParseOptions::STRICT
-
-
options = Nokogiri::XML::ParseOptions.new(options) if Fixnum === options
-
# Give the options to the user
-
yield options if block_given?
-
-
if string_or_io.respond_to? :read
-
return Reader.from_io(string_or_io, url, encoding, options.to_i)
-
end
-
Reader.from_memory(string_or_io, url, encoding, options.to_i)
-
end
-
-
###
-
# Parse XML. Convenience method for Nokogiri::XML::Document.parse
-
2
def parse thing, url = nil, encoding = nil, options = ParseOptions::DEFAULT_XML, &block
-
Document.parse(thing, url, encoding, options, &block)
-
end
-
-
####
-
# Parse a fragment from +string+ in to a NodeSet.
-
2
def fragment string
-
XML::DocumentFragment.parse(string)
-
end
-
end
-
end
-
end
-
2
module Nokogiri
-
2
module XML
-
2
class Attr < Node
-
2
alias :value :content
-
2
alias :to_s :content
-
2
alias :content= :value=
-
-
2
private
-
2
def inspect_attributes
-
[:name, :namespace, :value]
-
end
-
end
-
end
-
end
-
2
module Nokogiri
-
2
module XML
-
###
-
# Represents an attribute declaration in a DTD
-
2
class AttributeDecl < Nokogiri::XML::Node
-
2
undef_method :attribute_nodes
-
2
undef_method :attributes
-
2
undef_method :content
-
2
undef_method :namespace
-
2
undef_method :namespace_definitions
-
2
undef_method :line if method_defined?(:line)
-
-
2
def inspect
-
"#<#{self.class.name}:#{sprintf("0x%x", object_id)} #{to_s.inspect}>"
-
end
-
end
-
end
-
end
-
2
module Nokogiri
-
2
module XML
-
###
-
# Nokogiri builder can be used for building XML and HTML documents.
-
#
-
# == Synopsis:
-
#
-
# builder = Nokogiri::XML::Builder.new do |xml|
-
# xml.root {
-
# xml.products {
-
# xml.widget {
-
# xml.id_ "10"
-
# xml.name "Awesome widget"
-
# }
-
# }
-
# }
-
# end
-
# puts builder.to_xml
-
#
-
# Will output:
-
#
-
# <?xml version="1.0"?>
-
# <root>
-
# <products>
-
# <widget>
-
# <id>10</id>
-
# <name>Awesome widget</name>
-
# </widget>
-
# </products>
-
# </root>
-
#
-
#
-
# === Builder scope
-
#
-
# The builder allows two forms. When the builder is supplied with a block
-
# that has a parameter, the outside scope is maintained. This means you
-
# can access variables that are outside your builder. If you don't need
-
# outside scope, you can use the builder without the "xml" prefix like
-
# this:
-
#
-
# builder = Nokogiri::XML::Builder.new do
-
# root {
-
# products {
-
# widget {
-
# id_ "10"
-
# name "Awesome widget"
-
# }
-
# }
-
# }
-
# end
-
#
-
# == Special Tags
-
#
-
# The builder works by taking advantage of method_missing. Unfortunately
-
# some methods are defined in ruby that are difficult or dangerous to
-
# remove. You may want to create tags with the name "type", "class", and
-
# "id" for example. In that case, you can use an underscore to
-
# disambiguate your tag name from the method call.
-
#
-
# Here is an example of using the underscore to disambiguate tag names from
-
# ruby methods:
-
#
-
# @objects = [Object.new, Object.new, Object.new]
-
#
-
# builder = Nokogiri::XML::Builder.new do |xml|
-
# xml.root {
-
# xml.objects {
-
# @objects.each do |o|
-
# xml.object {
-
# xml.type_ o.type
-
# xml.class_ o.class.name
-
# xml.id_ o.id
-
# }
-
# end
-
# }
-
# }
-
# end
-
# puts builder.to_xml
-
#
-
# The underscore may be used with any tag name, and the last underscore
-
# will just be removed. This code will output the following XML:
-
#
-
# <?xml version="1.0"?>
-
# <root>
-
# <objects>
-
# <object>
-
# <type>Object</type>
-
# <class>Object</class>
-
# <id>48390</id>
-
# </object>
-
# <object>
-
# <type>Object</type>
-
# <class>Object</class>
-
# <id>48380</id>
-
# </object>
-
# <object>
-
# <type>Object</type>
-
# <class>Object</class>
-
# <id>48370</id>
-
# </object>
-
# </objects>
-
# </root>
-
#
-
# == Tag Attributes
-
#
-
# Tag attributes may be supplied as method arguments. Here is our
-
# previous example, but using attributes rather than tags:
-
#
-
# @objects = [Object.new, Object.new, Object.new]
-
#
-
# builder = Nokogiri::XML::Builder.new do |xml|
-
# xml.root {
-
# xml.objects {
-
# @objects.each do |o|
-
# xml.object(:type => o.type, :class => o.class, :id => o.id)
-
# end
-
# }
-
# }
-
# end
-
# puts builder.to_xml
-
#
-
# === Tag Attribute Short Cuts
-
#
-
# A couple attribute short cuts are available when building tags. The
-
# short cuts are available by special method calls when building a tag.
-
#
-
# This example builds an "object" tag with the class attribute "classy"
-
# and the id of "thing":
-
#
-
# builder = Nokogiri::XML::Builder.new do |xml|
-
# xml.root {
-
# xml.objects {
-
# xml.object.classy.thing!
-
# }
-
# }
-
# end
-
# puts builder.to_xml
-
#
-
# Which will output:
-
#
-
# <?xml version="1.0"?>
-
# <root>
-
# <objects>
-
# <object class="classy" id="thing"/>
-
# </objects>
-
# </root>
-
#
-
# All other options are still supported with this syntax, including
-
# blocks and extra tag attributes.
-
#
-
# == Namespaces
-
#
-
# Namespaces are added similarly to attributes. Nokogiri::XML::Builder
-
# assumes that when an attribute starts with "xmlns", it is meant to be
-
# a namespace:
-
#
-
# builder = Nokogiri::XML::Builder.new { |xml|
-
# xml.root('xmlns' => 'default', 'xmlns:foo' => 'bar') do
-
# xml.tenderlove
-
# end
-
# }
-
# puts builder.to_xml
-
#
-
# Will output XML like this:
-
#
-
# <?xml version="1.0"?>
-
# <root xmlns:foo="bar" xmlns="default">
-
# <tenderlove/>
-
# </root>
-
#
-
# === Referencing declared namespaces
-
#
-
# Tags that reference non-default namespaces (i.e. a tag "foo:bar") can be
-
# built by using the Nokogiri::XML::Builder#[] method.
-
#
-
# For example:
-
#
-
# builder = Nokogiri::XML::Builder.new do |xml|
-
# xml.root('xmlns:foo' => 'bar') {
-
# xml.objects {
-
# xml['foo'].object.classy.thing!
-
# }
-
# }
-
# end
-
# puts builder.to_xml
-
#
-
# Will output this XML:
-
#
-
# <?xml version="1.0"?>
-
# <root xmlns:foo="bar">
-
# <objects>
-
# <foo:object class="classy" id="thing"/>
-
# </objects>
-
# </root>
-
#
-
# Note the "foo:object" tag.
-
#
-
# == Document Types
-
#
-
# To create a document type (DTD), access use the Builder#doc method to get
-
# the current context document. Then call Node#create_internal_subset to
-
# create the DTD node.
-
#
-
# For example, this Ruby:
-
#
-
# builder = Nokogiri::XML::Builder.new do |xml|
-
# xml.doc.create_internal_subset(
-
# 'html',
-
# "-//W3C//DTD HTML 4.01 Transitional//EN",
-
# "http://www.w3.org/TR/html4/loose.dtd"
-
# )
-
# xml.root do
-
# xml.foo
-
# end
-
# end
-
#
-
# puts builder.to_xml
-
#
-
# Will output this xml:
-
#
-
# <?xml version="1.0"?>
-
# <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
-
# <root>
-
# <foo/>
-
# </root>
-
#
-
2
class Builder
-
# The current Document object being built
-
2
attr_accessor :doc
-
-
# The parent of the current node being built
-
2
attr_accessor :parent
-
-
# A context object for use when the block has no arguments
-
2
attr_accessor :context
-
-
2
attr_accessor :arity # :nodoc:
-
-
###
-
# Create a builder with an existing root object. This is for use when
-
# you have an existing document that you would like to augment with
-
# builder methods. The builder context created will start with the
-
# given +root+ node.
-
#
-
# For example:
-
#
-
# doc = Nokogiri::XML(open('somedoc.xml'))
-
# Nokogiri::XML::Builder.with(doc.at('some_tag')) do |xml|
-
# # ... Use normal builder methods here ...
-
# xml.awesome # add the "awesome" tag below "some_tag"
-
# end
-
#
-
2
def self.with root, &block
-
new({}, root, &block)
-
end
-
-
###
-
# Create a new Builder object. +options+ are sent to the top level
-
# Document that is being built.
-
#
-
# Building a document with a particular encoding for example:
-
#
-
# Nokogiri::XML::Builder.new(:encoding => 'UTF-8') do |xml|
-
# ...
-
# end
-
2
def initialize options = {}, root = nil, &block
-
-
if root
-
@doc = root.document
-
@parent = root
-
else
-
namespace = self.class.name.split('::')
-
namespace[-1] = 'Document'
-
@doc = eval(namespace.join('::')).new
-
@parent = @doc
-
end
-
-
@context = nil
-
@arity = nil
-
@ns = nil
-
-
options.each do |k,v|
-
@doc.send(:"#{k}=", v)
-
end
-
-
return unless block_given?
-
-
@arity = block.arity
-
if @arity <= 0
-
@context = eval('self', block.binding)
-
instance_eval(&block)
-
else
-
yield self
-
end
-
-
@parent = @doc
-
end
-
-
###
-
# Create a Text Node with content of +string+
-
2
def text string
-
insert @doc.create_text_node(string)
-
end
-
-
###
-
# Create a CDATA Node with content of +string+
-
2
def cdata string
-
insert doc.create_cdata(string)
-
end
-
-
###
-
# Create a Comment Node with content of +string+
-
2
def comment string
-
insert doc.create_comment(string)
-
end
-
-
###
-
# Build a tag that is associated with namespace +ns+. Raises an
-
# ArgumentError if +ns+ has not been defined higher in the tree.
-
2
def [] ns
-
if @parent != @doc
-
@ns = @parent.namespace_definitions.find { |x| x.prefix == ns.to_s }
-
end
-
return self if @ns
-
-
@parent.ancestors.each do |a|
-
next if a == doc
-
@ns = a.namespace_definitions.find { |x| x.prefix == ns.to_s }
-
return self if @ns
-
end
-
-
@ns = { :pending => ns.to_s }
-
return self
-
end
-
-
###
-
# Convert this Builder object to XML
-
2
def to_xml(*args)
-
if Nokogiri.jruby?
-
options = args.first.is_a?(Hash) ? args.shift : {}
-
if !options[:save_with]
-
options[:save_with] = Node::SaveOptions::AS_BUILDER
-
end
-
args.insert(0, options)
-
end
-
@doc.to_xml(*args)
-
end
-
-
###
-
# Append the given raw XML +string+ to the document
-
2
def << string
-
@doc.fragment(string).children.each { |x| insert(x) }
-
end
-
-
2
def method_missing method, *args, &block # :nodoc:
-
if @context && @context.respond_to?(method)
-
@context.send(method, *args, &block)
-
else
-
node = @doc.create_element(method.to_s.sub(/[_!]$/, ''),*args) { |n|
-
# Set up the namespace
-
if @ns.is_a? Nokogiri::XML::Namespace
-
n.namespace = @ns
-
@ns = nil
-
end
-
}
-
-
if @ns.is_a? Hash
-
node.namespace = node.namespace_definitions.find { |x| x.prefix == @ns[:pending] }
-
if node.namespace.nil?
-
raise ArgumentError, "Namespace #{@ns[:pending]} has not been defined"
-
end
-
@ns = nil
-
end
-
-
insert(node, &block)
-
end
-
end
-
-
2
private
-
###
-
# Insert +node+ as a child of the current Node
-
2
def insert(node, &block)
-
node = @parent.add_child(node)
-
if block_given?
-
old_parent = @parent
-
@parent = node
-
@arity ||= block.arity
-
if @arity <= 0
-
instance_eval(&block)
-
else
-
block.call(self)
-
end
-
@parent = old_parent
-
end
-
NodeBuilder.new(node, self)
-
end
-
-
2
class NodeBuilder # :nodoc:
-
2
def initialize node, doc_builder
-
@node = node
-
@doc_builder = doc_builder
-
end
-
-
2
def []= k, v
-
@node[k] = v
-
end
-
-
2
def [] k
-
@node[k]
-
end
-
-
2
def method_missing(method, *args, &block)
-
opts = args.last.is_a?(Hash) ? args.pop : {}
-
case method.to_s
-
when /^(.*)!$/
-
@node['id'] = $1
-
@node.content = args.first if args.first
-
when /^(.*)=/
-
@node[$1] = args.first
-
else
-
@node['class'] =
-
((@node['class'] || '').split(/\s/) + [method.to_s]).join(' ')
-
@node.content = args.first if args.first
-
end
-
-
# Assign any extra options
-
opts.each do |k,v|
-
@node[k.to_s] = ((@node[k.to_s] || '').split(/\s/) + [v]).join(' ')
-
end
-
-
if block_given?
-
old_parent = @doc_builder.parent
-
@doc_builder.parent = @node
-
value = @doc_builder.instance_eval(&block)
-
@doc_builder.parent = old_parent
-
return value
-
end
-
self
-
end
-
end
-
end
-
end
-
end
-
2
module Nokogiri
-
2
module XML
-
2
class CDATA < Nokogiri::XML::Text
-
###
-
# Get the name of this CDATA node
-
2
def name
-
'#cdata-section'
-
end
-
end
-
end
-
end
-
2
module Nokogiri
-
2
module XML
-
2
class CharacterData < Nokogiri::XML::Node
-
2
include Nokogiri::XML::PP::CharacterData
-
end
-
end
-
end
-
2
module Nokogiri
-
2
module XML
-
##
-
# Nokogiri::XML::Document is the main entry point for dealing with
-
# XML documents. The Document is created by parsing an XML document.
-
# See Nokogiri::XML::Document.parse() for more information on parsing.
-
#
-
# For searching a Document, see Nokogiri::XML::Searchable#css and
-
# Nokogiri::XML::Searchable#xpath
-
#
-
2
class Document < Nokogiri::XML::Node
-
# I'm ignoring unicode characters here.
-
# See http://www.w3.org/TR/REC-xml-names/#ns-decl for more details.
-
2
NCNAME_START_CHAR = "A-Za-z_"
-
2
NCNAME_CHAR = NCNAME_START_CHAR + "\\-.0-9"
-
2
NCNAME_RE = /^xmlns(:[#{NCNAME_START_CHAR}][#{NCNAME_CHAR}]*)?$/
-
-
##
-
# Parse an XML file.
-
#
-
# +string_or_io+ may be a String, or any object that responds to
-
# _read_ and _close_ such as an IO, or StringIO.
-
#
-
# +url+ (optional) is the URI where this document is located.
-
#
-
# +encoding+ (optional) is the encoding that should be used when processing
-
# the document.
-
#
-
# +options+ (optional) is a configuration object that sets options during
-
# parsing, such as Nokogiri::XML::ParseOptions::RECOVER. See the
-
# Nokogiri::XML::ParseOptions for more information.
-
#
-
# +block+ (optional) is passed a configuration object on which
-
# parse options may be set.
-
#
-
# When parsing untrusted documents, it's recommended that the
-
# +nonet+ option be used, as shown in this example code:
-
#
-
# Nokogiri::XML::Document.parse(xml_string) { |config| config.nonet }
-
#
-
# Nokogiri.XML() is a convenience method which will call this method.
-
#
-
2
def self.parse string_or_io, url = nil, encoding = nil, options = ParseOptions::DEFAULT_XML, &block
-
options = Nokogiri::XML::ParseOptions.new(options) if Fixnum === options
-
# Give the options to the user
-
yield options if block_given?
-
-
return new if !options.strict? && empty_doc?(string_or_io)
-
-
doc = if string_or_io.respond_to?(:read)
-
url ||= string_or_io.respond_to?(:path) ? string_or_io.path : nil
-
read_io(string_or_io, url, encoding, options.to_i)
-
else
-
# read_memory pukes on empty docs
-
read_memory(string_or_io, url, encoding, options.to_i)
-
end
-
-
# do xinclude processing
-
doc.do_xinclude(options) if options.xinclude?
-
-
return doc
-
end
-
-
# A list of Nokogiri::XML::SyntaxError found when parsing a document
-
2
attr_accessor :errors
-
-
2
def initialize *args # :nodoc:
-
7
@errors = []
-
7
@decorators = nil
-
end
-
-
##
-
# Create an element with +name+, and optionally setting the content and attributes.
-
#
-
# doc.create_element "div" # <div></div>
-
# doc.create_element "div", :class => "container" # <div class='container'></div>
-
# doc.create_element "div", "contents" # <div>contents</div>
-
# doc.create_element "div", "contents", :class => "container" # <div class='container'>contents</div>
-
# doc.create_element "div" { |node| node['class'] = "container" } # <div class='container'></div>
-
#
-
2
def create_element name, *args, &block
-
elm = Nokogiri::XML::Element.new(name, self, &block)
-
args.each do |arg|
-
case arg
-
when Hash
-
arg.each { |k,v|
-
key = k.to_s
-
if key =~ NCNAME_RE
-
ns_name = key.split(":", 2)[1]
-
elm.add_namespace_definition ns_name, v
-
else
-
elm[k.to_s] = v.to_s
-
end
-
}
-
else
-
elm.content = arg
-
end
-
end
-
if ns = elm.namespace_definitions.find { |n| n.prefix.nil? or n.prefix == '' }
-
elm.namespace = ns
-
end
-
elm
-
end
-
-
# Create a Text Node with +string+
-
2
def create_text_node string, &block
-
Nokogiri::XML::Text.new string.to_s, self, &block
-
end
-
-
# Create a CDATA Node containing +string+
-
2
def create_cdata string, &block
-
Nokogiri::XML::CDATA.new self, string.to_s, &block
-
end
-
-
# Create a Comment Node containing +string+
-
2
def create_comment string, &block
-
Nokogiri::XML::Comment.new self, string.to_s, &block
-
end
-
-
# The name of this document. Always returns "document"
-
2
def name
-
'document'
-
end
-
-
# A reference to +self+
-
2
def document
-
144
self
-
end
-
-
##
-
# Recursively get all namespaces from this node and its subtree and
-
# return them as a hash.
-
#
-
# For example, given this document:
-
#
-
# <root xmlns:foo="bar">
-
# <bar xmlns:hello="world" />
-
# </root>
-
#
-
# This method will return:
-
#
-
# { 'xmlns:foo' => 'bar', 'xmlns:hello' => 'world' }
-
#
-
# WARNING: this method will clobber duplicate names in the keys.
-
# For example, given this document:
-
#
-
# <root xmlns:foo="bar">
-
# <bar xmlns:foo="baz" />
-
# </root>
-
#
-
# The hash returned will look like this: { 'xmlns:foo' => 'bar' }
-
#
-
# Non-prefixed default namespaces (as in "xmlns=") are not included
-
# in the hash.
-
#
-
# Note that this method does an xpath lookup for nodes with
-
# namespaces, and as a result the order may be dependent on the
-
# implementation of the underlying XML library.
-
#
-
2
def collect_namespaces
-
xpath("//namespace::*").inject({}) do |hash, ns|
-
hash[["xmlns",ns.prefix].compact.join(":")] = ns.href if ns.prefix != "xml"
-
hash
-
end
-
end
-
-
# Get the list of decorators given +key+
-
2
def decorators key
-
@decorators ||= Hash.new
-
@decorators[key] ||= []
-
end
-
-
##
-
# Validate this Document against it's DTD. Returns a list of errors on
-
# the document or +nil+ when there is no DTD.
-
2
def validate
-
return nil unless internal_subset
-
internal_subset.validate self
-
end
-
-
##
-
# Explore a document with shortcut methods. See Nokogiri::Slop for details.
-
#
-
# Note that any nodes that have been instantiated before #slop!
-
# is called will not be decorated with sloppy behavior. So, if you're in
-
# irb, the preferred idiom is:
-
#
-
# irb> doc = Nokogiri::Slop my_markup
-
#
-
# and not
-
#
-
# irb> doc = Nokogiri::HTML my_markup
-
# ... followed by irb's implicit inspect (and therefore instantiation of every node) ...
-
# irb> doc.slop!
-
# ... which does absolutely nothing.
-
#
-
2
def slop!
-
unless decorators(XML::Node).include? Nokogiri::Decorators::Slop
-
decorators(XML::Node) << Nokogiri::Decorators::Slop
-
decorate!
-
end
-
-
self
-
end
-
-
##
-
# Apply any decorators to +node+
-
2
def decorate node
-
131
return unless @decorators
-
@decorators.each { |klass,list|
-
next unless node.is_a?(klass)
-
list.each { |moodule| node.extend(moodule) }
-
}
-
end
-
-
2
alias :to_xml :serialize
-
2
alias :clone :dup
-
-
# Get the hash of namespaces on the root Nokogiri::XML::Node
-
2
def namespaces
-
root ? root.namespaces : {}
-
end
-
-
##
-
# Create a Nokogiri::XML::DocumentFragment from +tags+
-
# Returns an empty fragment if +tags+ is nil.
-
2
def fragment tags = nil
-
DocumentFragment.new(self, tags, self.root)
-
end
-
-
2
undef_method :swap, :parent, :namespace, :default_namespace=
-
2
undef_method :add_namespace_definition, :attributes
-
2
undef_method :namespace_definitions, :line, :add_namespace
-
-
2
def add_child node_or_tags
-
raise "Document already has a root node" if root && root.name != 'nokogiri_text_wrapper'
-
node_or_tags = coerce(node_or_tags)
-
if node_or_tags.is_a?(XML::NodeSet)
-
raise "Document cannot have multiple root nodes" if node_or_tags.size > 1
-
super(node_or_tags.first)
-
else
-
super
-
end
-
end
-
2
alias :<< :add_child
-
-
##
-
# +JRuby+
-
# Wraps Java's org.w3c.dom.document and returns Nokogiri::XML::Document
-
2
def self.wrap document
-
raise "JRuby only method" unless Nokogiri.jruby?
-
return wrapJavaDocument(document)
-
end
-
-
##
-
# +JRuby+
-
# Returns Java's org.w3c.dom.document of this Document.
-
2
def to_java
-
raise "JRuby only method" unless Nokogiri.jruby?
-
return toJavaDocument()
-
end
-
-
2
private
-
2
def self.empty_doc? string_or_io
-
string_or_io.nil? ||
-
(string_or_io.respond_to?(:empty?) && string_or_io.empty?) ||
-
(string_or_io.respond_to?(:eof?) && string_or_io.eof?)
-
end
-
-
2
def implied_xpath_contexts # :nodoc:
-
34
["//"]
-
end
-
-
2
def inspect_attributes
-
[:name, :children]
-
end
-
end
-
end
-
end
-
2
module Nokogiri
-
2
module XML
-
2
class DocumentFragment < Nokogiri::XML::Node
-
##
-
# Create a new DocumentFragment from +tags+.
-
#
-
# If +ctx+ is present, it is used as a context node for the
-
# subtree created, e.g., namespaces will be resolved relative
-
# to +ctx+.
-
2
def initialize document, tags = nil, ctx = nil
-
return self unless tags
-
-
children = if ctx
-
# Fix for issue#490
-
if Nokogiri.jruby?
-
# fix for issue #770
-
ctx.parse("<root #{namespace_declarations(ctx)}>#{tags}</root>").children
-
else
-
ctx.parse(tags)
-
end
-
else
-
XML::Document.parse("<root>#{tags}</root>") \
-
.xpath("/root/node()")
-
end
-
children.each { |child| child.parent = self }
-
end
-
-
###
-
# return the name for DocumentFragment
-
2
def name
-
'#document-fragment'
-
end
-
-
###
-
# Convert this DocumentFragment to a string
-
2
def to_s
-
children.to_s
-
end
-
-
###
-
# Convert this DocumentFragment to html
-
# See Nokogiri::XML::NodeSet#to_html
-
2
def to_html *args
-
if Nokogiri.jruby?
-
options = args.first.is_a?(Hash) ? args.shift : {}
-
if !options[:save_with]
-
options[:save_with] = Node::SaveOptions::NO_DECLARATION | Node::SaveOptions::NO_EMPTY_TAGS | Node::SaveOptions::AS_HTML
-
end
-
args.insert(0, options)
-
end
-
children.to_html(*args)
-
end
-
-
###
-
# Convert this DocumentFragment to xhtml
-
# See Nokogiri::XML::NodeSet#to_xhtml
-
2
def to_xhtml *args
-
if Nokogiri.jruby?
-
options = args.first.is_a?(Hash) ? args.shift : {}
-
if !options[:save_with]
-
options[:save_with] = Node::SaveOptions::NO_DECLARATION | Node::SaveOptions::NO_EMPTY_TAGS | Node::SaveOptions::AS_XHTML
-
end
-
args.insert(0, options)
-
end
-
children.to_xhtml(*args)
-
end
-
-
###
-
# Convert this DocumentFragment to xml
-
# See Nokogiri::XML::NodeSet#to_xml
-
2
def to_xml *args
-
children.to_xml(*args)
-
end
-
-
###
-
# call-seq: css *rules, [namespace-bindings, custom-pseudo-class]
-
#
-
# Search this fragment for CSS +rules+. +rules+ must be one or more CSS
-
# selectors. For example:
-
#
-
# For more information see Nokogiri::XML::Searchable#css
-
2
def css *args
-
if children.any?
-
children.css(*args) # 'children' is a smell here
-
else
-
NodeSet.new(document)
-
end
-
end
-
-
#
-
# NOTE that we don't delegate #xpath to children ... another smell.
-
# def xpath ; end
-
#
-
-
###
-
# call-seq: search *paths, [namespace-bindings, xpath-variable-bindings, custom-handler-class]
-
#
-
# Search this fragment for +paths+. +paths+ must be one or more XPath or CSS queries.
-
#
-
# For more information see Nokogiri::XML::Searchable#search
-
2
def search *rules
-
rules, handler, ns, binds = extract_params(rules)
-
-
rules.inject(NodeSet.new(document)) do |set, rule|
-
set += if rule =~ Searchable::LOOKS_LIKE_XPATH
-
xpath(*([rule, ns, handler, binds].compact))
-
else
-
children.css(*([rule, ns, handler].compact)) # 'children' is a smell here
-
end
-
end
-
end
-
-
2
alias :serialize :to_s
-
-
2
class << self
-
####
-
# Create a Nokogiri::XML::DocumentFragment from +tags+
-
2
def parse tags
-
self.new(XML::Document.new, tags)
-
end
-
end
-
-
# A list of Nokogiri::XML::SyntaxError found when parsing a document
-
2
def errors
-
document.errors
-
end
-
-
2
def errors= things # :nodoc:
-
document.errors = things
-
end
-
-
2
private
-
-
# fix for issue 770
-
2
def namespace_declarations ctx
-
ctx.namespace_scopes.map do |namespace|
-
prefix = namespace.prefix.nil? ? "" : ":#{namespace.prefix}"
-
%Q{xmlns#{prefix}="#{namespace.href}"}
-
end.join ' '
-
end
-
-
2
def coerce data
-
return super unless String === data
-
-
document.fragment(data).children
-
end
-
end
-
end
-
end
-
2
module Nokogiri
-
2
module XML
-
2
class DTD < Nokogiri::XML::Node
-
2
undef_method :attribute_nodes
-
2
undef_method :values
-
2
undef_method :content
-
2
undef_method :namespace
-
2
undef_method :namespace_definitions
-
2
undef_method :line if method_defined?(:line)
-
-
2
def keys
-
attributes.keys
-
end
-
-
2
def each &block
-
attributes.each { |key, value|
-
block.call([key, value])
-
}
-
end
-
-
2
def html_dtd?
-
name.casecmp('html').zero?
-
end
-
-
2
def html5_dtd?
-
html_dtd? &&
-
external_id.nil? &&
-
(system_id.nil? || system_id == 'about:legacy-compat')
-
end
-
end
-
end
-
end
-
2
module Nokogiri
-
2
module XML
-
###
-
# Represents the allowed content in an Element Declaration inside a DTD:
-
#
-
# <?xml version="1.0"?><?TEST-STYLE PIDATA?>
-
# <!DOCTYPE staff SYSTEM "staff.dtd" [
-
# <!ELEMENT div1 (head, (p | list | note)*, div2*)>
-
# ]>
-
# </root>
-
#
-
# ElementContent represents the tree inside the <!ELEMENT> tag shown above
-
# that lists the possible content for the div1 tag.
-
2
class ElementContent
-
# Possible definitions of type
-
2
PCDATA = 1
-
2
ELEMENT = 2
-
2
SEQ = 3
-
2
OR = 4
-
-
# Possible content occurrences
-
2
ONCE = 1
-
2
OPT = 2
-
2
MULT = 3
-
2
PLUS = 4
-
-
2
attr_reader :document
-
-
###
-
# Get the children of this ElementContent node
-
2
def children
-
[c1, c2].compact
-
end
-
end
-
end
-
end
-
2
module Nokogiri
-
2
module XML
-
2
class ElementDecl < Nokogiri::XML::Node
-
2
undef_method :namespace
-
2
undef_method :namespace_definitions
-
2
undef_method :line if method_defined?(:line)
-
-
2
def inspect
-
"#<#{self.class.name}:#{sprintf("0x%x", object_id)} #{to_s.inspect}>"
-
end
-
end
-
end
-
end
-
2
module Nokogiri
-
2
module XML
-
2
class EntityDecl < Nokogiri::XML::Node
-
2
undef_method :attribute_nodes
-
2
undef_method :attributes
-
2
undef_method :namespace
-
2
undef_method :namespace_definitions
-
2
undef_method :line if method_defined?(:line)
-
-
2
def self.new name, doc, *args
-
doc.create_entity(name, *args)
-
end
-
-
2
def inspect
-
"#<#{self.class.name}:#{sprintf("0x%x", object_id)} #{to_s.inspect}>"
-
end
-
end
-
end
-
end
-
2
module Nokogiri
-
2
module XML
-
2
class Namespace
-
2
include Nokogiri::XML::PP::Node
-
2
attr_reader :document
-
-
2
private
-
2
def inspect_attributes
-
[:prefix, :href]
-
end
-
end
-
end
-
end
-
2
require 'stringio'
-
2
require 'nokogiri/xml/node/save_options'
-
-
2
module Nokogiri
-
2
module XML
-
####
-
# Nokogiri::XML::Node is your window to the fun filled world of dealing
-
# with XML and HTML tags. A Nokogiri::XML::Node may be treated similarly
-
# to a hash with regard to attributes. For example (from irb):
-
#
-
# irb(main):004:0> node
-
# => <a href="#foo" id="link">link</a>
-
# irb(main):005:0> node['href']
-
# => "#foo"
-
# irb(main):006:0> node.keys
-
# => ["href", "id"]
-
# irb(main):007:0> node.values
-
# => ["#foo", "link"]
-
# irb(main):008:0> node['class'] = 'green'
-
# => "green"
-
# irb(main):009:0> node
-
# => <a href="#foo" id="link" class="green">link</a>
-
# irb(main):010:0>
-
#
-
# See Nokogiri::XML::Node#[] and Nokogiri::XML#[]= for more information.
-
#
-
# Nokogiri::XML::Node also has methods that let you move around your
-
# tree. For navigating your tree, see:
-
#
-
# * Nokogiri::XML::Node#parent
-
# * Nokogiri::XML::Node#children
-
# * Nokogiri::XML::Node#next
-
# * Nokogiri::XML::Node#previous
-
#
-
#
-
# When printing or otherwise emitting a document or a node (and
-
# its subtree), there are a few methods you might want to use:
-
#
-
# * content, text, inner_text, to_str: emit plaintext
-
#
-
# These methods will all emit the plaintext version of your
-
# document, meaning that entities will be replaced (e.g., "<"
-
# will be replaced with "<"), meaning that any sanitizing will
-
# likely be un-done in the output.
-
#
-
# * to_s, to_xml, to_html, inner_html: emit well-formed markup
-
#
-
# These methods will all emit properly-escaped markup, meaning
-
# that it's suitable for consumption by browsers, parsers, etc.
-
#
-
# You may search this node's subtree using Searchable#xpath and Searchable#css
-
2
class Node
-
2
include Nokogiri::XML::PP::Node
-
2
include Nokogiri::XML::Searchable
-
2
include Enumerable
-
-
# Element node type, see Nokogiri::XML::Node#element?
-
2
ELEMENT_NODE = 1
-
# Attribute node type
-
2
ATTRIBUTE_NODE = 2
-
# Text node type, see Nokogiri::XML::Node#text?
-
2
TEXT_NODE = 3
-
# CDATA node type, see Nokogiri::XML::Node#cdata?
-
2
CDATA_SECTION_NODE = 4
-
# Entity reference node type
-
2
ENTITY_REF_NODE = 5
-
# Entity node type
-
2
ENTITY_NODE = 6
-
# PI node type
-
2
PI_NODE = 7
-
# Comment node type, see Nokogiri::XML::Node#comment?
-
2
COMMENT_NODE = 8
-
# Document node type, see Nokogiri::XML::Node#xml?
-
2
DOCUMENT_NODE = 9
-
# Document type node type
-
2
DOCUMENT_TYPE_NODE = 10
-
# Document fragment node type
-
2
DOCUMENT_FRAG_NODE = 11
-
# Notation node type
-
2
NOTATION_NODE = 12
-
# HTML document node type, see Nokogiri::XML::Node#html?
-
2
HTML_DOCUMENT_NODE = 13
-
# DTD node type
-
2
DTD_NODE = 14
-
# Element declaration type
-
2
ELEMENT_DECL = 15
-
# Attribute declaration type
-
2
ATTRIBUTE_DECL = 16
-
# Entity declaration type
-
2
ENTITY_DECL = 17
-
# Namespace declaration type
-
2
NAMESPACE_DECL = 18
-
# XInclude start type
-
2
XINCLUDE_START = 19
-
# XInclude end type
-
2
XINCLUDE_END = 20
-
# DOCB document node type
-
2
DOCB_DOCUMENT_NODE = 21
-
-
2
def initialize name, document # :nodoc:
-
# ... Ya. This is empty on purpose.
-
end
-
-
###
-
# Decorate this node with the decorators set up in this node's Document
-
2
def decorate!
-
document.decorate(self)
-
end
-
-
###
-
# Search this node's immediate children using CSS selector +selector+
-
2
def > selector
-
ns = document.root.namespaces
-
xpath CSS.xpath_for(selector, :prefix => "./", :ns => ns).first
-
end
-
-
###
-
# Get the attribute value for the attribute +name+
-
2
def [] name
-
194
get(name.to_s)
-
end
-
-
###
-
# Set the attribute value for the attribute +name+ to +value+
-
2
def []= name, value
-
set name.to_s, value.to_s
-
end
-
-
###
-
# Add +node_or_tags+ as a child of this Node.
-
# +node_or_tags+ can be a Nokogiri::XML::Node, a ::DocumentFragment, a ::NodeSet, or a string containing markup.
-
#
-
# Returns the reparented node (if +node_or_tags+ is a Node), or NodeSet (if +node_or_tags+ is a DocumentFragment, NodeSet, or string).
-
#
-
# Also see related method +<<+.
-
2
def add_child node_or_tags
-
node_or_tags = coerce(node_or_tags)
-
if node_or_tags.is_a?(XML::NodeSet)
-
node_or_tags.each { |n| add_child_node_and_reparent_attrs n }
-
else
-
add_child_node_and_reparent_attrs node_or_tags
-
end
-
node_or_tags
-
end
-
-
###
-
# Add +node_or_tags+ as the first child of this Node.
-
# +node_or_tags+ can be a Nokogiri::XML::Node, a ::DocumentFragment, a ::NodeSet, or a string containing markup.
-
#
-
# Returns the reparented node (if +node_or_tags+ is a Node), or NodeSet (if +node_or_tags+ is a DocumentFragment, NodeSet, or string).
-
#
-
# Also see related method +add_child+.
-
2
def prepend_child node_or_tags
-
if first = children.first
-
# Mimic the error add_child would raise.
-
raise RuntimeError, "Document already has a root node" if document? && !node_or_tags.processing_instruction?
-
first.__send__(:add_sibling, :previous, node_or_tags)
-
else
-
add_child(node_or_tags)
-
end
-
end
-
-
###
-
# Add +node_or_tags+ as a child of this Node.
-
# +node_or_tags+ can be a Nokogiri::XML::Node, a ::DocumentFragment, a ::NodeSet, or a string containing markup.
-
#
-
# Returns self, to support chaining of calls (e.g., root << child1 << child2)
-
#
-
# Also see related method +add_child+.
-
2
def << node_or_tags
-
add_child node_or_tags
-
self
-
end
-
###
-
# Insert +node_or_tags+ before this Node (as a sibling).
-
# +node_or_tags+ can be a Nokogiri::XML::Node, a ::DocumentFragment, a ::NodeSet, or a string containing markup.
-
#
-
# Returns the reparented node (if +node_or_tags+ is a Node), or NodeSet (if +node_or_tags+ is a DocumentFragment, NodeSet, or string).
-
#
-
# Also see related method +before+.
-
2
def add_previous_sibling node_or_tags
-
raise ArgumentError.new("A document may not have multiple root nodes.") if (parent && parent.document?) && !node_or_tags.processing_instruction?
-
-
add_sibling :previous, node_or_tags
-
end
-
-
###
-
# Insert +node_or_tags+ after this Node (as a sibling).
-
# +node_or_tags+ can be a Nokogiri::XML::Node, a ::DocumentFragment, a ::NodeSet, or a string containing markup.
-
#
-
# Returns the reparented node (if +node_or_tags+ is a Node), or NodeSet (if +node_or_tags+ is a DocumentFragment, NodeSet, or string).
-
#
-
# Also see related method +after+.
-
2
def add_next_sibling node_or_tags
-
raise ArgumentError.new("A document may not have multiple root nodes.") if (parent && parent.document?) && !node_or_tags.processing_instruction?
-
-
add_sibling :next, node_or_tags
-
end
-
-
####
-
# Insert +node_or_tags+ before this node (as a sibling).
-
# +node_or_tags+ can be a Nokogiri::XML::Node, a ::DocumentFragment, a ::NodeSet, or a string containing markup.
-
#
-
# Returns self, to support chaining of calls.
-
#
-
# Also see related method +add_previous_sibling+.
-
2
def before node_or_tags
-
add_previous_sibling node_or_tags
-
self
-
end
-
-
####
-
# Insert +node_or_tags+ after this node (as a sibling).
-
# +node_or_tags+ can be a Nokogiri::XML::Node, a Nokogiri::XML::DocumentFragment, or a string containing markup.
-
#
-
# Returns self, to support chaining of calls.
-
#
-
# Also see related method +add_next_sibling+.
-
2
def after node_or_tags
-
add_next_sibling node_or_tags
-
self
-
end
-
-
####
-
# Set the inner html for this Node to +node_or_tags+
-
# +node_or_tags+ can be a Nokogiri::XML::Node, a Nokogiri::XML::DocumentFragment, or a string containing markup.
-
#
-
# Returns self.
-
#
-
# Also see related method +children=+
-
2
def inner_html= node_or_tags
-
self.children = node_or_tags
-
self
-
end
-
-
####
-
# Set the inner html for this Node +node_or_tags+
-
# +node_or_tags+ can be a Nokogiri::XML::Node, a Nokogiri::XML::DocumentFragment, or a string containing markup.
-
#
-
# Returns the reparented node (if +node_or_tags+ is a Node), or NodeSet (if +node_or_tags+ is a DocumentFragment, NodeSet, or string).
-
#
-
# Also see related method +inner_html=+
-
2
def children= node_or_tags
-
node_or_tags = coerce(node_or_tags)
-
children.unlink
-
if node_or_tags.is_a?(XML::NodeSet)
-
node_or_tags.each { |n| add_child_node_and_reparent_attrs n }
-
else
-
add_child_node_and_reparent_attrs node_or_tags
-
end
-
node_or_tags
-
end
-
-
####
-
# Replace this Node with +node_or_tags+.
-
# +node_or_tags+ can be a Nokogiri::XML::Node, a ::DocumentFragment, a ::NodeSet, or a string containing markup.
-
#
-
# Returns the reparented node (if +node_or_tags+ is a Node), or NodeSet (if +node_or_tags+ is a DocumentFragment, NodeSet, or string).
-
#
-
# Also see related method +swap+.
-
2
def replace node_or_tags
-
# We cannot replace a text node directly, otherwise libxml will return
-
# an internal error at parser.c:13031, I don't know exactly why
-
# libxml is trying to find a parent node that is an element or document
-
# so I can't tell if this is bug in libxml or not. issue #775.
-
if text?
-
replacee = Nokogiri::XML::Node.new 'dummy', document
-
add_previous_sibling_node replacee
-
unlink
-
return replacee.replace node_or_tags
-
end
-
-
node_or_tags = coerce(node_or_tags)
-
-
if node_or_tags.is_a?(XML::NodeSet)
-
node_or_tags.each { |n| add_previous_sibling n }
-
unlink
-
else
-
replace_node node_or_tags
-
end
-
node_or_tags
-
end
-
-
####
-
# Swap this Node for +node_or_tags+
-
# +node_or_tags+ can be a Nokogiri::XML::Node, a ::DocumentFragment, a ::NodeSet, or a string containing markup.
-
#
-
# Returns self, to support chaining of calls.
-
#
-
# Also see related method +replace+.
-
2
def swap node_or_tags
-
replace node_or_tags
-
self
-
end
-
-
2
alias :next :next_sibling
-
2
alias :previous :previous_sibling
-
-
# :stopdoc:
-
# HACK: This is to work around an RDoc bug
-
2
alias :next= :add_next_sibling
-
# :startdoc:
-
-
2
alias :previous= :add_previous_sibling
-
2
alias :remove :unlink
-
2
alias :get_attribute :[]
-
2
alias :attr :[]
-
2
alias :set_attribute :[]=
-
2
alias :text :content
-
2
alias :inner_text :content
-
2
alias :has_attribute? :key?
-
2
alias :name :node_name
-
2
alias :name= :node_name=
-
2
alias :type :node_type
-
2
alias :to_str :text
-
2
alias :clone :dup
-
2
alias :elements :element_children
-
-
####
-
# Returns a hash containing the node's attributes. The key is
-
# the attribute name without any namespace, the value is a Nokogiri::XML::Attr
-
# representing the attribute.
-
# If you need to distinguish attributes with the same name, with different namespaces
-
# use #attribute_nodes instead.
-
2
def attributes
-
Hash[attribute_nodes.map { |node|
-
[node.node_name, node]
-
}]
-
end
-
-
###
-
# Get the attribute values for this Node.
-
2
def values
-
attribute_nodes.map { |node| node.value }
-
end
-
-
###
-
# Get the attribute names for this Node.
-
2
def keys
-
attribute_nodes.map { |node| node.node_name }
-
end
-
-
###
-
# Iterate over each attribute name and value pair for this Node.
-
2
def each
-
attribute_nodes.each { |node|
-
yield [node.node_name, node.value]
-
}
-
end
-
-
###
-
# Remove the attribute named +name+
-
2
def remove_attribute name
-
attr = attributes[name].remove if key? name
-
clear_xpath_context if Nokogiri.jruby?
-
attr
-
end
-
2
alias :delete :remove_attribute
-
-
###
-
# Returns true if this Node matches +selector+
-
2
def matches? selector
-
ancestors.last.search(selector).include?(self)
-
end
-
-
###
-
# Create a DocumentFragment containing +tags+ that is relative to _this_
-
# context node.
-
2
def fragment tags
-
type = document.html? ? Nokogiri::HTML : Nokogiri::XML
-
type::DocumentFragment.new(document, tags, self)
-
end
-
-
###
-
# Parse +string_or_io+ as a document fragment within the context of
-
# *this* node. Returns a XML::NodeSet containing the nodes parsed from
-
# +string_or_io+.
-
2
def parse string_or_io, options = nil
-
##
-
# When the current node is unparented and not an element node, use the
-
# document as the parsing context instead. Otherwise, the in-context
-
# parser cannot find an element or a document node.
-
# Document Fragments are also not usable by the in-context parser.
-
if !element? && !document? && (!parent || parent.fragment?)
-
return document.parse(string_or_io, options)
-
end
-
-
options ||= (document.html? ? ParseOptions::DEFAULT_HTML : ParseOptions::DEFAULT_XML)
-
if Fixnum === options
-
options = Nokogiri::XML::ParseOptions.new(options)
-
end
-
# Give the options to the user
-
yield options if block_given?
-
-
contents = string_or_io.respond_to?(:read) ?
-
string_or_io.read :
-
string_or_io
-
-
return Nokogiri::XML::NodeSet.new(document) if contents.empty?
-
-
##
-
# This is a horrible hack, but I don't care. See #313 for background.
-
error_count = document.errors.length
-
node_set = in_context(contents, options.to_i)
-
if node_set.empty? and document.errors.length > error_count and options.recover?
-
fragment = Nokogiri::HTML::DocumentFragment.parse contents
-
node_set = fragment.children
-
end
-
node_set
-
end
-
-
####
-
# Set the Node's content to a Text node containing +string+. The string gets XML escaped, not interpreted as markup.
-
2
def content= string
-
self.native_content = encode_special_chars(string.to_s)
-
end
-
-
###
-
# Set the parent Node for this Node
-
2
def parent= parent_node
-
parent_node.add_child(self)
-
parent_node
-
end
-
-
###
-
# Returns a Hash of {prefix => value} for all namespaces on this
-
# node and its ancestors.
-
#
-
# This method returns the same namespaces as #namespace_scopes.
-
#
-
# Returns namespaces in scope for self -- those defined on self
-
# element directly or any ancestor node -- as a Hash of
-
# attribute-name/value pairs. Note that the keys in this hash
-
# XML attributes that would be used to define this namespace,
-
# such as "xmlns:prefix", not just the prefix. Default namespace
-
# set on self will be included with key "xmlns". However,
-
# default namespaces set on ancestor will NOT be, even if self
-
# has no explicit default namespace.
-
2
def namespaces
-
63
Hash[namespace_scopes.map { |nd|
-
key = ['xmlns', nd.prefix].compact.join(':')
-
if RUBY_VERSION >= '1.9' && document.encoding
-
begin
-
key.force_encoding document.encoding
-
rescue ArgumentError
-
end
-
end
-
[key, nd.href]
-
}]
-
end
-
-
# Returns true if this is a Comment
-
2
def comment?
-
type == COMMENT_NODE
-
end
-
-
# Returns true if this is a CDATA
-
2
def cdata?
-
type == CDATA_SECTION_NODE
-
end
-
-
# Returns true if this is an XML::Document node
-
2
def xml?
-
type == DOCUMENT_NODE
-
end
-
-
# Returns true if this is an HTML::Document node
-
2
def html?
-
type == HTML_DOCUMENT_NODE
-
end
-
-
# Returns true if this is a Document
-
2
def document?
-
is_a? XML::Document
-
end
-
-
# Returns true if this is a ProcessingInstruction node
-
2
def processing_instruction?
-
type == PI_NODE
-
end
-
-
# Returns true if this is a Text node
-
2
def text?
-
type == TEXT_NODE
-
end
-
-
# Returns true if this is a DocumentFragment
-
2
def fragment?
-
type == DOCUMENT_FRAG_NODE
-
end
-
-
###
-
# Fetch the Nokogiri::HTML::ElementDescription for this node. Returns
-
# nil on XML documents and on unknown tags.
-
2
def description
-
return nil if document.xml?
-
Nokogiri::HTML::ElementDescription[name]
-
end
-
-
###
-
# Is this a read only node?
-
2
def read_only?
-
# According to gdome2, these are read-only node types
-
[NOTATION_NODE, ENTITY_NODE, ENTITY_DECL].include?(type)
-
end
-
-
# Returns true if this is an Element node
-
2
def element?
-
type == ELEMENT_NODE
-
end
-
2
alias :elem? :element?
-
-
###
-
# Turn this node in to a string. If the document is HTML, this method
-
# returns html. If the document is XML, this method returns XML.
-
2
def to_s
-
document.xml? ? to_xml : to_html
-
end
-
-
# Get the inner_html for this node's Node#children
-
2
def inner_html *args
-
children.map { |x| x.to_html(*args) }.join
-
end
-
-
# Get the path to this node as a CSS expression
-
2
def css_path
-
path.split(/\//).map { |part|
-
part.length == 0 ? nil : part.gsub(/\[(\d+)\]/, ':nth-of-type(\1)')
-
}.compact.join(' > ')
-
end
-
-
###
-
# Get a list of ancestor Node for this Node. If +selector+ is given,
-
# the ancestors must match +selector+
-
2
def ancestors selector = nil
-
4
return NodeSet.new(document) unless respond_to?(:parent)
-
4
return NodeSet.new(document) unless parent
-
-
4
parents = [parent]
-
-
4
while parents.last.respond_to?(:parent)
-
30
break unless ctx_parent = parents.last.parent
-
30
parents << ctx_parent
-
end
-
-
4
return NodeSet.new(document, parents) unless selector
-
-
4
root = parents.last
-
-
4
NodeSet.new(document, parents.find_all { |parent|
-
34
root.search(selector).include?(parent)
-
})
-
end
-
-
###
-
# Adds a default namespace supplied as a string +url+ href, to self.
-
# The consequence is as an xmlns attribute with supplied argument were
-
# present in parsed XML. A default namespace set with this method will
-
# now show up in #attributes, but when this node is serialized to XML an
-
# "xmlns" attribute will appear. See also #namespace and #namespace=
-
2
def default_namespace= url
-
add_namespace_definition(nil, url)
-
end
-
2
alias :add_namespace :add_namespace_definition
-
-
###
-
# Set the default namespace on this node (as would be defined with an
-
# "xmlns=" attribute in XML source), as a Namespace object +ns+. Note that
-
# a Namespace added this way will NOT be serialized as an xmlns attribute
-
# for this node. You probably want #default_namespace= instead, or perhaps
-
# #add_namespace_definition with a nil prefix argument.
-
2
def namespace= ns
-
return set_namespace(ns) unless ns
-
-
unless Nokogiri::XML::Namespace === ns
-
raise TypeError, "#{ns.class} can't be coerced into Nokogiri::XML::Namespace"
-
end
-
if ns.document != document
-
raise ArgumentError, 'namespace must be declared on the same document'
-
end
-
-
set_namespace ns
-
end
-
-
####
-
# Yields self and all children to +block+ recursively.
-
2
def traverse &block
-
children.each{|j| j.traverse(&block) }
-
block.call(self)
-
end
-
-
###
-
# Accept a visitor. This method calls "visit" on +visitor+ with self.
-
2
def accept visitor
-
visitor.visit(self)
-
end
-
-
###
-
# Test to see if this Node is equal to +other+
-
2
def == other
-
return false unless other
-
return false unless other.respond_to?(:pointer_id)
-
pointer_id == other.pointer_id
-
end
-
-
###
-
# Serialize Node using +options+. Save options can also be set using a
-
# block. See SaveOptions.
-
#
-
# These two statements are equivalent:
-
#
-
# node.serialize(:encoding => 'UTF-8', :save_with => FORMAT | AS_XML)
-
#
-
# or
-
#
-
# node.serialize(:encoding => 'UTF-8') do |config|
-
# config.format.as_xml
-
# end
-
#
-
2
def serialize *args, &block
-
options = args.first.is_a?(Hash) ? args.shift : {
-
:encoding => args[0],
-
:save_with => args[1]
-
}
-
-
encoding = options[:encoding] || document.encoding
-
options[:encoding] = encoding
-
-
outstring = ""
-
if encoding && outstring.respond_to?(:force_encoding)
-
outstring.force_encoding(Encoding.find(encoding))
-
end
-
io = StringIO.new(outstring)
-
write_to io, options, &block
-
io.string
-
end
-
-
###
-
# Serialize this Node to HTML
-
#
-
# doc.to_html
-
#
-
# See Node#write_to for a list of +options+. For formatted output,
-
# use Node#to_xhtml instead.
-
2
def to_html options = {}
-
to_format SaveOptions::DEFAULT_HTML, options
-
end
-
-
###
-
# Serialize this Node to XML using +options+
-
#
-
# doc.to_xml(:indent => 5, :encoding => 'UTF-8')
-
#
-
# See Node#write_to for a list of +options+
-
2
def to_xml options = {}
-
options[:save_with] ||= SaveOptions::DEFAULT_XML
-
serialize(options)
-
end
-
-
###
-
# Serialize this Node to XHTML using +options+
-
#
-
# doc.to_xhtml(:indent => 5, :encoding => 'UTF-8')
-
#
-
# See Node#write_to for a list of +options+
-
2
def to_xhtml options = {}
-
to_format SaveOptions::DEFAULT_XHTML, options
-
end
-
-
###
-
# Write Node to +io+ with +options+. +options+ modify the output of
-
# this method. Valid options are:
-
#
-
# * +:encoding+ for changing the encoding
-
# * +:indent_text+ the indentation text, defaults to one space
-
# * +:indent+ the number of +:indent_text+ to use, defaults to 2
-
# * +:save_with+ a combination of SaveOptions constants.
-
#
-
# To save with UTF-8 indented twice:
-
#
-
# node.write_to(io, :encoding => 'UTF-8', :indent => 2)
-
#
-
# To save indented with two dashes:
-
#
-
# node.write_to(io, :indent_text => '-', :indent => 2
-
#
-
2
def write_to io, *options
-
options = options.first.is_a?(Hash) ? options.shift : {}
-
encoding = options[:encoding] || options[0]
-
if Nokogiri.jruby?
-
save_options = options[:save_with] || options[1]
-
indent_times = options[:indent] || 0
-
else
-
save_options = options[:save_with] || options[1] || SaveOptions::FORMAT
-
indent_times = options[:indent] || 2
-
end
-
indent_text = options[:indent_text] || ' '
-
-
config = SaveOptions.new(save_options.to_i)
-
yield config if block_given?
-
-
native_write_to(io, encoding, indent_text * indent_times, config.options)
-
end
-
-
###
-
# Write Node as HTML to +io+ with +options+
-
#
-
# See Node#write_to for a list of +options+
-
2
def write_html_to io, options = {}
-
write_format_to SaveOptions::DEFAULT_HTML, io, options
-
end
-
-
###
-
# Write Node as XHTML to +io+ with +options+
-
#
-
# See Node#write_to for a list of +options+
-
2
def write_xhtml_to io, options = {}
-
write_format_to SaveOptions::DEFAULT_XHTML, io, options
-
end
-
-
###
-
# Write Node as XML to +io+ with +options+
-
#
-
# doc.write_xml_to io, :encoding => 'UTF-8'
-
#
-
# See Node#write_to for a list of options
-
2
def write_xml_to io, options = {}
-
options[:save_with] ||= SaveOptions::DEFAULT_XML
-
write_to io, options
-
end
-
-
###
-
# Compare two Node objects with respect to their Document. Nodes from
-
# different documents cannot be compared.
-
2
def <=> other
-
return nil unless other.is_a?(Nokogiri::XML::Node)
-
return nil unless document == other.document
-
compare other
-
end
-
-
###
-
# Do xinclude substitution on the subtree below node. If given a block, a
-
# Nokogiri::XML::ParseOptions object initialized from +options+, will be
-
# passed to it, allowing more convenient modification of the parser options.
-
2
def do_xinclude options = XML::ParseOptions::DEFAULT_XML, &block
-
options = Nokogiri::XML::ParseOptions.new(options) if Fixnum === options
-
-
# give options to user
-
yield options if block_given?
-
-
# call c extension
-
process_xincludes(options.to_i)
-
end
-
-
2
def canonicalize(mode=XML::XML_C14N_1_0,inclusive_namespaces=nil,with_comments=false)
-
c14n_root = self
-
document.canonicalize(mode, inclusive_namespaces, with_comments) do |node, parent|
-
tn = node.is_a?(XML::Node) ? node : parent
-
tn == c14n_root || tn.ancestors.include?(c14n_root)
-
end
-
end
-
-
2
private
-
-
2
def add_sibling next_or_previous, node_or_tags
-
impl = (next_or_previous == :next) ? :add_next_sibling_node : :add_previous_sibling_node
-
iter = (next_or_previous == :next) ? :reverse_each : :each
-
-
node_or_tags = coerce node_or_tags
-
if node_or_tags.is_a?(XML::NodeSet)
-
if text?
-
pivot = Nokogiri::XML::Node.new 'dummy', document
-
send impl, pivot
-
else
-
pivot = self
-
end
-
node_or_tags.send(iter) { |n| pivot.send impl, n }
-
pivot.unlink if text?
-
else
-
send impl, node_or_tags
-
end
-
node_or_tags
-
end
-
-
2
def to_format save_option, options
-
# FIXME: this is a hack around broken libxml versions
-
return dump_html if Nokogiri.uses_libxml? && %w[2 6] === LIBXML_VERSION.split('.')[0..1]
-
-
options[:save_with] = save_option unless options[:save_with]
-
serialize(options)
-
end
-
-
2
def write_format_to save_option, io, options
-
# FIXME: this is a hack around broken libxml versions
-
return (io << dump_html) if Nokogiri.uses_libxml? && %w[2 6] === LIBXML_VERSION.split('.')[0..1]
-
-
options[:save_with] ||= save_option
-
write_to io, options
-
end
-
-
2
def inspect_attributes
-
[:name, :namespace, :attribute_nodes, :children]
-
end
-
-
2
def coerce data # :nodoc:
-
case data
-
when XML::NodeSet
-
return data
-
when XML::DocumentFragment
-
return data.children
-
when String
-
return fragment(data).children
-
when Document, XML::Attr
-
# unacceptable
-
when XML::Node
-
return data
-
end
-
-
raise ArgumentError, <<-EOERR
-
Requires a Node, NodeSet or String argument, and cannot accept a #{data.class}.
-
(You probably want to select a node from the Document with at() or search(), or create a new Node via Node.new().)
-
EOERR
-
end
-
-
2
def implied_xpath_contexts # :nodoc:
-
[".//"]
-
end
-
-
2
def add_child_node_and_reparent_attrs node # :nodoc:
-
add_child_node node
-
node.attribute_nodes.find_all { |a| a.name =~ /:/ }.each do |attr_node|
-
attr_node.remove
-
node[attr_node.name] = attr_node.value
-
end
-
end
-
end
-
end
-
end
-
2
module Nokogiri
-
2
module XML
-
2
class Node
-
###
-
# Save options for serializing nodes
-
2
class SaveOptions
-
# Format serialized xml
-
2
FORMAT = 1
-
# Do not include declarations
-
2
NO_DECLARATION = 2
-
# Do not include empty tags
-
2
NO_EMPTY_TAGS = 4
-
# Do not save XHTML
-
2
NO_XHTML = 8
-
# Save as XHTML
-
2
AS_XHTML = 16
-
# Save as XML
-
2
AS_XML = 32
-
# Save as HTML
-
2
AS_HTML = 64
-
-
2
if Nokogiri.jruby?
-
# Save builder created document
-
AS_BUILDER = 128
-
# the default for XML documents
-
DEFAULT_XML = AS_XML # https://github.com/sparklemotion/nokogiri/issues/#issue/415
-
# the default for HTML document
-
DEFAULT_HTML = NO_DECLARATION | NO_EMPTY_TAGS | AS_HTML
-
else
-
# the default for XML documents
-
2
DEFAULT_XML = FORMAT | AS_XML
-
# the default for HTML document
-
2
DEFAULT_HTML = FORMAT | NO_DECLARATION | NO_EMPTY_TAGS | AS_HTML
-
end
-
# the default for XHTML document
-
2
DEFAULT_XHTML = FORMAT | NO_DECLARATION | NO_EMPTY_TAGS | AS_XHTML
-
-
# Integer representation of the SaveOptions
-
2
attr_reader :options
-
-
# Create a new SaveOptions object with +options+
-
2
def initialize options = 0; @options = options; end
-
-
2
constants.each do |constant|
-
20
class_eval %{
-
def #{constant.downcase}
-
@options |= #{constant}
-
self
-
end
-
-
def #{constant.downcase}?
-
#{constant} & @options == #{constant}
-
end
-
}
-
end
-
-
2
alias :to_i :options
-
end
-
end
-
end
-
end
-
2
module Nokogiri
-
2
module XML
-
####
-
# A NodeSet contains a list of Nokogiri::XML::Node objects. Typically
-
# a NodeSet is return as a result of searching a Document via
-
# Nokogiri::XML::Searchable#css or Nokogiri::XML::Searchable#xpath
-
2
class NodeSet
-
2
include Nokogiri::XML::Searchable
-
2
include Enumerable
-
-
# The Document this NodeSet is associated with
-
2
attr_accessor :document
-
-
# Create a NodeSet with +document+ defaulting to +list+
-
2
def initialize document, list = []
-
4
@document = document
-
4
document.decorate(self)
-
8
list.each { |x| self << x }
-
4
yield self if block_given?
-
end
-
-
###
-
# Get the first element of the NodeSet.
-
2
def first n = nil
-
8
return self[0] unless n
-
list = []
-
n.times { |i| list << self[i] }
-
list
-
end
-
-
###
-
# Get the last element of the NodeSet.
-
2
def last
-
self[-1]
-
end
-
-
###
-
# Is this NodeSet empty?
-
2
def empty?
-
length == 0
-
end
-
-
###
-
# Returns the index of the first node in self that is == to +node+. Returns nil if no match is found.
-
2
def index(node)
-
each_with_index { |member, j| return j if member == node }
-
nil
-
end
-
-
###
-
# Insert +datum+ before the first Node in this NodeSet
-
2
def before datum
-
first.before datum
-
end
-
-
###
-
# Insert +datum+ after the last Node in this NodeSet
-
2
def after datum
-
last.after datum
-
end
-
-
2
alias :<< :push
-
2
alias :remove :unlink
-
-
###
-
# call-seq: css *rules, [namespace-bindings, custom-pseudo-class]
-
#
-
# Search this node set for CSS +rules+. +rules+ must be one or more CSS
-
# selectors. For example:
-
#
-
# For more information see Nokogiri::XML::Searchable#css
-
2
def css *args
-
rules, handler, ns, _ = extract_params(args)
-
-
inject(NodeSet.new(document)) do |set, node|
-
set += css_internal node, rules, handler, ns
-
end
-
end
-
-
###
-
# call-seq: xpath *paths, [namespace-bindings, variable-bindings, custom-handler-class]
-
#
-
# Search this node set for XPath +paths+. +paths+ must be one or more XPath
-
# queries.
-
#
-
# For more information see Nokogiri::XML::Searchable#xpath
-
2
def xpath *args
-
paths, handler, ns, binds = extract_params(args)
-
-
inject(NodeSet.new(document)) do |set, node|
-
set += node.xpath(*(paths + [ns, handler, binds].compact))
-
end
-
end
-
-
###
-
# Search this NodeSet's nodes' immediate children using CSS selector +selector+
-
2
def > selector
-
ns = document.root.namespaces
-
xpath CSS.xpath_for(selector, :prefix => "./", :ns => ns).first
-
end
-
-
###
-
# call-seq: search *paths, [namespace-bindings, xpath-variable-bindings, custom-handler-class]
-
#
-
# Search this object for +paths+, and return only the first
-
# result. +paths+ must be one or more XPath or CSS queries.
-
#
-
# See Searchable#search for more information.
-
#
-
# Or, if passed an integer, index into the NodeSet:
-
#
-
# node_set.at(3) # same as node_set[3]
-
#
-
2
def at *args
-
if args.length == 1 && args.first.is_a?(Numeric)
-
return self[args.first]
-
end
-
-
super(*args)
-
end
-
2
alias :% :at
-
-
###
-
# Filter this list for nodes that match +expr+
-
2
def filter expr
-
find_all { |node| node.matches?(expr) }
-
end
-
-
###
-
# Append the class attribute +name+ to all Node objects in the NodeSet.
-
2
def add_class name
-
each do |el|
-
classes = el['class'].to_s.split(/\s+/)
-
el['class'] = classes.push(name).uniq.join " "
-
end
-
self
-
end
-
-
###
-
# Remove the class attribute +name+ from all Node objects in the NodeSet.
-
# If +name+ is nil, remove the class attribute from all Nodes in the
-
# NodeSet.
-
2
def remove_class name = nil
-
each do |el|
-
if name
-
classes = el['class'].to_s.split(/\s+/)
-
if classes.empty?
-
el.delete 'class'
-
else
-
el['class'] = (classes - [name]).uniq.join " "
-
end
-
else
-
el.delete "class"
-
end
-
end
-
self
-
end
-
-
###
-
# Set the attribute +key+ to +value+ or the return value of +blk+
-
# on all Node objects in the NodeSet.
-
2
def attr key, value = nil, &blk
-
unless Hash === key || key && (value || blk)
-
return first.attribute(key)
-
end
-
-
hash = key.is_a?(Hash) ? key : { key => value }
-
-
hash.each { |k,v| each { |el| el[k] = v || blk[el] } }
-
-
self
-
end
-
2
alias :set :attr
-
2
alias :attribute :attr
-
-
###
-
# Remove the attributed named +name+ from all Node objects in the NodeSet
-
2
def remove_attr name
-
each { |el| el.delete name }
-
self
-
end
-
-
###
-
# Iterate over each node, yielding to +block+
-
2
def each(&block)
-
18
0.upto(length - 1) do |x|
-
33
yield self[x]
-
end
-
end
-
-
###
-
# Get the inner text of all contained Node objects
-
2
def inner_text
-
collect{|j| j.inner_text}.join('')
-
end
-
2
alias :text :inner_text
-
-
###
-
# Get the inner html of all contained Node objects
-
2
def inner_html *args
-
collect{|j| j.inner_html(*args) }.join('')
-
end
-
-
###
-
# Wrap this NodeSet with +html+ or the results of the builder in +blk+
-
2
def wrap(html, &blk)
-
each do |j|
-
new_parent = document.parse(html).first
-
j.add_next_sibling(new_parent)
-
new_parent.add_child(j)
-
end
-
self
-
end
-
-
###
-
# Convert this NodeSet to a string.
-
2
def to_s
-
map { |x| x.to_s }.join
-
end
-
-
###
-
# Convert this NodeSet to HTML
-
2
def to_html *args
-
if Nokogiri.jruby?
-
options = args.first.is_a?(Hash) ? args.shift : {}
-
if !options[:save_with]
-
options[:save_with] = Node::SaveOptions::NO_DECLARATION | Node::SaveOptions::NO_EMPTY_TAGS | Node::SaveOptions::AS_HTML
-
end
-
args.insert(0, options)
-
end
-
map { |x| x.to_html(*args) }.join
-
end
-
-
###
-
# Convert this NodeSet to XHTML
-
2
def to_xhtml *args
-
map { |x| x.to_xhtml(*args) }.join
-
end
-
-
###
-
# Convert this NodeSet to XML
-
2
def to_xml *args
-
map { |x| x.to_xml(*args) }.join
-
end
-
-
2
alias :size :length
-
2
alias :to_ary :to_a
-
-
###
-
# Removes the last element from set and returns it, or +nil+ if
-
# the set is empty
-
2
def pop
-
return nil if length == 0
-
delete last
-
end
-
-
###
-
# Returns the first element of the NodeSet and removes it. Returns
-
# +nil+ if the set is empty.
-
2
def shift
-
return nil if length == 0
-
delete first
-
end
-
-
###
-
# Equality -- Two NodeSets are equal if the contain the same number
-
# of elements and if each element is equal to the corresponding
-
# element in the other NodeSet
-
2
def == other
-
return false unless other.is_a?(Nokogiri::XML::NodeSet)
-
return false unless length == other.length
-
each_with_index do |node, i|
-
return false unless node == other[i]
-
end
-
true
-
end
-
-
###
-
# Returns a new NodeSet containing all the children of all the nodes in
-
# the NodeSet
-
2
def children
-
inject(NodeSet.new(document)) { |set, node| set += node.children }
-
end
-
-
###
-
# Returns a new NodeSet containing all the nodes in the NodeSet
-
# in reverse order
-
2
def reverse
-
node_set = NodeSet.new(document)
-
(length - 1).downto(0) do |x|
-
node_set.push self[x]
-
end
-
node_set
-
end
-
-
###
-
# Return a nicely formated string representation
-
2
def inspect
-
"[#{map { |c| c.inspect }.join ', '}]"
-
end
-
-
2
alias :+ :|
-
-
2
private
-
-
2
def implied_xpath_contexts # :nodoc:
-
[".//", "self::"]
-
end
-
end
-
end
-
end
-
2
module Nokogiri
-
2
module XML
-
2
class Notation < Struct.new(:name, :public_id, :system_id)
-
end
-
end
-
end
-
2
module Nokogiri
-
2
module XML
-
###
-
# Parse options for passing to Nokogiri.XML or Nokogiri.HTML
-
2
class ParseOptions
-
# Strict parsing
-
2
STRICT = 0
-
# Recover from errors
-
2
RECOVER = 1 << 0
-
# Substitute entities
-
2
NOENT = 1 << 1
-
# Load external subsets
-
2
DTDLOAD = 1 << 2
-
# Default DTD attributes
-
2
DTDATTR = 1 << 3
-
# validate with the DTD
-
2
DTDVALID = 1 << 4
-
# suppress error reports
-
2
NOERROR = 1 << 5
-
# suppress warning reports
-
2
NOWARNING = 1 << 6
-
# pedantic error reporting
-
2
PEDANTIC = 1 << 7
-
# remove blank nodes
-
2
NOBLANKS = 1 << 8
-
# use the SAX1 interface internally
-
2
SAX1 = 1 << 9
-
# Implement XInclude substitution
-
2
XINCLUDE = 1 << 10
-
# Forbid network access. Recommended for dealing with untrusted documents.
-
2
NONET = 1 << 11
-
# Do not reuse the context dictionary
-
2
NODICT = 1 << 12
-
# remove redundant namespaces declarations
-
2
NSCLEAN = 1 << 13
-
# merge CDATA as text nodes
-
2
NOCDATA = 1 << 14
-
# do not generate XINCLUDE START/END nodes
-
2
NOXINCNODE = 1 << 15
-
# compact small text nodes; no modification of the tree allowed afterwards (will possibly crash if you try to modify the tree)
-
2
COMPACT = 1 << 16
-
# parse using XML-1.0 before update 5
-
2
OLD10 = 1 << 17
-
# do not fixup XINCLUDE xml:base uris
-
2
NOBASEFIX = 1 << 18
-
# relax any hardcoded limit from the parser
-
2
HUGE = 1 << 19
-
-
# the default options used for parsing XML documents
-
2
DEFAULT_XML = RECOVER | NONET
-
# the default options used for parsing HTML documents
-
2
DEFAULT_HTML = RECOVER | NOERROR | NOWARNING | NONET
-
-
2
attr_accessor :options
-
2
def initialize options = STRICT
-
7
@options = options
-
end
-
-
2
constants.each do |constant|
-
46
next if constant.to_sym == :STRICT
-
44
class_eval %{
-
def #{constant.downcase}
-
@options |= #{constant}
-
self
-
end
-
-
def no#{constant.downcase}
-
@options &= ~#{constant}
-
self
-
end
-
-
def #{constant.downcase}?
-
#{constant} & @options == #{constant}
-
end
-
}
-
end
-
-
2
def strict
-
@options &= ~RECOVER
-
self
-
end
-
-
2
def strict?
-
@options & RECOVER == STRICT
-
end
-
-
2
alias :to_i :options
-
-
2
def inspect
-
options = []
-
self.class.constants.each do |k|
-
options << k.downcase if send(:"#{k.downcase}?")
-
end
-
super.sub(/>$/, " " + options.join(', ') + ">")
-
end
-
end
-
end
-
end
-
2
require 'nokogiri/xml/pp/node'
-
2
require 'nokogiri/xml/pp/character_data'
-
2
module Nokogiri
-
2
module XML
-
2
module PP
-
2
module CharacterData
-
2
def pretty_print pp # :nodoc:
-
nice_name = self.class.name.split('::').last
-
pp.group(2, "#(#{nice_name} ", ')') do
-
pp.pp text
-
end
-
end
-
-
2
def inspect # :nodoc:
-
"#<#{self.class.name}:#{sprintf("0x%x",object_id)} #{text.inspect}>"
-
end
-
end
-
end
-
end
-
end
-
2
module Nokogiri
-
2
module XML
-
2
module PP
-
2
module Node
-
2
def inspect # :nodoc:
-
attributes = inspect_attributes.reject { |x|
-
begin
-
attribute = send x
-
!attribute || (attribute.respond_to?(:empty?) && attribute.empty?)
-
rescue NoMethodError
-
true
-
end
-
}.map { |attribute|
-
"#{attribute.to_s.sub(/_\w+/, 's')}=#{send(attribute).inspect}"
-
}.join ' '
-
"#<#{self.class.name}:#{sprintf("0x%x", object_id)} #{attributes}>"
-
end
-
-
2
def pretty_print pp # :nodoc:
-
nice_name = self.class.name.split('::').last
-
pp.group(2, "#(#{nice_name}:#{sprintf("0x%x", object_id)} {", '})') do
-
-
pp.breakable
-
attrs = inspect_attributes.map { |t|
-
[t, send(t)] if respond_to?(t)
-
}.compact.find_all { |x|
-
if x.last
-
if [:attribute_nodes, :children].include? x.first
-
!x.last.empty?
-
else
-
true
-
end
-
end
-
}
-
-
pp.seplist(attrs) do |v|
-
if [:attribute_nodes, :children].include? v.first
-
pp.group(2, "#{v.first.to_s.sub(/_\w+$/, 's')} = [", "]") do
-
pp.breakable
-
pp.seplist(v.last) do |item|
-
pp.pp item
-
end
-
end
-
else
-
pp.text "#{v.first} = "
-
pp.pp v.last
-
end
-
end
-
pp.breakable
-
-
end
-
end
-
end
-
end
-
end
-
end
-
2
module Nokogiri
-
2
module XML
-
2
class ProcessingInstruction < Node
-
2
def initialize document, name, content
-
end
-
end
-
end
-
end
-
2
module Nokogiri
-
2
module XML
-
2
class << self
-
###
-
# Create a new Nokogiri::XML::RelaxNG document from +string_or_io+.
-
# See Nokogiri::XML::RelaxNG for an example.
-
2
def RelaxNG string_or_io
-
RelaxNG.new(string_or_io)
-
end
-
end
-
-
###
-
# Nokogiri::XML::RelaxNG is used for validating XML against a
-
# RelaxNG schema.
-
#
-
# == Synopsis
-
#
-
# Validate an XML document against a RelaxNG schema. Loop over the errors
-
# that are returned and print them out:
-
#
-
# schema = Nokogiri::XML::RelaxNG(File.open(ADDRESS_SCHEMA_FILE))
-
# doc = Nokogiri::XML(File.open(ADDRESS_XML_FILE))
-
#
-
# schema.validate(doc).each do |error|
-
# puts error.message
-
# end
-
#
-
# The list of errors are Nokogiri::XML::SyntaxError objects.
-
2
class RelaxNG < Nokogiri::XML::Schema
-
end
-
end
-
end
-
2
require 'nokogiri/xml/sax/document'
-
2
require 'nokogiri/xml/sax/parser_context'
-
2
require 'nokogiri/xml/sax/parser'
-
2
require 'nokogiri/xml/sax/push_parser'
-
2
module Nokogiri
-
2
module XML
-
###
-
# SAX Parsers are event driven parsers. Nokogiri provides two different
-
# event based parsers when dealing with XML. If you want to do SAX style
-
# parsing using HTML, check out Nokogiri::HTML::SAX.
-
#
-
# The basic way a SAX style parser works is by creating a parser,
-
# telling the parser about the events we're interested in, then giving
-
# the parser some XML to process. The parser will notify you when
-
# it encounters events you said you would like to know about.
-
#
-
# To register for events, you simply subclass Nokogiri::XML::SAX::Document,
-
# and implement the methods for which you would like notification.
-
#
-
# For example, if I want to be notified when a document ends, and when an
-
# element starts, I would write a class like this:
-
#
-
# class MyDocument < Nokogiri::XML::SAX::Document
-
# def end_document
-
# puts "the document has ended"
-
# end
-
#
-
# def start_element name, attributes = []
-
# puts "#{name} started"
-
# end
-
# end
-
#
-
# Then I would instantiate a SAX parser with this document, and feed the
-
# parser some XML
-
#
-
# # Create a new parser
-
# parser = Nokogiri::XML::SAX::Parser.new(MyDocument.new)
-
#
-
# # Feed the parser some XML
-
# parser.parse(File.open(ARGV[0]))
-
#
-
# Now my document handler will be called when each node starts, and when
-
# then document ends. To see what kinds of events are available, take
-
# a look at Nokogiri::XML::SAX::Document.
-
#
-
# Two SAX parsers for XML are available, a parser that reads from a string
-
# or IO object as it feels necessary, and a parser that lets you spoon
-
# feed it XML. If you want to let Nokogiri deal with reading your XML,
-
# use the Nokogiri::XML::SAX::Parser. If you want to have fine grain
-
# control over the XML input, use the Nokogiri::XML::SAX::PushParser.
-
2
module SAX
-
###
-
# This class is used for registering types of events you are interested
-
# in handling. All of the methods on this class are available as
-
# possible events while parsing an XML document. To register for any
-
# particular event, just subclass this class and implement the methods
-
# you are interested in knowing about.
-
#
-
# To only be notified about start and end element events, write a class
-
# like this:
-
#
-
# class MyDocument < Nokogiri::XML::SAX::Document
-
# def start_element name, attrs = []
-
# puts "#{name} started!"
-
# end
-
#
-
# def end_element name
-
# puts "#{name} ended"
-
# end
-
# end
-
#
-
# You can use this event handler for any SAX style parser included with
-
# Nokogiri. See Nokogiri::XML::SAX, and Nokogiri::HTML::SAX.
-
2
class Document
-
###
-
# Called when an XML declaration is parsed
-
2
def xmldecl version, encoding, standalone
-
end
-
-
###
-
# Called when document starts parsing
-
2
def start_document
-
end
-
-
###
-
# Called when document ends parsing
-
2
def end_document
-
end
-
-
###
-
# Called at the beginning of an element
-
# * +name+ is the name of the tag
-
# * +attrs+ are an assoc list of namespaces and attributes, e.g.:
-
# [ ["xmlns:foo", "http://sample.net"], ["size", "large"] ]
-
2
def start_element name, attrs = []
-
end
-
-
###
-
# Called at the end of an element
-
# +name+ is the tag name
-
2
def end_element name
-
end
-
-
###
-
# Called at the beginning of an element
-
# +name+ is the element name
-
# +attrs+ is a list of attributes
-
# +prefix+ is the namespace prefix for the element
-
# +uri+ is the associated namespace URI
-
# +ns+ is a hash of namespace prefix:urls associated with the element
-
2
def start_element_namespace name, attrs = [], prefix = nil, uri = nil, ns = []
-
###
-
# Deal with SAX v1 interface
-
name = [prefix, name].compact.join(':')
-
attributes = ns.map { |ns_prefix,ns_uri|
-
[['xmlns', ns_prefix].compact.join(':'), ns_uri]
-
} + attrs.map { |attr|
-
[[attr.prefix, attr.localname].compact.join(':'), attr.value]
-
}
-
start_element name, attributes
-
end
-
-
###
-
# Called at the end of an element
-
# +name+ is the element's name
-
# +prefix+ is the namespace prefix associated with the element
-
# +uri+ is the associated namespace URI
-
2
def end_element_namespace name, prefix = nil, uri = nil
-
###
-
# Deal with SAX v1 interface
-
end_element [prefix, name].compact.join(':')
-
end
-
-
###
-
# Characters read between a tag. This method might be called multiple
-
# times given one contiguous string of characters.
-
#
-
# +string+ contains the character data
-
2
def characters string
-
end
-
-
###
-
# Called when comments are encountered
-
# +string+ contains the comment data
-
2
def comment string
-
end
-
-
###
-
# Called on document warnings
-
# +string+ contains the warning
-
2
def warning string
-
end
-
-
###
-
# Called on document errors
-
# +string+ contains the error
-
2
def error string
-
end
-
-
###
-
# Called when cdata blocks are found
-
# +string+ contains the cdata content
-
2
def cdata_block string
-
end
-
-
###
-
# Called when processing instructions are found
-
# +name+ is the target of the instruction
-
# +content+ is the value of the instruction
-
2
def processing_instruction name, content
-
end
-
end
-
end
-
end
-
end
-
2
module Nokogiri
-
2
module XML
-
2
module SAX
-
###
-
# This parser is a SAX style parser that reads it's input as it
-
# deems necessary. The parser takes a Nokogiri::XML::SAX::Document,
-
# an optional encoding, then given an XML input, sends messages to
-
# the Nokogiri::XML::SAX::Document.
-
#
-
# Here is an example of using this parser:
-
#
-
# # Create a subclass of Nokogiri::XML::SAX::Document and implement
-
# # the events we care about:
-
# class MyDoc < Nokogiri::XML::SAX::Document
-
# def start_element name, attrs = []
-
# puts "starting: #{name}"
-
# end
-
#
-
# def end_element name
-
# puts "ending: #{name}"
-
# end
-
# end
-
#
-
# # Create our parser
-
# parser = Nokogiri::XML::SAX::Parser.new(MyDoc.new)
-
#
-
# # Send some XML to the parser
-
# parser.parse(File.open(ARGV[0]))
-
#
-
# For more information about SAX parsers, see Nokogiri::XML::SAX. Also
-
# see Nokogiri::XML::SAX::Document for the available events.
-
2
class Parser
-
2
class Attribute < Struct.new(:localname, :prefix, :uri, :value)
-
end
-
-
# Encodinds this parser supports
-
2
ENCODINGS = {
-
'NONE' => 0, # No char encoding detected
-
'UTF-8' => 1, # UTF-8
-
'UTF16LE' => 2, # UTF-16 little endian
-
'UTF16BE' => 3, # UTF-16 big endian
-
'UCS4LE' => 4, # UCS-4 little endian
-
'UCS4BE' => 5, # UCS-4 big endian
-
'EBCDIC' => 6, # EBCDIC uh!
-
'UCS4-2143' => 7, # UCS-4 unusual ordering
-
'UCS4-3412' => 8, # UCS-4 unusual ordering
-
'UCS2' => 9, # UCS-2
-
'ISO-8859-1' => 10, # ISO-8859-1 ISO Latin 1
-
'ISO-8859-2' => 11, # ISO-8859-2 ISO Latin 2
-
'ISO-8859-3' => 12, # ISO-8859-3
-
'ISO-8859-4' => 13, # ISO-8859-4
-
'ISO-8859-5' => 14, # ISO-8859-5
-
'ISO-8859-6' => 15, # ISO-8859-6
-
'ISO-8859-7' => 16, # ISO-8859-7
-
'ISO-8859-8' => 17, # ISO-8859-8
-
'ISO-8859-9' => 18, # ISO-8859-9
-
'ISO-2022-JP' => 19, # ISO-2022-JP
-
'SHIFT-JIS' => 20, # Shift_JIS
-
'EUC-JP' => 21, # EUC-JP
-
'ASCII' => 22, # pure ASCII
-
}
-
-
# The Nokogiri::XML::SAX::Document where events will be sent.
-
2
attr_accessor :document
-
-
# The encoding beings used for this document.
-
2
attr_accessor :encoding
-
-
# Create a new Parser with +doc+ and +encoding+
-
2
def initialize doc = Nokogiri::XML::SAX::Document.new, encoding = 'UTF-8'
-
check_encoding(encoding)
-
@encoding = encoding
-
@document = doc
-
@warned = false
-
end
-
-
###
-
# Parse given +thing+ which may be a string containing xml, or an
-
# IO object.
-
2
def parse thing, &block
-
if thing.respond_to?(:read) && thing.respond_to?(:close)
-
parse_io(thing, &block)
-
else
-
parse_memory(thing, &block)
-
end
-
end
-
-
###
-
# Parse given +io+
-
2
def parse_io io, encoding = 'ASCII'
-
check_encoding(encoding)
-
@encoding = encoding
-
ctx = ParserContext.io(io, ENCODINGS[encoding])
-
yield ctx if block_given?
-
ctx.parse_with self
-
end
-
-
###
-
# Parse a file with +filename+
-
2
def parse_file filename
-
raise ArgumentError unless filename
-
raise Errno::ENOENT unless File.exist?(filename)
-
raise Errno::EISDIR if File.directory?(filename)
-
ctx = ParserContext.file filename
-
yield ctx if block_given?
-
ctx.parse_with self
-
end
-
-
2
def parse_memory data
-
ctx = ParserContext.memory data
-
yield ctx if block_given?
-
ctx.parse_with self
-
end
-
-
2
private
-
2
def check_encoding(encoding)
-
encoding.upcase!
-
raise ArgumentError.new("'#{encoding}' is not a valid encoding") unless ENCODINGS[encoding]
-
end
-
end
-
end
-
end
-
end
-
2
module Nokogiri
-
2
module XML
-
2
module SAX
-
###
-
# Context for XML SAX parsers. This class is usually not instantiated
-
# by the user. Instead, you should be looking at
-
# Nokogiri::XML::SAX::Parser
-
2
class ParserContext
-
2
def self.new thing, encoding = 'UTF-8'
-
[:read, :close].all? { |x| thing.respond_to?(x) } ?
-
io(thing, Parser::ENCODINGS[encoding]) : memory(thing)
-
end
-
end
-
end
-
end
-
end
-
2
module Nokogiri
-
2
module XML
-
2
module SAX
-
###
-
# PushParser can parse a document that is fed to it manually. It
-
# must be given a SAX::Document object which will be called with
-
# SAX events as the document is being parsed.
-
#
-
# Calling PushParser#<< writes XML to the parser, calling any SAX
-
# callbacks it can.
-
#
-
# PushParser#finish tells the parser that the document is finished
-
# and calls the end_document SAX method.
-
#
-
# Example:
-
#
-
# parser = PushParser.new(Class.new(XML::SAX::Document) {
-
# def start_document
-
# puts "start document called"
-
# end
-
# }.new)
-
# parser << "<div>hello<"
-
# parser << "/div>"
-
# parser.finish
-
2
class PushParser
-
-
# The Nokogiri::XML::SAX::Document on which the PushParser will be
-
# operating
-
2
attr_accessor :document
-
-
###
-
# Create a new PushParser with +doc+ as the SAX Document, providing
-
# an optional +file_name+ and +encoding+
-
2
def initialize(doc = XML::SAX::Document.new, file_name = nil, encoding = 'UTF-8')
-
@document = doc
-
@encoding = encoding
-
@sax_parser = XML::SAX::Parser.new(doc)
-
-
## Create our push parser context
-
initialize_native(@sax_parser, file_name)
-
end
-
-
###
-
# Write a +chunk+ of XML to the PushParser. Any callback methods
-
# that can be called will be called immediately.
-
2
def write chunk, last_chunk = false
-
native_write(chunk, last_chunk)
-
end
-
2
alias :<< :write
-
-
###
-
# Finish the parsing. This method is only necessary for
-
# Nokogiri::XML::SAX::Document#end_document to be called.
-
2
def finish
-
write '', true
-
end
-
end
-
end
-
end
-
end
-
2
module Nokogiri
-
2
module XML
-
2
class << self
-
###
-
# Create a new Nokogiri::XML::Schema object using a +string_or_io+
-
# object.
-
2
def Schema string_or_io
-
Schema.new(string_or_io)
-
end
-
end
-
-
###
-
# Nokogiri::XML::Schema is used for validating XML against a schema
-
# (usually from an xsd file).
-
#
-
# == Synopsis
-
#
-
# Validate an XML document against a Schema. Loop over the errors that
-
# are returned and print them out:
-
#
-
# xsd = Nokogiri::XML::Schema(File.read(PO_SCHEMA_FILE))
-
# doc = Nokogiri::XML(File.read(PO_XML_FILE))
-
#
-
# xsd.validate(doc).each do |error|
-
# puts error.message
-
# end
-
#
-
# The list of errors are Nokogiri::XML::SyntaxError objects.
-
2
class Schema
-
# Errors while parsing the schema file
-
2
attr_accessor :errors
-
-
###
-
# Create a new Nokogiri::XML::Schema object using a +string_or_io+
-
# object.
-
2
def self.new string_or_io
-
from_document Nokogiri::XML(string_or_io)
-
end
-
-
###
-
# Validate +thing+ against this schema. +thing+ can be a
-
# Nokogiri::XML::Document object, or a filename. An Array of
-
# Nokogiri::XML::SyntaxError objects found while validating the
-
# +thing+ is returned.
-
2
def validate thing
-
if thing.is_a?(Nokogiri::XML::Document)
-
validate_document(thing)
-
elsif File.file?(thing)
-
validate_file(thing)
-
else
-
raise ArgumentError, "Must provide Nokogiri::Xml::Document or the name of an existing file"
-
end
-
end
-
-
###
-
# Returns true if +thing+ is a valid Nokogiri::XML::Document or
-
# file.
-
2
def valid? thing
-
validate(thing).length == 0
-
end
-
end
-
end
-
end
-
2
module Nokogiri
-
2
module XML
-
#
-
# The Searchable module declares the interface used for searching your DOM.
-
#
-
# It implements the public methods `search`, `css`, and `xpath`,
-
# as well as allowing specific implementations to specialize some
-
# of the important behaviors.
-
#
-
2
module Searchable
-
# Regular expression used by Searchable#search to determine if a query
-
# string is CSS or XPath
-
2
LOOKS_LIKE_XPATH = /^(\.\/|\/|\.\.|\.$)/
-
-
###
-
# call-seq: search *paths, [namespace-bindings, xpath-variable-bindings, custom-handler-class]
-
#
-
# Search this object for +paths+. +paths+ must be one or more XPath or CSS queries:
-
#
-
# node.search("div.employee", ".//title")
-
#
-
# A hash of namespace bindings may be appended:
-
#
-
# node.search('.//bike:tire', {'bike' => 'http://schwinn.com/'})
-
# node.search('bike|tire', {'bike' => 'http://schwinn.com/'})
-
#
-
# For XPath queries, a hash of variable bindings may also be
-
# appended to the namespace bindings. For example:
-
#
-
# node.search('.//address[@domestic=$value]', nil, {:value => 'Yes'})
-
#
-
# Custom XPath functions and CSS pseudo-selectors may also be
-
# defined. To define custom functions create a class and
-
# implement the function you want to define. The first argument
-
# to the method will be the current matching NodeSet. Any other
-
# arguments are ones that you pass in. Note that this class may
-
# appear anywhere in the argument list. For example:
-
#
-
# node.search('.//title[regex(., "\w+")]', 'div.employee:regex("[0-9]+")'
-
# Class.new {
-
# def regex node_set, regex
-
# node_set.find_all { |node| node['some_attribute'] =~ /#{regex}/ }
-
# end
-
# }.new
-
# )
-
#
-
# See Searchable#xpath and Searchable#css for further usage help.
-
2
def search *args
-
34
paths, handler, ns, binds = extract_params(args)
-
-
34
xpaths = paths.map(&:to_s).map do |path|
-
34
(path =~ LOOKS_LIKE_XPATH) ? path : xpath_query_from_css_rule(path, ns)
-
end.flatten.uniq
-
-
34
xpath(*(xpaths + [ns, handler, binds].compact))
-
end
-
2
alias :/ :search
-
-
###
-
# call-seq: search *paths, [namespace-bindings, xpath-variable-bindings, custom-handler-class]
-
#
-
# Search this object for +paths+, and return only the first
-
# result. +paths+ must be one or more XPath or CSS queries.
-
#
-
# See Searchable#search for more information.
-
2
def at *args
-
search(*args).first
-
end
-
2
alias :% :at
-
-
###
-
# call-seq: css *rules, [namespace-bindings, custom-pseudo-class]
-
#
-
# Search this object for CSS +rules+. +rules+ must be one or more CSS
-
# selectors. For example:
-
#
-
# node.css('title')
-
# node.css('body h1.bold')
-
# node.css('div + p.green', 'div#one')
-
#
-
# A hash of namespace bindings may be appended. For example:
-
#
-
# node.css('bike|tire', {'bike' => 'http://schwinn.com/'})
-
#
-
# Custom CSS pseudo classes may also be defined. To define
-
# custom pseudo classes, create a class and implement the custom
-
# pseudo class you want defined. The first argument to the
-
# method will be the current matching NodeSet. Any other
-
# arguments are ones that you pass in. For example:
-
#
-
# node.css('title:regex("\w+")', Class.new {
-
# def regex node_set, regex
-
# node_set.find_all { |node| node['some_attribute'] =~ /#{regex}/ }
-
# end
-
# }.new)
-
#
-
# Note that the CSS query string is case-sensitive with regards
-
# to your document type. That is, if you're looking for "H1" in
-
# an HTML document, you'll never find anything, since HTML tags
-
# will match only lowercase CSS queries. However, "H1" might be
-
# found in an XML document, where tags names are case-sensitive
-
# (e.g., "H1" is distinct from "h1").
-
#
-
2
def css *args
-
rules, handler, ns, _ = extract_params(args)
-
-
css_internal self, rules, handler, ns
-
end
-
-
##
-
# call-seq: css *rules, [namespace-bindings, custom-pseudo-class]
-
#
-
# Search this object for CSS +rules+, and return only the first
-
# match. +rules+ must be one or more CSS selectors.
-
#
-
# See Searchable#css for more information.
-
2
def at_css *args
-
css(*args).first
-
end
-
-
###
-
# call-seq: xpath *paths, [namespace-bindings, variable-bindings, custom-handler-class]
-
#
-
# Search this node for XPath +paths+. +paths+ must be one or more XPath
-
# queries.
-
#
-
# node.xpath('.//title')
-
#
-
# A hash of namespace bindings may be appended. For example:
-
#
-
# node.xpath('.//foo:name', {'foo' => 'http://example.org/'})
-
# node.xpath('.//xmlns:name', node.root.namespaces)
-
#
-
# A hash of variable bindings may also be appended to the namespace bindings. For example:
-
#
-
# node.xpath('.//address[@domestic=$value]', nil, {:value => 'Yes'})
-
#
-
# Custom XPath functions may also be defined. To define custom
-
# functions create a class and implement the function you want
-
# to define. The first argument to the method will be the
-
# current matching NodeSet. Any other arguments are ones that
-
# you pass in. Note that this class may appear anywhere in the
-
# argument list. For example:
-
#
-
# node.xpath('.//title[regex(., "\w+")]', Class.new {
-
# def regex node_set, regex
-
# node_set.find_all { |node| node['some_attribute'] =~ /#{regex}/ }
-
# end
-
# }.new)
-
#
-
2
def xpath *args
-
63
return NodeSet.new(document) unless document
-
-
63
paths, handler, ns, binds = extract_params(args)
-
-
63
sets = paths.map do |path|
-
63
ctx = XPathContext.new(self)
-
63
ctx.register_namespaces(ns)
-
63
path = path.gsub(/xmlns:/, ' :') unless Nokogiri.uses_libxml?
-
-
binds.each do |key,value|
-
ctx.register_variable key.to_s, value
-
63
end if binds
-
-
63
ctx.evaluate(path, handler)
-
end
-
63
return sets.first if sets.length == 1
-
-
NodeSet.new(document) do |combined|
-
sets.each do |set|
-
set.each do |node|
-
combined << node
-
end
-
end
-
end
-
end
-
-
##
-
# call-seq: xpath *paths, [namespace-bindings, variable-bindings, custom-handler-class]
-
#
-
# Search this node for XPath +paths+, and return only the first
-
# match. +paths+ must be one or more XPath queries.
-
#
-
# See Searchable#xpath for more information.
-
2
def at_xpath *args
-
xpath(*args).first
-
end
-
-
2
private
-
-
2
def css_internal node, rules, handler, ns
-
xpaths = rules.map { |rule| xpath_query_from_css_rule(rule, ns) }
-
node.xpath(*(xpaths + [ns, handler].compact))
-
end
-
-
2
def xpath_query_from_css_rule rule, ns
-
implied_xpath_contexts.map do |implied_xpath_context|
-
34
CSS.xpath_for(rule.to_s, :prefix => implied_xpath_context, :ns => ns)
-
34
end.join(' | ')
-
end
-
-
2
def extract_params params # :nodoc:
-
97
handler = params.find do |param|
-
131
![Hash, String, Symbol].include?(param.class)
-
end
-
97
params -= [handler] if handler
-
-
97
hashes = []
-
97
while Hash === params.last || params.last.nil?
-
34
hashes << params.pop
-
34
break if params.empty?
-
end
-
97
ns, binds = hashes.reverse
-
-
97
ns ||= document.root ? document.root.namespaces : {}
-
-
97
[params, handler, ns, binds]
-
end
-
end
-
end
-
end
-
2
module Nokogiri
-
2
module XML
-
###
-
# This class provides information about XML SyntaxErrors. These
-
# exceptions are typically stored on Nokogiri::XML::Document#errors.
-
2
class SyntaxError < ::Nokogiri::SyntaxError
-
2
attr_reader :domain
-
2
attr_reader :code
-
2
attr_reader :level
-
2
attr_reader :file
-
2
attr_reader :line
-
2
attr_reader :str1
-
2
attr_reader :str2
-
2
attr_reader :str3
-
2
attr_reader :int1
-
2
attr_reader :column
-
-
###
-
# return true if this is a non error
-
2
def none?
-
level == 0
-
end
-
-
###
-
# return true if this is a warning
-
2
def warning?
-
level == 1
-
end
-
-
###
-
# return true if this is an error
-
2
def error?
-
level == 2
-
end
-
-
###
-
# return true if this error is fatal
-
2
def fatal?
-
level == 3
-
end
-
-
2
def to_s
-
super.chomp
-
end
-
end
-
end
-
end
-
2
module Nokogiri
-
2
module XML
-
2
class Text < Nokogiri::XML::CharacterData
-
2
def content=(string)
-
self.native_content = string.to_s
-
end
-
end
-
end
-
end
-
2
require 'nokogiri/xml/xpath/syntax_error'
-
-
2
module Nokogiri
-
2
module XML
-
2
class XPath
-
# The Nokogiri::XML::Document tied to this XPath instance
-
2
attr_accessor :document
-
end
-
end
-
end
-
2
module Nokogiri
-
2
module XML
-
2
class XPath
-
2
class SyntaxError < XML::SyntaxError
-
2
def to_s
-
[super.chomp, str1].compact.join(': ')
-
end
-
end
-
end
-
end
-
end
-
2
module Nokogiri
-
2
module XML
-
2
class XPathContext
-
-
###
-
# Register namespaces in +namespaces+
-
2
def register_namespaces(namespaces)
-
63
namespaces.each do |k, v|
-
k = k.to_s.gsub(/.*:/,'') # strip off 'xmlns:' or 'xml:'
-
register_ns(k, v)
-
end
-
end
-
-
end
-
end
-
end
-
2
require 'nokogiri/xslt/stylesheet'
-
-
2
module Nokogiri
-
2
class << self
-
###
-
# Create a Nokogiri::XSLT::Stylesheet with +stylesheet+.
-
#
-
# Example:
-
#
-
# xslt = Nokogiri::XSLT(File.read(ARGV[0]))
-
#
-
2
def XSLT stylesheet, modules = {}
-
XSLT.parse(stylesheet, modules)
-
end
-
end
-
-
###
-
# See Nokogiri::XSLT::Stylesheet for creating and manipulating
-
# Stylesheet object.
-
2
module XSLT
-
2
class << self
-
###
-
# Parse the stylesheet in +string+, register any +modules+
-
2
def parse string, modules = {}
-
modules.each do |url, klass|
-
XSLT.register url, klass
-
end
-
-
if Nokogiri.jruby?
-
Stylesheet.parse_stylesheet_doc(XML.parse(string), string)
-
else
-
Stylesheet.parse_stylesheet_doc(XML.parse(string))
-
end
-
end
-
-
###
-
# Quote parameters in +params+ for stylesheet safety
-
2
def quote_params params
-
parray = (params.instance_of?(Hash) ? params.to_a.flatten : params).dup
-
parray.each_with_index do |v,i|
-
if i % 2 > 0
-
parray[i]=
-
if v =~ /'/
-
"concat('#{ v.gsub(/'/, %q{', "'", '}) }')"
-
else
-
"'#{v}'";
-
end
-
else
-
parray[i] = v.to_s
-
end
-
end
-
parray.flatten
-
end
-
end
-
end
-
end
-
2
module Nokogiri
-
2
module XSLT
-
###
-
# A Stylesheet represents an XSLT Stylesheet object. Stylesheet creation
-
# is done through Nokogiri.XSLT. Here is an example of transforming
-
# an XML::Document with a Stylesheet:
-
#
-
# doc = Nokogiri::XML(File.read('some_file.xml'))
-
# xslt = Nokogiri::XSLT(File.read('some_transformer.xslt'))
-
#
-
# puts xslt.transform(doc)
-
#
-
# See Nokogiri::XSLT::Stylesheet#transform for more transformation
-
# information.
-
2
class Stylesheet
-
###
-
# Apply an XSLT stylesheet to an XML::Document.
-
# +params+ is an array of strings used as XSLT parameters.
-
# returns serialized document
-
2
def apply_to document, params = []
-
serialize(transform(document, params))
-
end
-
end
-
end
-
end
-
2
require "yaml"
-
2
require "rbconfig"
-
2
require "pathname"
-
2
require "nenv"
-
2
require "logger"
-
-
2
require "notiffany/notifier/detected"
-
-
2
module Notiffany
-
# The notifier handles sending messages to different notifiers. Currently the
-
# following libraries are supported:
-
#
-
# * Ruby GNTP
-
# * Growl
-
# * Libnotify
-
# * rb-notifu
-
# * emacs
-
# * Terminal Notifier
-
# * Terminal Title
-
# * Tmux
-
#
-
# Please see the documentation of each notifier for more information about
-
# the requirements
-
# and configuration possibilities.
-
#
-
# Notiffany knows four different notification types:
-
#
-
# * success
-
# * pending
-
# * failed
-
# * notify
-
#
-
# The notification type selection is based on the image option that is
-
# sent to {#notify}. Each image type has its own notification type, and
-
# notifications with custom images goes all sent as type `notify`. The
-
# `gntp` notifier is able to register these types
-
# at Growl and allows customization of each notification type.
-
#
-
# Notiffany can be configured to make use of more than one notifier at once.
-
#
-
2
def self.connect(options = {})
-
Notifier.new(options)
-
end
-
-
2
class Notifier
-
2
DEFAULTS = { notify: true }
-
-
2
NOTIFICATIONS_DISABLED = "Notifications disabled by GUARD_NOTIFY" +
-
" environment variable"
-
-
2
USING_NOTIFIER = "Notiffany is using %s to send notifications."
-
-
2
ONLY_NOTIFY = "Only notify() is available from a child process"
-
-
# List of available notifiers, grouped by functionality
-
2
SUPPORTED = [
-
{
-
gntp: GNTP,
-
growl: Growl,
-
terminal_notifier: TerminalNotifier,
-
libnotify: Libnotify,
-
notifysend: NotifySend,
-
notifu: Notifu
-
},
-
{ emacs: Emacs },
-
{ tmux: Tmux },
-
{ terminal_title: TerminalTitle },
-
{ file: File }
-
]
-
-
2
Env = Nenv::Builder.build do
-
2
create_method(:notify?) { |data| data != "false" }
-
2
create_method(:notify_pid) { |data| data && Integer(data) }
-
2
create_method(:notify_pid=)
-
2
create_method(:notify_active?)
-
2
create_method(:notify_active=)
-
end
-
-
2
class NotServer < RuntimeError
-
end
-
-
2
def initialize(opts)
-
@env_namespace = opts.fetch(:namespace, "notiffany")
-
@logger = opts.fetch(:logger) do
-
Logger.new($stderr).tap { |l| l.level = Logger::WARN }
-
end
-
-
-
@detected = Detected.new(SUPPORTED, @env_namespace, @logger)
-
return if _client?
-
-
_env.notify_pid = $$
-
-
fail "Already connected" if active?
-
-
options = DEFAULTS.merge(opts)
-
return unless enabled? && options[:notify]
-
-
notifiers = opts.fetch(:notifiers, {})
-
if notifiers.any?
-
notifiers.each do |name, notifier_options|
-
@detected.add(name, notifier_options)
-
end
-
else
-
@detected.detect
-
end
-
-
turn_on
-
rescue Detected::NoneAvailableError => e
-
@logger.info e.to_s
-
end
-
-
2
def disconnect
-
if _client?
-
@detected = nil
-
return
-
end
-
-
turn_off if active?
-
@detected.reset unless @detected.nil?
-
_env.notify_pid = nil
-
@detected = nil
-
end
-
-
# Turn notifications on.
-
#
-
# @param [Hash] options the turn_on options
-
# @option options [Boolean] silent disable any logging
-
#
-
2
def turn_on(options = {})
-
_check_server!
-
return unless enabled?
-
-
fail "Already active!" if active?
-
-
silent = options[:silent]
-
-
@detected.available.each do |obj|
-
@logger.debug(format(USING_NOTIFIER, obj.title)) unless silent
-
obj.turn_on if obj.respond_to?(:turn_on)
-
end
-
-
_env.notify_active = true
-
end
-
-
# Turn notifications off.
-
2
def turn_off
-
_check_server!
-
-
fail "Not active!" unless active?
-
-
@detected.available.each do |obj|
-
obj.turn_off if obj.respond_to?(:turn_off)
-
end
-
-
_env.notify_active = false
-
end
-
-
# Test if the notifications can be enabled based on ENV['GUARD_NOTIFY']
-
2
def enabled?
-
_env.notify?
-
end
-
-
# Test if notifiers are currently turned on
-
2
def active?
-
_env.notify_active?
-
end
-
-
# Show a system notification with all configured notifiers.
-
#
-
# @param [String] message the message to show
-
# @option opts [Symbol, String] image the image symbol or path to an image
-
# @option opts [String] title the notification title
-
#
-
2
def notify(message, message_opts = {})
-
if _client?
-
return unless enabled?
-
else
-
return unless active?
-
end
-
-
@detected.available.each do |notifier|
-
notifier.notify(message, message_opts.dup)
-
end
-
end
-
-
2
def available
-
@detected.available
-
end
-
-
2
private
-
-
2
def _env
-
@environment ||= Env.new(@env_namespace)
-
end
-
-
2
def _check_server!
-
_client? && fail(NotServer, ONLY_NOTIFY)
-
end
-
-
2
def _client?
-
(pid = _env.notify_pid) && (pid != $$)
-
end
-
end
-
end
-
2
require "rbconfig"
-
-
2
module Notiffany
-
2
class Notifier
-
2
class Base
-
2
HOSTS = {
-
darwin: "Mac OS X",
-
linux: "Linux",
-
'linux-gnu' => "Linux",
-
freebsd: "FreeBSD",
-
openbsd: "OpenBSD",
-
sunos: "SunOS",
-
solaris: "Solaris",
-
mswin: "Windows",
-
mingw: "Windows",
-
cygwin: "Windows"
-
}
-
-
2
ERROR_ADD_GEM_AND_RUN_BUNDLE = "Please add \"gem '%s'\" to your Gemfile "\
-
"and run your app with \"bundle exec\"."
-
-
2
class UnavailableError < RuntimeError
-
2
def initialize(reason)
-
super
-
@reason = reason
-
end
-
-
2
def message
-
@reason
-
end
-
end
-
-
2
class RequireFailed < UnavailableError
-
2
def initialize(gem_name)
-
super ERROR_ADD_GEM_AND_RUN_BUNDLE % gem_name
-
end
-
end
-
-
2
class UnsupportedPlatform < UnavailableError
-
2
def initialize
-
super "Unsupported platform #{RbConfig::CONFIG["host_os"].inspect}"
-
end
-
end
-
-
2
attr_reader :options
-
-
2
def initialize(opts = {})
-
options = opts.dup
-
options.delete(:silent)
-
@options =
-
{ title: "Notiffany" }.
-
merge(self.class.const_get(:DEFAULTS)).
-
merge(options).freeze
-
-
@images_path = Pathname.new(__FILE__).dirname + "../../../images"
-
-
_check_host_supported
-
_require_gem
-
_check_available(@options)
-
end
-
-
2
def title
-
self.class.to_s[/.+::(\w+)$/, 1]
-
end
-
-
2
def name
-
title.gsub(/([a-z])([A-Z])/, '\1_\2').downcase
-
end
-
-
2
def notify(message, opts = {})
-
new_opts = _notify_options(opts).freeze
-
_perform_notify(message, new_opts)
-
end
-
-
2
def _image_path(image)
-
images = [:failed, :pending, :success, :guard]
-
images.include?(image) ? @images_path.join("#{image}.png").to_s : image
-
end
-
-
2
private
-
-
# Override if necessary
-
2
def _gem_name
-
name
-
end
-
-
# Override if necessary
-
2
def _supported_hosts
-
:all
-
end
-
-
# Override
-
2
def _check_available(_options)
-
fail NotImplementedError
-
end
-
-
# Override
-
2
def _perform_notify(_message, _opts)
-
fail NotImplementedError
-
end
-
-
2
def _notification_type(image)
-
[:failed, :pending, :success].include?(image) ? image : :notify
-
end
-
-
2
def _notify_options(overrides = {})
-
opts = @options.merge(overrides)
-
img_type = opts.fetch(:image, :success)
-
opts[:type] ||= _notification_type(img_type)
-
opts[:image] = _image_path(img_type)
-
opts
-
end
-
-
2
def _check_host_supported
-
return if _supported_hosts == :all
-
expr = /#{_supported_hosts * '|'}/
-
fail UnsupportedPlatform unless expr.match(RbConfig::CONFIG["host_os"])
-
end
-
-
2
def _require_gem
-
Kernel.require _gem_name unless _gem_name.nil?
-
rescue LoadError, NameError
-
fail RequireFailed, _gem_name
-
end
-
end
-
end
-
end
-
2
require "nenv"
-
2
require "yaml"
-
-
2
require_relative "emacs"
-
2
require_relative "file"
-
2
require_relative "gntp"
-
2
require_relative "growl"
-
2
require_relative "libnotify"
-
2
require_relative "notifysend"
-
2
require_relative "rb_notifu"
-
2
require_relative "terminal_notifier"
-
2
require_relative "terminal_title"
-
2
require_relative "tmux"
-
-
2
module Notiffany
-
2
class Notifier
-
# @private api
-
-
# TODO: use a socket instead of passing env variables to child processes
-
# (currently probably only used by guard-cucumber anyway)
-
2
YamlEnvStorage = Nenv::Builder.build do
-
2
create_method(:notifiers=) { |data| YAML::dump(data || []) }
-
2
create_method(:notifiers) { |data| data ? YAML::load(data) : [] }
-
end
-
-
# @private api
-
2
class Detected
-
2
NO_SUPPORTED_NOTIFIERS = "Notiffany could not detect any of the"\
-
" supported notification libraries."
-
-
2
class NoneAvailableError < RuntimeError
-
end
-
-
2
class UnknownNotifier < RuntimeError
-
2
def initialize(name)
-
super
-
@name = name
-
end
-
-
2
def name
-
@name
-
end
-
-
2
def message
-
"Unknown notifier: #{@name.inspect}"
-
end
-
end
-
-
2
def initialize(supported, env_namespace, logger)
-
@supported = supported
-
@environment = YamlEnvStorage.new(env_namespace)
-
@logger = logger
-
end
-
-
2
def reset
-
@environment.notifiers = []
-
end
-
-
2
def detect
-
return unless _notifiers.empty?
-
@supported.each do |group|
-
group.detect do |name, _|
-
begin
-
add(name, {})
-
true
-
rescue Notifier::Base::UnavailableError => e
-
@logger.debug "Notiffany: #{name} not available (#{e.message})."
-
false
-
end
-
end
-
end
-
-
fail NoneAvailableError, NO_SUPPORTED_NOTIFIERS if _notifiers.empty?
-
end
-
-
2
def available
-
@available ||= _notifiers.map do |entry|
-
_to_module(entry[:name]).new(entry[:options])
-
end
-
end
-
-
2
def add(name, opts)
-
@available = nil
-
all = _notifiers
-
-
# Silently skip if it's already available, because otherwise
-
# we'd have to do :turn_off, then configure, then :turn_on
-
names = all.map(&:first).map(&:last)
-
unless names.include?(name)
-
fail UnknownNotifier, name unless (klass = _to_module(name))
-
-
klass.new(opts) # raises if unavailable
-
@environment.notifiers = all << { name: name, options: opts }
-
end
-
-
# Just overwrite the options (without turning the notifier off or on),
-
# so those options will be passed in next calls to notify()
-
all.each { |item| item[:options] = opts if item[:name] == name }
-
end
-
-
2
private
-
-
2
def _to_module(name)
-
@supported.each do |group|
-
next unless (notifier = group.detect { |n, _| n == name })
-
return notifier.last
-
end
-
nil
-
end
-
-
2
def _notifiers
-
@environment.notifiers
-
end
-
end
-
end
-
end
-
2
require "notiffany/notifier/base"
-
2
require "shellany/sheller"
-
-
2
module Notiffany
-
2
class Notifier
-
# Send a notification to Emacs with emacsclient
-
# (http://www.emacswiki.org/emacs/EmacsClient).
-
#
-
2
class Emacs < Base
-
2
DEFAULTS = {
-
client: "emacsclient",
-
success: "ForestGreen",
-
failed: "Firebrick",
-
default: "Black",
-
fontcolor: "White",
-
}
-
-
2
class Client
-
2
def initialize(options)
-
@client = options[:client]
-
end
-
-
2
def available?
-
emacs_eval({ 'ALTERNATE_EDITOR' =>'false' }, "'1'")
-
end
-
-
2
def notify(color, bgcolor)
-
elisp = <<-EOF.gsub(/\s+/, " ").strip
-
(set-face-attribute 'mode-line nil
-
:background "#{bgcolor}"
-
:foreground "#{color}")
-
EOF
-
emacs_eval(elisp)
-
end
-
-
2
private
-
-
2
def emacs_eval(env={}, code)
-
Shellany::Sheller.run(env, @client, "--eval", code)
-
end
-
end
-
-
2
private
-
-
2
def _gem_name
-
nil
-
end
-
-
2
def _check_available(options)
-
return if Client.new(options).available?
-
fail UnavailableError, "Emacs client failed"
-
end
-
-
# Shows a system notification.
-
#
-
# @param [String] type the notification type. Either 'success',
-
# 'pending', 'failed' or 'notify'
-
# @param [String] title the notification title
-
# @param [String] message the notification message body
-
# @param [String] image the path to the notification image
-
# @param [Hash] opts additional notification library options
-
# @option opts [String] success the color to use for success
-
# notifications (default is 'ForestGreen')
-
# @option opts [String] failed the color to use for failure
-
# notifications (default is 'Firebrick')
-
# @option opts [String] pending the color to use for pending
-
# notifications
-
# @option opts [String] default the default color to use (default is
-
# 'Black')
-
# @option opts [String] client the client to use for notification
-
# (default is 'emacsclient')
-
# @option opts [String, Integer] priority specify an int or named key
-
# (default is 0)
-
#
-
2
def _perform_notify(_message, opts = {})
-
color = _emacs_color(opts[:type], opts)
-
fontcolor = _emacs_color(:fontcolor, opts)
-
Client.new(opts).notify(fontcolor, color)
-
end
-
-
# Get the Emacs color for the notification type.
-
# You can configure your own color by overwrite the defaults.
-
#
-
# @param [String] type the notification type
-
# @param [Hash] options aditional notification options
-
#
-
# @option options [String] success the color to use for success
-
# notifications (default is 'ForestGreen')
-
#
-
# @option options [String] failed the color to use for failure
-
# notifications (default is 'Firebrick')
-
#
-
# @option options [String] pending the color to use for pending
-
# notifications
-
#
-
# @option options [String] default the default color to use (default is
-
# 'Black')
-
#
-
# @return [String] the name of the emacs color
-
#
-
2
def _emacs_color(type, options = {})
-
default = options.fetch(:default, DEFAULTS[:default])
-
options.fetch(type.to_sym, default)
-
end
-
end
-
end
-
end
-
2
require "notiffany/notifier/base"
-
-
2
module Notiffany
-
2
class Notifier
-
# Writes notifications to a file.
-
#
-
2
class File < Base
-
2
DEFAULTS = { format: "%s\n%s\n%s\n" }
-
-
2
private
-
-
# @param [Hash] opts some options
-
# @option opts [Boolean] path the path to a file where notification
-
# message will be written
-
#
-
2
def _check_available(opts = {})
-
fail UnavailableError, "No :path option given" unless opts[:path]
-
end
-
-
# Writes the notification to a file. By default it writes type, title,
-
# and message separated by newlines.
-
#
-
# @param [String] message the notification message body
-
# @param [Hash] opts additional notification library options
-
# @option opts [String] type the notification type. Either 'success',
-
# 'pending', 'failed' or 'notify'
-
# @option opts [String] title the notification title
-
# @option opts [String] image the path to the notification image
-
# @option opts [String] format printf style format for file contents
-
# @option opts [String] path the path of where to write the file
-
#
-
2
def _perform_notify(message, opts = {})
-
fail UnavailableError, "No :path option given" unless opts[:path]
-
-
format = opts[:format]
-
::File.write(opts[:path], format % [opts[:type], opts[:title], message])
-
end
-
-
2
def _gem_name
-
nil
-
end
-
end
-
end
-
end
-
2
require "notiffany/notifier/base"
-
-
2
module Notiffany
-
2
class Notifier
-
# System notifications using the
-
# [ruby_gntp](https://github.com/snaka/ruby_gntp) gem.
-
#
-
# This gem is available for OS X, Linux and Windows and sends system
-
# notifications to the following system notification frameworks through the
-
#
-
# [Growl Network Transport
-
# Protocol](http://www.growlforwindows.com/gfw/help/gntp.aspx):
-
#
-
# * [Growl](http://growl.info)
-
# * [Growl for Windows](http://www.growlforwindows.com)
-
# * [Growl for Linux](http://mattn.github.com/growl-for-linux)
-
# * [Snarl](https://sites.google.com/site/snarlapp)
-
2
class GNTP < Base
-
2
DEFAULTS = {
-
sticky: false
-
}
-
-
# Default options for the ruby gtnp client.
-
2
CLIENT_DEFAULTS = {
-
host: "127.0.0.1",
-
password: "",
-
port: 23053
-
}
-
-
2
def _supported_hosts
-
%w(darwin linux linux-gnu freebsd openbsd sunos solaris mswin mingw cygwin)
-
end
-
-
2
def _gem_name
-
"ruby_gntp"
-
end
-
-
2
def _check_available(_opts)
-
end
-
-
# Shows a system notification.
-
#
-
# @param [String] message the notification message body
-
# @param [Hash] opts additional notification library options
-
# @option opts [String] type the notification type. Either 'success',
-
# 'pending', 'failed' or 'notify'
-
# @option opts [String] title the notification title
-
# @option opts [String] image the path to the notification image
-
# @option opts [String] host the hostname or IP address to which to send
-
# a remote notification
-
# @option opts [String] password the password used for remote
-
# notifications
-
# @option opts [Integer] port the port to send a remote notification
-
# @option opts [Boolean] sticky make the notification sticky
-
#
-
2
def _perform_notify(message, opts = {})
-
opts = {
-
name: opts[:type].to_s,
-
text: message,
-
icon: opts[:image]
-
}.merge(opts)
-
-
_gntp_client(opts).notify(opts)
-
end
-
-
2
private
-
-
2
def _gntp_client(opts = {})
-
@_client ||= begin
-
gntp = ::GNTP.new(
-
"Notiffany",
-
opts.fetch(:host) { CLIENT_DEFAULTS[:host] },
-
opts.fetch(:password) { CLIENT_DEFAULTS[:password] },
-
opts.fetch(:port) { CLIENT_DEFAULTS[:port] }
-
)
-
-
gntp.register(
-
app_icon: _image_path(:guard),
-
notifications: [
-
{ name: "notify", enabled: true },
-
{ name: "failed", enabled: true },
-
{ name: "pending", enabled: true },
-
{ name: "success", enabled: true }
-
]
-
)
-
gntp
-
end
-
end
-
end
-
end
-
end
-
2
require "notiffany/notifier/base"
-
-
2
module Notiffany
-
2
class Notifier
-
# System notifications using the
-
# [growl](https://github.com/visionmedia/growl) gem.
-
#
-
# This gem is available for OS X and sends system notifications to
-
# [Growl](http://growl.info) through the
-
# [GrowlNotify](http://growl.info/downloads) executable.
-
#
-
# The `growlnotify` executable must be installed manually or by using
-
# [Homebrew](http://mxcl.github.com/homebrew/).
-
#
-
# Sending notifications with this notifier will not show the different
-
# notifications in the Growl preferences. Use the :gntp notifier if you
-
# want to customize each notification type in Growl.
-
#
-
# @example Install `growlnotify` with Homebrew
-
# brew install growlnotify
-
#
-
# @example Add the `growl` gem to your `Gemfile`
-
# group :development
-
# gem 'growl'
-
# end
-
#
-
# @example Add the `:growl` notifier to your `Guardfile`
-
# notification :growl
-
#
-
# @example Add the `:growl_notify` notifier with configuration options to
-
# your `Guardfile` notification :growl, sticky: true, host: '192.168.1.5',
-
# password: 'secret'
-
#
-
2
class Growl < Base
-
2
INSTALL_GROWLNOTIFY = "Please install the 'growlnotify' executable'\
-
' (available by installing the 'growl' gem)."
-
-
# Default options for the growl notifications.
-
2
DEFAULTS = {
-
sticky: false,
-
priority: 0
-
}
-
-
2
def _supported_hosts
-
%w(darwin)
-
end
-
-
2
def _check_available(_opts = {})
-
fail UnavailableError, INSTALL_GROWLNOTIFY unless ::Growl.installed?
-
end
-
-
# Shows a system notification.
-
#
-
# The documented options are for GrowlNotify 1.3, but the older options
-
# are also supported. Please see `growlnotify --help`.
-
#
-
# Priority can be one of the following named keys: `Very Low`,
-
# `Moderate`, `Normal`, `High`, `Emergency`. It can also be an integer
-
# between -2 and 2.
-
#
-
# @param [String] message the notification message body
-
# @param [Hash] opts additional notification library options
-
# @option opts [String] type the notification type. Either 'success',
-
# 'pending', 'failed' or 'notify'
-
# @option opts [String] title the notification title
-
# @option opts [String] image the path to the notification image
-
# @option opts [Boolean] sticky make the notification sticky
-
# @option opts [String, Integer] priority specify an int or named key
-
# (default is 0)
-
# @option opts [String] host the hostname or IP address to which to
-
# send a remote notification
-
# @option opts [String] password the password used for remote
-
# notifications
-
#
-
2
def _perform_notify(message, opts = {})
-
opts = { name: "Notiffany" }.merge(opts)
-
opts.select! { |k, _| ::Growl::Base.switches.include?(k) }
-
::Growl.notify(message, opts)
-
end
-
end
-
end
-
end
-
2
require "notiffany/notifier/base"
-
-
2
module Notiffany
-
2
class Notifier
-
# System notifications using the
-
# [libnotify](https://github.com/splattael/libnotify) gem.
-
#
-
# This gem is available for Linux, FreeBSD, OpenBSD and Solaris and sends
-
# system notifications to
-
# Gnome [libnotify](http://developer.gnome.org/libnotify):
-
#
-
2
class Libnotify < Base
-
2
DEFAULTS = {
-
transient: false,
-
append: true,
-
timeout: 3
-
}
-
-
2
private
-
-
2
def _supported_hosts
-
%w(linux linux-gnu freebsd openbsd sunos solaris)
-
end
-
-
2
def _check_available(_opts = {})
-
end
-
-
# Shows a system notification.
-
#
-
# @param [String] message the notification message body
-
# @param [Hash] opts additional notification library options
-
# @option opts [String] type the notification type. Either 'success',
-
# 'pending', 'failed' or 'notify'
-
# @option opts [String] title the notification title
-
# @option opts [String] image the path to the notification image
-
# @option opts [Boolean] transient keep the notifications around after
-
# display
-
# @option opts [Boolean] append append onto existing notification
-
# @option opts [Number, Boolean] timeout the number of seconds to display
-
# (1.5 (s), 1000 (ms), false)
-
#
-
2
def _perform_notify(message, opts = {})
-
opts = opts.merge(
-
summary: opts[:title],
-
icon_path: opts[:image],
-
body: message,
-
urgency: opts[:urgency] || (opts[:type] == "failed" ? :normal : :low)
-
)
-
-
::Libnotify.show(opts)
-
end
-
end
-
end
-
end
-
2
require "notiffany/notifier/base"
-
-
2
require "shellany/sheller"
-
-
2
module Notiffany
-
2
class Notifier
-
# System notifications using notify-send, a binary that ships with
-
# the libnotify-bin package on many Debian-based distributions.
-
#
-
# @example Add the `:notifysend` notifier to your `Guardfile`
-
# notification :notifysend
-
#
-
2
class NotifySend < Base
-
# Default options for the notify-send notifications.
-
2
DEFAULTS = {
-
t: 3000, # Default timeout is 3000ms
-
h: "int:transient:1" # Automatically close the notification
-
}
-
-
# Full list of options supported by notify-send.
-
2
SUPPORTED = [:u, :t, :i, :c, :h]
-
-
2
private
-
-
# notify-send has no gem, just a binary to shell out
-
2
def _gem_name
-
nil
-
end
-
-
2
def _supported_hosts
-
%w(linux linux-gnu freebsd openbsd sunos solaris)
-
end
-
-
2
def _check_available(_opts = {})
-
return true unless Shellany::Sheller.stdout("which notify-send").empty?
-
-
fail UnavailableError, "libnotify-bin package is not installed"
-
end
-
-
# Shows a system notification.
-
#
-
# @param [String] message the notification message body
-
# @param [Hash] opts additional notification library options
-
# @option opts [String] type the notification type. Either 'success',
-
# 'pending', 'failed' or 'notify'
-
# @option opts [String] title the notification title
-
# @option opts [String] image the path to the notification image
-
# @option opts [String] c the notification category
-
# @option opts [Number] t the number of milliseconds to display (1000,
-
# 3000)
-
#
-
2
def _perform_notify(message, opts = {})
-
command = [opts[:title], message]
-
opts = opts.merge(
-
i: opts[:i] || opts[:image],
-
u: opts[:u] || _notifysend_urgency(opts[:type])
-
)
-
-
Shellany::Sheller.
-
run("notify-send", *_to_arguments(command, SUPPORTED, opts))
-
end
-
-
# Converts Guards notification type to the best matching
-
# notify-send urgency.
-
#
-
# @param [String] type the Guard notification type
-
# @return [String] the notify-send urgency
-
#
-
2
def _notifysend_urgency(type)
-
{ failed: "normal", pending: "low" }.fetch(type, "low")
-
end
-
-
# Builds a shell command out of a command string and option hash.
-
#
-
# @param [String] command the command execute
-
# @param [Array] supported list of supported option flags
-
# @param [Hash] opts additional command options
-
#
-
# @return [Array<String>] the command and its options converted to a
-
# shell command.
-
#
-
2
def _to_arguments(command, supported, opts = {})
-
opts.inject(command) do |cmd, (flag, value)|
-
supported.include?(flag) ? (cmd << "-#{ flag }" << value.to_s) : cmd
-
end
-
end
-
end
-
end
-
end
-
2
require "notiffany/notifier/base"
-
-
2
module Notiffany
-
2
class Notifier
-
# System notifications using the
-
# [rb-notifu](https://github.com/stereobooster/rb-notifu) gem.
-
#
-
# This gem is available for Windows and sends system notifications to
-
# [Notifu](http://www.paralint.com/projects/notifu/index.html):
-
#
-
# @example Add the `rb-notifu` gem to your `Gemfile`
-
# group :development
-
# gem 'rb-notifu'
-
# end
-
#
-
2
class Notifu < Base
-
# Default options for the rb-notifu notifications.
-
2
DEFAULTS = {
-
time: 3,
-
icon: false,
-
baloon: false,
-
nosound: false,
-
noquiet: false,
-
xp: false
-
}
-
-
2
private
-
-
2
def _supported_hosts
-
%w(mswin mingw)
-
end
-
-
2
def _gem_name
-
"rb-notifu"
-
end
-
-
2
def _check_available(_opts = {})
-
end
-
-
# Shows a system notification.
-
#
-
# @param [String] message the notification message body
-
# @param [Hash] opts additional notification library options
-
# @option opts [String] type the notification type. Either 'success',
-
# 'pending', 'failed' or 'notify'
-
# @option opts [String] title the notification title
-
# @option opts [String] image the path to the notification image
-
# @option opts [Number] time the number of seconds to display (0 for
-
# infinit)
-
# @option opts [Boolean] icon specify an icon to use ("parent" uses the
-
# icon of the parent process)
-
# @option opts [Boolean] baloon enable ballon tips in the registry (for
-
# this user only)
-
# @option opts [Boolean] nosound do not play a sound when the tooltip is
-
# displayed
-
# @option opts [Boolean] noquiet show the tooltip even if the user is in
-
# the quiet period that follows his very first login (Windows 7 and up)
-
# @option opts [Boolean] xp use IUserNotification interface event when
-
# IUserNotification2 is available
-
#
-
2
def _perform_notify(message, opts = {})
-
options = opts.dup
-
options[:type] = _notifu_type(opts[:type])
-
options[:message] = message
-
-
# The empty block is needed until
-
# https://github.com/stereobooster/rb-notifu/pull/1 is merged
-
::Notifu.show(options) {}
-
end
-
-
# Converts generic notification type to the best matching
-
# Notifu type.
-
#
-
# @param [String] type the generic notification type
-
# @return [Symbol] the Notify notification type
-
#
-
2
def _notifu_type(type)
-
case type.to_sym
-
when :failed
-
:error
-
when :pending
-
:warn
-
else
-
:info
-
end
-
end
-
end
-
end
-
end
-
2
require "notiffany/notifier/base"
-
-
2
module Notiffany
-
2
class Notifier
-
# System notifications using the
-
#
-
# [terminal-notifier](https://github.com/Springest/terminal-notifier-guard)
-
#
-
# gem.
-
#
-
# This gem is available for OS X 10.8 Mountain Lion and sends notifications
-
# to the OS X notification center.
-
2
class TerminalNotifier < Base
-
2
DEFAULTS = { app_name: "Notiffany" }
-
-
2
ERROR_ONLY_OSX10 = "The :terminal_notifier only runs"\
-
" on Mac OS X 10.8 and later."
-
-
2
def _supported_hosts
-
%w(darwin)
-
end
-
-
2
def _gem_name
-
"terminal-notifier-guard"
-
end
-
-
2
def _check_available(_opts = {})
-
return if ::TerminalNotifier::Guard.available?
-
fail UnavailableError, ERROR_ONLY_OSX10
-
end
-
-
# Shows a system notification.
-
#
-
# @param [String] message the notification message body
-
# @param [Hash] opts additional notification library options
-
# @option opts [String] type the notification type. Either 'success',
-
# 'pending', 'failed' or 'notify'
-
# @option opts [String] title the notification title
-
# @option opts [String] image the path to the notification image (ignored)
-
# @option opts [String] app_name name of your app
-
# @option opts [String] execute a command
-
# @option opts [String] activate an app bundle
-
# @option opts [String] open some url or file
-
#
-
2
def _perform_notify(message, opts = {})
-
title = [opts[:app_name], opts[:type].downcase.capitalize].join(" ")
-
opts = {
-
title: title
-
}.merge(opts)
-
opts[:message] = message
-
opts[:title] ||= title
-
opts.delete(:image)
-
opts.delete(:app_name)
-
-
::TerminalNotifier::Guard.execute(false, opts)
-
end
-
end
-
end
-
end
-
2
require "notiffany/notifier/base"
-
-
2
module Notiffany
-
2
class Notifier
-
# Shows system notifications in the terminal title bar.
-
#
-
2
class TerminalTitle < Base
-
2
DEFAULTS = {}
-
-
# Clears the terminal title
-
2
def turn_off
-
STDOUT.puts "\e]2;\a"
-
end
-
-
2
private
-
-
2
def _gem_name
-
nil
-
end
-
-
2
def _check_available(_options)
-
end
-
-
# Shows a system notification.
-
#
-
# @param [Hash] opts additional notification library options
-
# @option opts [String] message the notification message body
-
# @option opts [String] type the notification type. Either 'success',
-
# 'pending', 'failed' or 'notify'
-
# @option opts [String] title the notification title
-
#
-
2
def _perform_notify(message, opts = {})
-
first_line = message.sub(/^\n/, "").sub(/\n.*/m, "")
-
-
STDOUT.puts "\e]2;[#{ opts[:title] }] #{ first_line }\a"
-
end
-
end
-
end
-
end
-
2
require "notiffany/notifier/base"
-
2
require "shellany/sheller"
-
-
# TODO: this probably deserves a gem of it's own
-
2
module Notiffany
-
2
class Notifier
-
# Changes the color of the Tmux status bar and optionally
-
# shows messages in the status bar.
-
2
class Tmux < Base
-
2
@session = nil
-
-
2
DEFAULTS = {
-
tmux_environment: "TMUX",
-
success: "green",
-
failed: "red",
-
pending: "yellow",
-
default: "green",
-
timeout: 5,
-
display_message: false,
-
default_message_format: "%s - %s",
-
default_message_color: "white",
-
display_on_all_clients: false,
-
display_title: false,
-
default_title_format: "%s - %s",
-
line_separator: " - ",
-
change_color: true,
-
color_location: "status-left-bg"
-
}
-
-
2
class Client
-
2
CLIENT = "tmux"
-
-
2
class << self
-
2
def version
-
Float(_capture("-V")[/\d+\.\d+/])
-
end
-
-
2
def _capture(*args)
-
Shellany::Sheller.stdout(([CLIENT] + args).join(" "))
-
end
-
-
2
def _run(*args)
-
Shellany::Sheller.run(([CLIENT] + args).join(" "))
-
end
-
end
-
-
2
def initialize(client)
-
@client = client
-
end
-
-
2
def clients
-
return [@client] unless @client == :all
-
ttys = _capture("list-clients", "-F", "'\#{client_tty}'")
-
ttys = ttys.split(/\n/)
-
-
# if user is running 'tmux -C' remove this client from list
-
ttys.delete("(null)")
-
ttys
-
end
-
-
2
def set(key, value)
-
clients.each do |client|
-
args = client ? ["-t", client.strip] : nil
-
_run("set", "-q", *args, key, value)
-
end
-
end
-
-
2
def display_message(message)
-
clients.each do |client|
-
args = ["-c", client.strip] if client
-
# TODO: should properly escape message here
-
_run("display", *args, "'#{message}'")
-
end
-
end
-
-
2
def unset(key, value)
-
clients.each do |client|
-
args = client ? ["-t", client.strip] : []
-
if value
-
_run("set", "-q", *args, key, value)
-
else
-
_run("set", "-q", "-u", *args, key)
-
end
-
end
-
end
-
-
2
def parse_options
-
output = _capture("show", "-t", @client)
-
Hash[output.lines.map { |line| _parse_option(line) }]
-
end
-
-
2
def message_fg=(color)
-
set("message-fg", color)
-
end
-
-
2
def message_bg=(color)
-
set("message-bg", color)
-
end
-
-
2
def display_time=(time)
-
set("display-time", time)
-
end
-
-
2
def title=(string)
-
# TODO: properly escape?
-
set("set-titles-string", "'#{string}'")
-
end
-
-
2
private
-
-
2
def _run(*args)
-
self.class._run(*args)
-
end
-
-
2
def _capture(*args)
-
self.class._capture(*args)
-
end
-
-
2
def _parse_option(line)
-
line.partition(" ").map(&:strip).reject(&:empty?)
-
end
-
end
-
-
2
class Session
-
2
def initialize
-
@options_store = {}
-
-
# NOTE: we are reading the settings of all clients
-
# - regardless of the :display_on_all_clients option
-
-
# Ideally, this should be done incrementally (e.g. if we start with
-
# "current" client and then override the :display_on_all_clients to
-
# true, only then the option store should be updated to contain
-
# settings of all clients
-
Client.new(:all).clients.each do |client|
-
@options_store[client] = {
-
"status-left-bg" => nil,
-
"status-right-bg" => nil,
-
"status-left-fg" => nil,
-
"status-right-fg" => nil,
-
"message-bg" => nil,
-
"message-fg" => nil,
-
"display-time" => nil
-
}.merge(Client.new(client).parse_options)
-
end
-
end
-
-
2
def close
-
@options_store.each do |client, options|
-
options.each do |key, value|
-
Client.new(client).unset(key, value)
-
end
-
end
-
@options_store = nil
-
end
-
end
-
-
2
class Error < RuntimeError
-
end
-
-
2
ERROR_NOT_INSIDE_TMUX = ":tmux notifier is only available inside a "\
-
"TMux session."
-
-
2
ERROR_ANCIENT_TMUX = "Your tmux version is way too old (%s)!"
-
-
# Notification starting, save the current Tmux settings
-
# and quiet the Tmux output.
-
#
-
2
def turn_on
-
self.class._start_session
-
end
-
-
# Notification stopping. Restore the previous Tmux state
-
# if available (existing options are restored, new options
-
# are unset) and unquiet the Tmux output.
-
#
-
2
def turn_off
-
self.class._end_session
-
end
-
-
2
private
-
-
2
def _gem_name
-
nil
-
end
-
-
2
def _check_available(opts = {})
-
@session ||= nil # to avoid unitialized error
-
fail "PREVIOUS TMUX SESSION NOT CLEARED!" if @session
-
-
var_name = opts[:tmux_environment]
-
fail Error, ERROR_NOT_INSIDE_TMUX unless ENV.key?(var_name)
-
-
version = Client.version
-
fail Error, format(ERROR_ANCIENT_TMUX, version) if version < 1.7
-
-
true
-
rescue Error => e
-
fail UnavailableError, e.message
-
end
-
-
# Shows a system notification.
-
#
-
# By default, the Tmux notifier only makes
-
# use of a color based notification, changing the background color of the
-
# `color_location` to the color defined in either the `success`,
-
# `failed`, `pending` or `default`, depending on the notification type.
-
#
-
# You may enable an extra explicit message by setting `display_message`
-
# to true, and may further disable the colorization by setting
-
# `change_color` to false.
-
#
-
# @param [String] message the notification message
-
# @param [Hash] options additional notification library options
-
# @option options [String] type the notification type. Either 'success',
-
# 'pending', 'failed' or 'notify'
-
# @option options [String] message the notification message body
-
# @option options [String] image the path to the notification image
-
# @option options [Boolean] change_color whether to show a color
-
# notification
-
# @option options [String,Array] color_location the location where to draw
-
# the color notification
-
# @option options [Boolean] display_message whether to display a message
-
# or not
-
# @option options [Boolean] display_on_all_clients whether to display a
-
# message on all tmux clients or not
-
#
-
2
def _perform_notify(message, options = {})
-
change_color = options[:change_color]
-
locations = Array(options[:color_location])
-
display_the_title = options[:display_title]
-
display_message = options[:display_message]
-
type = options[:type].to_s
-
title = options[:title]
-
-
if change_color
-
color = _tmux_color(type, options)
-
locations.each do |location|
-
Client.new(client(options)).set(location, color)
-
end
-
end
-
-
_display_title(type, title, message, options) if display_the_title
-
-
return unless display_message
-
_display_message(type, title, message, options)
-
end
-
-
# Displays a message in the title bar of the terminal.
-
#
-
# @param [String] title the notification title
-
# @param [String] message the notification message body
-
# @param [Hash] options additional notification library options
-
# @option options [String] success_message_format a string to use as
-
# formatter for the success message.
-
# @option options [String] failed_message_format a string to use as
-
# formatter for the failed message.
-
# @option options [String] pending_message_format a string to use as
-
# formatter for the pending message.
-
# @option options [String] default_message_format a string to use as
-
# formatter when no format per type is defined.
-
#
-
2
def _display_title(type, title, message, options = {})
-
format = "#{type}_title_format".to_sym
-
default_title_format = options[:default_title_format]
-
title_format = options.fetch(format, default_title_format)
-
teaser_message = message.split("\n").first
-
display_title = title_format % [title, teaser_message]
-
-
Client.new(client(options)).title = display_title
-
end
-
-
# Displays a message in the status bar of tmux.
-
#
-
# @param [String] type the notification type. Either 'success',
-
# 'pending', 'failed' or 'notify'
-
# @param [String] title the notification title
-
# @param [String] message the notification message body
-
# @param [Hash] options additional notification library options
-
# @option options [Integer] timeout the amount of seconds to show the
-
# message in the status bar
-
# @option options [String] success_message_format a string to use as
-
# formatter for the success message.
-
# @option options [String] failed_message_format a string to use as
-
# formatter for the failed message.
-
# @option options [String] pending_message_format a string to use as
-
# formatter for the pending message.
-
# @option options [String] default_message_format a string to use as
-
# formatter when no format per type is defined.
-
# @option options [String] success_message_color the success notification
-
# foreground color name.
-
# @option options [String] failed_message_color the failed notification
-
# foreground color name.
-
# @option options [String] pending_message_color the pending notification
-
# foreground color name.
-
# @option options [String] default_message_color a notification
-
# foreground color to use when no color per type is defined.
-
# @option options [String] line_separator a string to use instead of a
-
# line-break.
-
#
-
2
def _display_message(type, title, message, opts = {})
-
default_format = opts[:default_message_format]
-
default_color = opts[:default_message_color]
-
display_time = opts[:timeout]
-
separator = opts[:line_separator]
-
-
format = "#{type}_message_format".to_sym
-
message_format = opts.fetch(format, default_format)
-
-
color = "#{type}_message_color".to_sym
-
message_color = opts.fetch(color, default_color)
-
-
color = _tmux_color(type, opts)
-
formatted_message = message.split("\n").join(separator)
-
msg = message_format % [title, formatted_message]
-
-
cl = Client.new(client(opts))
-
cl.display_time = display_time * 1000
-
cl.message_fg = message_color
-
cl.message_bg = color
-
cl.display_message(msg)
-
end
-
-
# Get the Tmux color for the notification type.
-
# You can configure your own color by overwriting the defaults.
-
#
-
# @param [String] type the notification type
-
# @return [String] the name of the emacs color
-
#
-
2
def _tmux_color(type, opts = {})
-
type = type.to_sym
-
opts[type] || opts[:default]
-
end
-
-
2
def self._start_session
-
fail "Already turned on!" if @session
-
@session = Session.new
-
end
-
-
2
def self._end_session
-
fail "Already turned off!" unless @session || nil
-
@session.close
-
@session = nil
-
end
-
-
2
def self._session
-
@session
-
end
-
-
2
def client(options)
-
options[:display_on_all_clients] ? :all : nil
-
end
-
end
-
end
-
end
-
2
require 'orm_adapter/base'
-
2
require 'orm_adapter/to_adapter'
-
2
require 'orm_adapter/version'
-
-
2
module OrmAdapter
-
# A collection of registered adapters
-
2
def self.adapters
-
2
@@adapters ||= []
-
end
-
end
-
-
2
require 'orm_adapter/adapters/active_record' if defined?(ActiveRecord::Base)
-
2
require 'orm_adapter/adapters/data_mapper' if defined?(DataMapper::Resource)
-
2
require 'orm_adapter/adapters/mongoid' if defined?(Mongoid::Document)
-
2
require 'orm_adapter/adapters/mongo_mapper' if defined?(MongoMapper::Document)
-
2
require 'active_record'
-
-
2
module OrmAdapter
-
2
class ActiveRecord < Base
-
# Return list of column/property names
-
2
def column_names
-
klass.column_names
-
end
-
-
# @see OrmAdapter::Base#get!
-
2
def get!(id)
-
klass.find(wrap_key(id))
-
end
-
-
# @see OrmAdapter::Base#get
-
2
def get(id)
-
klass.where(klass.primary_key => wrap_key(id)).first
-
end
-
-
# @see OrmAdapter::Base#find_first
-
2
def find_first(options = {})
-
construct_relation(klass, options).first
-
end
-
-
# @see OrmAdapter::Base#find_all
-
2
def find_all(options = {})
-
construct_relation(klass, options)
-
end
-
-
# @see OrmAdapter::Base#create!
-
2
def create!(attributes = {})
-
klass.create!(attributes)
-
end
-
-
# @see OrmAdapter::Base#destroy
-
2
def destroy(object)
-
object.destroy && true if valid_object?(object)
-
end
-
-
2
protected
-
2
def construct_relation(relation, options)
-
conditions, order, limit, offset = extract_conditions!(options)
-
-
relation = relation.where(conditions_to_fields(conditions))
-
relation = relation.order(order_clause(order)) if order.any?
-
relation = relation.limit(limit) if limit
-
relation = relation.offset(offset) if offset
-
-
relation
-
end
-
-
# Introspects the klass to convert and objects in conditions into foreign key and type fields
-
2
def conditions_to_fields(conditions)
-
fields = {}
-
conditions.each do |key, value|
-
if value.is_a?(::ActiveRecord::Base) && (assoc = klass.reflect_on_association(key.to_sym)) && assoc.belongs_to?
-
-
if ::ActiveRecord::VERSION::STRING < "3.1"
-
fields[assoc.primary_key_name] = value.send(value.class.primary_key)
-
fields[assoc.options[:foreign_type]] = value.class.base_class.name.to_s if assoc.options[:polymorphic]
-
else # >= 3.1
-
fields[assoc.foreign_key] = value.send(value.class.primary_key)
-
fields[assoc.foreign_type] = value.class.base_class.name.to_s if assoc.options[:polymorphic]
-
end
-
-
else
-
fields[key] = value
-
end
-
end
-
fields
-
end
-
-
2
def order_clause(order)
-
order.map {|pair| "#{pair[0]} #{pair[1]}"}.join(",")
-
end
-
end
-
end
-
-
2
ActiveSupport.on_load(:active_record) do
-
2
extend ::OrmAdapter::ToAdapter
-
2
self::OrmAdapter = ::OrmAdapter::ActiveRecord
-
end
-
2
module OrmAdapter
-
2
class Base
-
2
attr_reader :klass
-
-
# Your ORM adapter needs to inherit from this Base class and its adapter
-
# will be registered. To create an adapter you should create an inner
-
# constant "OrmAdapter" e.g. ActiveRecord::Base::OrmAdapter
-
#
-
# @see orm_adapters/active_record
-
# @see orm_adapters/datamapper
-
# @see orm_adapters/mongoid
-
2
def self.inherited(adapter)
-
2
OrmAdapter.adapters << adapter
-
2
super
-
end
-
-
2
def initialize(klass)
-
@klass = klass
-
end
-
-
# Get a list of column/property/field names
-
2
def column_names
-
raise NotSupportedError
-
end
-
-
# Get an instance by id of the model. Raises an error if a model is not found.
-
# This should comply with ActiveModel#to_key API, i.e.:
-
#
-
# User.to_adapter.get!(@user.to_key) == @user
-
#
-
2
def get!(id)
-
raise NotSupportedError
-
end
-
-
# Get an instance by id of the model. Returns nil if a model is not found.
-
# This should comply with ActiveModel#to_key API, i.e.:
-
#
-
# User.to_adapter.get(@user.to_key) == @user
-
#
-
2
def get(id)
-
raise NotSupportedError
-
end
-
-
# Find the first instance, optionally matching conditions, and specifying order
-
#
-
# You can call with just conditions, providing a hash
-
#
-
# User.to_adapter.find_first :name => "Fred", :age => 23
-
#
-
# Or you can specify :order, and :conditions as keys
-
#
-
# User.to_adapter.find_first :conditions => {:name => "Fred", :age => 23}
-
# User.to_adapter.find_first :order => [:age, :desc]
-
# User.to_adapter.find_first :order => :name, :conditions => {:age => 18}
-
#
-
# When specifying :order, it may be
-
# * a single arg e.g. <tt>:order => :name</tt>
-
# * a single pair with :asc, or :desc as last, e.g. <tt>:order => [:name, :desc]</tt>
-
# * an array of single args or pairs (with :asc or :desc as last), e.g. <tt>:order => [[:name, :asc], [:age, :desc]]</tt>
-
#
-
2
def find_first(options = {})
-
raise NotSupportedError
-
end
-
-
# Find all models, optionally matching conditions, and specifying order
-
# @see OrmAdapter::Base#find_first for how to specify order and conditions
-
2
def find_all(options = {})
-
raise NotSupportedError
-
end
-
-
# Create a model using attributes
-
2
def create!(attributes = {})
-
raise NotSupportedError
-
end
-
-
# Destroy an instance by passing in the instance itself.
-
2
def destroy(object)
-
raise NotSupportedError
-
end
-
-
2
protected
-
-
2
def valid_object?(object)
-
object.class == klass
-
end
-
-
2
def wrap_key(key)
-
key.is_a?(Array) ? key.first : key
-
end
-
-
# given an options hash,
-
# with optional :conditions, :order, :limit and :offset keys,
-
# returns conditions, normalized order, limit and offset
-
2
def extract_conditions!(options = {})
-
order = normalize_order(options.delete(:order))
-
limit = options.delete(:limit)
-
offset = options.delete(:offset)
-
conditions = options.delete(:conditions) || options
-
-
[conditions, order, limit, offset]
-
end
-
-
# given an order argument, returns an array of pairs, with each pair containing the attribute, and :asc or :desc
-
2
def normalize_order(order)
-
order = Array(order)
-
-
if order.length == 2 && !order[0].is_a?(Array) && [:asc, :desc].include?(order[1])
-
order = [order]
-
else
-
order = order.map {|pair| pair.is_a?(Array) ? pair : [pair, :asc] }
-
end
-
-
order.each do |pair|
-
pair.length == 2 or raise ArgumentError, "each order clause must be a pair (unknown clause #{pair.inspect})"
-
[:asc, :desc].include?(pair[1]) or raise ArgumentError, "order must be specified with :asc or :desc (unknown key #{pair[1].inspect})"
-
end
-
-
order
-
end
-
end
-
-
2
class NotSupportedError < NotImplementedError
-
2
def to_s
-
"method not supported by this orm adapter"
-
end
-
end
-
end
-
2
module OrmAdapter
-
# Extend into a class that has an OrmAdapter
-
2
module ToAdapter
-
2
def to_adapter
-
@_to_adapter ||= self::OrmAdapter.new(self)
-
end
-
end
-
end
-
2
module OrmAdapter
-
2
VERSION = "0.5.0"
-
end
-
# Paperclip allows file attachments that are stored in the filesystem. All graphical
-
# transformations are done using the Graphics/ImageMagick command line utilities and
-
# are stored in Tempfiles until the record is saved. Paperclip does not require a
-
# separate model for storing the attachment's information, instead adding a few simple
-
# columns to your table.
-
#
-
# Author:: Jon Yurek
-
# Copyright:: Copyright (c) 2008-2011 thoughtbot, inc.
-
# License:: MIT License (http://www.opensource.org/licenses/mit-license.php)
-
#
-
# Paperclip defines an attachment as any file, though it makes special considerations
-
# for image files. You can declare that a model has an attached file with the
-
# +has_attached_file+ method:
-
#
-
# class User < ActiveRecord::Base
-
# has_attached_file :avatar, :styles => { :thumb => "100x100" }
-
# end
-
#
-
# user = User.new
-
# user.avatar = params[:user][:avatar]
-
# user.avatar.url
-
# # => "/users/avatars/4/original_me.jpg"
-
# user.avatar.url(:thumb)
-
# # => "/users/avatars/4/thumb_me.jpg"
-
#
-
# See the +has_attached_file+ documentation for more details.
-
-
2
require 'erb'
-
2
require 'digest'
-
2
require 'tempfile'
-
2
require 'paperclip/version'
-
2
require 'paperclip/geometry_parser_factory'
-
2
require 'paperclip/geometry_detector_factory'
-
2
require 'paperclip/geometry'
-
2
require 'paperclip/processor'
-
2
require 'paperclip/processor_helpers'
-
2
require 'paperclip/tempfile'
-
2
require 'paperclip/thumbnail'
-
2
require 'paperclip/interpolations/plural_cache'
-
2
require 'paperclip/interpolations'
-
2
require 'paperclip/tempfile_factory'
-
2
require 'paperclip/style'
-
2
require 'paperclip/attachment'
-
2
require 'paperclip/storage'
-
2
require 'paperclip/callbacks'
-
2
require 'paperclip/file_command_content_type_detector'
-
2
require 'paperclip/media_type_spoof_detector'
-
2
require 'paperclip/content_type_detector'
-
2
require 'paperclip/glue'
-
2
require 'paperclip/errors'
-
2
require 'paperclip/missing_attachment_styles'
-
2
require 'paperclip/validators'
-
2
require 'paperclip/logger'
-
2
require 'paperclip/helpers'
-
2
require 'paperclip/has_attached_file'
-
2
require 'paperclip/attachment_registry'
-
2
require 'paperclip/filename_cleaner'
-
2
require 'paperclip/rails_environment'
-
-
2
begin
-
# Use mime/types/columnar if available, for reduced memory usage
-
2
require "mime/types/columnar"
-
rescue LoadError
-
require "mime/types"
-
end
-
-
2
require 'mimemagic'
-
2
require 'mimemagic/overlay'
-
2
require 'logger'
-
2
require 'cocaine'
-
-
2
require 'paperclip/railtie' if defined?(Rails::Railtie)
-
-
# The base module that gets included in ActiveRecord::Base. See the
-
# documentation for Paperclip::ClassMethods for more useful information.
-
2
module Paperclip
-
2
extend Helpers
-
2
extend Logger
-
2
extend ProcessorHelpers
-
-
# Provides configurability to Paperclip. The options available are:
-
# * whiny: Will raise an error if Paperclip cannot process thumbnails of
-
# an uploaded image. Defaults to true.
-
# * log: Logs progress to the Rails log. Uses ActiveRecord's logger, so honors
-
# log levels, etc. Defaults to true.
-
# * command_path: Defines the path at which to find the command line
-
# programs if they are not visible to Rails the system's search path. Defaults to
-
# nil, which uses the first executable found in the user's search path.
-
# * use_exif_orientation: Whether to inspect EXIF data to determine an
-
# image's orientation. Defaults to true.
-
2
def self.options
-
@options ||= {
-
:whiny => true,
-
:image_magick_path => nil,
-
:command_path => nil,
-
:log => true,
-
:log_command => true,
-
:swallow_stderr => true,
-
:content_type_mappings => {},
-
:use_exif_orientation => true
-
4
}
-
end
-
-
2
def self.io_adapters=(new_registry)
-
@io_adapters = new_registry
-
end
-
-
2
def self.io_adapters
-
20
@io_adapters ||= Paperclip::AdapterRegistry.new
-
end
-
-
2
module ClassMethods
-
# +has_attached_file+ gives the class it is called on an attribute that maps to a file. This
-
# is typically a file stored somewhere on the filesystem and has been uploaded by a user.
-
# The attribute returns a Paperclip::Attachment object which handles the management of
-
# that file. The intent is to make the attachment as much like a normal attribute. The
-
# thumbnails will be created when the new file is assigned, but they will *not* be saved
-
# until +save+ is called on the record. Likewise, if the attribute is set to +nil+ is
-
# called on it, the attachment will *not* be deleted until +save+ is called. See the
-
# Paperclip::Attachment documentation for more specifics. There are a number of options
-
# you can set to change the behavior of a Paperclip attachment:
-
# * +url+: The full URL of where the attachment is publically accessible. This can just
-
# as easily point to a directory served directly through Apache as it can to an action
-
# that can control permissions. You can specify the full domain and path, but usually
-
# just an absolute path is sufficient. The leading slash *must* be included manually for
-
# absolute paths. The default value is
-
# "/system/:class/:attachment/:id_partition/:style/:filename". See
-
# Paperclip::Attachment#interpolate for more information on variable interpolaton.
-
# :url => "/:class/:attachment/:id/:style_:filename"
-
# :url => "http://some.other.host/stuff/:class/:id_:extension"
-
# * +default_url+: The URL that will be returned if there is no attachment assigned.
-
# This field is interpolated just as the url is. The default value is
-
# "/:attachment/:style/missing.png"
-
# has_attached_file :avatar, :default_url => "/images/default_:style_avatar.png"
-
# User.new.avatar_url(:small) # => "/images/default_small_avatar.png"
-
# * +styles+: A hash of thumbnail styles and their geometries. You can find more about
-
# geometry strings at the ImageMagick website
-
# (http://www.imagemagick.org/script/command-line-options.php#resize). Paperclip
-
# also adds the "#" option (e.g. "50x50#"), which will resize the image to fit maximally
-
# inside the dimensions and then crop the rest off (weighted at the center). The
-
# default value is to generate no thumbnails.
-
# * +default_style+: The thumbnail style that will be used by default URLs.
-
# Defaults to +original+.
-
# has_attached_file :avatar, :styles => { :normal => "100x100#" },
-
# :default_style => :normal
-
# user.avatar.url # => "/avatars/23/normal_me.png"
-
# * +keep_old_files+: Keep the existing attachment files (original + resized) from
-
# being automatically deleted when an attachment is cleared or updated. Defaults to +false+.
-
# * +preserve_files+: Keep the existing attachment files in all cases, even if the parent
-
# record is destroyed. Defaults to +false+.
-
# * +whiny+: Will raise an error if Paperclip cannot post_process an uploaded file due
-
# to a command line error. This will override the global setting for this attachment.
-
# Defaults to true.
-
# * +convert_options+: When creating thumbnails, use this free-form options
-
# array to pass in various convert command options. Typical options are "-strip" to
-
# remove all Exif data from the image (save space for thumbnails and avatars) or
-
# "-depth 8" to specify the bit depth of the resulting conversion. See ImageMagick
-
# convert documentation for more options: (http://www.imagemagick.org/script/convert.php)
-
# Note that this option takes a hash of options, each of which correspond to the style
-
# of thumbnail being generated. You can also specify :all as a key, which will apply
-
# to all of the thumbnails being generated. If you specify options for the :original,
-
# it would be best if you did not specify destructive options, as the intent of keeping
-
# the original around is to regenerate all the thumbnails when requirements change.
-
# has_attached_file :avatar, :styles => { :large => "300x300", :negative => "100x100" }
-
# :convert_options => {
-
# :all => "-strip",
-
# :negative => "-negate"
-
# }
-
# NOTE: While not deprecated yet, it is not recommended to specify options this way.
-
# It is recommended that :convert_options option be included in the hash passed to each
-
# :styles for compatibility with future versions.
-
# NOTE: Strings supplied to :convert_options are split on space in order to undergo
-
# shell quoting for safety. If your options require a space, please pre-split them
-
# and pass an array to :convert_options instead.
-
# * +storage+: Chooses the storage backend where the files will be stored. The current
-
# choices are :filesystem, :fog and :s3. The default is :filesystem. Make sure you read the
-
# documentation for Paperclip::Storage::Filesystem, Paperclip::Storage::Fog and Paperclip::Storage::S3
-
# for backend-specific options.
-
#
-
# It's also possible for you to dynamically define your interpolation string for :url,
-
# :default_url, and :path in your model by passing a method name as a symbol as a argument
-
# for your has_attached_file definition:
-
#
-
# class Person
-
# has_attached_file :avatar, :default_url => :default_url_by_gender
-
#
-
# private
-
#
-
# def default_url_by_gender
-
# "/assets/avatars/default_#{gender}.png"
-
# end
-
# end
-
2
def has_attached_file(name, options = {})
-
HasAttachedFile.define_on(self, name, options)
-
end
-
end
-
end
-
-
# This stuff needs to be run after Paperclip is defined.
-
2
require 'paperclip/io_adapters/registry'
-
2
require 'paperclip/io_adapters/abstract_adapter'
-
2
require 'paperclip/io_adapters/empty_string_adapter'
-
2
require 'paperclip/io_adapters/identity_adapter'
-
2
require 'paperclip/io_adapters/file_adapter'
-
2
require 'paperclip/io_adapters/stringio_adapter'
-
2
require 'paperclip/io_adapters/data_uri_adapter'
-
2
require 'paperclip/io_adapters/nil_adapter'
-
2
require 'paperclip/io_adapters/attachment_adapter'
-
2
require 'paperclip/io_adapters/uploaded_file_adapter'
-
2
require 'paperclip/io_adapters/uri_adapter'
-
2
require 'paperclip/io_adapters/http_url_proxy_adapter'
-
# encoding: utf-8
-
2
require 'uri'
-
2
require 'paperclip/url_generator'
-
2
require 'active_support/deprecation'
-
-
2
module Paperclip
-
# The Attachment class manages the files for a given attachment. It saves
-
# when the model saves, deletes when the model is destroyed, and processes
-
# the file upon assignment.
-
2
class Attachment
-
2
def self.default_options
-
@default_options ||= {
-
:convert_options => {},
-
:default_style => :original,
-
:default_url => "/:attachment/:style/missing.png",
-
:escape_url => true,
-
:restricted_characters => /[&$+,\/:;=?@<>\[\]\{\}\|\\\^~%# ]/,
-
:filename_cleaner => nil,
-
:hash_data => ":class/:attachment/:id/:style/:updated_at",
-
:hash_digest => "SHA1",
-
:interpolator => Paperclip::Interpolations,
-
:only_process => [],
-
:path => ":rails_root/public:url",
-
:preserve_files => false,
-
:processors => [:thumbnail],
-
:source_file_options => {},
-
:storage => :filesystem,
-
:styles => {},
-
:url => "/system/:class/:attachment/:id_partition/:style/:filename",
-
:url_generator => Paperclip::UrlGenerator,
-
:use_default_time_zone => true,
-
:use_timestamp => true,
-
:whiny => Paperclip.options[:whiny] || Paperclip.options[:whiny_thumbnails],
-
:validate_media_type => true,
-
:check_validity_before_processing => true
-
}
-
end
-
-
2
attr_reader :name, :instance, :default_style, :convert_options, :queued_for_write, :whiny,
-
:options, :interpolator, :source_file_options
-
2
attr_accessor :post_processing
-
-
# Creates an Attachment object. +name+ is the name of the attachment,
-
# +instance+ is the model object instance it's attached to, and
-
# +options+ is the same as the hash passed to +has_attached_file+.
-
#
-
# Options include:
-
#
-
# +url+ - a relative URL of the attachment. This is interpolated using +interpolator+
-
# +path+ - where on the filesystem to store the attachment. This is interpolated using +interpolator+
-
# +styles+ - a hash of options for processing the attachment. See +has_attached_file+ for the details
-
# +only_process+ - style args to be run through the post-processor. This defaults to the empty list
-
# +default_url+ - a URL for the missing image
-
# +default_style+ - the style to use when an argument is not specified e.g. #url, #path
-
# +storage+ - the storage mechanism. Defaults to :filesystem
-
# +use_timestamp+ - whether to append an anti-caching timestamp to image URLs. Defaults to true
-
# +whiny+, +whiny_thumbnails+ - whether to raise when thumbnailing fails
-
# +use_default_time_zone+ - related to +use_timestamp+. Defaults to true
-
# +hash_digest+ - a string representing a class that will be used to hash URLs for obfuscation
-
# +hash_data+ - the relative URL for the hash data. This is interpolated using +interpolator+
-
# +hash_secret+ - a secret passed to the +hash_digest+
-
# +convert_options+ - flags passed to the +convert+ command for processing
-
# +source_file_options+ - flags passed to the +convert+ command that controls how the file is read
-
# +processors+ - classes that transform the attachment. Defaults to [:thumbnail]
-
# +preserve_files+ - whether to keep files on the filesystem when deleting or clearing the attachment. Defaults to false
-
# +filename_cleaner+ - An object that responds to #call(filename) that will strip unacceptable charcters from filename
-
# +interpolator+ - the object used to interpolate filenames and URLs. Defaults to Paperclip::Interpolations
-
# +url_generator+ - the object used to generate URLs, using the interpolator. Defaults to Paperclip::UrlGenerator
-
# +escape_url+ - Perform URI escaping to URLs. Defaults to true
-
2
def initialize(name, instance, options = {})
-
@name = name.to_sym
-
@name_string = name.to_s
-
@instance = instance
-
-
options = self.class.default_options.deep_merge(options)
-
-
@options = options
-
@post_processing = true
-
@queued_for_delete = []
-
@queued_for_write = {}
-
@errors = {}
-
@dirty = false
-
@interpolator = options[:interpolator]
-
@url_generator = options[:url_generator].new(self, @options)
-
@source_file_options = options[:source_file_options]
-
@whiny = options[:whiny]
-
-
initialize_storage
-
end
-
-
# What gets called when you call instance.attachment = File. It clears
-
# errors, assigns attributes, and processes the file. It also queues up the
-
# previous file for deletion, to be flushed away on #save of its host. In
-
# addition to form uploads, you can also assign another Paperclip
-
# attachment:
-
# new_user.avatar = old_user.avatar
-
2
def assign(uploaded_file)
-
@file = Paperclip.io_adapters.for(uploaded_file)
-
ensure_required_accessors!
-
ensure_required_validations!
-
-
if @file.assignment?
-
clear(*only_process)
-
-
if @file.nil?
-
nil
-
else
-
assign_attributes
-
post_process_file
-
reset_file_if_original_reprocessed
-
end
-
else
-
nil
-
end
-
end
-
-
# Returns the public URL of the attachment with a given style. This does
-
# not necessarily need to point to a file that your Web server can access
-
# and can instead point to an action in your app, for example for fine grained
-
# security; this has a serious performance tradeoff.
-
#
-
# Options:
-
#
-
# +timestamp+ - Add a timestamp to the end of the URL. Default: true.
-
# +escape+ - Perform URI escaping to the URL. Default: true.
-
#
-
# Global controls (set on has_attached_file):
-
#
-
# +interpolator+ - The object that fills in a URL pattern's variables.
-
# +default_url+ - The image to show when the attachment has no image.
-
# +url+ - The URL for a saved image.
-
# +url_generator+ - The object that generates a URL. Default: Paperclip::UrlGenerator.
-
#
-
# As mentioned just above, the object that generates this URL can be passed
-
# in, for finer control. This object must respond to two methods:
-
#
-
# +#new(Paperclip::Attachment, options_hash)+
-
# +#for(style_name, options_hash)+
-
-
2
def url(style_name = default_style, options = {})
-
if options == true || options == false # Backwards compatibility.
-
@url_generator.for(style_name, default_options.merge(:timestamp => options))
-
else
-
@url_generator.for(style_name, default_options.merge(options))
-
end
-
end
-
-
2
def default_options
-
{
-
:timestamp => @options[:use_timestamp],
-
:escape => @options[:escape_url]
-
}
-
end
-
-
# Alias to +url+ that allows using the expiring_url method provided by the cloud
-
# storage implementations, but keep using filesystem storage for development and
-
# testing.
-
2
def expiring_url(time = 3600, style_name = default_style)
-
url(style_name)
-
end
-
-
# Returns the path of the attachment as defined by the :path option. If the
-
# file is stored in the filesystem the path refers to the path of the file
-
# on disk. If the file is stored in S3, the path is the "key" part of the
-
# URL, and the :bucket option refers to the S3 bucket.
-
2
def path(style_name = default_style)
-
path = original_filename.nil? ? nil : interpolate(path_option, style_name)
-
path.respond_to?(:unescape) ? path.unescape : path
-
end
-
-
# :nodoc:
-
2
def staged_path(style_name = default_style)
-
if staged?
-
@queued_for_write[style_name].path
-
end
-
end
-
-
# :nodoc:
-
2
def staged?
-
! @queued_for_write.empty?
-
end
-
-
# Alias to +url+
-
2
def to_s style_name = default_style
-
url(style_name)
-
end
-
-
2
def as_json(options = nil)
-
to_s((options && options[:style]) || default_style)
-
end
-
-
2
def default_style
-
@options[:default_style]
-
end
-
-
2
def styles
-
if @options[:styles].respond_to?(:call) || @normalized_styles.nil?
-
styles = @options[:styles]
-
styles = styles.call(self) if styles.respond_to?(:call)
-
-
@normalized_styles = styles.dup
-
styles.each_pair do |name, options|
-
@normalized_styles[name.to_sym] = Paperclip::Style.new(name.to_sym, options.dup, self)
-
end
-
end
-
@normalized_styles
-
end
-
-
2
def only_process
-
only_process = @options[:only_process].dup
-
only_process = only_process.call(self) if only_process.respond_to?(:call)
-
only_process.map(&:to_sym)
-
end
-
-
2
def processors
-
processing_option = @options[:processors]
-
-
if processing_option.respond_to?(:call)
-
processing_option.call(instance)
-
else
-
processing_option
-
end
-
end
-
-
# Returns an array containing the errors on this attachment.
-
2
def errors
-
@errors
-
end
-
-
# Returns true if there are changes that need to be saved.
-
2
def dirty?
-
@dirty
-
end
-
-
# Saves the file, if there are no errors. If there are, it flushes them to
-
# the instance's errors and returns false, cancelling the save.
-
2
def save
-
flush_deletes unless @options[:keep_old_files]
-
flush_writes
-
@dirty = false
-
true
-
end
-
-
# Clears out the attachment. Has the same effect as previously assigning
-
# nil to the attachment. Does NOT save. If you wish to clear AND save,
-
# use #destroy.
-
2
def clear(*styles_to_clear)
-
if styles_to_clear.any?
-
queue_some_for_delete(*styles_to_clear)
-
else
-
queue_all_for_delete
-
@queued_for_write = {}
-
@errors = {}
-
end
-
end
-
-
# Destroys the attachment. Has the same effect as previously assigning
-
# nil to the attachment *and saving*. This is permanent. If you wish to
-
# wipe out the existing attachment but not save, use #clear.
-
2
def destroy
-
clear
-
save
-
end
-
-
# Returns the uploaded file if present.
-
2
def uploaded_file
-
instance_read(:uploaded_file)
-
end
-
-
# Returns the name of the file as originally assigned, and lives in the
-
# <attachment>_file_name attribute of the model.
-
2
def original_filename
-
instance_read(:file_name)
-
end
-
-
# Returns the size of the file as originally assigned, and lives in the
-
# <attachment>_file_size attribute of the model.
-
2
def size
-
instance_read(:file_size) || (@queued_for_write[:original] && @queued_for_write[:original].size)
-
end
-
-
# Returns the fingerprint of the file, if one's defined. The fingerprint is
-
# stored in the <attachment>_fingerprint attribute of the model.
-
2
def fingerprint
-
instance_read(:fingerprint)
-
end
-
-
# Returns the content_type of the file as originally assigned, and lives
-
# in the <attachment>_content_type attribute of the model.
-
2
def content_type
-
instance_read(:content_type)
-
end
-
-
# Returns the creation time of the file as originally assigned, and
-
# lives in the <attachment>_created_at attribute of the model.
-
2
def created_at
-
if able_to_store_created_at?
-
time = instance_read(:created_at)
-
time && time.to_f.to_i
-
end
-
end
-
-
# Returns the last modified time of the file as originally assigned, and
-
# lives in the <attachment>_updated_at attribute of the model.
-
2
def updated_at
-
time = instance_read(:updated_at)
-
time && time.to_f.to_i
-
end
-
-
# The time zone to use for timestamp interpolation. Using the default
-
# time zone ensures that results are consistent across all threads.
-
2
def time_zone
-
@options[:use_default_time_zone] ? Time.zone_default : Time.zone
-
end
-
-
# Returns a unique hash suitable for obfuscating the URL of an otherwise
-
# publicly viewable attachment.
-
2
def hash_key(style_name = default_style)
-
raise ArgumentError, "Unable to generate hash without :hash_secret" unless @options[:hash_secret]
-
require 'openssl' unless defined?(OpenSSL)
-
data = interpolate(@options[:hash_data], style_name)
-
OpenSSL::HMAC.hexdigest(OpenSSL::Digest.const_get(@options[:hash_digest]).new, @options[:hash_secret], data)
-
end
-
-
# This method really shouldn't be called that often. It's expected use is
-
# in the paperclip:refresh rake task and that's it. It will regenerate all
-
# thumbnails forcefully, by reobtaining the original file and going through
-
# the post-process again.
-
# NOTE: Calling reprocess WILL NOT delete existing files. This is due to
-
# inconsistencies in timing of S3 commands. It's possible that calling
-
# #reprocess! will lose data if the files are not kept.
-
2
def reprocess!(*style_args)
-
saved_only_process, @options[:only_process] = @options[:only_process], style_args
-
saved_preserve_files, @options[:preserve_files] = @options[:preserve_files], true
-
begin
-
assign(self)
-
save
-
instance.save
-
rescue Errno::EACCES => e
-
warn "#{e} - skipping file."
-
false
-
ensure
-
@options[:only_process] = saved_only_process
-
@options[:preserve_files] = saved_preserve_files
-
end
-
end
-
-
# Returns true if a file has been assigned.
-
2
def file?
-
!original_filename.blank?
-
end
-
-
2
alias :present? :file?
-
-
2
def blank?
-
not present?
-
end
-
-
# Determines whether the instance responds to this attribute. Used to prevent
-
# calculations on fields we won't even store.
-
2
def instance_respond_to?(attr)
-
instance.respond_to?(:"#{name}_#{attr}")
-
end
-
-
# Writes the attachment-specific attribute on the instance. For example,
-
# instance_write(:file_name, "me.jpg") will write "me.jpg" to the instance's
-
# "avatar_file_name" field (assuming the attachment is called avatar).
-
2
def instance_write(attr, value)
-
setter = :"#{@name_string}_#{attr}="
-
if instance.respond_to?(setter)
-
instance.send(setter, value)
-
end
-
end
-
-
# Reads the attachment-specific attribute on the instance. See instance_write
-
# for more details.
-
2
def instance_read(attr)
-
getter = :"#{@name_string}_#{attr}"
-
if instance.respond_to?(getter)
-
instance.send(getter)
-
end
-
end
-
-
2
private
-
-
2
def path_option
-
@options[:path].respond_to?(:call) ? @options[:path].call(self) : @options[:path]
-
end
-
-
2
def active_validator_classes
-
@instance.class.validators.map(&:class)
-
end
-
-
2
def missing_required_validator?
-
(active_validator_classes.flat_map(&:ancestors) & Paperclip::REQUIRED_VALIDATORS).empty?
-
end
-
-
2
def ensure_required_validations!
-
if missing_required_validator?
-
raise Paperclip::Errors::MissingRequiredValidatorError
-
end
-
end
-
-
2
def ensure_required_accessors! #:nodoc:
-
%w(file_name).each do |field|
-
unless @instance.respond_to?("#{@name_string}_#{field}") && @instance.respond_to?("#{@name_string}_#{field}=")
-
raise Paperclip::Error.new("#{@instance.class} model missing required attr_accessor for '#{@name_string}_#{field}'")
-
end
-
end
-
end
-
-
2
def log message #:nodoc:
-
Paperclip.log(message)
-
end
-
-
2
def initialize_storage #:nodoc:
-
storage_class_name = @options[:storage].to_s.downcase.camelize
-
begin
-
storage_module = Paperclip::Storage.const_get(storage_class_name)
-
rescue NameError
-
raise Errors::StorageMethodNotFound, "Cannot load storage module '#{storage_class_name}'"
-
end
-
self.extend(storage_module)
-
end
-
-
2
def assign_attributes
-
@queued_for_write[:original] = @file
-
assign_file_information
-
assign_fingerprint(@file.fingerprint)
-
assign_timestamps
-
end
-
-
2
def assign_file_information
-
instance_write(:file_name, cleanup_filename(@file.original_filename))
-
instance_write(:content_type, @file.content_type.to_s.strip)
-
instance_write(:file_size, @file.size)
-
end
-
-
2
def assign_fingerprint(fingerprint)
-
if instance_respond_to?(:fingerprint)
-
instance_write(:fingerprint, fingerprint)
-
end
-
end
-
-
2
def assign_timestamps
-
if has_enabled_but_unset_created_at?
-
instance_write(:created_at, Time.now)
-
end
-
-
instance_write(:updated_at, Time.now)
-
end
-
-
2
def post_process_file
-
dirty!
-
-
if post_processing
-
post_process(*only_process)
-
end
-
end
-
-
2
def dirty!
-
@dirty = true
-
end
-
-
2
def reset_file_if_original_reprocessed
-
instance_write(:file_size, @queued_for_write[:original].size)
-
assign_fingerprint(@queued_for_write[:original].fingerprint)
-
reset_updater
-
end
-
-
2
def reset_updater
-
if instance.respond_to?(updater)
-
instance.send(updater)
-
end
-
end
-
-
2
def updater
-
:"#{name}_file_name_will_change!"
-
end
-
-
2
def extra_options_for(style) #:nodoc:
-
process_options(:convert_options, style)
-
end
-
-
2
def extra_source_file_options_for(style) #:nodoc:
-
process_options(:source_file_options, style)
-
end
-
-
2
def process_options(options_type, style) #:nodoc:
-
all_options = @options[options_type][:all]
-
all_options = all_options.call(instance) if all_options.respond_to?(:call)
-
style_options = @options[options_type][style]
-
style_options = style_options.call(instance) if style_options.respond_to?(:call)
-
-
[ style_options, all_options ].compact.join(" ")
-
end
-
-
2
def post_process(*style_args) #:nodoc:
-
return if @queued_for_write[:original].nil?
-
-
instance.run_paperclip_callbacks(:post_process) do
-
instance.run_paperclip_callbacks(:"#{name}_post_process") do
-
unless @options[:check_validity_before_processing] && instance.errors.any?
-
post_process_styles(*style_args)
-
end
-
end
-
end
-
end
-
-
2
def post_process_styles(*style_args) #:nodoc:
-
post_process_style(:original, styles[:original]) if styles.include?(:original) && process_style?(:original, style_args)
-
styles.reject{ |name, style| name == :original }.each do |name, style|
-
post_process_style(name, style) if process_style?(name, style_args)
-
end
-
end
-
-
2
def post_process_style(name, style) #:nodoc:
-
begin
-
raise RuntimeError.new("Style #{name} has no processors defined.") if style.processors.blank?
-
intermediate_files = []
-
-
@queued_for_write[name] = style.processors.inject(@queued_for_write[:original]) do |file, processor|
-
file = Paperclip.processor(processor).make(file, style.processor_options, self)
-
intermediate_files << file
-
file
-
end
-
-
unadapted_file = @queued_for_write[name]
-
@queued_for_write[name] = Paperclip.io_adapters.for(@queued_for_write[name])
-
unadapted_file.close if unadapted_file.respond_to?(:close)
-
@queued_for_write[name]
-
rescue Paperclip::Errors::NotIdentifiedByImageMagickError => e
-
log("An error was received while processing: #{e.inspect}")
-
(@errors[:processing] ||= []) << e.message if @options[:whiny]
-
ensure
-
unlink_files(intermediate_files)
-
end
-
end
-
-
2
def process_style?(style_name, style_args) #:nodoc:
-
style_args.empty? || style_args.include?(style_name)
-
end
-
-
2
def interpolate(pattern, style_name = default_style) #:nodoc:
-
interpolator.interpolate(pattern, self, style_name)
-
end
-
-
2
def queue_some_for_delete(*styles)
-
@queued_for_delete += styles.uniq.map do |style|
-
path(style) if exists?(style)
-
end.compact
-
end
-
-
2
def queue_all_for_delete #:nodoc:
-
return if !file?
-
unless @options[:preserve_files]
-
@queued_for_delete += [:original, *styles.keys].uniq.map do |style|
-
path(style) if exists?(style)
-
end.compact
-
end
-
instance_write(:file_name, nil)
-
instance_write(:content_type, nil)
-
instance_write(:file_size, nil)
-
instance_write(:fingerprint, nil)
-
instance_write(:created_at, nil) if has_enabled_but_unset_created_at?
-
instance_write(:updated_at, nil)
-
end
-
-
2
def flush_errors #:nodoc:
-
@errors.each do |error, message|
-
[message].flatten.each {|m| instance.errors.add(name, m) }
-
end
-
end
-
-
# called by storage after the writes are flushed and before @queued_for_write is cleared
-
2
def after_flush_writes
-
unlink_files(@queued_for_write.values)
-
end
-
-
2
def unlink_files(files)
-
Array(files).each do |file|
-
file.close unless file.closed?
-
file.unlink if file.respond_to?(:unlink) && file.path.present? && File.exist?(file.path)
-
end
-
end
-
-
# You can either specifiy :restricted_characters or you can define your own
-
# :filename_cleaner object. This object needs to respond to #call and takes
-
# the filename that will be cleaned. It should return the cleaned filenme.
-
2
def filename_cleaner
-
@options[:filename_cleaner] || FilenameCleaner.new(@options[:restricted_characters])
-
end
-
-
2
def cleanup_filename(filename)
-
filename_cleaner.call(filename)
-
end
-
-
# Check if attachment database table has a created_at field
-
2
def able_to_store_created_at?
-
@instance.respond_to?("#{name}_created_at".to_sym)
-
end
-
-
# Check if attachment database table has a created_at field which is not yet set
-
2
def has_enabled_but_unset_created_at?
-
able_to_store_created_at? && !instance_read(:created_at)
-
end
-
end
-
end
-
2
require 'singleton'
-
-
2
module Paperclip
-
2
class AttachmentRegistry
-
2
include Singleton
-
-
2
def self.register(klass, attachment_name, attachment_options)
-
instance.register(klass, attachment_name, attachment_options)
-
end
-
-
2
def self.clear
-
instance.clear
-
end
-
-
2
def self.names_for(klass)
-
instance.names_for(klass)
-
end
-
-
2
def self.each_definition(&block)
-
instance.each_definition(&block)
-
end
-
-
2
def self.definitions_for(klass)
-
instance.definitions_for(klass)
-
end
-
-
2
def initialize
-
clear
-
end
-
-
2
def register(klass, attachment_name, attachment_options)
-
@attachments ||= {}
-
@attachments[klass] ||= {}
-
@attachments[klass][attachment_name] = attachment_options
-
end
-
-
2
def clear
-
@attachments = Hash.new { |h,k| h[k] = {} }
-
end
-
-
2
def names_for(klass)
-
@attachments[klass].keys
-
end
-
-
2
def each_definition
-
@attachments.each do |klass, attachments|
-
attachments.each do |name, options|
-
yield klass, name, options
-
end
-
end
-
end
-
-
2
def definitions_for(klass)
-
klass.ancestors.each_with_object({}) do |ancestor, inherited_definitions|
-
inherited_definitions.deep_merge! @attachments[ancestor]
-
end
-
end
-
end
-
end
-
2
module Paperclip
-
2
module Callbacks
-
2
def self.included(base)
-
2
base.extend(Defining)
-
2
base.send(:include, Running)
-
end
-
-
2
module Defining
-
2
def define_paperclip_callbacks(*callbacks)
-
define_callbacks(*[callbacks, {:terminator => callback_terminator}].flatten)
-
callbacks.each do |callback|
-
eval <<-end_callbacks
-
def before_#{callback}(*args, &blk)
-
set_callback(:#{callback}, :before, *args, &blk)
-
end
-
def after_#{callback}(*args, &blk)
-
set_callback(:#{callback}, :after, *args, &blk)
-
end
-
end_callbacks
-
end
-
end
-
-
2
private
-
-
2
def callback_terminator
-
if ::ActiveSupport::VERSION::STRING >= '4.1'
-
lambda { |target, result| result == false }
-
else
-
'result == false'
-
end
-
end
-
end
-
-
2
module Running
-
2
def run_paperclip_callbacks(callback, &block)
-
run_callbacks(callback, &block)
-
end
-
end
-
end
-
end
-
2
module Paperclip
-
2
class ContentTypeDetector
-
# The content-type detection strategy is as follows:
-
#
-
# 1. Blank/Empty files: If there's no filepath or the file is empty,
-
# provide a sensible default (application/octet-stream or inode/x-empty)
-
#
-
# 2. Calculated match: Return the first result that is found by both the
-
# `file` command and MIME::Types.
-
#
-
# 3. Standard types: Return the first standard (without an x- prefix) entry
-
# in MIME::Types
-
#
-
# 4. Experimental types: If there were no standard types in MIME::Types
-
# list, try to return the first experimental one
-
#
-
# 5. Raw `file` command: Just use the output of the `file` command raw, or
-
# a sensible default. This is cached from Step 2.
-
-
2
EMPTY_TYPE = "inode/x-empty"
-
2
SENSIBLE_DEFAULT = "application/octet-stream"
-
-
2
def initialize(filepath)
-
@filepath = filepath
-
end
-
-
# Returns a String describing the file's content type
-
2
def detect
-
if blank_name?
-
SENSIBLE_DEFAULT
-
elsif empty_file?
-
EMPTY_TYPE
-
elsif calculated_type_matches.any?
-
calculated_type_matches.first
-
else
-
type_from_file_contents || SENSIBLE_DEFAULT
-
end.to_s
-
end
-
-
2
private
-
-
2
def blank_name?
-
@filepath.nil? || @filepath.empty?
-
end
-
-
2
def empty_file?
-
File.exist?(@filepath) && File.size(@filepath) == 0
-
end
-
-
2
alias :empty? :empty_file?
-
-
2
def calculated_type_matches
-
possible_types.select do |content_type|
-
content_type == type_from_file_contents
-
end
-
end
-
-
2
def possible_types
-
MIME::Types.type_for(@filepath).collect(&:content_type)
-
end
-
-
2
def type_from_file_contents
-
type_from_mime_magic || type_from_file_command
-
rescue Errno::ENOENT => e
-
Paperclip.log("Error while determining content type: #{e}")
-
SENSIBLE_DEFAULT
-
end
-
-
2
def type_from_mime_magic
-
@type_from_mime_magic ||=
-
MimeMagic.by_magic(File.open(@filepath)).try(:type)
-
end
-
-
2
def type_from_file_command
-
@type_from_file_command ||=
-
FileCommandContentTypeDetector.new(@filepath).detect
-
end
-
end
-
end
-
2
module Paperclip
-
# A base error class for Paperclip. Most of the error that will be thrown
-
# from Paperclip will inherits from this class.
-
2
class Error < StandardError
-
end
-
-
2
module Errors
-
# Will be thrown when a storage method is not found.
-
2
class StorageMethodNotFound < Paperclip::Error
-
end
-
-
# Will be thrown when a command or executable is not found.
-
2
class CommandNotFoundError < Paperclip::Error
-
end
-
-
# Attachments require a content_type or file_name validator,
-
# or to have explicitly opted out of them.
-
2
class MissingRequiredValidatorError < Paperclip::Error
-
end
-
-
# Will be thrown when ImageMagic cannot determine the uploaded file's
-
# metadata, usually this would mean the file is not an image.
-
2
class NotIdentifiedByImageMagickError < Paperclip::Error
-
end
-
-
# Will be thrown if the interpolation is creating an infinite loop. If you
-
# are creating an interpolator which might cause an infinite loop, you
-
# should be throwing this error upon the infinite loop as well.
-
2
class InfiniteInterpolationError < Paperclip::Error
-
end
-
end
-
end
-
2
module Paperclip
-
2
class FileCommandContentTypeDetector
-
2
SENSIBLE_DEFAULT = "application/octet-stream"
-
-
2
def initialize(filename)
-
@filename = filename
-
end
-
-
2
def detect
-
type_from_file_command
-
end
-
-
2
private
-
-
2
def type_from_file_command
-
# On BSDs, `file` doesn't give a result code of 1 if the file doesn't exist.
-
type = begin
-
Paperclip.run("file", "-b --mime :file", file: @filename)
-
rescue Cocaine::CommandLineError => e
-
Paperclip.log("Error while determining content type: #{e}")
-
SENSIBLE_DEFAULT
-
end
-
-
if type.nil? || type.match(/\(.*?\)/)
-
type = SENSIBLE_DEFAULT
-
end
-
type.split(/[:;\s]+/)[0]
-
end
-
end
-
end
-
# encoding: utf-8
-
2
module Paperclip
-
2
class FilenameCleaner
-
2
def initialize(invalid_character_regex)
-
@invalid_character_regex = invalid_character_regex
-
end
-
-
2
def call(filename)
-
if @invalid_character_regex
-
filename.gsub(@invalid_character_regex, "_")
-
else
-
filename
-
end
-
end
-
end
-
end
-
2
module Paperclip
-
-
# Defines the geometry of an image.
-
2
class Geometry
-
2
attr_accessor :height, :width, :modifier
-
-
2
EXIF_ROTATED_ORIENTATION_VALUES = [5, 6, 7, 8]
-
-
# Gives a Geometry representing the given height and width
-
2
def initialize(width = nil, height = nil, modifier = nil)
-
if width.is_a?(Hash)
-
options = width
-
@height = options[:height].to_f
-
@width = options[:width].to_f
-
@modifier = options[:modifier]
-
@orientation = options[:orientation].to_i
-
else
-
@height = height.to_f
-
@width = width.to_f
-
@modifier = modifier
-
end
-
end
-
-
# Extracts the Geometry from a file (or path to a file)
-
2
def self.from_file(file)
-
GeometryDetector.new(file).make
-
end
-
-
# Extracts the Geometry from a "WxH,O" string
-
# Where W is the width, H is the height,
-
# and O is the EXIF orientation
-
2
def self.parse(string)
-
GeometryParser.new(string).make
-
end
-
-
# Swaps the height and width if necessary
-
2
def auto_orient
-
if EXIF_ROTATED_ORIENTATION_VALUES.include?(@orientation)
-
@height, @width = @width, @height
-
@orientation -= 4
-
end
-
end
-
-
# True if the dimensions represent a square
-
2
def square?
-
height == width
-
end
-
-
# True if the dimensions represent a horizontal rectangle
-
2
def horizontal?
-
height < width
-
end
-
-
# True if the dimensions represent a vertical rectangle
-
2
def vertical?
-
height > width
-
end
-
-
# The aspect ratio of the dimensions.
-
2
def aspect
-
width / height
-
end
-
-
# Returns the larger of the two dimensions
-
2
def larger
-
[height, width].max
-
end
-
-
# Returns the smaller of the two dimensions
-
2
def smaller
-
[height, width].min
-
end
-
-
# Returns the width and height in a format suitable to be passed to Geometry.parse
-
2
def to_s
-
s = ""
-
s << width.to_i.to_s if width > 0
-
s << "x#{height.to_i}" if height > 0
-
s << modifier.to_s
-
s
-
end
-
-
# Same as to_s
-
2
def inspect
-
to_s
-
end
-
-
# Returns the scaling and cropping geometries (in string-based ImageMagick format)
-
# neccessary to transform this Geometry into the Geometry given. If crop is true,
-
# then it is assumed the destination Geometry will be the exact final resolution.
-
# In this case, the source Geometry is scaled so that an image containing the
-
# destination Geometry would be completely filled by the source image, and any
-
# overhanging image would be cropped. Useful for square thumbnail images. The cropping
-
# is weighted at the center of the Geometry.
-
2
def transformation_to dst, crop = false
-
if crop
-
ratio = Geometry.new( dst.width / self.width, dst.height / self.height )
-
scale_geometry, scale = scaling(dst, ratio)
-
crop_geometry = cropping(dst, ratio, scale)
-
else
-
scale_geometry = dst.to_s
-
end
-
-
[ scale_geometry, crop_geometry ]
-
end
-
-
# resize to a new geometry
-
# @param geometry [String] the Paperclip geometry definition to resize to
-
# @example
-
# Paperclip::Geometry.new(150, 150).resize_to('50x50!')
-
# #=> Paperclip::Geometry(50, 50)
-
2
def resize_to(geometry)
-
new_geometry = Paperclip::Geometry.parse geometry
-
case new_geometry.modifier
-
when '!', '#'
-
new_geometry
-
when '>'
-
if new_geometry.width >= self.width && new_geometry.height >= self.height
-
self
-
else
-
scale_to new_geometry
-
end
-
when '<'
-
if new_geometry.width <= self.width || new_geometry.height <= self.height
-
self
-
else
-
scale_to new_geometry
-
end
-
else
-
scale_to new_geometry
-
end
-
end
-
-
2
private
-
-
2
def scaling dst, ratio
-
if ratio.horizontal? || ratio.square?
-
[ "%dx" % dst.width, ratio.width ]
-
else
-
[ "x%d" % dst.height, ratio.height ]
-
end
-
end
-
-
2
def cropping dst, ratio, scale
-
if ratio.horizontal? || ratio.square?
-
"%dx%d+%d+%d" % [ dst.width, dst.height, 0, (self.height * scale - dst.height) / 2 ]
-
else
-
"%dx%d+%d+%d" % [ dst.width, dst.height, (self.width * scale - dst.width) / 2, 0 ]
-
end
-
end
-
-
# scale to the requested geometry and preserve the aspect ratio
-
2
def scale_to(new_geometry)
-
scale = [new_geometry.width.to_f / self.width.to_f , new_geometry.height.to_f / self.height.to_f].min
-
Paperclip::Geometry.new((self.width * scale).round, (self.height * scale).round)
-
end
-
end
-
end
-
2
module Paperclip
-
2
class GeometryDetector
-
2
def initialize(file)
-
@file = file
-
raise_if_blank_file
-
end
-
-
2
def make
-
geometry = GeometryParser.new(geometry_string.strip).make
-
geometry || raise(Errors::NotIdentifiedByImageMagickError.new)
-
end
-
-
2
private
-
-
2
def geometry_string
-
begin
-
orientation = Paperclip.options[:use_exif_orientation] ?
-
"%[exif:orientation]" : "1"
-
Paperclip.run(
-
"identify",
-
"-format '%wx%h,#{orientation}' :file", {
-
:file => "#{path}[0]"
-
}, {
-
:swallow_stderr => true
-
}
-
)
-
rescue Cocaine::ExitStatusError
-
""
-
rescue Cocaine::CommandNotFoundError => e
-
raise_because_imagemagick_missing
-
end
-
end
-
-
2
def path
-
@file.respond_to?(:path) ? @file.path : @file
-
end
-
-
2
def raise_if_blank_file
-
if path.blank?
-
raise Errors::NotIdentifiedByImageMagickError.new("Cannot find the geometry of a file with a blank name")
-
end
-
end
-
-
2
def raise_because_imagemagick_missing
-
raise Errors::CommandNotFoundError.new("Could not run the `identify` command. Please install ImageMagick.")
-
end
-
end
-
end
-
2
module Paperclip
-
2
class GeometryParser
-
2
FORMAT = /\b(\d*)x?(\d*)\b(?:,(\d?))?(\@\>|\>\@|[\>\<\#\@\%^!])?/i
-
2
def initialize(string)
-
@string = string
-
end
-
-
2
def make
-
if match
-
Geometry.new(
-
:height => @height,
-
:width => @width,
-
:modifier => @modifier,
-
:orientation => @orientation
-
)
-
end
-
end
-
-
2
private
-
-
2
def match
-
if actual_match = @string && @string.match(FORMAT)
-
@width = actual_match[1]
-
@height = actual_match[2]
-
@orientation = actual_match[3]
-
@modifier = actual_match[4]
-
end
-
actual_match
-
end
-
end
-
end
-
2
require 'paperclip/callbacks'
-
2
require 'paperclip/validators'
-
2
require 'paperclip/schema'
-
-
2
module Paperclip
-
2
module Glue
-
2
def self.included(base)
-
2
base.extend ClassMethods
-
2
base.send :include, Callbacks
-
2
base.send :include, Validators
-
2
base.send :include, Schema if defined? ActiveRecord
-
-
2
locale_path = Dir.glob(File.dirname(__FILE__) + "/locales/*.{rb,yml}")
-
2
I18n.load_path += locale_path unless I18n.load_path.include?(locale_path)
-
end
-
end
-
end
-
2
module Paperclip
-
2
class HasAttachedFile
-
2
def self.define_on(klass, name, options)
-
new(klass, name, options).define
-
end
-
-
2
def initialize(klass, name, options)
-
@klass = klass
-
@name = name
-
@options = options
-
end
-
-
2
def define
-
define_flush_errors
-
define_getters
-
define_setter
-
define_query
-
register_new_attachment
-
add_active_record_callbacks
-
add_paperclip_callbacks
-
add_required_validations
-
end
-
-
2
private
-
-
2
def define_flush_errors
-
@klass.send(:validates_each, @name) do |record, attr, value|
-
attachment = record.send(@name)
-
attachment.send(:flush_errors)
-
end
-
end
-
-
2
def define_getters
-
define_instance_getter
-
define_class_getter
-
end
-
-
2
def define_instance_getter
-
name = @name
-
options = @options
-
-
@klass.send :define_method, @name do |*args|
-
ivar = "@attachment_#{name}"
-
attachment = instance_variable_get(ivar)
-
-
if attachment.nil?
-
attachment = Attachment.new(name, self, options)
-
instance_variable_set(ivar, attachment)
-
end
-
-
if args.length > 0
-
attachment.to_s(args.first)
-
else
-
attachment
-
end
-
end
-
end
-
-
2
def define_class_getter
-
@klass.extend(ClassMethods)
-
end
-
-
2
def define_setter
-
name = @name
-
@klass.send :define_method, "#{@name}=" do |file|
-
send(name).assign(file)
-
end
-
end
-
-
2
def define_query
-
name = @name
-
@klass.send :define_method, "#{@name}?" do
-
send(name).file?
-
end
-
end
-
-
2
def register_new_attachment
-
Paperclip::AttachmentRegistry.register(@klass, @name, @options)
-
end
-
-
2
def add_required_validations
-
options = Paperclip::Attachment.default_options.deep_merge(@options)
-
if options[:validate_media_type] != false
-
name = @name
-
@klass.validates_media_type_spoof_detection name,
-
:if => ->(instance){ instance.send(name).dirty? }
-
end
-
end
-
-
2
def add_active_record_callbacks
-
name = @name
-
@klass.send(:after_save) { send(name).send(:save) }
-
@klass.send(:before_destroy) { send(name).send(:queue_all_for_delete) }
-
@klass.send(:after_commit, :on => :destroy) { send(name).send(:flush_deletes) }
-
end
-
-
2
def add_paperclip_callbacks
-
@klass.send(
-
:define_paperclip_callbacks,
-
:post_process, :"#{@name}_post_process")
-
end
-
-
2
module ClassMethods
-
2
def attachment_definitions
-
Paperclip::AttachmentRegistry.definitions_for(self)
-
end
-
end
-
end
-
end
-
2
module Paperclip
-
2
module Helpers
-
2
def configure
-
yield(self) if block_given?
-
end
-
-
2
def interpolates key, &block
-
Paperclip::Interpolations[key] = block
-
end
-
-
# The run method takes the name of a binary to run, the arguments to that binary
-
# and some options:
-
#
-
# :command_path -> A $PATH-like variable that defines where to look for the binary
-
# on the filesystem. Colon-separated, just like $PATH.
-
#
-
# :expected_outcodes -> An array of integers that defines the expected exit codes
-
# of the binary. Defaults to [0].
-
#
-
# :log_command -> Log the command being run when set to true (defaults to true).
-
# This will only log if logging in general is set to true as well.
-
#
-
# :swallow_stderr -> Set to true if you don't care what happens on STDERR.
-
#
-
2
def run(cmd, arguments = "", interpolation_values = {}, local_options = {})
-
command_path = options[:command_path]
-
Cocaine::CommandLine.path = [Cocaine::CommandLine.path, command_path].flatten.compact.uniq
-
if logging? && (options[:log_command] || local_options[:log_command])
-
local_options = local_options.merge(:logger => logger)
-
end
-
Cocaine::CommandLine.new(cmd, arguments, local_options).run(interpolation_values)
-
end
-
-
# Find all instances of the given Active Record model +klass+ with attachment +name+.
-
# This method is used by the refresh rake tasks.
-
2
def each_instance_with_attachment(klass, name)
-
class_for(klass).unscoped.where("#{name}_file_name IS NOT NULL").find_each do |instance|
-
yield(instance)
-
end
-
end
-
-
2
def class_for(class_name)
-
class_name.split('::').inject(Object) do |klass, partial_class_name|
-
if klass.const_defined?(partial_class_name)
-
klass.const_get(partial_class_name, false)
-
else
-
klass.const_missing(partial_class_name)
-
end
-
end
-
end
-
-
2
def reset_duplicate_clash_check!
-
@names_url = nil
-
end
-
end
-
end
-
2
module Paperclip
-
# This module contains all the methods that are available for interpolation
-
# in paths and urls. To add your own (or override an existing one), you
-
# can either open this module and define it, or call the
-
# Paperclip.interpolates method.
-
2
module Interpolations
-
2
extend self
-
-
# Hash assignment of interpolations. Included only for compatibility,
-
# and is not intended for normal use.
-
2
def self.[]= name, block
-
define_method(name, &block)
-
@interpolators_cache = nil
-
end
-
-
# Hash access of interpolations. Included only for compatibility,
-
# and is not intended for normal use.
-
2
def self.[] name
-
method(name)
-
end
-
-
# Returns a sorted list of all interpolations.
-
2
def self.all
-
self.instance_methods(false).sort!
-
end
-
-
# Perform the actual interpolation. Takes the pattern to interpolate
-
# and the arguments to pass, which are the attachment and style name.
-
# You can pass a method name on your record as a symbol, which should turn
-
# an interpolation pattern for Paperclip to use.
-
2
def self.interpolate pattern, *args
-
pattern = args.first.instance.send(pattern) if pattern.kind_of? Symbol
-
result = pattern.dup
-
interpolators_cache.each do |method, token|
-
result.gsub!(token) { send(method, *args) } if result.include?(token)
-
end
-
result
-
end
-
-
2
def self.interpolators_cache
-
@interpolators_cache ||= all.reverse!.map! { |method| [method, ":#{method}"] }
-
end
-
-
2
def self.plural_cache
-
@plural_cache ||= PluralCache.new
-
end
-
-
# Returns the filename, the same way as ":basename.:extension" would.
-
2
def filename attachment, style_name
-
[ basename(attachment, style_name), extension(attachment, style_name) ].delete_if(&:empty?).join(".".freeze)
-
end
-
-
# Returns the interpolated URL. Will raise an error if the url itself
-
# contains ":url" to prevent infinite recursion. This interpolation
-
# is used in the default :path to ease default specifications.
-
2
RIGHT_HERE = "#{__FILE__.gsub(%r{\A\./}, "")}:#{__LINE__ + 3}"
-
2
def url attachment, style_name
-
raise Errors::InfiniteInterpolationError if caller.any?{|b| b.index(RIGHT_HERE) }
-
attachment.url(style_name, :timestamp => false, :escape => false)
-
end
-
-
# Returns the timestamp as defined by the <attachment>_updated_at field
-
# in the server default time zone unless :use_global_time_zone is set
-
# to false. Note that a Rails.config.time_zone change will still
-
# invalidate any path or URL that uses :timestamp. For a
-
# time_zone-agnostic timestamp, use #updated_at.
-
2
def timestamp attachment, style_name
-
attachment.instance_read(:updated_at).in_time_zone(attachment.time_zone).to_s
-
end
-
-
# Returns an integer timestamp that is time zone-neutral, so that paths
-
# remain valid even if a server's time zone changes.
-
2
def updated_at attachment, style_name
-
attachment.updated_at
-
end
-
-
# Returns the Rails.root constant.
-
2
def rails_root attachment, style_name
-
Rails.root
-
end
-
-
# Returns the Rails.env constant.
-
2
def rails_env attachment, style_name
-
Rails.env
-
end
-
-
# Returns the underscored, pluralized version of the class name.
-
# e.g. "users" for the User class.
-
# NOTE: The arguments need to be optional, because some tools fetch
-
# all class names. Calling #class will return the expected class.
-
2
def class attachment = nil, style_name = nil
-
return super() if attachment.nil? && style_name.nil?
-
plural_cache.underscore_and_pluralize_class(attachment.instance.class)
-
end
-
-
# Returns the basename of the file. e.g. "file" for "file.jpg"
-
2
def basename attachment, style_name
-
File.basename(attachment.original_filename, ".*".freeze)
-
end
-
-
# Returns the extension of the file. e.g. "jpg" for "file.jpg"
-
# If the style has a format defined, it will return the format instead
-
# of the actual extension.
-
2
def extension attachment, style_name
-
((style = attachment.styles[style_name.to_s.to_sym]) && style[:format]) ||
-
File.extname(attachment.original_filename).sub(/\A\.+/, "".freeze)
-
end
-
-
# Returns the dot+extension of the file. e.g. ".jpg" for "file.jpg"
-
# If the style has a format defined, it will return the format instead
-
# of the actual extension. If the extension is empty, no dot is added.
-
2
def dotextension attachment, style_name
-
ext = extension(attachment, style_name)
-
ext.empty? ? ext : ".#{ext}"
-
end
-
-
# Returns an extension based on the content type. e.g. "jpeg" for
-
# "image/jpeg". If the style has a specified format, it will override the
-
# content-type detection.
-
#
-
# Each mime type generally has multiple extensions associated with it, so
-
# if the extension from the original filename is one of these extensions,
-
# that extension is used, otherwise, the first in the list is used.
-
2
def content_type_extension attachment, style_name
-
mime_type = MIME::Types[attachment.content_type]
-
extensions_for_mime_type = unless mime_type.empty?
-
mime_type.first.extensions
-
else
-
[]
-
end
-
-
original_extension = extension(attachment, style_name)
-
style = attachment.styles[style_name.to_s.to_sym]
-
if style && style[:format]
-
style[:format].to_s
-
elsif extensions_for_mime_type.include? original_extension
-
original_extension
-
elsif !extensions_for_mime_type.empty?
-
extensions_for_mime_type.first
-
else
-
# It's possible, though unlikely, that the mime type is not in the
-
# database, so just use the part after the '/' in the mime type as the
-
# extension.
-
%r{/([^/]*)\Z}.match(attachment.content_type)[1]
-
end
-
end
-
-
# Returns the id of the instance.
-
2
def id attachment, style_name
-
attachment.instance.id
-
end
-
-
# Returns the #to_param of the instance.
-
2
def param attachment, style_name
-
attachment.instance.to_param
-
end
-
-
# Returns the fingerprint of the instance.
-
2
def fingerprint attachment, style_name
-
attachment.fingerprint
-
end
-
-
# Returns a the attachment hash. See Paperclip::Attachment#hash_key for
-
# more details.
-
2
def hash attachment=nil, style_name=nil
-
if attachment && style_name
-
attachment.hash_key(style_name)
-
else
-
super()
-
end
-
end
-
-
# Returns the id of the instance in a split path form. e.g. returns
-
# 000/001/234 for an id of 1234.
-
2
def id_partition attachment, style_name
-
case id = attachment.instance.id
-
when Integer
-
("%09d".freeze % id).scan(/\d{3}/).join("/".freeze)
-
when String
-
id.scan(/.{3}/).first(3).join("/".freeze)
-
else
-
nil
-
end
-
end
-
-
# Returns the pluralized form of the attachment name. e.g.
-
# "avatars" for an attachment of :avatar
-
2
def attachment attachment, style_name
-
plural_cache.pluralize_symbol(attachment.name)
-
end
-
-
# Returns the style, or the default style if nil is supplied.
-
2
def style attachment, style_name
-
style_name || attachment.default_style
-
end
-
end
-
end
-
2
module Paperclip
-
2
module Interpolations
-
2
class PluralCache
-
2
def initialize
-
@symbol_cache = {}.compare_by_identity
-
@klass_cache = {}.compare_by_identity
-
end
-
-
2
def pluralize_symbol(symbol)
-
@symbol_cache[symbol] ||= symbol.to_s.downcase.pluralize
-
end
-
-
2
def underscore_and_pluralize_class(klass)
-
@klass_cache[klass] ||= klass.name.underscore.pluralize
-
end
-
end
-
end
-
end
-
2
require 'active_support/core_ext/module/delegation'
-
-
2
module Paperclip
-
2
class AbstractAdapter
-
2
OS_RESTRICTED_CHARACTERS = %r{[/:]}
-
-
2
attr_reader :content_type, :original_filename, :size
-
2
delegate :binmode, :binmode?, :close, :close!, :closed?, :eof?, :path, :rewind, :unlink, :to => :@tempfile
-
2
alias :length :size
-
-
2
def fingerprint
-
@fingerprint ||= Digest::MD5.file(path).to_s
-
end
-
-
2
def read(length = nil, buffer = nil)
-
@tempfile.read(length, buffer)
-
end
-
-
2
def inspect
-
"#{self.class}: #{self.original_filename}"
-
end
-
-
2
def original_filename=(new_filename)
-
return unless new_filename
-
@original_filename = new_filename.gsub(OS_RESTRICTED_CHARACTERS, "_")
-
end
-
-
2
def nil?
-
false
-
end
-
-
2
def assignment?
-
true
-
end
-
-
2
private
-
-
2
def destination
-
@destination ||= TempfileFactory.new.generate(@original_filename.to_s)
-
end
-
-
2
def copy_to_tempfile(src)
-
FileUtils.cp(src.path, destination.path)
-
destination
-
end
-
end
-
end
-
2
module Paperclip
-
2
class AttachmentAdapter < AbstractAdapter
-
2
def initialize(target)
-
@target, @style = case target
-
when Paperclip::Attachment
-
[target, :original]
-
when Paperclip::Style
-
[target.attachment, target.name]
-
end
-
-
cache_current_values
-
end
-
-
2
private
-
-
2
def cache_current_values
-
self.original_filename = @target.original_filename
-
@content_type = @target.content_type
-
@tempfile = copy_to_tempfile(@target)
-
@size = @tempfile.size || @target.size
-
end
-
-
2
def copy_to_tempfile(source)
-
if source.staged?
-
FileUtils.cp(source.staged_path(@style), destination.path)
-
else
-
source.copy_to_local_file(@style, destination.path)
-
end
-
destination
-
end
-
end
-
end
-
-
2
Paperclip.io_adapters.register Paperclip::AttachmentAdapter do |target|
-
Paperclip::Attachment === target || Paperclip::Style === target
-
end
-
2
module Paperclip
-
2
class DataUriAdapter < StringioAdapter
-
-
2
REGEXP = /\Adata:([-\w]+\/[-\w\+\.]+)?;base64,(.*)/m
-
-
2
def initialize(target_uri)
-
super(extract_target(target_uri))
-
end
-
-
2
private
-
-
2
def extract_target(uri)
-
data_uri_parts = uri.match(REGEXP) || []
-
StringIO.new(Base64.decode64(data_uri_parts[2] || ''))
-
end
-
-
end
-
end
-
-
2
Paperclip.io_adapters.register Paperclip::DataUriAdapter do |target|
-
String === target && target =~ Paperclip::DataUriAdapter::REGEXP
-
end
-
2
module Paperclip
-
2
class EmptyStringAdapter < AbstractAdapter
-
2
def initialize(target)
-
end
-
-
2
def nil?
-
false
-
end
-
-
2
def assignment?
-
false
-
end
-
end
-
end
-
-
2
Paperclip.io_adapters.register Paperclip::EmptyStringAdapter do |target|
-
target.is_a?(String) && target.empty?
-
end
-
2
module Paperclip
-
2
class FileAdapter < AbstractAdapter
-
2
def initialize(target)
-
@target = target
-
cache_current_values
-
end
-
-
2
private
-
-
2
def cache_current_values
-
self.original_filename = @target.original_filename if @target.respond_to?(:original_filename)
-
self.original_filename ||= File.basename(@target.path)
-
@tempfile = copy_to_tempfile(@target)
-
@content_type = ContentTypeDetector.new(@target.path).detect
-
@size = File.size(@target)
-
end
-
end
-
end
-
-
2
Paperclip.io_adapters.register Paperclip::FileAdapter do |target|
-
File === target || Tempfile === target
-
end
-
2
module Paperclip
-
2
class HttpUrlProxyAdapter < UriAdapter
-
-
2
REGEXP = /\Ahttps?:\/\//
-
-
2
def initialize(target)
-
super(URI(target))
-
end
-
-
end
-
end
-
-
2
Paperclip.io_adapters.register Paperclip::HttpUrlProxyAdapter do |target|
-
String === target && target =~ Paperclip::HttpUrlProxyAdapter::REGEXP
-
end
-
2
module Paperclip
-
2
class IdentityAdapter < AbstractAdapter
-
2
def new(adapter)
-
adapter
-
end
-
end
-
end
-
-
2
Paperclip.io_adapters.register Paperclip::IdentityAdapter.new do |target|
-
Paperclip.io_adapters.registered?(target)
-
end
-
-
2
module Paperclip
-
2
class NilAdapter < AbstractAdapter
-
2
def initialize(target)
-
end
-
-
2
def original_filename
-
""
-
end
-
-
2
def content_type
-
""
-
end
-
-
2
def size
-
0
-
end
-
-
2
def nil?
-
true
-
end
-
-
2
def read(*args)
-
nil
-
end
-
-
2
def eof?
-
true
-
end
-
end
-
end
-
-
2
Paperclip.io_adapters.register Paperclip::NilAdapter do |target|
-
target.nil? || ( (Paperclip::Attachment === target) && !target.present? )
-
end
-
2
module Paperclip
-
2
class AdapterRegistry
-
2
class NoHandlerError < Paperclip::Error; end
-
-
2
attr_reader :registered_handlers
-
-
2
def initialize
-
2
@registered_handlers = []
-
end
-
-
2
def register(handler_class, &block)
-
20
@registered_handlers << [block, handler_class]
-
end
-
-
2
def handler_for(target)
-
@registered_handlers.each do |tester, handler|
-
return handler if tester.call(target)
-
end
-
raise NoHandlerError.new("No handler found for #{target.inspect}")
-
end
-
-
2
def registered?(target)
-
@registered_handlers.any? do |tester, handler|
-
handler === target
-
end
-
end
-
-
2
def for(target)
-
handler_for(target).new(target)
-
end
-
end
-
end
-
2
module Paperclip
-
2
class StringioAdapter < AbstractAdapter
-
2
def initialize(target)
-
@target = target
-
cache_current_values
-
end
-
-
2
attr_writer :content_type
-
-
2
private
-
-
2
def cache_current_values
-
self.original_filename = @target.original_filename if @target.respond_to?(:original_filename)
-
self.original_filename ||= "data"
-
@tempfile = copy_to_tempfile(@target)
-
@content_type = ContentTypeDetector.new(@tempfile.path).detect
-
@size = @target.size
-
end
-
-
2
def copy_to_tempfile(source)
-
while data = source.read(16*1024)
-
destination.write(data)
-
end
-
destination.rewind
-
destination
-
end
-
-
end
-
end
-
-
2
Paperclip.io_adapters.register Paperclip::StringioAdapter do |target|
-
StringIO === target
-
end
-
2
module Paperclip
-
2
class UploadedFileAdapter < AbstractAdapter
-
2
def initialize(target)
-
@target = target
-
cache_current_values
-
-
if @target.respond_to?(:tempfile)
-
@tempfile = copy_to_tempfile(@target.tempfile)
-
else
-
@tempfile = copy_to_tempfile(@target)
-
end
-
end
-
-
2
class << self
-
2
attr_accessor :content_type_detector
-
end
-
-
2
private
-
-
2
def cache_current_values
-
self.original_filename = @target.original_filename
-
@content_type = determine_content_type
-
@size = File.size(@target.path)
-
end
-
-
2
def content_type_detector
-
self.class.content_type_detector
-
end
-
-
2
def determine_content_type
-
content_type = @target.content_type.to_s.strip
-
if content_type_detector
-
content_type = content_type_detector.new(@target.path).detect
-
end
-
content_type
-
end
-
end
-
end
-
-
2
Paperclip.io_adapters.register Paperclip::UploadedFileAdapter do |target|
-
target.class.name.include?("UploadedFile")
-
end
-
2
require 'open-uri'
-
-
2
module Paperclip
-
2
class UriAdapter < AbstractAdapter
-
2
def initialize(target)
-
@target = target
-
@content = download_content
-
cache_current_values
-
@tempfile = copy_to_tempfile(@content)
-
end
-
-
2
attr_writer :content_type
-
-
2
private
-
-
2
def download_content
-
open(@target)
-
end
-
-
2
def cache_current_values
-
@original_filename = @target.path.split("/").last
-
@original_filename ||= "index.html"
-
self.original_filename = @original_filename.strip
-
-
@content_type = @content.content_type if @content.respond_to?(:content_type)
-
@content_type ||= "text/html"
-
-
@size = @content.size
-
end
-
-
2
def copy_to_tempfile(src)
-
while data = src.read(16*1024)
-
destination.write(data)
-
end
-
src.close
-
destination.rewind
-
destination
-
end
-
end
-
end
-
-
2
Paperclip.io_adapters.register Paperclip::UriAdapter do |target|
-
target.kind_of?(URI)
-
end
-
2
module Paperclip
-
2
module Logger
-
# Log a paperclip-specific line. This will log to STDOUT
-
# by default. Set Paperclip.options[:log] to false to turn off.
-
2
def log message
-
logger.info("[paperclip] #{message}") if logging?
-
end
-
-
2
def logger #:nodoc:
-
@logger ||= options[:logger] || ::Logger.new(STDOUT)
-
end
-
-
2
def logger=(logger)
-
@logger = logger
-
end
-
-
2
def logging? #:nodoc:
-
options[:log]
-
end
-
end
-
end
-
2
module Paperclip
-
2
class MediaTypeSpoofDetector
-
2
def self.using(file, name, content_type)
-
new(file, name, content_type)
-
end
-
-
2
def initialize(file, name, content_type)
-
@file = file
-
@name = name
-
@content_type = content_type || ""
-
end
-
-
2
def spoofed?
-
if has_name? && has_extension? && media_type_mismatch? && mapping_override_mismatch?
-
Paperclip.log("Content Type Spoof: Filename #{File.basename(@name)} (#{supplied_content_type} from Headers, #{content_types_from_name.map(&:to_s)} from Extension), content type discovered from file command: #{calculated_content_type}. See documentation to allow this combination.")
-
true
-
else
-
false
-
end
-
end
-
-
2
private
-
-
2
def has_name?
-
@name.present?
-
end
-
-
2
def has_extension?
-
File.extname(@name).present?
-
end
-
-
2
def media_type_mismatch?
-
supplied_type_mismatch? || calculated_type_mismatch?
-
end
-
-
2
def supplied_type_mismatch?
-
supplied_media_type.present? && !media_types_from_name.include?(supplied_media_type)
-
end
-
-
2
def calculated_type_mismatch?
-
!media_types_from_name.include?(calculated_media_type)
-
end
-
-
2
def mapping_override_mismatch?
-
!Array(mapped_content_type).include?(calculated_content_type)
-
end
-
-
-
2
def supplied_content_type
-
@content_type
-
end
-
-
2
def supplied_media_type
-
@content_type.split("/").first
-
end
-
-
2
def content_types_from_name
-
@content_types_from_name ||= MIME::Types.type_for(@name)
-
end
-
-
2
def media_types_from_name
-
@media_types_from_name ||= content_types_from_name.collect(&:media_type)
-
end
-
-
2
def calculated_content_type
-
@calculated_content_type ||= type_from_file_command.chomp
-
end
-
-
2
def calculated_media_type
-
@calculated_media_type ||= calculated_content_type.split("/").first
-
end
-
-
2
def type_from_file_command
-
begin
-
Paperclip.run("file", "-b --mime :file", :file => @file.path).split(/[:;]\s+/).first
-
rescue Cocaine::CommandLineError
-
""
-
end
-
end
-
-
2
def mapped_content_type
-
Paperclip.options[:content_type_mappings][filename_extension]
-
end
-
-
2
def filename_extension
-
File.extname(@name.to_s.downcase).sub(/^\./, '').to_sym
-
end
-
end
-
end
-
2
require 'paperclip/attachment_registry'
-
2
require 'set'
-
-
2
module Paperclip
-
2
class << self
-
2
attr_writer :registered_attachments_styles_path
-
2
def registered_attachments_styles_path
-
@registered_attachments_styles_path ||= Rails.root.join('public/system/paperclip_attachments.yml').to_s
-
end
-
end
-
-
# Get list of styles saved on previous deploy (running rake paperclip:refresh:missing_styles)
-
2
def self.get_registered_attachments_styles
-
YAML.load_file(Paperclip.registered_attachments_styles_path)
-
rescue Errno::ENOENT
-
nil
-
end
-
2
private_class_method :get_registered_attachments_styles
-
-
2
def self.save_current_attachments_styles!
-
File.open(Paperclip.registered_attachments_styles_path, 'w') do |f|
-
YAML.dump(current_attachments_styles, f)
-
end
-
end
-
-
# Returns hash with styles for all classes using Paperclip.
-
# Unfortunately current version does not work with lambda styles:(
-
# {
-
# :User => {:avatar => [:small, :big]},
-
# :Book => {
-
# :cover => [:thumb, :croppable]},
-
# :sample => [:thumb, :big]},
-
# }
-
# }
-
2
def self.current_attachments_styles
-
Hash.new.tap do |current_styles|
-
Paperclip::AttachmentRegistry.each_definition do |klass, attachment_name, attachment_attributes|
-
# TODO: is it even possible to take into account Procs?
-
next if attachment_attributes[:styles].kind_of?(Proc)
-
attachment_attributes[:styles].try(:keys).try(:each) do |style_name|
-
klass_sym = klass.to_s.to_sym
-
current_styles[klass_sym] ||= Hash.new
-
current_styles[klass_sym][attachment_name.to_sym] ||= Array.new
-
current_styles[klass_sym][attachment_name.to_sym] << style_name.to_sym
-
current_styles[klass_sym][attachment_name.to_sym].map!(&:to_s).sort!.map!(&:to_sym).uniq!
-
end
-
end
-
end
-
end
-
2
private_class_method :current_attachments_styles
-
-
# Returns hash with styles missing from recent run of rake paperclip:refresh:missing_styles
-
# {
-
# :User => {:avatar => [:big]},
-
# :Book => {
-
# :cover => [:croppable]},
-
# }
-
# }
-
2
def self.missing_attachments_styles
-
current_styles = current_attachments_styles
-
registered_styles = get_registered_attachments_styles
-
-
Hash.new.tap do |missing_styles|
-
current_styles.each do |klass, attachment_definitions|
-
attachment_definitions.each do |attachment_name, styles|
-
registered = registered_styles[klass][attachment_name] || [] rescue []
-
missed = styles - registered
-
if missed.present?
-
klass_sym = klass.to_s.to_sym
-
missing_styles[klass_sym] ||= Hash.new
-
missing_styles[klass_sym][attachment_name.to_sym] ||= Array.new
-
missing_styles[klass_sym][attachment_name.to_sym].concat(missed.to_a)
-
missing_styles[klass_sym][attachment_name.to_sym].map!(&:to_s).sort!.map!(&:to_sym).uniq!
-
end
-
end
-
end
-
end
-
end
-
end
-
2
module Paperclip
-
# Paperclip processors allow you to modify attached files when they are
-
# attached in any way you are able. Paperclip itself uses command-line
-
# programs for its included Thumbnail processor, but custom processors
-
# are not required to follow suit.
-
#
-
# Processors are required to be defined inside the Paperclip module and
-
# are also required to be a subclass of Paperclip::Processor. There is
-
# only one method you *must* implement to properly be a subclass:
-
# #make, but #initialize may also be of use. Both methods accept 3
-
# arguments: the file that will be operated on (which is an instance of
-
# File), a hash of options that were defined in has_attached_file's
-
# style hash, and the Paperclip::Attachment itself.
-
#
-
# All #make needs to return is an instance of File (Tempfile is
-
# acceptable) which contains the results of the processing.
-
#
-
# See Paperclip.run for more information about using command-line
-
# utilities from within Processors.
-
2
class Processor
-
2
attr_accessor :file, :options, :attachment
-
-
2
def initialize file, options = {}, attachment = nil
-
@file = file
-
@options = options
-
@attachment = attachment
-
end
-
-
2
def make
-
end
-
-
2
def self.make file, options = {}, attachment = nil
-
new(file, options, attachment).make
-
end
-
-
# The convert method runs the convert binary with the provided arguments.
-
# See Paperclip.run for the available options.
-
2
def convert(arguments = "", local_options = {})
-
Paperclip.run('convert', arguments, local_options)
-
end
-
-
# The identify method runs the identify binary with the provided arguments.
-
# See Paperclip.run for the available options.
-
2
def identify(arguments = "", local_options = {})
-
Paperclip.run('identify', arguments, local_options)
-
end
-
end
-
end
-
2
module Paperclip
-
2
module ProcessorHelpers
-
2
class NoSuchProcessor < StandardError; end
-
-
2
def processor(name) #:nodoc:
-
@known_processors ||= {}
-
if @known_processors[name.to_s]
-
@known_processors[name.to_s]
-
else
-
name = name.to_s.camelize
-
load_processor(name) unless Paperclip.const_defined?(name)
-
processor = Paperclip.const_get(name)
-
@known_processors[name.to_s] = processor
-
end
-
end
-
-
2
def load_processor(name)
-
if defined?(Rails.root) && Rails.root
-
filename = "#{name.to_s.underscore}.rb"
-
directories = %w(lib/paperclip lib/paperclip_processors)
-
-
required = directories.map do |directory|
-
pathname = File.expand_path(Rails.root.join(directory, filename))
-
file_exists = File.exist?(pathname)
-
require pathname if file_exists
-
file_exists
-
end
-
-
raise LoadError, "Could not find the '#{name}' processor in any of these paths: #{directories.join(', ')}" unless required.any?
-
end
-
end
-
-
2
def clear_processors!
-
@known_processors.try(:clear)
-
end
-
-
# You can add your own processor via the Paperclip configuration. Normally
-
# Paperclip will load all processors from the
-
# Rails.root/lib/paperclip_processors directory, but here you can add any
-
# existing class using this mechanism.
-
#
-
# Paperclip.configure do |c|
-
# c.register_processor :watermarker, WatermarkingProcessor.new
-
# end
-
2
def register_processor(name, processor)
-
@known_processors ||= {}
-
@known_processors[name.to_s] = processor
-
end
-
end
-
end
-
2
module Paperclip
-
2
class RailsEnvironment
-
2
def self.get
-
new.get
-
end
-
-
2
def get
-
if rails_exists? && rails_environment_exists?
-
Rails.env
-
else
-
nil
-
end
-
end
-
-
2
private
-
-
2
def rails_exists?
-
Object.const_defined?(:Rails)
-
end
-
-
2
def rails_environment_exists?
-
Rails.respond_to?(:env)
-
end
-
end
-
end
-
2
require 'paperclip'
-
2
require 'paperclip/schema'
-
-
2
module Paperclip
-
2
require 'rails'
-
-
2
class Railtie < Rails::Railtie
-
2
initializer 'paperclip.insert_into_active_record' do |app|
-
2
ActiveSupport.on_load :active_record do
-
2
Paperclip::Railtie.insert
-
end
-
-
2
if app.config.respond_to?(:paperclip_defaults)
-
Paperclip::Attachment.default_options.merge!(app.config.paperclip_defaults)
-
end
-
end
-
-
2
rake_tasks { load "tasks/paperclip.rake" }
-
end
-
-
2
class Railtie
-
2
def self.insert
-
2
Paperclip.options[:logger] = Rails.logger
-
-
2
if defined?(ActiveRecord)
-
2
Paperclip.options[:logger] = ActiveRecord::Base.logger
-
2
ActiveRecord::Base.send(:include, Paperclip::Glue)
-
end
-
end
-
end
-
end
-
2
require 'active_support/deprecation'
-
-
2
module Paperclip
-
# Provides helper methods that can be used in migrations.
-
2
module Schema
-
2
COLUMNS = {:file_name => :string,
-
:content_type => :string,
-
:file_size => :integer,
-
:updated_at => :datetime}
-
-
2
def self.included(base)
-
2
ActiveRecord::ConnectionAdapters::Table.send :include, TableDefinition
-
2
ActiveRecord::ConnectionAdapters::TableDefinition.send :include, TableDefinition
-
2
ActiveRecord::ConnectionAdapters::AbstractAdapter.send :include, Statements
-
-
2
if defined?(ActiveRecord::Migration::CommandRecorder) # Rails 3.1+
-
2
ActiveRecord::Migration::CommandRecorder.send :include, CommandRecorder
-
end
-
end
-
-
2
module Statements
-
2
def add_attachment(table_name, *attachment_names)
-
raise ArgumentError, "Please specify attachment name in your add_attachment call in your migration." if attachment_names.empty?
-
-
options = attachment_names.extract_options!
-
-
attachment_names.each do |attachment_name|
-
COLUMNS.each_pair do |column_name, column_type|
-
column_options = options.merge(options[column_name.to_sym] || {})
-
add_column(table_name, "#{attachment_name}_#{column_name}", column_type, column_options)
-
end
-
end
-
end
-
-
2
def remove_attachment(table_name, *attachment_names)
-
raise ArgumentError, "Please specify attachment name in your remove_attachment call in your migration." if attachment_names.empty?
-
-
options = attachment_names.extract_options!
-
-
attachment_names.each do |attachment_name|
-
COLUMNS.each_pair do |column_name, column_type|
-
column_options = options.merge(options[column_name.to_sym] || {})
-
remove_column(table_name, "#{attachment_name}_#{column_name}")
-
end
-
end
-
end
-
-
2
def drop_attached_file(*args)
-
ActiveSupport::Deprecation.warn "Method `drop_attached_file` in the migration has been deprecated and will be replaced by `remove_attachment`."
-
remove_attachment(*args)
-
end
-
end
-
-
2
module TableDefinition
-
2
def attachment(*attachment_names)
-
options = attachment_names.extract_options!
-
attachment_names.each do |attachment_name|
-
COLUMNS.each_pair do |column_name, column_type|
-
column_options = options.merge(options[column_name.to_sym] || {})
-
column("#{attachment_name}_#{column_name}", column_type, column_options)
-
end
-
end
-
end
-
-
2
def has_attached_file(*attachment_names)
-
ActiveSupport::Deprecation.warn "Method `t.has_attached_file` in the migration has been deprecated and will be replaced by `t.attachment`."
-
attachment(*attachment_names)
-
end
-
end
-
-
2
module CommandRecorder
-
2
def add_attachment(*args)
-
record(:add_attachment, args)
-
end
-
-
2
private
-
-
2
def invert_add_attachment(args)
-
[:remove_attachment, args]
-
end
-
end
-
end
-
end
-
2
require "paperclip/storage/filesystem"
-
2
require "paperclip/storage/fog"
-
2
require "paperclip/storage/s3"
-
2
module Paperclip
-
2
module Storage
-
# The default place to store attachments is in the filesystem. Files on the local
-
# filesystem can be very easily served by Apache without requiring a hit to your app.
-
# They also can be processed more easily after they've been saved, as they're just
-
# normal files. There are two Filesystem-specific options for has_attached_file:
-
# * +path+: The location of the repository of attachments on disk. This can (and, in
-
# almost all cases, should) be coordinated with the value of the +url+ option to
-
# allow files to be saved into a place where Apache can serve them without
-
# hitting your app. Defaults to
-
# ":rails_root/public/:attachment/:id/:style/:basename.:extension"
-
# By default this places the files in the app's public directory which can be served
-
# directly. If you are using capistrano for deployment, a good idea would be to
-
# make a symlink to the capistrano-created system directory from inside your app's
-
# public directory.
-
# See Paperclip::Attachment#interpolate for more information on variable interpolaton.
-
# :path => "/var/app/attachments/:class/:id/:style/:basename.:extension"
-
# * +override_file_permissions+: This allows you to override the file permissions for files
-
# saved by paperclip. If you set this to an explicit octal value (0755, 0644, etc) then
-
# that value will be used to set the permissions for an uploaded file. The default is 0666.
-
# If you set :override_file_permissions to false, the chmod will be skipped. This allows
-
# you to use paperclip on filesystems that don't understand unix file permissions, and has the
-
# added benefit of using the storage directories default umask on those that do.
-
2
module Filesystem
-
2
def self.extended base
-
end
-
-
2
def exists?(style_name = default_style)
-
if original_filename
-
File.exist?(path(style_name))
-
else
-
false
-
end
-
end
-
-
2
def flush_writes #:nodoc:
-
@queued_for_write.each do |style_name, file|
-
FileUtils.mkdir_p(File.dirname(path(style_name)))
-
begin
-
FileUtils.mv(file.path, path(style_name))
-
rescue SystemCallError
-
File.open(path(style_name), "wb") do |new_file|
-
while chunk = file.read(16 * 1024)
-
new_file.write(chunk)
-
end
-
end
-
end
-
unless @options[:override_file_permissions] == false
-
resolved_chmod = (@options[:override_file_permissions] &~ 0111) || (0666 &~ File.umask)
-
FileUtils.chmod( resolved_chmod, path(style_name) )
-
end
-
file.rewind
-
end
-
-
after_flush_writes # allows attachment to clean up temp files
-
-
@queued_for_write = {}
-
end
-
-
2
def flush_deletes #:nodoc:
-
@queued_for_delete.each do |path|
-
begin
-
log("deleting #{path}")
-
FileUtils.rm(path) if File.exist?(path)
-
rescue Errno::ENOENT => e
-
# ignore file-not-found, let everything else pass
-
end
-
begin
-
while(true)
-
path = File.dirname(path)
-
FileUtils.rmdir(path)
-
break if File.exist?(path) # Ruby 1.9.2 does not raise if the removal failed.
-
end
-
rescue Errno::EEXIST, Errno::ENOTEMPTY, Errno::ENOENT, Errno::EINVAL, Errno::ENOTDIR, Errno::EACCES
-
# Stop trying to remove parent directories
-
rescue SystemCallError => e
-
log("There was an unexpected error while deleting directories: #{e.class}")
-
# Ignore it
-
end
-
end
-
@queued_for_delete = []
-
end
-
-
2
def copy_to_local_file(style, local_dest_path)
-
FileUtils.cp(path(style), local_dest_path)
-
end
-
end
-
-
end
-
end
-
2
module Paperclip
-
2
module Storage
-
# fog is a modern and versatile cloud computing library for Ruby.
-
# Among others, it supports Amazon S3 to store your files. In
-
# contrast to the outdated AWS-S3 gem it is actively maintained and
-
# supports multiple locations.
-
# Amazon's S3 file hosting service is a scalable, easy place to
-
# store files for distribution. You can find out more about it at
-
# http://aws.amazon.com/s3 There are a few fog-specific options for
-
# has_attached_file, which will be explained using S3 as an example:
-
# * +fog_credentials+: Takes a Hash with your credentials. For S3,
-
# you can use the following format:
-
# aws_access_key_id: '<your aws_access_key_id>'
-
# aws_secret_access_key: '<your aws_secret_access_key>'
-
# provider: 'AWS'
-
# region: 'eu-west-1'
-
# scheme: 'https'
-
# * +fog_directory+: This is the name of the S3 bucket that will
-
# store your files. Remember that the bucket must be unique across
-
# all of Amazon S3. If the bucket does not exist, Paperclip will
-
# attempt to create it.
-
# * +fog_file*: This can be hash or lambda returning hash. The
-
# value is used as base properties for new uploaded file.
-
# * +path+: This is the key under the bucket in which the file will
-
# be stored. The URL will be constructed from the bucket and the
-
# path. This is what you will want to interpolate. Keys should be
-
# unique, like filenames, and despite the fact that S3 (strictly
-
# speaking) does not support directories, you can still use a / to
-
# separate parts of your file name.
-
# * +fog_public+: (optional, defaults to true) Should the uploaded
-
# files be public or not? (true/false)
-
# * +fog_host+: (optional) The fully-qualified domain name (FQDN)
-
# that is the alias to the S3 domain of your bucket, e.g.
-
# 'http://images.example.com'. This can also be used in
-
# conjunction with Cloudfront (http://aws.amazon.com/cloudfront)
-
-
2
module Fog
-
2
def self.extended base
-
begin
-
require 'fog'
-
rescue LoadError => e
-
e.message << " (You may need to install the fog gem)"
-
raise e
-
end unless defined?(Fog)
-
-
base.instance_eval do
-
unless @options[:url].to_s.match(/\A:fog.*url\Z/)
-
@options[:path] = @options[:path].gsub(/:url/, @options[:url]).gsub(/\A:rails_root\/public\/system\//, '')
-
@options[:url] = ':fog_public_url'
-
end
-
Paperclip.interpolates(:fog_public_url) do |attachment, style|
-
attachment.public_url(style)
-
end unless Paperclip::Interpolations.respond_to? :fog_public_url
-
end
-
end
-
-
2
AWS_BUCKET_SUBDOMAIN_RESTRICTON_REGEX = /\A(?:[a-z]|\d(?!\d{0,2}(?:\.\d{1,3}){3}\Z))(?:[a-z0-9]|\.(?![\.\-])|\-(?![\.])){1,61}[a-z0-9]\Z/
-
-
2
def exists?(style = default_style)
-
if original_filename
-
!!directory.files.head(path(style))
-
else
-
false
-
end
-
end
-
-
2
def fog_credentials
-
@fog_credentials ||= parse_credentials(@options[:fog_credentials])
-
end
-
-
2
def fog_file
-
@fog_file ||= begin
-
value = @options[:fog_file]
-
if !value
-
{}
-
elsif value.respond_to?(:call)
-
value.call(self)
-
else
-
value
-
end
-
end
-
end
-
-
2
def fog_public(style = default_style)
-
if @options.has_key?(:fog_public)
-
if @options[:fog_public].respond_to?(:has_key?) && @options[:fog_public].has_key?(style)
-
@options[:fog_public][style]
-
else
-
@options[:fog_public]
-
end
-
else
-
true
-
end
-
end
-
-
2
def flush_writes
-
for style, file in @queued_for_write do
-
log("saving #{path(style)}")
-
retried = false
-
begin
-
directory.files.create(fog_file.merge(
-
:body => file,
-
:key => path(style),
-
:public => fog_public(style),
-
:content_type => file.content_type
-
))
-
rescue Excon::Errors::NotFound
-
raise if retried
-
retried = true
-
directory.save
-
retry
-
ensure
-
file.rewind
-
end
-
end
-
-
after_flush_writes # allows attachment to clean up temp files
-
-
@queued_for_write = {}
-
end
-
-
2
def flush_deletes
-
for path in @queued_for_delete do
-
log("deleting #{path}")
-
directory.files.new(:key => path).destroy
-
end
-
@queued_for_delete = []
-
end
-
-
2
def public_url(style = default_style)
-
if @options[:fog_host]
-
"#{dynamic_fog_host_for_style(style)}/#{path(style)}"
-
else
-
if fog_credentials[:provider] == 'AWS'
-
"#{scheme}://#{host_name_for_directory}/#{path(style)}"
-
else
-
directory.files.new(:key => path(style)).public_url
-
end
-
end
-
end
-
-
2
def expiring_url(time = (Time.now + 3600), style_name = default_style)
-
time = convert_time(time)
-
http_url_method = "get_#{scheme}_url"
-
if path(style_name) && directory.files.respond_to?(http_url_method)
-
expiring_url = directory.files.public_send(http_url_method, path(style_name), time)
-
-
if @options[:fog_host]
-
expiring_url.gsub!(/#{host_name_for_directory}/, dynamic_fog_host_for_style(style_name))
-
end
-
else
-
expiring_url = url(style_name)
-
end
-
-
return expiring_url
-
end
-
-
2
def parse_credentials(creds)
-
creds = find_credentials(creds).stringify_keys
-
(creds[RailsEnvironment.get] || creds).symbolize_keys
-
end
-
-
2
def copy_to_local_file(style, local_dest_path)
-
log("copying #{path(style)} to local file #{local_dest_path}")
-
::File.open(local_dest_path, 'wb') do |local_file|
-
file = directory.files.get(path(style))
-
local_file.write(file.body)
-
end
-
rescue ::Fog::Errors::Error => e
-
warn("#{e} - cannot copy #{path(style)} to local file #{local_dest_path}")
-
false
-
end
-
-
2
private
-
-
2
def convert_time(time)
-
if time.is_a?(Fixnum)
-
time = Time.now + time
-
end
-
time
-
end
-
-
2
def dynamic_fog_host_for_style(style)
-
if @options[:fog_host].respond_to?(:call)
-
@options[:fog_host].call(self)
-
else
-
(@options[:fog_host] =~ /%d/) ? @options[:fog_host] % (path(style).hash % 4) : @options[:fog_host]
-
end
-
end
-
-
2
def host_name_for_directory
-
if @options[:fog_directory].to_s =~ Fog::AWS_BUCKET_SUBDOMAIN_RESTRICTON_REGEX
-
"#{@options[:fog_directory]}.s3.amazonaws.com"
-
else
-
"s3.amazonaws.com/#{@options[:fog_directory]}"
-
end
-
end
-
-
2
def find_credentials(creds)
-
case creds
-
when File
-
YAML::load(ERB.new(File.read(creds.path)).result)
-
when String, Pathname
-
YAML::load(ERB.new(File.read(creds)).result)
-
when Hash
-
creds
-
else
-
if creds.respond_to?(:call)
-
creds.call(self)
-
else
-
raise ArgumentError, "Credentials are not a path, file, hash or proc."
-
end
-
end
-
end
-
-
2
def connection
-
@connection ||= ::Fog::Storage.new(fog_credentials)
-
end
-
-
2
def directory
-
dir = if @options[:fog_directory].respond_to?(:call)
-
@options[:fog_directory].call(self)
-
else
-
@options[:fog_directory]
-
end
-
-
@directory ||= connection.directories.new(:key => dir)
-
end
-
-
2
def scheme
-
@scheme ||= fog_credentials[:scheme] || 'https'
-
end
-
end
-
end
-
end
-
2
module Paperclip
-
2
module Storage
-
# Amazon's S3 file hosting service is a scalable, easy place to store files for
-
# distribution. You can find out more about it at http://aws.amazon.com/s3
-
#
-
# To use Paperclip with S3, include the +aws-sdk+ gem in your Gemfile:
-
# gem 'aws-sdk', '~> 1.6'
-
# There are a few S3-specific options for has_attached_file:
-
# * +s3_credentials+: Takes a path, a File, a Hash or a Proc. The path (or File) must point
-
# to a YAML file containing the +access_key_id+ and +secret_access_key+ that Amazon
-
# gives you. You can 'environment-space' this just like you do to your
-
# database.yml file, so different environments can use different accounts:
-
# development:
-
# access_key_id: 123...
-
# secret_access_key: 123...
-
# test:
-
# access_key_id: abc...
-
# secret_access_key: abc...
-
# production:
-
# access_key_id: 456...
-
# secret_access_key: 456...
-
# This is not required, however, and the file may simply look like this:
-
# access_key_id: 456...
-
# secret_access_key: 456...
-
# In which case, those access keys will be used in all environments. You can also
-
# put your bucket name in this file, instead of adding it to the code directly.
-
# This is useful when you want the same account but a different bucket for
-
# development versus production.
-
# When using a Proc it provides a single parameter which is the attachment itself. A
-
# method #instance is available on the attachment which will take you back to your
-
# code. eg.
-
# class User
-
# has_attached_file :download,
-
# :storage => :s3,
-
# :s3_credentials => Proc.new{|a| a.instance.s3_credentials }
-
#
-
# def s3_credentials
-
# {:bucket => "xxx", :access_key_id => "xxx", :secret_access_key => "xxx"}
-
# end
-
# end
-
# * +s3_permissions+: This is a String that should be one of the "canned" access
-
# policies that S3 provides (more information can be found here:
-
# http://docs.aws.amazon.com/AmazonS3/latest/dev/ACLOverview.html)
-
# The default for Paperclip is :public_read.
-
#
-
# You can set permission on a per style bases by doing the following:
-
# :s3_permissions => {
-
# :original => :private
-
# }
-
# Or globally:
-
# :s3_permissions => :private
-
#
-
# * +s3_protocol+: The protocol for the URLs generated to your S3 assets. Can be either
-
# 'http', 'https', or an empty string to generate protocol-relative URLs. Defaults to 'http'
-
# when your :s3_permissions are :public_read (the default), and 'https' when your
-
# :s3_permissions are anything else.
-
# * +s3_headers+: A hash of headers or a Proc. You may specify a hash such as
-
# {'Expires' => 1.year.from_now.httpdate}. If you use a Proc, headers are determined at
-
# runtime. Paperclip will call that Proc with attachment as the only argument.
-
# Can be defined both globally and within a style-specific hash.
-
# * +bucket+: This is the name of the S3 bucket that will store your files. Remember
-
# that the bucket must be unique across all of Amazon S3. If the bucket does not exist
-
# Paperclip will attempt to create it. The bucket name will not be interpolated.
-
# You can define the bucket as a Proc if you want to determine it's name at runtime.
-
# Paperclip will call that Proc with attachment as the only argument.
-
# * +s3_host_alias+: The fully-qualified domain name (FQDN) that is the alias to the
-
# S3 domain of your bucket. Used with the :s3_alias_url url interpolation. See the
-
# link in the +url+ entry for more information about S3 domains and buckets.
-
# * +url+: There are four options for the S3 url. You can choose to have the bucket's name
-
# placed domain-style (bucket.s3.amazonaws.com) or path-style (s3.amazonaws.com/bucket).
-
# You can also specify a CNAME (which requires the CNAME to be specified as
-
# :s3_alias_url. You can read more about CNAMEs and S3 at
-
# http://docs.amazonwebservices.com/AmazonS3/latest/index.html?VirtualHosting.html
-
# Normally, this won't matter in the slightest and you can leave the default (which is
-
# path-style, or :s3_path_url). But in some cases paths don't work and you need to use
-
# the domain-style (:s3_domain_url). Anything else here will be treated like path-style.
-
#
-
# Notes:
-
# * The value of this option is a string, not a symbol.
-
# <b>right:</b> <tt>":s3_domain_url"</tt>
-
# <b>wrong:</b> <tt>:s3_domain_url</tt>
-
# * If you use a CNAME for use with CloudFront, you can NOT specify https as your
-
# :s3_protocol;
-
# This is *not supported* by S3/CloudFront. Finally, when using the host
-
# alias, the :bucket parameter is ignored, as the hostname is used as the bucket name
-
# by S3. The fourth option for the S3 url is :asset_host, which uses Rails' built-in
-
# asset_host settings.
-
# * To get the full url from a paperclip'd object, use the
-
# image_path helper; this is what image_tag uses to generate the url for an img tag.
-
# * +path+: This is the key under the bucket in which the file will be stored. The
-
# URL will be constructed from the bucket and the path. This is what you will want
-
# to interpolate. Keys should be unique, like filenames, and despite the fact that
-
# S3 (strictly speaking) does not support directories, you can still use a / to
-
# separate parts of your file name.
-
# * +s3_host_name+: If you are using your bucket in Tokyo region etc, write host_name.
-
# * +s3_metadata+: These key/value pairs will be stored with the
-
# object. This option works by prefixing each key with
-
# "x-amz-meta-" before sending it as a header on the object
-
# upload request. Can be defined both globally and within a style-specific hash.
-
# * +s3_storage_class+: If this option is set to
-
# <tt>:reduced_redundancy</tt>, the object will be stored using Reduced
-
# Redundancy Storage. RRS enables customers to reduce their
-
# costs by storing non-critical, reproducible data at lower
-
# levels of redundancy than Amazon S3's standard storage.
-
#
-
# You can set storage class on a per style bases by doing the following:
-
# :s3_storage_class => {
-
# :thumb => :reduced_reduncancy
-
# }
-
# Or globally:
-
# :s3_storage_class => :reduced_redundancy
-
-
2
module S3
-
2
def self.extended base
-
begin
-
require 'aws-sdk'
-
rescue LoadError => e
-
e.message << " (You may need to install the aws-sdk gem)"
-
raise e
-
end unless defined?(AWS::Core)
-
-
# Overriding log formatter to make sure it return a UTF-8 string
-
if defined?(AWS::Core::LogFormatter)
-
AWS::Core::LogFormatter.class_eval do
-
def summarize_hash(hash)
-
hash.map { |key, value| ":#{key}=>#{summarize_value(value)}".force_encoding('UTF-8') }.sort.join(',')
-
end
-
end
-
elsif defined?(AWS::Core::ClientLogging)
-
AWS::Core::ClientLogging.class_eval do
-
def sanitize_hash(hash)
-
hash.map { |key, value| "#{sanitize_value(key)}=>#{sanitize_value(value)}".force_encoding('UTF-8') }.sort.join(',')
-
end
-
end
-
end
-
-
base.instance_eval do
-
@s3_options = @options[:s3_options] || {}
-
@s3_permissions = set_permissions(@options[:s3_permissions])
-
@s3_protocol = @options[:s3_protocol] ||
-
Proc.new do |style, attachment|
-
permission = (@s3_permissions[style.to_s.to_sym] || @s3_permissions[:default])
-
permission = permission.call(attachment, style) if permission.respond_to?(:call)
-
(permission == :public_read) ? 'http'.freeze : 'https'.freeze
-
end
-
@s3_metadata = @options[:s3_metadata] || {}
-
@s3_headers = {}
-
merge_s3_headers(@options[:s3_headers], @s3_headers, @s3_metadata)
-
-
@s3_storage_class = set_storage_class(@options[:s3_storage_class])
-
-
@s3_server_side_encryption = :aes256
-
if @options[:s3_server_side_encryption].blank?
-
@s3_server_side_encryption = false
-
end
-
if @s3_server_side_encryption
-
@s3_server_side_encryption = @options[:s3_server_side_encryption]
-
end
-
-
unless @options[:url].to_s.match(/\A:s3.*url\Z/) || @options[:url] == ":asset_host".freeze
-
@options[:path] = path_option.gsub(/:url/, @options[:url]).sub(/\A:rails_root\/public\/system/, "".freeze)
-
@options[:url] = ":s3_path_url".freeze
-
end
-
@options[:url] = @options[:url].inspect if @options[:url].is_a?(Symbol)
-
-
@http_proxy = @options[:http_proxy] || nil
-
end
-
-
Paperclip.interpolates(:s3_alias_url) do |attachment, style|
-
"#{attachment.s3_protocol(style, true)}//#{attachment.s3_host_alias}/#{attachment.path(style).sub(%r{\A/}, "".freeze)}"
-
end unless Paperclip::Interpolations.respond_to? :s3_alias_url
-
Paperclip.interpolates(:s3_path_url) do |attachment, style|
-
"#{attachment.s3_protocol(style, true)}//#{attachment.s3_host_name}/#{attachment.bucket_name}/#{attachment.path(style).sub(%r{\A/}, "".freeze)}"
-
end unless Paperclip::Interpolations.respond_to? :s3_path_url
-
Paperclip.interpolates(:s3_domain_url) do |attachment, style|
-
"#{attachment.s3_protocol(style, true)}//#{attachment.bucket_name}.#{attachment.s3_host_name}/#{attachment.path(style).sub(%r{\A/}, "".freeze)}"
-
end unless Paperclip::Interpolations.respond_to? :s3_domain_url
-
Paperclip.interpolates(:asset_host) do |attachment, style|
-
"#{attachment.path(style).sub(%r{\A/}, "".freeze)}"
-
end unless Paperclip::Interpolations.respond_to? :asset_host
-
end
-
-
2
def expiring_url(time = 3600, style_name = default_style)
-
if path(style_name)
-
base_options = { :expires => time, :secure => use_secure_protocol?(style_name) }
-
s3_object(style_name).url_for(:read, base_options.merge(s3_url_options)).to_s
-
else
-
url(style_name)
-
end
-
end
-
-
2
def s3_credentials
-
@s3_credentials ||= parse_credentials(@options[:s3_credentials])
-
end
-
-
2
def s3_host_name
-
host_name = @options[:s3_host_name]
-
host_name = host_name.call(self) if host_name.is_a?(Proc)
-
-
host_name || s3_credentials[:s3_host_name] || "s3.amazonaws.com".freeze
-
end
-
-
2
def s3_host_alias
-
@s3_host_alias = @options[:s3_host_alias]
-
@s3_host_alias = @s3_host_alias.call(self) if @s3_host_alias.respond_to?(:call)
-
@s3_host_alias
-
end
-
-
2
def s3_url_options
-
s3_url_options = @options[:s3_url_options] || {}
-
s3_url_options = s3_url_options.call(instance) if s3_url_options.respond_to?(:call)
-
s3_url_options
-
end
-
-
2
def bucket_name
-
@bucket = @options[:bucket] || s3_credentials[:bucket]
-
@bucket = @bucket.call(self) if @bucket.respond_to?(:call)
-
@bucket or raise ArgumentError, "missing required :bucket option"
-
end
-
-
2
def s3_interface
-
@s3_interface ||= begin
-
config = { :s3_endpoint => s3_host_name }
-
-
if using_http_proxy?
-
-
proxy_opts = { :host => http_proxy_host }
-
proxy_opts[:port] = http_proxy_port if http_proxy_port
-
if http_proxy_user
-
userinfo = http_proxy_user.to_s
-
userinfo += ":#{http_proxy_password}" if http_proxy_password
-
proxy_opts[:userinfo] = userinfo
-
end
-
config[:proxy_uri] = URI::HTTP.build(proxy_opts)
-
end
-
-
[:access_key_id, :secret_access_key, :credential_provider].each do |opt|
-
config[opt] = s3_credentials[opt] if s3_credentials[opt]
-
end
-
-
obtain_s3_instance_for(config.merge(@s3_options))
-
end
-
end
-
-
2
def obtain_s3_instance_for(options)
-
instances = (Thread.current[:paperclip_s3_instances] ||= {})
-
instances[options] ||= AWS::S3.new(options)
-
end
-
-
2
def s3_bucket
-
@s3_bucket ||= s3_interface.buckets[bucket_name]
-
end
-
-
2
def s3_object style_name = default_style
-
s3_bucket.objects[path(style_name).sub(%r{\A/},'')]
-
end
-
-
2
def using_http_proxy?
-
!!@http_proxy
-
end
-
-
2
def http_proxy_host
-
using_http_proxy? ? @http_proxy[:host] : nil
-
end
-
-
2
def http_proxy_port
-
using_http_proxy? ? @http_proxy[:port] : nil
-
end
-
-
2
def http_proxy_user
-
using_http_proxy? ? @http_proxy[:user] : nil
-
end
-
-
2
def http_proxy_password
-
using_http_proxy? ? @http_proxy[:password] : nil
-
end
-
-
2
def set_permissions permissions
-
permissions = { :default => permissions } unless permissions.respond_to?(:merge)
-
permissions.merge :default => (permissions[:default] || :public_read)
-
end
-
-
2
def set_storage_class(storage_class)
-
storage_class = {:default => storage_class} unless storage_class.respond_to?(:merge)
-
storage_class
-
end
-
-
2
def parse_credentials creds
-
creds = creds.respond_to?(:call) ? creds.call(self) : creds
-
creds = find_credentials(creds).stringify_keys
-
(creds[RailsEnvironment.get] || creds).symbolize_keys
-
end
-
-
2
def exists?(style = default_style)
-
if original_filename
-
s3_object(style).exists?
-
else
-
false
-
end
-
rescue AWS::Errors::Base => e
-
false
-
end
-
-
2
def s3_permissions(style = default_style)
-
s3_permissions = @s3_permissions[style] || @s3_permissions[:default]
-
s3_permissions = s3_permissions.call(self, style) if s3_permissions.respond_to?(:call)
-
s3_permissions
-
end
-
-
2
def s3_storage_class(style = default_style)
-
@s3_storage_class[style] || @s3_storage_class[:default]
-
end
-
-
2
def s3_protocol(style = default_style, with_colon = false)
-
protocol = @s3_protocol
-
protocol = protocol.call(style, self) if protocol.respond_to?(:call)
-
-
if with_colon && !protocol.empty?
-
"#{protocol}:"
-
else
-
protocol.to_s
-
end
-
end
-
-
2
def create_bucket
-
s3_interface.buckets.create(bucket_name)
-
end
-
-
2
def flush_writes #:nodoc:
-
@queued_for_write.each do |style, file|
-
retries = 0
-
begin
-
log("saving #{path(style)}")
-
acl = @s3_permissions[style] || @s3_permissions[:default]
-
acl = acl.call(self, style) if acl.respond_to?(:call)
-
write_options = {
-
:content_type => file.content_type,
-
:acl => acl
-
}
-
-
# add storage class for this style if defined
-
storage_class = s3_storage_class(style)
-
write_options.merge!(:storage_class => storage_class) if storage_class
-
-
if @s3_server_side_encryption
-
write_options[:server_side_encryption] = @s3_server_side_encryption
-
end
-
-
style_specific_options = styles[style]
-
-
if style_specific_options
-
merge_s3_headers( style_specific_options[:s3_headers], @s3_headers, @s3_metadata) if style_specific_options[:s3_headers]
-
@s3_metadata.merge!(style_specific_options[:s3_metadata]) if style_specific_options[:s3_metadata]
-
end
-
-
write_options[:metadata] = @s3_metadata unless @s3_metadata.empty?
-
write_options.merge!(@s3_headers)
-
-
s3_object(style).write(file, write_options)
-
rescue AWS::S3::Errors::NoSuchBucket
-
create_bucket
-
retry
-
rescue AWS::S3::Errors::SlowDown
-
retries += 1
-
if retries <= 5
-
sleep((2 ** retries) * 0.5)
-
retry
-
else
-
raise
-
end
-
ensure
-
file.rewind
-
end
-
end
-
-
after_flush_writes # allows attachment to clean up temp files
-
-
@queued_for_write = {}
-
end
-
-
2
def flush_deletes #:nodoc:
-
@queued_for_delete.each do |path|
-
begin
-
log("deleting #{path}")
-
s3_bucket.objects[path.sub(%r{\A/},'')].delete
-
rescue AWS::Errors::Base => e
-
# Ignore this.
-
end
-
end
-
@queued_for_delete = []
-
end
-
-
2
def copy_to_local_file(style, local_dest_path)
-
log("copying #{path(style)} to local file #{local_dest_path}")
-
::File.open(local_dest_path, 'wb') do |local_file|
-
s3_object(style).read do |chunk|
-
local_file.write(chunk)
-
end
-
end
-
rescue AWS::Errors::Base => e
-
warn("#{e} - cannot copy #{path(style)} to local file #{local_dest_path}")
-
false
-
end
-
-
2
private
-
-
2
def find_credentials creds
-
case creds
-
when File
-
YAML::load(ERB.new(File.read(creds.path)).result)
-
when String, Pathname
-
YAML::load(ERB.new(File.read(creds)).result)
-
when Hash
-
creds
-
when NilClass
-
{}
-
else
-
raise ArgumentError, "Credentials given are not a path, file, proc, or hash."
-
end
-
end
-
-
2
def use_secure_protocol?(style_name)
-
s3_protocol(style_name) == "https"
-
end
-
-
2
def merge_s3_headers(http_headers, s3_headers, s3_metadata)
-
return if http_headers.nil?
-
http_headers = http_headers.call(instance) if http_headers.respond_to?(:call)
-
http_headers.inject({}) do |headers,(name,value)|
-
case name.to_s
-
when /\Ax-amz-meta-(.*)/i
-
s3_metadata[$1.downcase] = value
-
else
-
s3_headers[name.to_s.downcase.sub(/\Ax-amz-/,'').tr("-","_").to_sym] = value
-
end
-
end
-
end
-
end
-
end
-
end
-
# encoding: utf-8
-
2
module Paperclip
-
# The Style class holds the definition of a thumbnail style, applying
-
# whatever processing is required to normalize the definition and delaying
-
# the evaluation of block parameters until useful context is available.
-
-
2
class Style
-
-
2
attr_reader :name, :attachment, :format
-
-
# Creates a Style object. +name+ is the name of the attachment,
-
# +definition+ is the style definition from has_attached_file, which
-
# can be string, array or hash
-
2
def initialize name, definition, attachment
-
@name = name
-
@attachment = attachment
-
if definition.is_a? Hash
-
@geometry = definition.delete(:geometry)
-
@format = definition.delete(:format)
-
@processors = definition.delete(:processors)
-
@convert_options = definition.delete(:convert_options)
-
@source_file_options = definition.delete(:source_file_options)
-
@other_args = definition
-
elsif definition.is_a? String
-
@geometry = definition
-
@format = nil
-
@other_args = {}
-
else
-
@geometry, @format = [definition, nil].flatten[0..1]
-
@other_args = {}
-
end
-
@format = default_format if @format.blank?
-
end
-
-
# retrieves from the attachment the processors defined in the has_attached_file call
-
# (which method (in the attachment) will call any supplied procs)
-
# There is an important change of interface here: a style rule can set its own processors
-
# by default we behave as before, though.
-
# if a proc has been supplied, we call it here
-
2
def processors
-
@processors.respond_to?(:call) ? @processors.call(attachment.instance) : (@processors || attachment.processors)
-
end
-
-
# retrieves from the attachment the whiny setting
-
2
def whiny
-
attachment.whiny
-
end
-
-
# returns true if we're inclined to grumble
-
2
def whiny?
-
!!whiny
-
end
-
-
2
def convert_options
-
@convert_options.respond_to?(:call) ? @convert_options.call(attachment.instance) :
-
(@convert_options || attachment.send(:extra_options_for, name))
-
end
-
-
2
def source_file_options
-
@source_file_options.respond_to?(:call) ? @source_file_options.call(attachment.instance) :
-
(@source_file_options || attachment.send(:extra_source_file_options_for, name))
-
end
-
-
# returns the geometry string for this style
-
# if a proc has been supplied, we call it here
-
2
def geometry
-
@geometry.respond_to?(:call) ? @geometry.call(attachment.instance) : @geometry
-
end
-
-
# Supplies the hash of options that processors expect to receive as their second argument
-
# Arguments other than the standard geometry, format etc are just passed through from
-
# initialization and any procs are called here, just before post-processing.
-
2
def processor_options
-
args = {:style => name}
-
@other_args.each do |k,v|
-
args[k] = v.respond_to?(:call) ? v.call(attachment) : v
-
end
-
[:processors, :geometry, :format, :whiny, :convert_options, :source_file_options].each do |k|
-
(arg = send(k)) && args[k] = arg
-
end
-
args
-
end
-
-
# Supports getting and setting style properties with hash notation to ensure backwards-compatibility
-
# eg. @attachment.styles[:large][:geometry]@ will still work
-
2
def [](key)
-
if [:name, :convert_options, :whiny, :processors, :geometry, :format, :animated, :source_file_options].include?(key)
-
send(key)
-
elsif defined? @other_args[key]
-
@other_args[key]
-
end
-
end
-
-
2
def []=(key, value)
-
if [:name, :convert_options, :whiny, :processors, :geometry, :format, :animated, :source_file_options].include?(key)
-
send("#{key}=".intern, value)
-
else
-
@other_args[key] = value
-
end
-
end
-
-
# defaults to default format (nil by default)
-
2
def default_format
-
base = attachment.options[:default_format]
-
base.respond_to?(:call) ? base.call(attachment, name) : base
-
end
-
-
end
-
end
-
2
module Paperclip
-
# Overriding some implementation of Tempfile
-
2
class Tempfile < ::Tempfile
-
# Due to how ImageMagick handles its image format conversion and how
-
# Tempfile handles its naming scheme, it is necessary to override how
-
# Tempfile makes # its names so as to allow for file extensions. Idea
-
# taken from the comments on this blog post:
-
# http://marsorange.com/archives/of-mogrify-ruby-tempfile-dynamic-class-definitions
-
#
-
# This is Ruby 1.9.3's implementation.
-
2
def make_tmpname(prefix_suffix, n)
-
if RUBY_PLATFORM =~ /java/
-
case prefix_suffix
-
when String
-
prefix, suffix = prefix_suffix, ''
-
when Array
-
prefix, suffix = *prefix_suffix
-
else
-
raise ArgumentError, "unexpected prefix_suffix: #{prefix_suffix.inspect}"
-
end
-
-
t = Time.now.strftime("%y%m%d")
-
path = "#{prefix}#{t}-#{$$}-#{rand(0x100000000).to_s(36)}-#{n}#{suffix}"
-
else
-
super
-
end
-
end
-
end
-
-
2
module TempfileEncoding
-
# This overrides Tempfile#binmode to make sure that the extenal encoding
-
# for binary mode is ASCII-8BIT. This behavior is what's in CRuby, but not
-
# in JRuby
-
2
def binmode
-
set_encoding('ASCII-8BIT')
-
super
-
end
-
end
-
end
-
-
2
if RUBY_PLATFORM =~ /java/
-
::Tempfile.send :include, Paperclip::TempfileEncoding
-
end
-
2
module Paperclip
-
2
class TempfileFactory
-
-
2
def generate(name = random_name)
-
@name = name
-
file = Tempfile.new([basename, extension])
-
file.binmode
-
file
-
end
-
-
2
def extension
-
File.extname(@name)
-
end
-
-
2
def basename
-
Digest::MD5.hexdigest(File.basename(@name, extension))
-
end
-
-
2
def random_name
-
SecureRandom.uuid
-
end
-
end
-
end
-
2
module Paperclip
-
# Handles thumbnailing images that are uploaded.
-
2
class Thumbnail < Processor
-
-
2
attr_accessor :current_geometry, :target_geometry, :format, :whiny, :convert_options,
-
:source_file_options, :animated, :auto_orient
-
-
# List of formats that we need to preserve animation
-
2
ANIMATED_FORMATS = %w(gif)
-
-
# Creates a Thumbnail object set to work on the +file+ given. It
-
# will attempt to transform the image into one defined by +target_geometry+
-
# which is a "WxH"-style string. +format+ will be inferred from the +file+
-
# unless specified. Thumbnail creation will raise no errors unless
-
# +whiny+ is true (which it is, by default. If +convert_options+ is
-
# set, the options will be appended to the convert command upon image conversion
-
#
-
# Options include:
-
#
-
# +geometry+ - the desired width and height of the thumbnail (required)
-
# +file_geometry_parser+ - an object with a method named +from_file+ that takes an image file and produces its geometry and a +transformation_to+. Defaults to Paperclip::Geometry
-
# +string_geometry_parser+ - an object with a method named +parse+ that takes a string and produces an object with +width+, +height+, and +to_s+ accessors. Defaults to Paperclip::Geometry
-
# +source_file_options+ - flags passed to the +convert+ command that influence how the source file is read
-
# +convert_options+ - flags passed to the +convert+ command that influence how the image is processed
-
# +whiny+ - whether to raise an error when processing fails. Defaults to true
-
# +format+ - the desired filename extension
-
# +animated+ - whether to merge all the layers in the image. Defaults to true
-
2
def initialize(file, options = {}, attachment = nil)
-
super
-
-
geometry = options[:geometry].to_s
-
@crop = geometry[-1,1] == '#'
-
@target_geometry = options.fetch(:string_geometry_parser, Geometry).parse(geometry)
-
@current_geometry = options.fetch(:file_geometry_parser, Geometry).from_file(@file)
-
@source_file_options = options[:source_file_options]
-
@convert_options = options[:convert_options]
-
@whiny = options.fetch(:whiny, true)
-
@format = options[:format]
-
@animated = options.fetch(:animated, true)
-
@auto_orient = options.fetch(:auto_orient, true)
-
if @auto_orient && @current_geometry.respond_to?(:auto_orient)
-
@current_geometry.auto_orient
-
end
-
-
@source_file_options = @source_file_options.split(/\s+/) if @source_file_options.respond_to?(:split)
-
@convert_options = @convert_options.split(/\s+/) if @convert_options.respond_to?(:split)
-
-
@current_format = File.extname(@file.path)
-
@basename = File.basename(@file.path, @current_format)
-
end
-
-
# Returns true if the +target_geometry+ is meant to crop.
-
2
def crop?
-
@crop
-
end
-
-
# Returns true if the image is meant to make use of additional convert options.
-
2
def convert_options?
-
!@convert_options.nil? && !@convert_options.empty?
-
end
-
-
# Performs the conversion of the +file+ into a thumbnail. Returns the Tempfile
-
# that contains the new image.
-
2
def make
-
src = @file
-
filename = [@basename, @format ? ".#{@format}" : ""].join
-
dst = TempfileFactory.new.generate(filename)
-
-
begin
-
parameters = []
-
parameters << source_file_options
-
parameters << ":source"
-
parameters << transformation_command
-
parameters << convert_options
-
parameters << ":dest"
-
-
parameters = parameters.flatten.compact.join(" ").strip.squeeze(" ")
-
-
success = convert(parameters, :source => "#{File.expand_path(src.path)}#{'[0]' unless animated?}", :dest => File.expand_path(dst.path))
-
rescue Cocaine::ExitStatusError => e
-
raise Paperclip::Error, "There was an error processing the thumbnail for #{@basename}" if @whiny
-
rescue Cocaine::CommandNotFoundError => e
-
raise Paperclip::Errors::CommandNotFoundError.new("Could not run the `convert` command. Please install ImageMagick.")
-
end
-
-
dst
-
end
-
-
# Returns the command ImageMagick's +convert+ needs to transform the image
-
# into the thumbnail.
-
2
def transformation_command
-
scale, crop = @current_geometry.transformation_to(@target_geometry, crop?)
-
trans = []
-
trans << "-coalesce" if animated?
-
trans << "-auto-orient" if auto_orient
-
trans << "-resize" << %["#{scale}"] unless scale.nil? || scale.empty?
-
trans << "-crop" << %["#{crop}"] << "+repage" if crop
-
trans << '-layers "optimize"' if animated?
-
trans
-
end
-
-
2
protected
-
-
# Return true if the format is animated
-
2
def animated?
-
@animated && (ANIMATED_FORMATS.include?(@format.to_s) || @format.blank?) && identified_as_animated?
-
end
-
-
# Return true if ImageMagick's +identify+ returns an animated format
-
2
def identified_as_animated?
-
if @identified_as_animated.nil?
-
@identified_as_animated = ANIMATED_FORMATS.include? identify("-format %m :file", :file => "#{@file.path}[0]").to_s.downcase.strip
-
end
-
@identified_as_animated
-
rescue Cocaine::ExitStatusError => e
-
raise Paperclip::Error, "There was an error running `identify` for #{@basename}" if @whiny
-
rescue Cocaine::CommandNotFoundError => e
-
raise Paperclip::Errors::CommandNotFoundError.new("Could not run the `identify` command. Please install ImageMagick.")
-
end
-
end
-
end
-
2
require 'uri'
-
-
2
module Paperclip
-
2
class UrlGenerator
-
2
def initialize(attachment, attachment_options)
-
@attachment = attachment
-
@attachment_options = attachment_options
-
end
-
-
2
def for(style_name, options)
-
timestamp_as_needed(
-
escape_url_as_needed(
-
@attachment_options[:interpolator].interpolate(most_appropriate_url, @attachment, style_name),
-
options
-
), options)
-
end
-
-
2
private
-
-
# This method is all over the place.
-
2
def default_url
-
if @attachment_options[:default_url].respond_to?(:call)
-
@attachment_options[:default_url].call(@attachment)
-
elsif @attachment_options[:default_url].is_a?(Symbol)
-
@attachment.instance.send(@attachment_options[:default_url])
-
else
-
@attachment_options[:default_url]
-
end
-
end
-
-
2
def most_appropriate_url
-
if @attachment.original_filename.nil?
-
default_url
-
else
-
@attachment_options[:url]
-
end
-
end
-
-
2
def timestamp_as_needed(url, options)
-
if options[:timestamp] && timestamp_possible?
-
delimiter_char = url.match(/\?.+=/) ? '&' : '?'
-
"#{url}#{delimiter_char}#{@attachment.updated_at.to_s}"
-
else
-
url
-
end
-
end
-
-
2
def timestamp_possible?
-
@attachment.respond_to?(:updated_at) && @attachment.updated_at.present?
-
end
-
-
2
def escape_url_as_needed(url, options)
-
if options[:escape]
-
escape_url(url)
-
else
-
url
-
end
-
end
-
-
2
def escape_url(url)
-
if url.respond_to?(:escape)
-
url.escape
-
else
-
URI.escape(url).gsub(escape_regex){|m| "%#{m.ord.to_s(16).upcase}" }
-
end
-
end
-
-
2
def escape_regex
-
/[\?\(\)\[\]\+]/
-
end
-
end
-
end
-
2
require 'active_model'
-
2
require 'active_support/concern'
-
2
require 'active_support/core_ext/array/wrap'
-
2
require 'paperclip/validators/attachment_content_type_validator'
-
2
require 'paperclip/validators/attachment_file_name_validator'
-
2
require 'paperclip/validators/attachment_presence_validator'
-
2
require 'paperclip/validators/attachment_size_validator'
-
2
require 'paperclip/validators/media_type_spoof_detection_validator'
-
2
require 'paperclip/validators/attachment_file_type_ignorance_validator'
-
-
2
module Paperclip
-
2
module Validators
-
2
extend ActiveSupport::Concern
-
-
2
included do
-
2
extend HelperMethods
-
2
include HelperMethods
-
end
-
-
2
::Paperclip::REQUIRED_VALIDATORS = [AttachmentFileNameValidator, AttachmentContentTypeValidator, AttachmentFileTypeIgnoranceValidator]
-
-
2
module ClassMethods
-
# This method is a shortcut to validator classes that is in
-
# "Attachment...Validator" format. It is almost the same thing as the
-
# +validates+ method that shipped with Rails, but this is customized to
-
# be using with attachment validators. This is helpful when you're using
-
# multiple attachment validators on a single attachment.
-
#
-
# Example of using the validator:
-
#
-
# validates_attachment :avatar, :presence => true,
-
# :content_type => { :content_type => "image/jpg" },
-
# :size => { :in => 0..10.kilobytes }
-
#
-
2
def validates_attachment(*attributes)
-
options = attributes.extract_options!.dup
-
-
Paperclip::Validators.constants.each do |constant|
-
if constant.to_s =~ /\AAttachment(.+)Validator\Z/
-
validator_kind = $1.underscore.to_sym
-
-
if options.has_key?(validator_kind)
-
validator_options = options.delete(validator_kind)
-
validator_options = {} if validator_options == true
-
conditional_options = options.slice(:if, :unless)
-
Array.wrap(validator_options).each do |local_options|
-
method_name = Paperclip::Validators.const_get(constant.to_s).helper_method_name
-
send(method_name, attributes, local_options.merge(conditional_options))
-
end
-
end
-
end
-
end
-
end
-
-
2
def validate_before_processing(validator_class, options)
-
options = options.dup
-
attributes = options.delete(:attributes)
-
attributes.each do |attribute|
-
options[:attributes] = [attribute]
-
create_validating_before_filter(attribute, validator_class, options)
-
end
-
end
-
-
2
def create_validating_before_filter(attribute, validator_class, options)
-
if_clause = options.delete(:if)
-
unless_clause = options.delete(:unless)
-
send(:"before_#{attribute}_post_process", :if => if_clause, :unless => unless_clause) do |*args|
-
validator_class.new(options.dup).validate(self)
-
end
-
end
-
-
end
-
end
-
end
-
2
module Paperclip
-
2
module Validators
-
2
class AttachmentContentTypeValidator < ActiveModel::EachValidator
-
2
def initialize(options)
-
options[:allow_nil] = true unless options.has_key?(:allow_nil)
-
super
-
end
-
-
2
def self.helper_method_name
-
:validates_attachment_content_type
-
end
-
-
2
def validate_each(record, attribute, value)
-
base_attribute = attribute.to_sym
-
attribute = "#{attribute}_content_type".to_sym
-
value = record.send :read_attribute_for_validation, attribute
-
-
return if (value.nil? && options[:allow_nil]) || (value.blank? && options[:allow_blank])
-
-
validate_whitelist(record, attribute, value)
-
validate_blacklist(record, attribute, value)
-
-
if record.errors.include? attribute
-
record.errors[attribute].each do |error|
-
record.errors.add base_attribute, error
-
end
-
end
-
end
-
-
2
def validate_whitelist(record, attribute, value)
-
if allowed_types.present? && allowed_types.none? { |type| type === value }
-
mark_invalid record, attribute, allowed_types
-
end
-
end
-
-
2
def validate_blacklist(record, attribute, value)
-
if forbidden_types.present? && forbidden_types.any? { |type| type === value }
-
mark_invalid record, attribute, forbidden_types
-
end
-
end
-
-
2
def mark_invalid(record, attribute, types)
-
record.errors.add attribute, :invalid, options.merge(:types => types.join(', '))
-
end
-
-
2
def allowed_types
-
[options[:content_type]].flatten.compact
-
end
-
-
2
def forbidden_types
-
[options[:not]].flatten.compact
-
end
-
-
2
def check_validity!
-
unless options.has_key?(:content_type) || options.has_key?(:not)
-
raise ArgumentError, "You must pass in either :content_type or :not to the validator"
-
end
-
end
-
end
-
-
2
module HelperMethods
-
# Places ActiveModel validations on the content type of the file
-
# assigned. The possible options are:
-
# * +content_type+: Allowed content types. Can be a single content type
-
# or an array. Each type can be a String or a Regexp. It should be
-
# noted that Internet Explorer uploads files with content_types that you
-
# may not expect. For example, JPEG images are given image/pjpeg and
-
# PNGs are image/x-png, so keep that in mind when determining how you
-
# match. Allows all by default.
-
# * +not+: Forbidden content types.
-
# * +message+: The message to display when the uploaded file has an invalid
-
# content type.
-
# * +if+: A lambda or name of an instance method. Validation will only
-
# be run is this lambda or method returns true.
-
# * +unless+: Same as +if+ but validates if lambda or method returns false.
-
# NOTE: If you do not specify an [attachment]_content_type field on your
-
# model, content_type validation will work _ONLY upon assignment_ and
-
# re-validation after the instance has been reloaded will always succeed.
-
# You'll still need to have a virtual attribute (created by +attr_accessor+)
-
# name +[attachment]_content_type+ to be able to use this validator.
-
2
def validates_attachment_content_type(*attr_names)
-
options = _merge_attributes(attr_names)
-
validates_with AttachmentContentTypeValidator, options.dup
-
validate_before_processing AttachmentContentTypeValidator, options.dup
-
end
-
end
-
end
-
end
-
2
module Paperclip
-
2
module Validators
-
2
class AttachmentFileNameValidator < ActiveModel::EachValidator
-
2
def initialize(options)
-
options[:allow_nil] = true unless options.has_key?(:allow_nil)
-
super
-
end
-
-
2
def self.helper_method_name
-
:validates_attachment_file_name
-
end
-
-
2
def validate_each(record, attribute, value)
-
base_attribute = attribute.to_sym
-
attribute = "#{attribute}_file_name".to_sym
-
value = record.send :read_attribute_for_validation, attribute
-
-
return if (value.nil? && options[:allow_nil]) || (value.blank? && options[:allow_blank])
-
-
validate_whitelist(record, attribute, value)
-
validate_blacklist(record, attribute, value)
-
-
if record.errors.include? attribute
-
record.errors[attribute].each do |error|
-
record.errors.add base_attribute, error
-
end
-
end
-
end
-
-
2
def validate_whitelist(record, attribute, value)
-
if allowed.present? && allowed.none? { |type| type === value }
-
mark_invalid record, attribute, allowed
-
end
-
end
-
-
2
def validate_blacklist(record, attribute, value)
-
if forbidden.present? && forbidden.any? { |type| type === value }
-
mark_invalid record, attribute, forbidden
-
end
-
end
-
-
2
def mark_invalid(record, attribute, patterns)
-
record.errors.add attribute, :invalid, options.merge(:names => patterns.join(', '))
-
end
-
-
2
def allowed
-
[options[:matches]].flatten.compact
-
end
-
-
2
def forbidden
-
[options[:not]].flatten.compact
-
end
-
-
2
def check_validity!
-
unless options.has_key?(:matches) || options.has_key?(:not)
-
raise ArgumentError, "You must pass in either :matches or :not to the validator"
-
end
-
end
-
end
-
-
2
module HelperMethods
-
# Places ActiveModel validations on the name of the file
-
# assigned. The possible options are:
-
# * +matches+: Allowed filename patterns as Regexps. Can be a single one
-
# or an array.
-
# * +not+: Forbidden file name patterns, specified the same was as +matches+.
-
# * +message+: The message to display when the uploaded file has an invalid
-
# name.
-
# * +if+: A lambda or name of an instance method. Validation will only
-
# be run is this lambda or method returns true.
-
# * +unless+: Same as +if+ but validates if lambda or method returns false.
-
2
def validates_attachment_file_name(*attr_names)
-
options = _merge_attributes(attr_names)
-
validates_with AttachmentFileNameValidator, options.dup
-
validate_before_processing AttachmentFileNameValidator, options.dup
-
end
-
end
-
end
-
end
-
-
2
require 'active_model/validations/presence'
-
-
2
module Paperclip
-
2
module Validators
-
2
class AttachmentFileTypeIgnoranceValidator < ActiveModel::EachValidator
-
2
def validate_each(record, attribute, value)
-
# This doesn't do anything. It's just to mark that you don't care about
-
# the file_names or content_types of your incoming attachments.
-
end
-
-
2
def self.helper_method_name
-
:do_not_validate_attachment_file_type
-
end
-
end
-
-
2
module HelperMethods
-
# Places ActiveModel validations on the presence of a file.
-
# Options:
-
# * +if+: A lambda or name of an instance method. Validation will only
-
# be run if this lambda or method returns true.
-
# * +unless+: Same as +if+ but validates if lambda or method returns false.
-
2
def do_not_validate_attachment_file_type(*attr_names)
-
options = _merge_attributes(attr_names)
-
validates_with AttachmentFileTypeIgnoranceValidator, options.dup
-
end
-
end
-
end
-
end
-
-
2
require 'active_model/validations/presence'
-
-
2
module Paperclip
-
2
module Validators
-
2
class AttachmentPresenceValidator < ActiveModel::EachValidator
-
2
def validate_each(record, attribute, value)
-
if record.send("#{attribute}_file_name").blank?
-
record.errors.add(attribute, :blank, options)
-
end
-
end
-
-
2
def self.helper_method_name
-
:validates_attachment_presence
-
end
-
end
-
-
2
module HelperMethods
-
# Places ActiveModel validations on the presence of a file.
-
# Options:
-
# * +if+: A lambda or name of an instance method. Validation will only
-
# be run if this lambda or method returns true.
-
# * +unless+: Same as +if+ but validates if lambda or method returns false.
-
2
def validates_attachment_presence(*attr_names)
-
options = _merge_attributes(attr_names)
-
validates_with AttachmentPresenceValidator, options.dup
-
validate_before_processing AttachmentPresenceValidator, options.dup
-
end
-
end
-
end
-
end
-
2
require 'active_model/validations/numericality'
-
-
2
module Paperclip
-
2
module Validators
-
2
class AttachmentSizeValidator < ActiveModel::Validations::NumericalityValidator
-
2
AVAILABLE_CHECKS = [:less_than, :less_than_or_equal_to, :greater_than, :greater_than_or_equal_to]
-
-
2
def initialize(options)
-
extract_options(options)
-
super
-
end
-
-
2
def self.helper_method_name
-
:validates_attachment_size
-
end
-
-
2
def validate_each(record, attr_name, value)
-
base_attr_name = attr_name
-
attr_name = "#{attr_name}_file_size".to_sym
-
value = record.send(:read_attribute_for_validation, attr_name)
-
-
unless value.blank?
-
options.slice(*AVAILABLE_CHECKS).each do |option, option_value|
-
option_value = option_value.call(record) if option_value.is_a?(Proc)
-
option_value = extract_option_value(option, option_value)
-
-
unless value.send(CHECKS[option], option_value)
-
error_message_key = options[:in] ? :in_between : option
-
[ attr_name, base_attr_name ].each do |error_attr_name|
-
record.errors.add(error_attr_name, error_message_key, filtered_options(value).merge(
-
:min => min_value_in_human_size(record),
-
:max => max_value_in_human_size(record),
-
:count => human_size(option_value)
-
))
-
end
-
end
-
end
-
end
-
end
-
-
2
def check_validity!
-
unless (AVAILABLE_CHECKS + [:in]).any? { |argument| options.has_key?(argument) }
-
raise ArgumentError, "You must pass either :less_than, :greater_than, or :in to the validator"
-
end
-
end
-
-
2
private
-
-
2
def extract_options(options)
-
if range = options[:in]
-
if !options[:in].respond_to?(:call)
-
options[:less_than_or_equal_to] = range.max
-
options[:greater_than_or_equal_to] = range.min
-
else
-
options[:less_than_or_equal_to] = range
-
options[:greater_than_or_equal_to] = range
-
end
-
end
-
end
-
-
2
def extract_option_value(option, option_value)
-
if option_value.is_a?(Range)
-
if [:less_than, :less_than_or_equal_to].include?(option)
-
option_value.max
-
else
-
option_value.min
-
end
-
else
-
option_value
-
end
-
end
-
-
2
def human_size(size)
-
if defined?(ActiveSupport::NumberHelper) # Rails 4.0+
-
ActiveSupport::NumberHelper.number_to_human_size(size)
-
else
-
storage_units_format = I18n.translate(:'number.human.storage_units.format', :locale => options[:locale], :raise => true)
-
unit = I18n.translate(:'number.human.storage_units.units.byte', :locale => options[:locale], :count => size.to_i, :raise => true)
-
storage_units_format.gsub(/%n/, size.to_i.to_s).gsub(/%u/, unit).html_safe
-
end
-
end
-
-
2
def min_value_in_human_size(record)
-
value = options[:greater_than_or_equal_to] || options[:greater_than]
-
value = value.call(record) if value.respond_to?(:call)
-
value = value.min if value.respond_to?(:min)
-
human_size(value)
-
end
-
-
2
def max_value_in_human_size(record)
-
value = options[:less_than_or_equal_to] || options[:less_than]
-
value = value.call(record) if value.respond_to?(:call)
-
value = value.max if value.respond_to?(:max)
-
human_size(value)
-
end
-
end
-
-
2
module HelperMethods
-
# Places ActiveModel validations on the size of the file assigned. The
-
# possible options are:
-
# * +in+: a Range of bytes (i.e. +1..1.megabyte+),
-
# * +less_than+: equivalent to :in => 0..options[:less_than]
-
# * +greater_than+: equivalent to :in => options[:greater_than]..Infinity
-
# * +message+: error message to display, use :min and :max as replacements
-
# * +if+: A lambda or name of an instance method. Validation will only
-
# be run if this lambda or method returns true.
-
# * +unless+: Same as +if+ but validates if lambda or method returns false.
-
2
def validates_attachment_size(*attr_names)
-
options = _merge_attributes(attr_names)
-
validates_with AttachmentSizeValidator, options.dup
-
validate_before_processing AttachmentSizeValidator, options.dup
-
end
-
end
-
end
-
end
-
2
require 'active_model/validations/presence'
-
-
2
module Paperclip
-
2
module Validators
-
2
class MediaTypeSpoofDetectionValidator < ActiveModel::EachValidator
-
2
def validate_each(record, attribute, value)
-
adapter = Paperclip.io_adapters.for(value)
-
if Paperclip::MediaTypeSpoofDetector.using(adapter, value.original_filename, value.content_type).spoofed?
-
record.errors.add(attribute, :spoofed_media_type)
-
end
-
end
-
end
-
-
2
module HelperMethods
-
# Places ActiveModel validations on the presence of a file.
-
# Options:
-
# * +if+: A lambda or name of an instance method. Validation will only
-
# be run if this lambda or method returns true.
-
# * +unless+: Same as +if+ but validates if lambda or method returns false.
-
2
def validates_media_type_spoof_detection(*attr_names)
-
options = _merge_attributes(attr_names)
-
validates_with MediaTypeSpoofDetectionValidator, options.dup
-
validate_before_processing MediaTypeSpoofDetectionValidator, options.dup
-
end
-
end
-
end
-
end
-
2
module Paperclip
-
2
VERSION = "4.3.6" unless defined? Paperclip::VERSION
-
end
-
2
require 'active_support'
-
2
require 'action_view'
-
# +public_activity+ keeps track of changes made to models
-
# and allows you to display them to the users.
-
#
-
# Check {PublicActivity::Tracked::ClassMethods#tracked} for more details about customizing and specifying
-
# ownership to users.
-
2
module PublicActivity
-
2
extend ActiveSupport::Concern
-
2
extend ActiveSupport::Autoload
-
-
2
autoload :Activity, 'public_activity/models/activity'
-
2
autoload :Activist, 'public_activity/models/activist'
-
2
autoload :Adapter, 'public_activity/models/adapter'
-
2
autoload :Trackable, 'public_activity/models/trackable'
-
2
autoload :Common
-
2
autoload :Config
-
2
autoload :Creation, 'public_activity/actions/creation.rb'
-
2
autoload :Deactivatable,'public_activity/roles/deactivatable.rb'
-
2
autoload :Destruction, 'public_activity/actions/destruction.rb'
-
2
autoload :Renderable
-
2
autoload :Tracked, 'public_activity/roles/tracked.rb'
-
2
autoload :Update, 'public_activity/actions/update.rb'
-
2
autoload :VERSION
-
-
# Switches PublicActivity on or off.
-
# @param value [Boolean]
-
# @since 0.5.0
-
2
def self.enabled=(value)
-
PublicActivity.config.enabled = value
-
end
-
-
# Returns `true` if PublicActivity is on, `false` otherwise.
-
# Enabled by default.
-
# @return [Boolean]
-
# @since 0.5.0
-
2
def self.enabled?
-
72
!!PublicActivity.config.enabled
-
end
-
-
# Returns PublicActivity's configuration object.
-
# @since 0.5.0
-
2
def self.config
-
82
@@config ||= PublicActivity::Config.instance
-
end
-
-
# Method used to choose which ORM to load
-
# when PublicActivity::Activity class is being autoloaded
-
2
def self.inherit_orm(model="Activity")
-
8
orm = PublicActivity.config.orm
-
8
require "public_activity/orm/#{orm.to_s}"
-
8
"PublicActivity::ORM::#{orm.to_s.classify}::#{model}".constantize
-
end
-
-
# Module to be included in ActiveRecord models. Adds required functionality.
-
2
module Model
-
2
extend ActiveSupport::Concern
-
2
included do
-
3
include Common
-
3
include Deactivatable
-
3
include Tracked
-
3
include Activist # optional associations by recipient|owner
-
end
-
end
-
end
-
-
2
require 'public_activity/utility/store_controller'
-
2
require 'public_activity/utility/view_helpers'
-
2
module PublicActivity
-
# Handles creation of Activities upon destruction and update of tracked model.
-
2
module Creation
-
2
extend ActiveSupport::Concern
-
-
2
included do
-
3
after_create :activity_on_create
-
end
-
-
2
private
-
-
# Creates activity upon creation of the tracked model
-
2
def activity_on_create
-
72
create_activity(:create)
-
end
-
end
-
end
-
2
module PublicActivity
-
# Handles creation of Activities upon destruction of tracked model.
-
2
module Destruction
-
2
extend ActiveSupport::Concern
-
-
2
included do
-
3
before_destroy :activity_on_destroy
-
end
-
-
2
private
-
-
# Records an activity upon destruction of the tracked model
-
2
def activity_on_destroy
-
create_activity(:destroy)
-
end
-
end
-
end
-
2
module PublicActivity
-
# Handles creation of Activities upon destruction and update of tracked model.
-
2
module Update
-
2
extend ActiveSupport::Concern
-
-
2
included do
-
3
after_update :activity_on_update
-
end
-
-
2
private
-
-
# Creates activity upon modification of the tracked model
-
2
def activity_on_update
-
create_activity(:update)
-
end
-
end
-
end
-
2
module PublicActivity
-
# Happens when creating custom activities without either action or a key.
-
2
class NoKeyProvided < Exception; end
-
-
# Used to smartly transform value from metadata to data.
-
# Accepts Symbols, which it will send against context.
-
# Accepts Procs, which it will execute with controller and context.
-
# @since 0.4.0
-
2
def self.resolve_value(context, thing)
-
144
case thing
-
when Symbol
-
context.__send__(thing)
-
when Proc
-
72
thing.call(PublicActivity.get_controller, context)
-
else
-
72
thing
-
end
-
end
-
-
# Common methods shared across the gem.
-
2
module Common
-
2
extend ActiveSupport::Concern
-
-
2
included do
-
3
include Trackable
-
3
class_attribute :activity_owner_global, :activity_recipient_global,
-
:activity_params_global, :activity_hooks, :activity_custom_fields_global
-
3
set_public_activity_class_defaults
-
end
-
-
# @!group Global options
-
-
# @!attribute activity_owner_global
-
# Global version of activity owner
-
# @see #activity_owner
-
# @return [Model]
-
-
# @!attribute activity_recipient_global
-
# Global version of activity recipient
-
# @see #activity_recipient
-
# @return [Model]
-
-
# @!attribute activity_params_global
-
# Global version of activity parameters
-
# @see #activity_params
-
# @return [Hash<Symbol, Object>]
-
-
# @!attribute activity_hooks
-
# @return [Hash<Symbol, Proc>]
-
# Hooks/functions that will be used to decide *if* the activity should get
-
# created.
-
#
-
# The supported keys are:
-
# * :create
-
# * :update
-
# * :destroy
-
-
# @!endgroup
-
-
# @!group Instance options
-
-
# Set or get parameters that will be passed to {Activity} when saving
-
#
-
# == Usage:
-
#
-
# @article.activity_params = {:article_title => @article.title}
-
# @article.save
-
#
-
# This way you can pass strings that should remain constant, even when model attributes
-
# change after creating this {Activity}.
-
# @return [Hash<Symbol, Object>]
-
2
attr_accessor :activity_params
-
2
@activity_params = {}
-
# Set or get owner object responsible for the {Activity}.
-
#
-
# == Usage:
-
#
-
# # where current_user is an object of logged in user
-
# @article.activity_owner = current_user
-
# # OR: take @article.author association
-
# @article.activity_owner = :author
-
# # OR: provide a Proc with custom code
-
# @article.activity_owner = proc {|controller, model| model.author }
-
# @article.save
-
# @article.activities.last.owner #=> Returns owner object
-
# @return [Model] Polymorphic model
-
# @see #activity_owner_global
-
2
attr_accessor :activity_owner
-
2
@activity_owner = nil
-
-
# Set or get recipient for activity.
-
#
-
# Association is polymorphic, thus allowing assignment of
-
# all types of models. This can be used for example in the case of sending
-
# private notifications for only a single user.
-
# @return (see #activity_owner)
-
2
attr_accessor :activity_recipient
-
2
@activity_recipient = nil
-
# Set or get custom i18n key passed to {Activity}, later used in {Renderable#text}
-
#
-
# == Usage:
-
#
-
# @article = Article.new
-
# @article.activity_key = "my.custom.article.key"
-
# @article.save
-
# @article.activities.last.key #=> "my.custom.article.key"
-
#
-
# @return [String]
-
2
attr_accessor :activity_key
-
2
@activity_key = nil
-
-
# Set or get custom fields for later processing
-
#
-
# @return [Hash]
-
2
attr_accessor :activity_custom_fields
-
2
@activity_custom_fields = {}
-
-
# @!visibility private
-
2
@@activity_hooks = {}
-
-
# @!endgroup
-
-
# Provides some global methods for every model class.
-
2
module ClassMethods
-
#
-
# @since 1.0.0
-
# @api private
-
2
def set_public_activity_class_defaults
-
6
self.activity_owner_global = nil
-
6
self.activity_recipient_global = nil
-
6
self.activity_params_global = {}
-
6
self.activity_hooks = {}
-
6
self.activity_custom_fields_global = {}
-
end
-
-
# Extracts a hook from the _:on_ option provided in
-
# {Tracked::ClassMethods#tracked}. Returns nil when no hook exists for
-
# given action
-
# {Common#get_hook}
-
#
-
# @see Tracked#get_hook
-
# @param key [String, Symbol] action to retrieve a hook for
-
# @return [Proc, nil] callable hook or nil
-
# @since 0.4.0
-
# @api private
-
2
def get_hook(key)
-
72
key = key.to_sym
-
72
if self.activity_hooks.has_key?(key) and self.activity_hooks[key].is_a? Proc
-
self.activity_hooks[key]
-
else
-
nil
-
end
-
end
-
end
-
#
-
# Returns true if PublicActivity is enabled
-
# globally and for this class.
-
# @return [Boolean]
-
# @api private
-
# @since 0.5.0
-
2
def public_activity_enabled?
-
PublicActivity.enabled?
-
end
-
#
-
# Shortcut for {ClassMethods#get_hook}
-
# @param (see ClassMethods#get_hook)
-
# @return (see ClassMethods#get_hook)
-
# @since (see ClassMethods#get_hook)
-
# @api (see ClassMethods#get_hook)
-
2
def get_hook(key)
-
72
self.class.get_hook(key)
-
end
-
-
# Calls hook safely.
-
# If a hook for given action exists, calls it with model (self) and
-
# controller (if available, see {StoreController})
-
# @param key (see #get_hook)
-
# @return [Boolean] if hook exists, it's decision, if there's no hook, true
-
# @since 0.4.0
-
# @api private
-
2
def call_hook_safe(key)
-
72
hook = self.get_hook(key)
-
72
if hook
-
# provides hook with model and controller
-
hook.call(self, PublicActivity.get_controller)
-
else
-
72
true
-
end
-
end
-
-
# Directly creates activity record in the database, based on supplied options.
-
#
-
# It's meant for creating custom activities while *preserving* *all*
-
# *configuration* defined before. If you fire up the simplest of options:
-
#
-
# current_user.create_activity(:avatar_changed)
-
#
-
# It will still gather data from any procs or symbols you passed as params
-
# to {Tracked::ClassMethods#tracked}. It will ask the hooks you defined
-
# whether to really save this activity.
-
#
-
# But you can also overwrite instance and global settings with your options:
-
#
-
# @article.activity :owner => proc {|controller| controller.current_user }
-
# @article.create_activity(:commented_on, :owner => @user)
-
#
-
# And it's smart! It won't execute your proc, since you've chosen to
-
# overwrite instance parameter _:owner_ with @user.
-
#
-
# [:key]
-
# The key will be generated from either:
-
# * the first parameter you pass that is not a hash (*action*)
-
# * the _:action_ option in the options hash (*action*)
-
# * the _:key_ option in the options hash (it has to be a full key,
-
# including model name)
-
# When you pass an *action* (first two options above), they will be
-
# added to parameterized model name:
-
#
-
# Given Article model and instance: @article,
-
#
-
# @article.create_activity :commented_on
-
# @article.activities.last.key # => "article.commented_on"
-
#
-
# For other parameters, see {Tracked#activity}, and "Instance options"
-
# accessors at {Tracked}, information on hooks is available at
-
# {Tracked::ClassMethods#tracked}.
-
# @see #prepare_settings
-
# @return [Model, nil] If created successfully, new activity
-
# @since 0.4.0
-
# @api public
-
# @overload create_activity(action, options = {})
-
# @param [Symbol,String] action Name of the action
-
# @param [Hash] options Options with quality higher than instance options
-
# set in {Tracked#activity}
-
# @option options [Activist] :owner Owner
-
# @option options [Activist] :recipient Recipient
-
# @option options [Hash] :params Parameters, see
-
# {PublicActivity.resolve_value}
-
# @overload create_activity(options = {})
-
# @param [Hash] options Options with quality higher than instance options
-
# set in {Tracked#activity}
-
# @option options [Symbol,String] :action Name of the action
-
# @option options [String] :key Full key
-
# @option options [Activist] :owner Owner
-
# @option options [Activist] :recipient Recipient
-
# @option options [Hash] :params Parameters, see
-
# {PublicActivity.resolve_value}
-
2
def create_activity(*args)
-
72
return unless self.public_activity_enabled?
-
72
options = prepare_settings(*args)
-
-
72
if call_hook_safe(options[:key].split('.').last)
-
72
reset_activity_instance_options
-
72
return PublicActivity::Adapter.create_activity(self, options)
-
end
-
-
nil
-
end
-
-
# Prepares settings used during creation of Activity record.
-
# params passed directly to tracked model have priority over
-
# settings specified in tracked() method
-
#
-
# @see #create_activity
-
# @return [Hash] Settings with preserved options that were passed
-
# @api private
-
# @overload prepare_settings(action, options = {})
-
# @see #create_activity
-
# @overload prepare_settings(options = {})
-
# @see #create_activity
-
2
def prepare_settings(*args)
-
72
raw_options = args.extract_options!
-
72
action = [args.first, raw_options.delete(:action)].compact.first
-
72
key = prepare_key(action, raw_options)
-
-
72
raise NoKeyProvided, "No key provided for #{self.class.name}" unless key
-
-
72
prepare_custom_fields(raw_options.except(:params)).merge(
-
{
-
key: key,
-
owner: prepare_relation(:owner, raw_options),
-
recipient: prepare_relation(:recipient, raw_options),
-
parameters: prepare_parameters(raw_options),
-
}
-
)
-
end
-
-
# Prepares and resolves custom fields
-
# users can pass to `tracked` method
-
# @private
-
2
def prepare_custom_fields(options)
-
72
customs = self.class.activity_custom_fields_global.clone
-
72
customs.merge!(self.activity_custom_fields) if self.activity_custom_fields
-
72
customs.merge!(options)
-
72
customs.each do |k, v|
-
customs[k] = PublicActivity.resolve_value(self, v)
-
end
-
end
-
-
# Prepares i18n parameters that will
-
# be serialized into the Activity#parameters column
-
# @private
-
2
def prepare_parameters(options)
-
72
params = {}
-
72
params.merge!(self.class.activity_params_global)
-
72
params.merge!(self.activity_params) if self.activity_params
-
72
params.merge!([options.delete(:parameters), options.delete(:params), {}].compact.first)
-
72
params.each { |k, v| params[k] = PublicActivity.resolve_value(self, v) }
-
end
-
-
# Prepares relation to be saved
-
# to Activity. Can be :recipient or :owner
-
# @private
-
2
def prepare_relation(name, options)
-
144
PublicActivity.resolve_value(self,
-
144
(options.has_key?(name) ? options[name] : (
-
144
self.send("activity_#{name}") || self.class.send("activity_#{name}_global")
-
)
-
)
-
)
-
end
-
-
# Helper method to serialize class name into relevant key
-
# @return [String] the resulted key
-
# @param [Symbol] or [String] the name of the operation to be done on class
-
# @param [Hash] options to be used on key generation, defaults to {}
-
2
def prepare_key(action, options = {})
-
(
-
options[:key] ||
-
72
self.activity_key ||
-
72
((self.class.name.underscore.gsub('/', '_') + "." + action.to_s) if action)
-
72
).try(:to_s)
-
end
-
-
# Resets all instance options on the object
-
# triggered by a successful #create_activity, should not be
-
# called from any other place, or from application code.
-
# @private
-
2
def reset_activity_instance_options
-
72
@activity_params = {}
-
72
@activity_key = nil
-
72
@activity_owner = nil
-
72
@activity_recipient = nil
-
72
@activity_custom_fields = {}
-
end
-
end
-
end
-
2
require 'singleton'
-
-
2
module PublicActivity
-
# Class used to initialize configuration object.
-
2
class Config
-
2
include ::Singleton
-
2
attr_accessor :enabled, :table_name
-
-
2
@@orm = :active_record
-
-
2
def initialize
-
# Indicates whether PublicActivity is enabled globally
-
2
@enabled = true
-
2
@table_name = "activities"
-
end
-
-
# Evaluates given block to provide DSL configuration.
-
# @example Initializer for Rails
-
# PublicActivity::Config.set do
-
# orm :mongo_mapper
-
# enabled false
-
# table_name "activities"
-
# end
-
2
def self.set &block
-
b = Block.new
-
b.instance_eval &block
-
@@orm = b.orm unless b.orm.nil?
-
instance
-
instance.instance_variable_set(:@enabled, b.enabled) unless b.enabled.nil?
-
end
-
-
# Set the ORM for use by PublicActivity.
-
2
def self.orm(orm = nil)
-
8
@@orm = (orm ? orm.to_sym : false) || @@orm
-
end
-
-
# alias for {#orm}
-
# @see #orm
-
2
def self.orm=(orm = nil)
-
orm(orm)
-
end
-
-
# instance version of {Config#orm}
-
# @see Config#orm
-
2
def orm(orm=nil)
-
8
self.class.orm(orm)
-
end
-
-
# Provides simple DSL for the config block.
-
2
class Block
-
2
attr_reader :orm, :enabled, :table_name
-
# @see Config#orm
-
2
def orm(orm = nil)
-
@orm = (orm ? orm.to_sym : false) || @orm
-
end
-
-
# Decides whether to enable PublicActivity.
-
# @param en [Boolean] Enabled?
-
2
def enabled(en = nil)
-
@enabled = (en.nil? ? @enabled : en)
-
end
-
-
# Sets the table_name
-
# for the model
-
2
def table_name(name = nil)
-
PublicActivity.config.table_name = name
-
end
-
end
-
end
-
end
-
2
module PublicActivity
-
# Provides helper methods for selecting activities from a user.
-
2
module Activist
-
# Delegates to configured ORM.
-
2
def self.included(base)
-
3
base.extend PublicActivity::inherit_orm("Activist")
-
end
-
end
-
end
-
1
module PublicActivity
-
1
class Activity < inherit_orm("Activity")
-
end
-
end
-
1
module PublicActivity
-
# Loads database-specific routines for use by PublicActivity.
-
1
class Adapter < inherit_orm("Adapter")
-
end
-
end
-
2
module PublicActivity
-
# Provides association for activities bound to this object by *trackable*.
-
2
module Trackable
-
# Delegates to ORM.
-
2
def self.included(base)
-
3
base.extend PublicActivity::inherit_orm("Trackable")
-
end
-
end
-
end
-
2
require 'active_record'
-
2
require_relative 'active_record/activity.rb'
-
2
require_relative 'active_record/adapter.rb'
-
2
require_relative 'active_record/activist.rb'
-
2
require_relative 'active_record/trackable.rb'
-
2
module PublicActivity
-
2
module ORM
-
2
module ActiveRecord
-
# Module extending classes that serve as owners
-
2
module Activist
-
# Adds ActiveRecord associations to model to simplify fetching
-
# so you can list activities performed by the owner.
-
# It is completely optional. Any model can be an owner to an activity
-
# even without being an explicit activist.
-
#
-
# == Usage:
-
# In model:
-
#
-
# class User < ActiveRecord::Base
-
# include PublicActivity::Model
-
# activist
-
# end
-
#
-
# In controller:
-
# User.first.activities
-
#
-
2
def activist
-
has_many :activities_as_owner,
-
:class_name => "::PublicActivity::Activity",
-
:as => :owner
-
has_many :activities_as_recipient,
-
:class_name => "::PublicActivity::Activity",
-
:as => :recipient
-
end
-
end
-
end
-
end
-
end
-
2
module PublicActivity
-
2
module ORM
-
2
module ActiveRecord
-
# The ActiveRecord model containing
-
# details about recorded activity.
-
2
class Activity < ::ActiveRecord::Base
-
2
include Renderable
-
2
self.table_name = PublicActivity.config.table_name
-
-
# Define polymorphic association to the parent
-
2
belongs_to :trackable, :polymorphic => true
-
2
with_options(::ActiveRecord::VERSION::MAJOR >= 5 ? { :required => false } : { }) do
-
# Define ownership to a resource responsible for this activity
-
2
belongs_to :owner, :polymorphic => true
-
# Define ownership to a resource targeted by this activity
-
2
belongs_to :recipient, :polymorphic => true
-
end
-
# Serialize parameters Hash
-
2
serialize :parameters, Hash
-
-
2
if ::ActiveRecord::VERSION::MAJOR < 4 || defined?(ProtectedAttributes)
-
attr_accessible :key, :owner, :parameters, :recipient, :trackable
-
end
-
end
-
end
-
end
-
end
-
2
module PublicActivity
-
2
module ORM
-
# Support for ActiveRecord for PublicActivity. Used by default and supported
-
# officialy.
-
2
module ActiveRecord
-
# Provides ActiveRecord specific, database-related routines for use by
-
# PublicActivity.
-
2
class Adapter
-
# Creates the activity on `trackable` with `options`
-
2
def self.create_activity(trackable, options)
-
72
trackable.activities.create options
-
end
-
end
-
end
-
end
-
end
-
2
module PublicActivity
-
2
module ORM
-
2
module ActiveRecord
-
# Implements {PublicActivity::Trackable} for ActiveRecord
-
# @see PublicActivity::Trackable
-
2
module Trackable
-
# Creates an association for activities where self is the *trackable*
-
# object.
-
2
def self.extended(base)
-
3
base.has_many :activities, :class_name => "::PublicActivity::Activity", :as => :trackable
-
end
-
end
-
end
-
end
-
end
-
2
module PublicActivity
-
# Provides logic for rendering activities. Handles both i18n strings
-
# support and smart partials rendering (different templates per activity key).
-
2
module Renderable
-
# Virtual attribute returning text description of the activity
-
# using the activity's key to translate using i18n.
-
2
def text(params = {})
-
# TODO: some helper for key transformation for two supported formats
-
k = key.split('.')
-
k.unshift('activity') if k.first != 'activity'
-
k = k.join('.')
-
-
I18n.t(k, parameters.merge(params) || {})
-
end
-
-
# Renders activity from views.
-
#
-
# @param [ActionView::Base] context
-
# @return [nil] nil
-
#
-
# Renders activity to the given ActionView context with included
-
# AV::Helpers::RenderingHelper (most commonly just ActionView::Base)
-
#
-
# The *preferred* *way* of rendering activities is
-
# to provide a template specifying how the rendering should be happening.
-
# However, one may choose using _I18n_ based approach when developing
-
# an application that supports plenty of languages.
-
#
-
# If partial view exists that matches the *key* attribute
-
# renders that partial with local variables set to contain both
-
# Activity and activity_parameters (hash with indifferent access)
-
#
-
# Otherwise, it outputs the I18n translation to the context
-
# @example Render a list of all activities from a view (erb)
-
# <ul>
-
# <% for activity in PublicActivity::Activity.all %>
-
# <li><%= render_activity(activity) %></li>
-
# <% end %>
-
# </ul>
-
#
-
# = Layouts
-
# You can supply a layout that will be used for activity partials
-
# with :layout param.
-
# Keep in mind that layouts for partials are also partials.
-
# @example Supply a layout
-
# # in views:
-
# # All examples look for a layout in app/views/layouts/_activity.erb
-
# render_activity @activity, :layout => "activity"
-
# render_activity @activity, :layout => "layouts/activity"
-
# render_activity @activity, :layout => :activity
-
#
-
# # app/views/layouts/_activity.erb
-
# <p><%= a.created_at %></p>
-
# <%= yield %>
-
#
-
# == Custom Layout Location
-
# You can customize the layout directory by supplying :layout_root
-
# or by using an absolute path.
-
#
-
# @example Declare custom layout location
-
#
-
# # Both examples look for a layout in "app/views/custom/_layout.erb"
-
#
-
# render_activity @activity, :layout_root => "custom"
-
# render_activity @activity, :layout => "/custom/layout"
-
#
-
# = Creating a template
-
# To use templates for formatting how the activity should render,
-
# create a template based on activity key, for example:
-
#
-
# Given a key _activity.article.create_, create directory tree
-
# _app/views/public_activity/article/_ and create the _create_ partial there
-
#
-
# Note that if a key consists of more than three parts splitted by commas, your
-
# directory structure will have to be deeper, for example:
-
# activity.article.comments.destroy => app/views/public_activity/articles/comments/_destroy.html.erb
-
#
-
# == Custom Directory
-
# You can override the default `public_directory` template root with the :root parameter
-
#
-
# @example Custom template root
-
# # look for templates inside of /app/views/custom instead of /app/views/public_directory
-
# render_activity @activity, :root => "custom"
-
#
-
# == Variables in templates
-
# From within a template there are two variables at your disposal:
-
# * activity (aliased as *a* for a shortcut)
-
# * params (aliased as *p*) [converted into a HashWithIndifferentAccess]
-
#
-
# @example Template for key: _activity.article.create_ (erb)
-
# <p>
-
# Article <strong><%= p[:name] %></strong>
-
# was written by <em><%= p["author"] %></em>
-
# <%= distance_of_time_in_words_to_now(a.created_at) %>
-
# </p>
-
2
def render(context, params = {})
-
partial_root = params.delete(:root) || 'public_activity'
-
partial_path = nil
-
layout_root = params.delete(:layout_root) || 'layouts'
-
-
if params.has_key? :display
-
if params[:display].to_sym == :"i18n"
-
return context.render :text => self.text(params)
-
else
-
partial_path = File.join(partial_root, params[:display].to_s)
-
end
-
end
-
-
context.render(
-
params.merge({
-
:partial => prepare_partial(partial_root, partial_path),
-
:layout => prepare_layout(layout_root, params.delete(:layout)),
-
:locals => prepare_locals(params)
-
})
-
)
-
end
-
-
2
def prepare_partial(root, path)
-
path || self.template_path(self.key, root)
-
end
-
-
2
def prepare_locals(params)
-
locals = params.delete(:locals) || Hash.new
-
-
controller = PublicActivity.get_controller
-
prepared_params = prepare_parameters(params)
-
locals.merge(
-
{
-
:a => self,
-
:activity => self,
-
:controller => controller,
-
:current_user => controller.respond_to?(:current_user) ? controller.current_user : nil,
-
:p => prepared_params,
-
:params => prepared_params
-
}
-
)
-
end
-
-
2
def prepare_layout(root, layout)
-
if layout
-
path = layout.to_s
-
unless path.starts_with?(root) || path.starts_with?("/")
-
return File.join(root, path)
-
end
-
end
-
layout
-
end
-
-
2
def prepare_parameters(params)
-
@prepared_params ||= self.parameters.with_indifferent_access.merge(params)
-
end
-
-
2
protected
-
-
# Builds the path to template based on activity key
-
2
def template_path(key, partial_root)
-
path = key.split(".")
-
path.delete_at(0) if path[0] == "activity"
-
path.unshift partial_root
-
path.join("/")
-
end
-
end
-
end
-
2
module PublicActivity
-
# Enables per-class disabling of PublicActivity functionality.
-
2
module Deactivatable
-
2
extend ActiveSupport::Concern
-
-
2
included do
-
3
class_attribute :public_activity_enabled_for_model
-
3
set_public_activity_class_defaults
-
end
-
-
# Returns true if PublicActivity is enabled
-
# globally and for this class.
-
# @return [Boolean]
-
# @api private
-
# @since 0.5.0
-
# overrides the method from Common
-
2
def public_activity_enabled?
-
72
PublicActivity.enabled? && self.class.public_activity_enabled_for_model
-
end
-
-
# Provides global methods to disable or enable PublicActivity on a per-class
-
# basis.
-
2
module ClassMethods
-
# Switches public_activity off for this class
-
2
def public_activity_off
-
self.public_activity_enabled_for_model = false
-
end
-
-
# Switches public_activity on for this class
-
2
def public_activity_on
-
self.public_activity_enabled_for_model = true
-
end
-
-
# @since 1.0.0
-
# @api private
-
2
def set_public_activity_class_defaults
-
3
super
-
3
self.public_activity_enabled_for_model = true
-
end
-
end
-
end
-
end
-
2
module PublicActivity
-
# Main module extending classes we want to keep track of.
-
2
module Tracked
-
2
extend ActiveSupport::Concern
-
# A shortcut method for setting custom key, owner and parameters of {Activity}
-
# in one line. Accepts a hash with 3 keys:
-
# :key, :owner, :params. You can specify all of them or just the ones you want to overwrite.
-
#
-
# == Options
-
#
-
# [:key]
-
# See {Common#activity_key}
-
# [:owner]
-
# See {Common#activity_owner}
-
# [:params]
-
# See {Common#activity_params}
-
# [:recipient]
-
# Set the recipient for this activity. Useful for private notifications, which should only be visible to a certain user. See {Common#activity_recipient}.
-
# @example
-
#
-
# @article = Article.new
-
# @article.title = "New article"
-
# @article.activity :key => "my.custom.article.key", :owner => @article.author, :params => {:title => @article.title}
-
# @article.save
-
# @article.activities.last.key #=> "my.custom.article.key"
-
# @article.activities.last.parameters #=> {:title => "New article"}
-
#
-
# @param options [Hash] instance options to set on the tracked model
-
# @return [nil]
-
2
def activity(options = {})
-
rest = options.clone
-
self.activity_key = rest.delete(:key) if rest[:key]
-
self.activity_owner = rest.delete(:owner) if rest[:owner]
-
self.activity_params = rest.delete(:params) if rest[:params]
-
self.activity_recipient = rest.delete(:recipient) if rest[:recipient]
-
self.activity_custom_fields = rest if rest.count > 0
-
nil
-
end
-
-
# Module with basic +tracked+ method that enables tracking models.
-
2
module ClassMethods
-
# Adds required callbacks for creating and updating
-
# tracked models and adds +activities+ relation for listing
-
# associated activities.
-
#
-
# == Parameters:
-
# [:owner]
-
# Specify the owner of the {Activity} (person responsible for the action).
-
# It can be a Proc, Symbol or an ActiveRecord object:
-
# == Examples:
-
#
-
# tracked :owner => :author
-
# tracked :owner => proc {|o| o.author}
-
#
-
# Keep in mind that owner relation is polymorphic, so you can't just
-
# provide id number of the owner object.
-
# [:recipient]
-
# Specify the recipient of the {Activity}
-
# It can be a Proc, Symbol, or an ActiveRecord object
-
# == Examples:
-
#
-
# tracked :recipient => :author
-
# tracked :recipient => proc {|o| o.author}
-
#
-
# Keep in mind that recipient relation is polymorphic, so you can't just
-
# provide id number of the owner object.
-
# [:params]
-
# Accepts a Hash with custom parameters you want to pass to i18n.translate
-
# method. It is later used in {Renderable#text} method.
-
# == Example:
-
# class Article < ActiveRecord::Base
-
# include PublicActivity::Model
-
# tracked :params => {
-
# :title => :title,
-
# :author_name => "Michael",
-
# :category_name => proc {|controller, model_instance| model_instance.category.name},
-
# :summary => proc {|controller, model_instance| truncate(model.text, :length => 30)}
-
# }
-
# end
-
#
-
# Values in the :params hash can either be an *exact* *value*, a *Proc/Lambda* executed before saving the activity or a *Symbol*
-
# which is a an attribute or a method name executed on the tracked model's instance.
-
#
-
# Everything specified here has a lower priority than parameters
-
# specified directly in {#activity} method.
-
# So treat it as a place where you provide 'default' values or where you
-
# specify what data should be gathered for every activity.
-
# For more dynamic settings refer to {Activity} model documentation.
-
# [:skip_defaults]
-
# Disables recording of activities on create/update/destroy leaving that to programmer's choice. Check {PublicActivity::Common#create_activity}
-
# for a guide on how to manually record activities.
-
# [:only]
-
# Accepts a symbol or an array of symbols, of which any combination of the three is accepted:
-
# * _:create_
-
# * _:update_
-
# * _:destroy_
-
# Selecting one or more of these will make PublicActivity create activities
-
# automatically for the tracked model on selected actions.
-
#
-
# Resulting activities will have have keys assigned to, respectively:
-
# * _article.create_
-
# * _article.update_
-
# * _article.destroy_
-
# Since only three options are valid,
-
# see _:except_ option for a shorter version
-
# [:except]
-
# Accepts a symbol or an array of symbols with values like in _:only_, above.
-
# Values provided will be subtracted from all default actions:
-
# (create, update, destroy).
-
#
-
# So, passing _create_ would track and automatically create
-
# activities on _update_ and _destroy_ actions,
-
# but not on the _create_ action.
-
# [:on]
-
# Accepts a Hash with key being the *action* on which to execute *value* (proc)
-
# Currently supported only for CRUD actions which are enabled in _:only_
-
# or _:except_ options on this method.
-
#
-
# Key-value pairs in this option define callbacks that can decide
-
# whether to create an activity or not. Procs have two attributes for
-
# use: _model_ and _controller_. If the proc returns true, the activity
-
# will be created, if not, then activity will not be saved.
-
#
-
# == Example:
-
# # app/models/article.rb
-
# tracked :on => {:update => proc {|model, controller| model.published? }}
-
#
-
# In the example above, given a model Article with boolean column _published_.
-
# The activities with key _article.update_ will only be created
-
# if the published status is set to true on that article.
-
# @param opts [Hash] options
-
# @return [nil] options
-
2
def tracked(opts = {})
-
3
options = opts.clone
-
-
3
include_default_actions(options)
-
-
3
assign_globals options
-
3
assign_hooks options
-
3
assign_custom_fields options
-
-
nil
-
end
-
-
2
def include_default_actions(options)
-
3
defaults = {
-
create: Creation,
-
destroy: Destruction,
-
update: Update
-
}
-
-
3
if options[:skip_defaults] == true
-
return
-
end
-
-
3
modules = if options[:except]
-
defaults.except(*options[:except])
-
elsif options[:only]
-
defaults.slice(*options[:only])
-
else
-
3
defaults
-
end
-
-
3
modules.each do |key, value|
-
9
include value
-
end
-
end
-
-
2
def available_options
-
3
[:skip_defaults, :only, :except, :on, :owner, :recipient, :params].freeze
-
end
-
-
2
def assign_globals(options)
-
3
[:owner, :recipient, :params].each do |key|
-
9
if options[key]
-
3
self.send("activity_#{key}_global=".to_sym, options.delete(key))
-
end
-
end
-
end
-
-
2
def assign_hooks(options)
-
3
if options[:on].is_a?(Hash)
-
self.activity_hooks = options[:on].select {|_, v| v.is_a? Proc}.symbolize_keys
-
end
-
end
-
-
2
def assign_custom_fields(options)
-
3
options.except(*available_options).each do |k, v|
-
self.activity_custom_fields_global[k] = v
-
end
-
end
-
end
-
end
-
end
-
2
module PublicActivity
-
2
class << self
-
# Setter for remembering controller instance
-
2
def set_controller(controller)
-
48
Thread.current[:public_activity_controller] = controller
-
end
-
-
# Getter for accessing the controller instance
-
2
def get_controller
-
72
Thread.current[:public_activity_controller]
-
end
-
end
-
-
# Module included in controllers to allow p_a access to controller instance
-
2
module StoreController
-
2
extend ActiveSupport::Concern
-
-
2
included do
-
2
around_action :store_controller_for_public_activity if respond_to?(:around_action)
-
2
around_filter :store_controller_for_public_activity unless respond_to?(:around_action)
-
end
-
-
2
def store_controller_for_public_activity
-
24
PublicActivity.set_controller(self)
-
24
yield
-
ensure
-
24
PublicActivity.set_controller(nil)
-
end
-
end
-
end
-
# Provides a shortcut from views to the rendering method.
-
2
module PublicActivity
-
# Module extending ActionView::Base and adding `render_activity` helper.
-
2
module ViewHelpers
-
# View helper for rendering an activity, calls {PublicActivity::Activity#render} internally.
-
2
def render_activity activities, options = {}
-
if activities.is_a? PublicActivity::Activity
-
activities.render self, options
-
elsif activities.respond_to?(:map)
-
# depend on ORMs to fetch as needed
-
# maybe we can support Postgres streaming with this?
-
activities.map {|activity| activity.render self, options.dup }.join.html_safe
-
end
-
end
-
2
alias_method :render_activities, :render_activity
-
-
# Helper for setting content_for in activity partial, needed to
-
# flush remains in between partial renders.
-
2
def single_content_for(name, content = nil, &block)
-
@view_flow.set(name, ActiveSupport::SafeBuffer.new)
-
content_for(name, content, &block)
-
end
-
end
-
-
4
ActionView::Base.class_eval { include ViewHelpers }
-
end
-
# Copyright (C) 2007, 2008, 2009, 2010 Christian Neukirchen <purl.org/net/chneukirchen>
-
#
-
# Rack is freely distributable under the terms of an MIT-style license.
-
# See COPYING or http://www.opensource.org/licenses/mit-license.php.
-
-
# The Rack main module, serving as a namespace for all core Rack
-
# modules and classes.
-
#
-
# All modules meant for use in your application are <tt>autoload</tt>ed here,
-
# so it should be enough just to <tt>require rack.rb</tt> in your code.
-
-
2
module Rack
-
# The Rack protocol version number implemented.
-
2
VERSION = [1,2]
-
-
# Return the Rack protocol version as a dotted string.
-
2
def self.version
-
VERSION.join(".")
-
end
-
-
# Return the Rack release as a dotted string.
-
2
def self.release
-
"1.5.5"
-
end
-
-
2
autoload :Builder, "rack/builder"
-
2
autoload :BodyProxy, "rack/body_proxy"
-
2
autoload :Cascade, "rack/cascade"
-
2
autoload :Chunked, "rack/chunked"
-
2
autoload :CommonLogger, "rack/commonlogger"
-
2
autoload :ConditionalGet, "rack/conditionalget"
-
2
autoload :Config, "rack/config"
-
2
autoload :ContentLength, "rack/content_length"
-
2
autoload :ContentType, "rack/content_type"
-
2
autoload :ETag, "rack/etag"
-
2
autoload :File, "rack/file"
-
2
autoload :Deflater, "rack/deflater"
-
2
autoload :Directory, "rack/directory"
-
2
autoload :ForwardRequest, "rack/recursive"
-
2
autoload :Handler, "rack/handler"
-
2
autoload :Head, "rack/head"
-
2
autoload :Lint, "rack/lint"
-
2
autoload :Lock, "rack/lock"
-
2
autoload :Logger, "rack/logger"
-
2
autoload :MethodOverride, "rack/methodoverride"
-
2
autoload :Mime, "rack/mime"
-
2
autoload :NullLogger, "rack/nulllogger"
-
2
autoload :Recursive, "rack/recursive"
-
2
autoload :Reloader, "rack/reloader"
-
2
autoload :Runtime, "rack/runtime"
-
2
autoload :Sendfile, "rack/sendfile"
-
2
autoload :Server, "rack/server"
-
2
autoload :ShowExceptions, "rack/showexceptions"
-
2
autoload :ShowStatus, "rack/showstatus"
-
2
autoload :Static, "rack/static"
-
2
autoload :URLMap, "rack/urlmap"
-
2
autoload :Utils, "rack/utils"
-
2
autoload :Multipart, "rack/multipart"
-
-
2
autoload :MockRequest, "rack/mock"
-
2
autoload :MockResponse, "rack/mock"
-
-
2
autoload :Request, "rack/request"
-
2
autoload :Response, "rack/response"
-
-
2
module Auth
-
2
autoload :Basic, "rack/auth/basic"
-
2
autoload :AbstractRequest, "rack/auth/abstract/request"
-
2
autoload :AbstractHandler, "rack/auth/abstract/handler"
-
2
module Digest
-
2
autoload :MD5, "rack/auth/digest/md5"
-
2
autoload :Nonce, "rack/auth/digest/nonce"
-
2
autoload :Params, "rack/auth/digest/params"
-
2
autoload :Request, "rack/auth/digest/request"
-
end
-
end
-
-
2
module Session
-
2
autoload :Cookie, "rack/session/cookie"
-
2
autoload :Pool, "rack/session/pool"
-
2
autoload :Memcache, "rack/session/memcache"
-
end
-
-
2
module Utils
-
2
autoload :OkJson, "rack/utils/okjson"
-
end
-
end
-
2
module Rack
-
2
class BodyProxy
-
2
def initialize(body, &block)
-
89
@body, @block, @closed = body, block, false
-
end
-
-
2
def respond_to?(*args)
-
182
return false if args.first.to_s =~ /^to_ary$/
-
182
super or @body.respond_to?(*args)
-
end
-
-
2
def close
-
52
return if @closed
-
52
@closed = true
-
52
begin
-
52
@body.close if @body.respond_to? :close
-
ensure
-
52
@block.call
-
end
-
end
-
-
2
def closed?
-
@closed
-
end
-
-
# N.B. This method is a special case to address the bug described by #434.
-
# We are applying this special case for #each only. Future bugs of this
-
# class will be handled by requesting users to patch their ruby
-
# implementation, to save adding too many methods in this class.
-
2
def each(*args, &block)
-
65
@body.each(*args, &block)
-
end
-
-
2
def method_missing(*args, &block)
-
super if args.first.to_s =~ /^to_ary$/
-
@body.__send__(*args, &block)
-
end
-
end
-
end
-
2
module Rack
-
# Rack::Builder implements a small DSL to iteratively construct Rack
-
# applications.
-
#
-
# Example:
-
#
-
# require 'rack/lobster'
-
# app = Rack::Builder.new do
-
# use Rack::CommonLogger
-
# use Rack::ShowExceptions
-
# map "/lobster" do
-
# use Rack::Lint
-
# run Rack::Lobster.new
-
# end
-
# end
-
#
-
# run app
-
#
-
# Or
-
#
-
# app = Rack::Builder.app do
-
# use Rack::CommonLogger
-
# run lambda { |env| [200, {'Content-Type' => 'text/plain'}, ['OK']] }
-
# end
-
#
-
# run app
-
#
-
# +use+ adds middleware to the stack, +run+ dispatches to an application.
-
# You can use +map+ to construct a Rack::URLMap in a convenient way.
-
-
2
class Builder
-
2
def self.parse_file(config, opts = Server::Options.new)
-
options = {}
-
if config =~ /\.ru$/
-
cfgfile = ::File.read(config)
-
if cfgfile[/^#\\(.*)/] && opts
-
options = opts.parse! $1.split(/\s+/)
-
end
-
cfgfile.sub!(/^__END__\n.*\Z/m, '')
-
app = new_from_string cfgfile, config
-
else
-
require config
-
app = Object.const_get(::File.basename(config, '.rb').capitalize)
-
end
-
return app, options
-
end
-
-
2
def self.new_from_string(builder_script, file="(rackup)")
-
eval "Rack::Builder.new {\n" + builder_script + "\n}.to_app",
-
TOPLEVEL_BINDING, file, 0
-
end
-
-
2
def initialize(default_app = nil,&block)
-
4
@use, @map, @run = [], nil, default_app
-
4
instance_eval(&block) if block_given?
-
end
-
-
2
def self.app(default_app = nil, &block)
-
self.new(default_app, &block).to_app
-
end
-
-
# Specifies middleware to use in a stack.
-
#
-
# class Middleware
-
# def initialize(app)
-
# @app = app
-
# end
-
#
-
# def call(env)
-
# env["rack.some_header"] = "setting an example"
-
# @app.call(env)
-
# end
-
# end
-
#
-
# use Middleware
-
# run lambda { |env| [200, { "Content-Type => "text/plain" }, ["OK"]] }
-
#
-
# All requests through to this application will first be processed by the middleware class.
-
# The +call+ method in this example sets an additional environment key which then can be
-
# referenced in the application if required.
-
2
def use(middleware, *args, &block)
-
if @map
-
mapping, @map = @map, nil
-
@use << proc { |app| generate_map app, mapping }
-
end
-
@use << proc { |app| middleware.new(app, *args, &block) }
-
end
-
-
# Takes an argument that is an object that responds to #call and returns a Rack response.
-
# The simplest form of this is a lambda object:
-
#
-
# run lambda { |env| [200, { "Content-Type" => "text/plain" }, ["OK"]] }
-
#
-
# However this could also be a class:
-
#
-
# class Heartbeat
-
# def self.call(env)
-
# [200, { "Content-Type" => "text/plain" }, ["OK"]]
-
# end
-
# end
-
#
-
# run Heartbeat
-
2
def run(app)
-
2
@run = app
-
end
-
-
# Creates a route within the application.
-
#
-
# Rack::Builder.app do
-
# map '/' do
-
# run Heartbeat
-
# end
-
# end
-
#
-
# The +use+ method can also be used here to specify middleware to run under a specific path:
-
#
-
# Rack::Builder.app do
-
# map '/' do
-
# use Middleware
-
# run Heartbeat
-
# end
-
# end
-
#
-
# This example includes a piece of middleware which will run before requests hit +Heartbeat+.
-
#
-
2
def map(path, &block)
-
2
@map ||= {}
-
2
@map[path] = block
-
end
-
-
2
def to_app
-
15
app = @map ? generate_map(@run, @map) : @run
-
15
fail "missing run or map statement" unless app
-
15
@use.reverse.inject(app) { |a,e| e[a] }
-
end
-
-
2
def call(env)
-
13
to_app.call(env)
-
end
-
-
2
private
-
-
2
def generate_map(default_app, mapping)
-
2
mapped = default_app ? {'/' => default_app} : {}
-
4
mapping.each { |r,b| mapped[r] = self.class.new(default_app, &b) }
-
2
URLMap.new(mapped)
-
end
-
end
-
end
-
2
require 'rack/utils'
-
-
2
module Rack
-
-
# Middleware that applies chunked transfer encoding to response bodies
-
# when the response does not include a Content-Length header.
-
2
class Chunked
-
2
include Rack::Utils
-
-
# A body wrapper that emits chunked responses
-
2
class Body
-
2
TERM = "\r\n"
-
2
TAIL = "0#{TERM}#{TERM}"
-
-
2
include Rack::Utils
-
-
2
def initialize(body)
-
@body = body
-
end
-
-
2
def each
-
term = TERM
-
@body.each do |chunk|
-
size = bytesize(chunk)
-
next if size == 0
-
-
chunk = chunk.dup.force_encoding(Encoding::BINARY) if chunk.respond_to?(:force_encoding)
-
yield [size.to_s(16), term, chunk, term].join
-
end
-
yield TAIL
-
end
-
-
2
def close
-
@body.close if @body.respond_to?(:close)
-
end
-
end
-
-
2
def initialize(app)
-
@app = app
-
end
-
-
2
def call(env)
-
status, headers, body = @app.call(env)
-
headers = HeaderHash.new(headers)
-
-
if env['HTTP_VERSION'] == 'HTTP/1.0' ||
-
STATUS_WITH_NO_ENTITY_BODY.include?(status) ||
-
headers['Content-Length'] ||
-
headers['Transfer-Encoding']
-
[status, headers, body]
-
else
-
headers.delete('Content-Length')
-
headers['Transfer-Encoding'] = 'chunked'
-
[status, headers, Body.new(body)]
-
end
-
end
-
end
-
end
-
2
require 'rack/utils'
-
-
2
module Rack
-
-
# Middleware that enables conditional GET using If-None-Match and
-
# If-Modified-Since. The application should set either or both of the
-
# Last-Modified or Etag response headers according to RFC 2616. When
-
# either of the conditions is met, the response body is set to be zero
-
# length and the response status is set to 304 Not Modified.
-
#
-
# Applications that defer response body generation until the body's each
-
# message is received will avoid response body generation completely when
-
# a conditional GET matches.
-
#
-
# Adapted from Michael Klishin's Merb implementation:
-
# https://github.com/wycats/merb/blob/master/merb-core/lib/merb-core/rack/middleware/conditional_get.rb
-
2
class ConditionalGet
-
2
def initialize(app)
-
2
@app = app
-
end
-
-
2
def call(env)
-
13
case env['REQUEST_METHOD']
-
when "GET", "HEAD"
-
9
status, headers, body = @app.call(env)
-
9
headers = Utils::HeaderHash.new(headers)
-
9
if status == 200 && fresh?(env, headers)
-
status = 304
-
headers.delete('Content-Type')
-
headers.delete('Content-Length')
-
body = []
-
end
-
9
[status, headers, body]
-
else
-
4
@app.call(env)
-
end
-
end
-
-
2
private
-
-
2
def fresh?(env, headers)
-
9
modified_since = env['HTTP_IF_MODIFIED_SINCE']
-
9
none_match = env['HTTP_IF_NONE_MATCH']
-
-
9
return false unless modified_since || none_match
-
-
success = true
-
success &&= modified_since?(to_rfc2822(modified_since), headers) if modified_since
-
success &&= etag_matches?(none_match, headers) if none_match
-
success
-
end
-
-
2
def etag_matches?(none_match, headers)
-
etag = headers['ETag'] and etag == none_match
-
end
-
-
2
def modified_since?(modified_since, headers)
-
last_modified = to_rfc2822(headers['Last-Modified']) and
-
modified_since and
-
modified_since >= last_modified
-
end
-
-
2
def to_rfc2822(since)
-
Time.rfc2822(since) rescue nil
-
end
-
end
-
end
-
2
require 'digest/md5'
-
-
2
module Rack
-
# Automatically sets the ETag header on all String bodies.
-
#
-
# The ETag header is skipped if ETag or Last-Modified headers are sent or if
-
# a sendfile body (body.responds_to :to_path) is given (since such cases
-
# should be handled by apache/nginx).
-
#
-
# On initialization, you can pass two parameters: a Cache-Control directive
-
# used when Etag is absent and a directive when it is present. The first
-
# defaults to nil, while the second defaults to "max-age=0, private, must-revalidate"
-
2
class ETag
-
2
DEFAULT_CACHE_CONTROL = "max-age=0, private, must-revalidate".freeze
-
-
2
def initialize(app, no_cache_control = nil, cache_control = DEFAULT_CACHE_CONTROL)
-
2
@app = app
-
2
@cache_control = cache_control
-
2
@no_cache_control = no_cache_control
-
end
-
-
2
def call(env)
-
13
status, headers, body = @app.call(env)
-
-
13
if etag_status?(status) && etag_body?(body) && !skip_caching?(headers)
-
13
digest, body = digest_body(body)
-
13
headers['ETag'] = %("#{digest}") if digest
-
end
-
-
13
unless headers['Cache-Control']
-
13
if digest
-
13
headers['Cache-Control'] = @cache_control if @cache_control
-
else
-
headers['Cache-Control'] = @no_cache_control if @no_cache_control
-
end
-
end
-
-
13
[status, headers, body]
-
end
-
-
2
private
-
-
2
def etag_status?(status)
-
13
status == 200 || status == 201
-
end
-
-
2
def etag_body?(body)
-
13
!body.respond_to?(:to_path)
-
end
-
-
2
def skip_caching?(headers)
-
13
(headers['Cache-Control'] && headers['Cache-Control'].include?('no-cache')) ||
-
13
headers.key?('ETag') || headers.key?('Last-Modified')
-
end
-
-
2
def digest_body(body)
-
13
parts = []
-
26
body.each { |part| parts << part }
-
13
string_body = parts.join
-
13
digest = Digest::MD5.hexdigest(string_body) unless string_body.empty?
-
13
[digest, parts]
-
end
-
end
-
end
-
2
require 'time'
-
2
require 'rack/utils'
-
2
require 'rack/mime'
-
-
2
module Rack
-
# Rack::File serves files below the +root+ directory given, according to the
-
# path info of the Rack request.
-
# e.g. when Rack::File.new("/etc") is used, you can access 'passwd' file
-
# as http://localhost:9292/passwd
-
#
-
# Handlers can detect if bodies are a Rack::File, and use mechanisms
-
# like sendfile on the +path+.
-
-
2
class File
-
2
SEPS = Regexp.union(*[::File::SEPARATOR, ::File::ALT_SEPARATOR].compact)
-
2
ALLOWED_VERBS = %w[GET HEAD]
-
-
2
attr_accessor :root
-
2
attr_accessor :path
-
2
attr_accessor :cache_control
-
-
2
alias :to_path :path
-
-
2
def initialize(root, headers={}, default_mime = 'text/plain')
-
2
@root = root
-
2
@headers = headers
-
2
@default_mime = default_mime
-
end
-
-
2
def call(env)
-
dup._call(env)
-
end
-
-
2
F = ::File
-
-
2
def _call(env)
-
unless ALLOWED_VERBS.include? env["REQUEST_METHOD"]
-
return fail(405, "Method Not Allowed")
-
end
-
-
path_info = Utils.unescape(env["PATH_INFO"])
-
parts = path_info.split SEPS
-
-
clean = []
-
-
parts.each do |part|
-
next if part.empty? || part == '.'
-
part == '..' ? clean.pop : clean << part
-
end
-
-
@path = F.join(@root, *clean)
-
-
available = begin
-
F.file?(@path) && F.readable?(@path)
-
rescue SystemCallError
-
false
-
end
-
-
if available
-
serving(env)
-
else
-
fail(404, "File not found: #{path_info}")
-
end
-
end
-
-
2
def serving(env)
-
last_modified = F.mtime(@path).httpdate
-
return [304, {}, []] if env['HTTP_IF_MODIFIED_SINCE'] == last_modified
-
-
headers = { "Last-Modified" => last_modified }
-
mime = Mime.mime_type(F.extname(@path), @default_mime)
-
headers["Content-Type"] = mime if mime
-
-
# Set custom headers
-
@headers.each { |field, content| headers[field] = content } if @headers
-
-
response = [ 200, headers, env["REQUEST_METHOD"] == "HEAD" ? [] : self ]
-
-
# NOTE:
-
# We check via File::size? whether this file provides size info
-
# via stat (e.g. /proc files often don't), otherwise we have to
-
# figure it out by reading the whole file into memory.
-
size = F.size?(@path) || Utils.bytesize(F.read(@path))
-
-
ranges = Rack::Utils.byte_ranges(env, size)
-
if ranges.nil? || ranges.length > 1
-
# No ranges, or multiple ranges (which we don't support):
-
# TODO: Support multiple byte-ranges
-
response[0] = 200
-
@range = 0..size-1
-
elsif ranges.empty?
-
# Unsatisfiable. Return error, and file size:
-
response = fail(416, "Byte range unsatisfiable")
-
response[1]["Content-Range"] = "bytes */#{size}"
-
return response
-
else
-
# Partial content:
-
@range = ranges[0]
-
response[0] = 206
-
response[1]["Content-Range"] = "bytes #{@range.begin}-#{@range.end}/#{size}"
-
size = @range.end - @range.begin + 1
-
end
-
-
response[1]["Content-Length"] = size.to_s
-
response
-
end
-
-
2
def each
-
F.open(@path, "rb") do |file|
-
file.seek(@range.begin)
-
remaining_len = @range.end-@range.begin+1
-
while remaining_len > 0
-
part = file.read([8192, remaining_len].min)
-
break unless part
-
remaining_len -= part.length
-
-
yield part
-
end
-
end
-
end
-
-
2
private
-
-
2
def fail(status, body)
-
body += "\n"
-
[
-
status,
-
{
-
"Content-Type" => "text/plain",
-
"Content-Length" => body.size.to_s,
-
"X-Cascade" => "pass"
-
},
-
[body]
-
]
-
end
-
-
end
-
end
-
2
module Rack
-
-
2
class Head
-
# Rack::Head returns an empty body for all HEAD requests. It leaves
-
# all other requests unchanged.
-
2
def initialize(app)
-
2
@app = app
-
end
-
-
2
def call(env)
-
13
status, headers, body = @app.call(env)
-
-
13
if env["REQUEST_METHOD"] == "HEAD"
-
body.close if body.respond_to? :close
-
[status, headers, []]
-
else
-
13
[status, headers, body]
-
end
-
end
-
end
-
-
end
-
2
require 'rack/utils'
-
2
require 'forwardable'
-
-
2
module Rack
-
# Rack::Lint validates your application and the requests and
-
# responses according to the Rack spec.
-
-
2
class Lint
-
2
def initialize(app)
-
@app = app
-
@content_length = nil
-
end
-
-
# :stopdoc:
-
-
2
class LintError < RuntimeError; end
-
2
module Assertion
-
2
def assert(message, &block)
-
unless block.call
-
raise LintError, message
-
end
-
end
-
end
-
2
include Assertion
-
-
## This specification aims to formalize the Rack protocol. You
-
## can (and should) use Rack::Lint to enforce it.
-
##
-
## When you develop middleware, be sure to add a Lint before and
-
## after to catch all mistakes.
-
-
## = Rack applications
-
-
## A Rack application is a Ruby object (not a class) that
-
## responds to +call+.
-
2
def call(env=nil)
-
dup._call(env)
-
end
-
-
2
def _call(env)
-
## It takes exactly one argument, the *environment*
-
assert("No env given") { env }
-
check_env env
-
-
env['rack.input'] = InputWrapper.new(env['rack.input'])
-
env['rack.errors'] = ErrorWrapper.new(env['rack.errors'])
-
-
## and returns an Array of exactly three values:
-
status, headers, @body = @app.call(env)
-
## The *status*,
-
check_status status
-
## the *headers*,
-
check_headers headers
-
-
check_hijack_response headers, env
-
-
## and the *body*.
-
check_content_type status, headers
-
check_content_length status, headers
-
@head_request = env["REQUEST_METHOD"] == "HEAD"
-
[status, headers, self]
-
end
-
-
## == The Environment
-
2
def check_env(env)
-
## The environment must be an instance of Hash that includes
-
## CGI-like headers. The application is free to modify the
-
## environment.
-
assert("env #{env.inspect} is not a Hash, but #{env.class}") {
-
env.kind_of? Hash
-
}
-
-
##
-
## The environment is required to include these variables
-
## (adopted from PEP333), except when they'd be empty, but see
-
## below.
-
-
## <tt>REQUEST_METHOD</tt>:: The HTTP request method, such as
-
## "GET" or "POST". This cannot ever
-
## be an empty string, and so is
-
## always required.
-
-
## <tt>SCRIPT_NAME</tt>:: The initial portion of the request
-
## URL's "path" that corresponds to the
-
## application object, so that the
-
## application knows its virtual
-
## "location". This may be an empty
-
## string, if the application corresponds
-
## to the "root" of the server.
-
-
## <tt>PATH_INFO</tt>:: The remainder of the request URL's
-
## "path", designating the virtual
-
## "location" of the request's target
-
## within the application. This may be an
-
## empty string, if the request URL targets
-
## the application root and does not have a
-
## trailing slash. This value may be
-
## percent-encoded when I originating from
-
## a URL.
-
-
## <tt>QUERY_STRING</tt>:: The portion of the request URL that
-
## follows the <tt>?</tt>, if any. May be
-
## empty, but is always required!
-
-
## <tt>SERVER_NAME</tt>, <tt>SERVER_PORT</tt>:: When combined with <tt>SCRIPT_NAME</tt> and <tt>PATH_INFO</tt>, these variables can be used to complete the URL. Note, however, that <tt>HTTP_HOST</tt>, if present, should be used in preference to <tt>SERVER_NAME</tt> for reconstructing the request URL. <tt>SERVER_NAME</tt> and <tt>SERVER_PORT</tt> can never be empty strings, and so are always required.
-
-
## <tt>HTTP_</tt> Variables:: Variables corresponding to the
-
## client-supplied HTTP request
-
## headers (i.e., variables whose
-
## names begin with <tt>HTTP_</tt>). The
-
## presence or absence of these
-
## variables should correspond with
-
## the presence or absence of the
-
## appropriate HTTP header in the
-
## request. See <a href="https://tools.ietf.org/html/rfc3875#section-4.1.18">
-
## RFC3875 section 4.1.18</a> for specific behavior.
-
-
## In addition to this, the Rack environment must include these
-
## Rack-specific variables:
-
-
## <tt>rack.version</tt>:: The Array representing this version of Rack. See Rack::VERSION, that corresponds to the version of this SPEC.
-
## <tt>rack.url_scheme</tt>:: +http+ or +https+, depending on the request URL.
-
## <tt>rack.input</tt>:: See below, the input stream.
-
## <tt>rack.errors</tt>:: See below, the error stream.
-
## <tt>rack.multithread</tt>:: true if the application object may be simultaneously invoked by another thread in the same process, false otherwise.
-
## <tt>rack.multiprocess</tt>:: true if an equivalent application object may be simultaneously invoked by another process, false otherwise.
-
## <tt>rack.run_once</tt>:: true if the server expects (but does not guarantee!) that the application will only be invoked this one time during the life of its containing process. Normally, this will only be true for a server based on CGI (or something similar).
-
## <tt>rack.hijack?</tt>:: present and true if the server supports connection hijacking. See below, hijacking.
-
## <tt>rack.hijack</tt>:: an object responding to #call that must be called at least once before using rack.hijack_io. It is recommended #call return rack.hijack_io as well as setting it in env if necessary.
-
## <tt>rack.hijack_io</tt>:: if rack.hijack? is true, and rack.hijack has received #call, this will contain an object resembling an IO. See hijacking.
-
##
-
-
## Additional environment specifications have approved to
-
## standardized middleware APIs. None of these are required to
-
## be implemented by the server.
-
-
## <tt>rack.session</tt>:: A hash like interface for storing request session data.
-
## The store must implement:
-
if session = env['rack.session']
-
## store(key, value) (aliased as []=);
-
assert("session #{session.inspect} must respond to store and []=") {
-
session.respond_to?(:store) && session.respond_to?(:[]=)
-
}
-
-
## fetch(key, default = nil) (aliased as []);
-
assert("session #{session.inspect} must respond to fetch and []") {
-
session.respond_to?(:fetch) && session.respond_to?(:[])
-
}
-
-
## delete(key);
-
assert("session #{session.inspect} must respond to delete") {
-
session.respond_to?(:delete)
-
}
-
-
## clear;
-
assert("session #{session.inspect} must respond to clear") {
-
session.respond_to?(:clear)
-
}
-
end
-
-
## <tt>rack.logger</tt>:: A common object interface for logging messages.
-
## The object must implement:
-
if logger = env['rack.logger']
-
## info(message, &block)
-
assert("logger #{logger.inspect} must respond to info") {
-
logger.respond_to?(:info)
-
}
-
-
## debug(message, &block)
-
assert("logger #{logger.inspect} must respond to debug") {
-
logger.respond_to?(:debug)
-
}
-
-
## warn(message, &block)
-
assert("logger #{logger.inspect} must respond to warn") {
-
logger.respond_to?(:warn)
-
}
-
-
## error(message, &block)
-
assert("logger #{logger.inspect} must respond to error") {
-
logger.respond_to?(:error)
-
}
-
-
## fatal(message, &block)
-
assert("logger #{logger.inspect} must respond to fatal") {
-
logger.respond_to?(:fatal)
-
}
-
end
-
-
## The server or the application can store their own data in the
-
## environment, too. The keys must contain at least one dot,
-
## and should be prefixed uniquely. The prefix <tt>rack.</tt>
-
## is reserved for use with the Rack core distribution and other
-
## accepted specifications and must not be used otherwise.
-
##
-
-
%w[REQUEST_METHOD SERVER_NAME SERVER_PORT
-
QUERY_STRING
-
rack.version rack.input rack.errors
-
rack.multithread rack.multiprocess rack.run_once].each { |header|
-
assert("env missing required key #{header}") { env.include? header }
-
}
-
-
## The environment must not contain the keys
-
## <tt>HTTP_CONTENT_TYPE</tt> or <tt>HTTP_CONTENT_LENGTH</tt>
-
## (use the versions without <tt>HTTP_</tt>).
-
%w[HTTP_CONTENT_TYPE HTTP_CONTENT_LENGTH].each { |header|
-
assert("env contains #{header}, must use #{header[5,-1]}") {
-
not env.include? header
-
}
-
}
-
-
## The CGI keys (named without a period) must have String values.
-
env.each { |key, value|
-
next if key.include? "." # Skip extensions
-
assert("env variable #{key} has non-string value #{value.inspect}") {
-
value.kind_of? String
-
}
-
}
-
-
##
-
## There are the following restrictions:
-
-
## * <tt>rack.version</tt> must be an array of Integers.
-
assert("rack.version must be an Array, was #{env["rack.version"].class}") {
-
env["rack.version"].kind_of? Array
-
}
-
## * <tt>rack.url_scheme</tt> must either be +http+ or +https+.
-
assert("rack.url_scheme unknown: #{env["rack.url_scheme"].inspect}") {
-
%w[http https].include? env["rack.url_scheme"]
-
}
-
-
## * There must be a valid input stream in <tt>rack.input</tt>.
-
check_input env["rack.input"]
-
## * There must be a valid error stream in <tt>rack.errors</tt>.
-
check_error env["rack.errors"]
-
## * There may be a valid hijack stream in <tt>rack.hijack_io</tt>
-
check_hijack env
-
-
## * The <tt>REQUEST_METHOD</tt> must be a valid token.
-
assert("REQUEST_METHOD unknown: #{env["REQUEST_METHOD"]}") {
-
env["REQUEST_METHOD"] =~ /\A[0-9A-Za-z!\#$%&'*+.^_`|~-]+\z/
-
}
-
-
## * The <tt>SCRIPT_NAME</tt>, if non-empty, must start with <tt>/</tt>
-
assert("SCRIPT_NAME must start with /") {
-
!env.include?("SCRIPT_NAME") ||
-
env["SCRIPT_NAME"] == "" ||
-
env["SCRIPT_NAME"] =~ /\A\//
-
}
-
## * The <tt>PATH_INFO</tt>, if non-empty, must start with <tt>/</tt>
-
assert("PATH_INFO must start with /") {
-
!env.include?("PATH_INFO") ||
-
env["PATH_INFO"] == "" ||
-
env["PATH_INFO"] =~ /\A\//
-
}
-
## * The <tt>CONTENT_LENGTH</tt>, if given, must consist of digits only.
-
assert("Invalid CONTENT_LENGTH: #{env["CONTENT_LENGTH"]}") {
-
!env.include?("CONTENT_LENGTH") || env["CONTENT_LENGTH"] =~ /\A\d+\z/
-
}
-
-
## * One of <tt>SCRIPT_NAME</tt> or <tt>PATH_INFO</tt> must be
-
## set. <tt>PATH_INFO</tt> should be <tt>/</tt> if
-
## <tt>SCRIPT_NAME</tt> is empty.
-
assert("One of SCRIPT_NAME or PATH_INFO must be set (make PATH_INFO '/' if SCRIPT_NAME is empty)") {
-
env["SCRIPT_NAME"] || env["PATH_INFO"]
-
}
-
## <tt>SCRIPT_NAME</tt> never should be <tt>/</tt>, but instead be empty.
-
assert("SCRIPT_NAME cannot be '/', make it '' and PATH_INFO '/'") {
-
env["SCRIPT_NAME"] != "/"
-
}
-
end
-
-
## === The Input Stream
-
##
-
## The input stream is an IO-like object which contains the raw HTTP
-
## POST data.
-
2
def check_input(input)
-
## When applicable, its external encoding must be "ASCII-8BIT" and it
-
## must be opened in binary mode, for Ruby 1.9 compatibility.
-
assert("rack.input #{input} does not have ASCII-8BIT as its external encoding") {
-
input.external_encoding.name == "ASCII-8BIT"
-
} if input.respond_to?(:external_encoding)
-
assert("rack.input #{input} is not opened in binary mode") {
-
input.binmode?
-
} if input.respond_to?(:binmode?)
-
-
## The input stream must respond to +gets+, +each+, +read+ and +rewind+.
-
[:gets, :each, :read, :rewind].each { |method|
-
assert("rack.input #{input} does not respond to ##{method}") {
-
input.respond_to? method
-
}
-
}
-
end
-
-
2
class InputWrapper
-
2
include Assertion
-
-
2
def initialize(input)
-
@input = input
-
end
-
-
## * +gets+ must be called without arguments and return a string,
-
## or +nil+ on EOF.
-
2
def gets(*args)
-
assert("rack.input#gets called with arguments") { args.size == 0 }
-
v = @input.gets
-
assert("rack.input#gets didn't return a String") {
-
v.nil? or v.kind_of? String
-
}
-
v
-
end
-
-
## * +read+ behaves like IO#read. Its signature is <tt>read([length, [buffer]])</tt>.
-
## If given, +length+ must be a non-negative Integer (>= 0) or +nil+, and +buffer+ must
-
## be a String and may not be nil. If +length+ is given and not nil, then this method
-
## reads at most +length+ bytes from the input stream. If +length+ is not given or nil,
-
## then this method reads all data until EOF.
-
## When EOF is reached, this method returns nil if +length+ is given and not nil, or ""
-
## if +length+ is not given or is nil.
-
## If +buffer+ is given, then the read data will be placed into +buffer+ instead of a
-
## newly created String object.
-
2
def read(*args)
-
assert("rack.input#read called with too many arguments") {
-
args.size <= 2
-
}
-
if args.size >= 1
-
assert("rack.input#read called with non-integer and non-nil length") {
-
args.first.kind_of?(Integer) || args.first.nil?
-
}
-
assert("rack.input#read called with a negative length") {
-
args.first.nil? || args.first >= 0
-
}
-
end
-
if args.size >= 2
-
assert("rack.input#read called with non-String buffer") {
-
args[1].kind_of?(String)
-
}
-
end
-
-
v = @input.read(*args)
-
-
assert("rack.input#read didn't return nil or a String") {
-
v.nil? or v.kind_of? String
-
}
-
if args[0].nil?
-
assert("rack.input#read(nil) returned nil on EOF") {
-
!v.nil?
-
}
-
end
-
-
v
-
end
-
-
## * +each+ must be called without arguments and only yield Strings.
-
2
def each(*args)
-
assert("rack.input#each called with arguments") { args.size == 0 }
-
@input.each { |line|
-
assert("rack.input#each didn't yield a String") {
-
line.kind_of? String
-
}
-
yield line
-
}
-
end
-
-
## * +rewind+ must be called without arguments. It rewinds the input
-
## stream back to the beginning. It must not raise Errno::ESPIPE:
-
## that is, it may not be a pipe or a socket. Therefore, handler
-
## developers must buffer the input data into some rewindable object
-
## if the underlying input stream is not rewindable.
-
2
def rewind(*args)
-
assert("rack.input#rewind called with arguments") { args.size == 0 }
-
assert("rack.input#rewind raised Errno::ESPIPE") {
-
begin
-
@input.rewind
-
true
-
rescue Errno::ESPIPE
-
false
-
end
-
}
-
end
-
-
## * +close+ must never be called on the input stream.
-
2
def close(*args)
-
assert("rack.input#close must not be called") { false }
-
end
-
end
-
-
## === The Error Stream
-
2
def check_error(error)
-
## The error stream must respond to +puts+, +write+ and +flush+.
-
[:puts, :write, :flush].each { |method|
-
assert("rack.error #{error} does not respond to ##{method}") {
-
error.respond_to? method
-
}
-
}
-
end
-
-
2
class ErrorWrapper
-
2
include Assertion
-
-
2
def initialize(error)
-
@error = error
-
end
-
-
## * +puts+ must be called with a single argument that responds to +to_s+.
-
2
def puts(str)
-
@error.puts str
-
end
-
-
## * +write+ must be called with a single argument that is a String.
-
2
def write(str)
-
assert("rack.errors#write not called with a String") { str.kind_of? String }
-
@error.write str
-
end
-
-
## * +flush+ must be called without arguments and must be called
-
## in order to make the error appear for sure.
-
2
def flush
-
@error.flush
-
end
-
-
## * +close+ must never be called on the error stream.
-
2
def close(*args)
-
assert("rack.errors#close must not be called") { false }
-
end
-
end
-
-
2
class HijackWrapper
-
2
include Assertion
-
2
extend Forwardable
-
-
2
REQUIRED_METHODS = [
-
:read, :write, :read_nonblock, :write_nonblock, :flush, :close,
-
:close_read, :close_write, :closed?
-
]
-
-
2
def_delegators :@io, *REQUIRED_METHODS
-
-
2
def initialize(io)
-
@io = io
-
REQUIRED_METHODS.each do |meth|
-
assert("rack.hijack_io must respond to #{meth}") { io.respond_to? meth }
-
end
-
end
-
end
-
-
## === Hijacking
-
#
-
# AUTHORS: n.b. The trailing whitespace between paragraphs is important and
-
# should not be removed. The whitespace creates paragraphs in the RDoc
-
# output.
-
#
-
## ==== Request (before status)
-
2
def check_hijack(env)
-
if env['rack.hijack?']
-
## If rack.hijack? is true then rack.hijack must respond to #call.
-
original_hijack = env['rack.hijack']
-
assert("rack.hijack must respond to call") { original_hijack.respond_to?(:call) }
-
env['rack.hijack'] = proc do
-
## rack.hijack must return the io that will also be assigned (or is
-
## already present, in rack.hijack_io.
-
io = original_hijack.call
-
HijackWrapper.new(io)
-
##
-
## rack.hijack_io must respond to:
-
## <tt>read, write, read_nonblock, write_nonblock, flush, close,
-
## close_read, close_write, closed?</tt>
-
##
-
## The semantics of these IO methods must be a best effort match to
-
## those of a normal ruby IO or Socket object, using standard
-
## arguments and raising standard exceptions. Servers are encouraged
-
## to simply pass on real IO objects, although it is recognized that
-
## this approach is not directly compatible with SPDY and HTTP 2.0.
-
##
-
## IO provided in rack.hijack_io should preference the
-
## IO::WaitReadable and IO::WaitWritable APIs wherever supported.
-
##
-
## There is a deliberate lack of full specification around
-
## rack.hijack_io, as semantics will change from server to server.
-
## Users are encouraged to utilize this API with a knowledge of their
-
## server choice, and servers may extend the functionality of
-
## hijack_io to provide additional features to users. The purpose of
-
## rack.hijack is for Rack to "get out of the way", as such, Rack only
-
## provides the minimum of specification and support.
-
env['rack.hijack_io'] = HijackWrapper.new(env['rack.hijack_io'])
-
io
-
end
-
else
-
##
-
## If rack.hijack? is false, then rack.hijack should not be set.
-
assert("rack.hijack? is false, but rack.hijack is present") { env['rack.hijack'].nil? }
-
##
-
## If rack.hijack? is false, then rack.hijack_io should not be set.
-
assert("rack.hijack? is false, but rack.hijack_io is present") { env['rack.hijack_io'].nil? }
-
end
-
end
-
-
## ==== Response (after headers)
-
## It is also possible to hijack a response after the status and headers
-
## have been sent.
-
2
def check_hijack_response(headers, env)
-
-
# this check uses headers like a hash, but the spec only requires
-
# headers respond to #each
-
headers = Rack::Utils::HeaderHash.new(headers)
-
-
## In order to do this, an application may set the special header
-
## <tt>rack.hijack</tt> to an object that responds to <tt>call</tt>
-
## accepting an argument that conforms to the <tt>rack.hijack_io</tt>
-
## protocol.
-
##
-
## After the headers have been sent, and this hijack callback has been
-
## called, the application is now responsible for the remaining lifecycle
-
## of the IO. The application is also responsible for maintaining HTTP
-
## semantics. Of specific note, in almost all cases in the current SPEC,
-
## applications will have wanted to specify the header Connection:close in
-
## HTTP/1.1, and not Connection:keep-alive, as there is no protocol for
-
## returning hijacked sockets to the web server. For that purpose, use the
-
## body streaming API instead (progressively yielding strings via each).
-
##
-
## Servers must ignore the <tt>body</tt> part of the response tuple when
-
## the <tt>rack.hijack</tt> response API is in use.
-
-
if env['rack.hijack?'] && headers['rack.hijack']
-
assert('rack.hijack header must respond to #call') {
-
headers['rack.hijack'].respond_to? :call
-
}
-
original_hijack = headers['rack.hijack']
-
headers['rack.hijack'] = proc do |io|
-
original_hijack.call HijackWrapper.new(io)
-
end
-
else
-
##
-
## The special response header <tt>rack.hijack</tt> must only be set
-
## if the request env has <tt>rack.hijack?</tt> <tt>true</tt>.
-
assert('rack.hijack header must not be present if server does not support hijacking') {
-
headers['rack.hijack'].nil?
-
}
-
end
-
end
-
## ==== Conventions
-
## * Middleware should not use hijack unless it is handling the whole
-
## response.
-
## * Middleware may wrap the IO object for the response pattern.
-
## * Middleware should not wrap the IO object for the request pattern. The
-
## request pattern is intended to provide the hijacker with "raw tcp".
-
-
## == The Response
-
-
## === The Status
-
2
def check_status(status)
-
## This is an HTTP status. When parsed as integer (+to_i+), it must be
-
## greater than or equal to 100.
-
assert("Status must be >=100 seen as integer") { status.to_i >= 100 }
-
end
-
-
## === The Headers
-
2
def check_headers(header)
-
## The header must respond to +each+, and yield values of key and value.
-
assert("headers object should respond to #each, but doesn't (got #{header.class} as headers)") {
-
header.respond_to? :each
-
}
-
header.each { |key, value|
-
## Special headers starting "rack." are for communicating with the
-
## server, and must not be sent back to the client.
-
next if key =~ /^rack\..+$/
-
-
## The header keys must be Strings.
-
assert("header key must be a string, was #{key.class}") {
-
key.kind_of? String
-
}
-
## The header must not contain a +Status+ key,
-
assert("header must not contain Status") { key.downcase != "status" }
-
## contain keys with <tt>:</tt> or newlines in their name,
-
assert("header names must not contain : or \\n") { key !~ /[:\n]/ }
-
## contain keys names that end in <tt>-</tt> or <tt>_</tt>,
-
assert("header names must not end in - or _") { key !~ /[-_]\z/ }
-
## but only contain keys that consist of
-
## letters, digits, <tt>_</tt> or <tt>-</tt> and start with a letter.
-
assert("invalid header name: #{key}") { key =~ /\A[a-zA-Z][a-zA-Z0-9_-]*\z/ }
-
-
## The values of the header must be Strings,
-
assert("a header value must be a String, but the value of " +
-
"'#{key}' is a #{value.class}") { value.kind_of? String }
-
## consisting of lines (for multiple header values, e.g. multiple
-
## <tt>Set-Cookie</tt> values) seperated by "\n".
-
value.split("\n").each { |item|
-
## The lines must not contain characters below 037.
-
assert("invalid header value #{key}: #{item.inspect}") {
-
item !~ /[\000-\037]/
-
}
-
}
-
}
-
end
-
-
## === The Content-Type
-
2
def check_content_type(status, headers)
-
headers.each { |key, value|
-
## There must not be a <tt>Content-Type</tt>, when the +Status+ is 1xx,
-
## 204, 205 or 304.
-
if key.downcase == "content-type"
-
assert("Content-Type header found in #{status} response, not allowed") {
-
not Rack::Utils::STATUS_WITH_NO_ENTITY_BODY.include? status.to_i
-
}
-
return
-
end
-
}
-
end
-
-
## === The Content-Length
-
2
def check_content_length(status, headers)
-
headers.each { |key, value|
-
if key.downcase == 'content-length'
-
## There must not be a <tt>Content-Length</tt> header when the
-
## +Status+ is 1xx, 204, 205 or 304.
-
assert("Content-Length header found in #{status} response, not allowed") {
-
not Rack::Utils::STATUS_WITH_NO_ENTITY_BODY.include? status.to_i
-
}
-
@content_length = value
-
end
-
}
-
end
-
-
2
def verify_content_length(bytes)
-
if @head_request
-
assert("Response body was given for HEAD request, but should be empty") {
-
bytes == 0
-
}
-
elsif @content_length
-
assert("Content-Length header was #{@content_length}, but should be #{bytes}") {
-
@content_length == bytes.to_s
-
}
-
end
-
end
-
-
## === The Body
-
2
def each
-
@closed = false
-
bytes = 0
-
-
## The Body must respond to +each+
-
assert("Response body must respond to each") do
-
@body.respond_to?(:each)
-
end
-
-
@body.each { |part|
-
## and must only yield String values.
-
assert("Body yielded non-string value #{part.inspect}") {
-
part.kind_of? String
-
}
-
bytes += Rack::Utils.bytesize(part)
-
yield part
-
}
-
verify_content_length(bytes)
-
-
##
-
## The Body itself should not be an instance of String, as this will
-
## break in Ruby 1.9.
-
##
-
## If the Body responds to +close+, it will be called after iteration. If
-
## the body is replaced by a middleware after action, the original body
-
## must be closed first, if it repsonds to close.
-
# XXX howto: assert("Body has not been closed") { @closed }
-
-
-
##
-
## If the Body responds to +to_path+, it must return a String
-
## identifying the location of a file whose contents are identical
-
## to that produced by calling +each+; this may be used by the
-
## server as an alternative, possibly more efficient way to
-
## transport the response.
-
-
if @body.respond_to?(:to_path)
-
assert("The file identified by body.to_path does not exist") {
-
::File.exist? @body.to_path
-
}
-
end
-
-
##
-
## The Body commonly is an Array of Strings, the application
-
## instance itself, or a File-like object.
-
end
-
-
2
def close
-
@closed = true
-
@body.close if @body.respond_to?(:close)
-
end
-
-
# :startdoc:
-
-
end
-
end
-
-
## == Thanks
-
## Some parts of this specification are adopted from PEP333: Python
-
## Web Server Gateway Interface
-
## v1.0 (http://www.python.org/dev/peps/pep-0333/). I'd like to thank
-
## everyone involved in that effort.
-
2
module Rack
-
2
class MethodOverride
-
2
HTTP_METHODS = %w(GET HEAD PUT POST DELETE OPTIONS PATCH)
-
-
2
METHOD_OVERRIDE_PARAM_KEY = "_method".freeze
-
2
HTTP_METHOD_OVERRIDE_HEADER = "HTTP_X_HTTP_METHOD_OVERRIDE".freeze
-
-
2
def initialize(app)
-
2
@app = app
-
end
-
-
2
def call(env)
-
13
if env["REQUEST_METHOD"] == "POST"
-
4
method = method_override(env)
-
4
if HTTP_METHODS.include?(method)
-
env["rack.methodoverride.original_method"] = env["REQUEST_METHOD"]
-
env["REQUEST_METHOD"] = method
-
end
-
end
-
-
13
@app.call(env)
-
end
-
-
2
def method_override(env)
-
4
req = Request.new(env)
-
4
method = req.POST[METHOD_OVERRIDE_PARAM_KEY] ||
-
env[HTTP_METHOD_OVERRIDE_HEADER]
-
4
method.to_s.upcase
-
end
-
end
-
end
-
2
module Rack
-
2
module Mime
-
# Returns String with mime type if found, otherwise use +fallback+.
-
# +ext+ should be filename extension in the '.ext' format that
-
# File.extname(file) returns.
-
# +fallback+ may be any object
-
#
-
# Also see the documentation for MIME_TYPES
-
#
-
# Usage:
-
# Rack::Mime.mime_type('.foo')
-
#
-
# This is a shortcut for:
-
# Rack::Mime::MIME_TYPES.fetch('.foo', 'application/octet-stream')
-
-
2
def mime_type(ext, fallback='application/octet-stream')
-
MIME_TYPES.fetch(ext.to_s.downcase, fallback)
-
end
-
2
module_function :mime_type
-
-
# Returns true if the given value is a mime match for the given mime match
-
# specification, false otherwise.
-
#
-
# Rack::Mime.match?('text/html', 'text/*') => true
-
# Rack::Mime.match?('text/plain', '*') => true
-
# Rack::Mime.match?('text/html', 'application/json') => false
-
-
2
def match?(value, matcher)
-
v1, v2 = value.split('/', 2)
-
m1, m2 = matcher.split('/', 2)
-
-
if m1 == '*'
-
if m2.nil? || m2 == '*'
-
return true
-
elsif m2 == v2
-
return true
-
else
-
return false
-
end
-
end
-
-
return false if v1 != m1
-
-
return true if m2.nil? || m2 == '*'
-
-
m2 == v2
-
end
-
2
module_function :match?
-
-
# List of most common mime-types, selected various sources
-
# according to their usefulness in a webserving scope for Ruby
-
# users.
-
#
-
# To amend this list with your local mime.types list you can use:
-
#
-
# require 'webrick/httputils'
-
# list = WEBrick::HTTPUtils.load_mime_types('/etc/mime.types')
-
# Rack::Mime::MIME_TYPES.merge!(list)
-
#
-
# N.B. On Ubuntu the mime.types file does not include the leading period, so
-
# users may need to modify the data before merging into the hash.
-
#
-
# To add the list mongrel provides, use:
-
#
-
# require 'mongrel/handlers'
-
# Rack::Mime::MIME_TYPES.merge!(Mongrel::DirHandler::MIME_TYPES)
-
-
2
MIME_TYPES = {
-
".123" => "application/vnd.lotus-1-2-3",
-
".3dml" => "text/vnd.in3d.3dml",
-
".3g2" => "video/3gpp2",
-
".3gp" => "video/3gpp",
-
".a" => "application/octet-stream",
-
".acc" => "application/vnd.americandynamics.acc",
-
".ace" => "application/x-ace-compressed",
-
".acu" => "application/vnd.acucobol",
-
".aep" => "application/vnd.audiograph",
-
".afp" => "application/vnd.ibm.modcap",
-
".ai" => "application/postscript",
-
".aif" => "audio/x-aiff",
-
".aiff" => "audio/x-aiff",
-
".ami" => "application/vnd.amiga.ami",
-
".appcache" => "text/cache-manifest",
-
".apr" => "application/vnd.lotus-approach",
-
".asc" => "application/pgp-signature",
-
".asf" => "video/x-ms-asf",
-
".asm" => "text/x-asm",
-
".aso" => "application/vnd.accpac.simply.aso",
-
".asx" => "video/x-ms-asf",
-
".atc" => "application/vnd.acucorp",
-
".atom" => "application/atom+xml",
-
".atomcat" => "application/atomcat+xml",
-
".atomsvc" => "application/atomsvc+xml",
-
".atx" => "application/vnd.antix.game-component",
-
".au" => "audio/basic",
-
".avi" => "video/x-msvideo",
-
".bat" => "application/x-msdownload",
-
".bcpio" => "application/x-bcpio",
-
".bdm" => "application/vnd.syncml.dm+wbxml",
-
".bh2" => "application/vnd.fujitsu.oasysprs",
-
".bin" => "application/octet-stream",
-
".bmi" => "application/vnd.bmi",
-
".bmp" => "image/bmp",
-
".box" => "application/vnd.previewsystems.box",
-
".btif" => "image/prs.btif",
-
".bz" => "application/x-bzip",
-
".bz2" => "application/x-bzip2",
-
".c" => "text/x-c",
-
".c4g" => "application/vnd.clonk.c4group",
-
".cab" => "application/vnd.ms-cab-compressed",
-
".cc" => "text/x-c",
-
".ccxml" => "application/ccxml+xml",
-
".cdbcmsg" => "application/vnd.contact.cmsg",
-
".cdkey" => "application/vnd.mediastation.cdkey",
-
".cdx" => "chemical/x-cdx",
-
".cdxml" => "application/vnd.chemdraw+xml",
-
".cdy" => "application/vnd.cinderella",
-
".cer" => "application/pkix-cert",
-
".cgm" => "image/cgm",
-
".chat" => "application/x-chat",
-
".chm" => "application/vnd.ms-htmlhelp",
-
".chrt" => "application/vnd.kde.kchart",
-
".cif" => "chemical/x-cif",
-
".cii" => "application/vnd.anser-web-certificate-issue-initiation",
-
".cil" => "application/vnd.ms-artgalry",
-
".cla" => "application/vnd.claymore",
-
".class" => "application/octet-stream",
-
".clkk" => "application/vnd.crick.clicker.keyboard",
-
".clkp" => "application/vnd.crick.clicker.palette",
-
".clkt" => "application/vnd.crick.clicker.template",
-
".clkw" => "application/vnd.crick.clicker.wordbank",
-
".clkx" => "application/vnd.crick.clicker",
-
".clp" => "application/x-msclip",
-
".cmc" => "application/vnd.cosmocaller",
-
".cmdf" => "chemical/x-cmdf",
-
".cml" => "chemical/x-cml",
-
".cmp" => "application/vnd.yellowriver-custom-menu",
-
".cmx" => "image/x-cmx",
-
".com" => "application/x-msdownload",
-
".conf" => "text/plain",
-
".cpio" => "application/x-cpio",
-
".cpp" => "text/x-c",
-
".cpt" => "application/mac-compactpro",
-
".crd" => "application/x-mscardfile",
-
".crl" => "application/pkix-crl",
-
".crt" => "application/x-x509-ca-cert",
-
".csh" => "application/x-csh",
-
".csml" => "chemical/x-csml",
-
".csp" => "application/vnd.commonspace",
-
".css" => "text/css",
-
".csv" => "text/csv",
-
".curl" => "application/vnd.curl",
-
".cww" => "application/prs.cww",
-
".cxx" => "text/x-c",
-
".daf" => "application/vnd.mobius.daf",
-
".davmount" => "application/davmount+xml",
-
".dcr" => "application/x-director",
-
".dd2" => "application/vnd.oma.dd2+xml",
-
".ddd" => "application/vnd.fujixerox.ddd",
-
".deb" => "application/x-debian-package",
-
".der" => "application/x-x509-ca-cert",
-
".dfac" => "application/vnd.dreamfactory",
-
".diff" => "text/x-diff",
-
".dis" => "application/vnd.mobius.dis",
-
".djv" => "image/vnd.djvu",
-
".djvu" => "image/vnd.djvu",
-
".dll" => "application/x-msdownload",
-
".dmg" => "application/octet-stream",
-
".dna" => "application/vnd.dna",
-
".doc" => "application/msword",
-
".docx" => "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
-
".dot" => "application/msword",
-
".dp" => "application/vnd.osgi.dp",
-
".dpg" => "application/vnd.dpgraph",
-
".dsc" => "text/prs.lines.tag",
-
".dtd" => "application/xml-dtd",
-
".dts" => "audio/vnd.dts",
-
".dtshd" => "audio/vnd.dts.hd",
-
".dv" => "video/x-dv",
-
".dvi" => "application/x-dvi",
-
".dwf" => "model/vnd.dwf",
-
".dwg" => "image/vnd.dwg",
-
".dxf" => "image/vnd.dxf",
-
".dxp" => "application/vnd.spotfire.dxp",
-
".ear" => "application/java-archive",
-
".ecelp4800" => "audio/vnd.nuera.ecelp4800",
-
".ecelp7470" => "audio/vnd.nuera.ecelp7470",
-
".ecelp9600" => "audio/vnd.nuera.ecelp9600",
-
".ecma" => "application/ecmascript",
-
".edm" => "application/vnd.novadigm.edm",
-
".edx" => "application/vnd.novadigm.edx",
-
".efif" => "application/vnd.picsel",
-
".ei6" => "application/vnd.pg.osasli",
-
".eml" => "message/rfc822",
-
".eol" => "audio/vnd.digital-winds",
-
".eot" => "application/vnd.ms-fontobject",
-
".eps" => "application/postscript",
-
".es3" => "application/vnd.eszigno3+xml",
-
".esf" => "application/vnd.epson.esf",
-
".etx" => "text/x-setext",
-
".exe" => "application/x-msdownload",
-
".ext" => "application/vnd.novadigm.ext",
-
".ez" => "application/andrew-inset",
-
".ez2" => "application/vnd.ezpix-album",
-
".ez3" => "application/vnd.ezpix-package",
-
".f" => "text/x-fortran",
-
".f77" => "text/x-fortran",
-
".f90" => "text/x-fortran",
-
".fbs" => "image/vnd.fastbidsheet",
-
".fdf" => "application/vnd.fdf",
-
".fe_launch" => "application/vnd.denovo.fcselayout-link",
-
".fg5" => "application/vnd.fujitsu.oasysgp",
-
".fli" => "video/x-fli",
-
".flo" => "application/vnd.micrografx.flo",
-
".flv" => "video/x-flv",
-
".flw" => "application/vnd.kde.kivio",
-
".flx" => "text/vnd.fmi.flexstor",
-
".fly" => "text/vnd.fly",
-
".fm" => "application/vnd.framemaker",
-
".fnc" => "application/vnd.frogans.fnc",
-
".for" => "text/x-fortran",
-
".fpx" => "image/vnd.fpx",
-
".fsc" => "application/vnd.fsc.weblaunch",
-
".fst" => "image/vnd.fst",
-
".ftc" => "application/vnd.fluxtime.clip",
-
".fti" => "application/vnd.anser-web-funds-transfer-initiation",
-
".fvt" => "video/vnd.fvt",
-
".fzs" => "application/vnd.fuzzysheet",
-
".g3" => "image/g3fax",
-
".gac" => "application/vnd.groove-account",
-
".gdl" => "model/vnd.gdl",
-
".gem" => "application/octet-stream",
-
".gemspec" => "text/x-script.ruby",
-
".ghf" => "application/vnd.groove-help",
-
".gif" => "image/gif",
-
".gim" => "application/vnd.groove-identity-message",
-
".gmx" => "application/vnd.gmx",
-
".gph" => "application/vnd.flographit",
-
".gqf" => "application/vnd.grafeq",
-
".gram" => "application/srgs",
-
".grv" => "application/vnd.groove-injector",
-
".grxml" => "application/srgs+xml",
-
".gtar" => "application/x-gtar",
-
".gtm" => "application/vnd.groove-tool-message",
-
".gtw" => "model/vnd.gtw",
-
".gv" => "text/vnd.graphviz",
-
".gz" => "application/x-gzip",
-
".h" => "text/x-c",
-
".h261" => "video/h261",
-
".h263" => "video/h263",
-
".h264" => "video/h264",
-
".hbci" => "application/vnd.hbci",
-
".hdf" => "application/x-hdf",
-
".hh" => "text/x-c",
-
".hlp" => "application/winhlp",
-
".hpgl" => "application/vnd.hp-hpgl",
-
".hpid" => "application/vnd.hp-hpid",
-
".hps" => "application/vnd.hp-hps",
-
".hqx" => "application/mac-binhex40",
-
".htc" => "text/x-component",
-
".htke" => "application/vnd.kenameaapp",
-
".htm" => "text/html",
-
".html" => "text/html",
-
".hvd" => "application/vnd.yamaha.hv-dic",
-
".hvp" => "application/vnd.yamaha.hv-voice",
-
".hvs" => "application/vnd.yamaha.hv-script",
-
".icc" => "application/vnd.iccprofile",
-
".ice" => "x-conference/x-cooltalk",
-
".ico" => "image/vnd.microsoft.icon",
-
".ics" => "text/calendar",
-
".ief" => "image/ief",
-
".ifb" => "text/calendar",
-
".ifm" => "application/vnd.shana.informed.formdata",
-
".igl" => "application/vnd.igloader",
-
".igs" => "model/iges",
-
".igx" => "application/vnd.micrografx.igx",
-
".iif" => "application/vnd.shana.informed.interchange",
-
".imp" => "application/vnd.accpac.simply.imp",
-
".ims" => "application/vnd.ms-ims",
-
".ipk" => "application/vnd.shana.informed.package",
-
".irm" => "application/vnd.ibm.rights-management",
-
".irp" => "application/vnd.irepository.package+xml",
-
".iso" => "application/octet-stream",
-
".itp" => "application/vnd.shana.informed.formtemplate",
-
".ivp" => "application/vnd.immervision-ivp",
-
".ivu" => "application/vnd.immervision-ivu",
-
".jad" => "text/vnd.sun.j2me.app-descriptor",
-
".jam" => "application/vnd.jam",
-
".jar" => "application/java-archive",
-
".java" => "text/x-java-source",
-
".jisp" => "application/vnd.jisp",
-
".jlt" => "application/vnd.hp-jlyt",
-
".jnlp" => "application/x-java-jnlp-file",
-
".joda" => "application/vnd.joost.joda-archive",
-
".jp2" => "image/jp2",
-
".jpeg" => "image/jpeg",
-
".jpg" => "image/jpeg",
-
".jpgv" => "video/jpeg",
-
".jpm" => "video/jpm",
-
".js" => "application/javascript",
-
".json" => "application/json",
-
".karbon" => "application/vnd.kde.karbon",
-
".kfo" => "application/vnd.kde.kformula",
-
".kia" => "application/vnd.kidspiration",
-
".kml" => "application/vnd.google-earth.kml+xml",
-
".kmz" => "application/vnd.google-earth.kmz",
-
".kne" => "application/vnd.kinar",
-
".kon" => "application/vnd.kde.kontour",
-
".kpr" => "application/vnd.kde.kpresenter",
-
".ksp" => "application/vnd.kde.kspread",
-
".ktz" => "application/vnd.kahootz",
-
".kwd" => "application/vnd.kde.kword",
-
".latex" => "application/x-latex",
-
".lbd" => "application/vnd.llamagraphics.life-balance.desktop",
-
".lbe" => "application/vnd.llamagraphics.life-balance.exchange+xml",
-
".les" => "application/vnd.hhe.lesson-player",
-
".link66" => "application/vnd.route66.link66+xml",
-
".log" => "text/plain",
-
".lostxml" => "application/lost+xml",
-
".lrm" => "application/vnd.ms-lrm",
-
".ltf" => "application/vnd.frogans.ltf",
-
".lvp" => "audio/vnd.lucent.voice",
-
".lwp" => "application/vnd.lotus-wordpro",
-
".m3u" => "audio/x-mpegurl",
-
".m4a" => "audio/mp4a-latm",
-
".m4v" => "video/mp4",
-
".ma" => "application/mathematica",
-
".mag" => "application/vnd.ecowin.chart",
-
".man" => "text/troff",
-
".manifest" => "text/cache-manifest",
-
".mathml" => "application/mathml+xml",
-
".mbk" => "application/vnd.mobius.mbk",
-
".mbox" => "application/mbox",
-
".mc1" => "application/vnd.medcalcdata",
-
".mcd" => "application/vnd.mcd",
-
".mdb" => "application/x-msaccess",
-
".mdi" => "image/vnd.ms-modi",
-
".mdoc" => "text/troff",
-
".me" => "text/troff",
-
".mfm" => "application/vnd.mfmp",
-
".mgz" => "application/vnd.proteus.magazine",
-
".mid" => "audio/midi",
-
".midi" => "audio/midi",
-
".mif" => "application/vnd.mif",
-
".mime" => "message/rfc822",
-
".mj2" => "video/mj2",
-
".mlp" => "application/vnd.dolby.mlp",
-
".mmd" => "application/vnd.chipnuts.karaoke-mmd",
-
".mmf" => "application/vnd.smaf",
-
".mml" => "application/mathml+xml",
-
".mmr" => "image/vnd.fujixerox.edmics-mmr",
-
".mng" => "video/x-mng",
-
".mny" => "application/x-msmoney",
-
".mov" => "video/quicktime",
-
".movie" => "video/x-sgi-movie",
-
".mp3" => "audio/mpeg",
-
".mp4" => "video/mp4",
-
".mp4a" => "audio/mp4",
-
".mp4s" => "application/mp4",
-
".mp4v" => "video/mp4",
-
".mpc" => "application/vnd.mophun.certificate",
-
".mpeg" => "video/mpeg",
-
".mpg" => "video/mpeg",
-
".mpga" => "audio/mpeg",
-
".mpkg" => "application/vnd.apple.installer+xml",
-
".mpm" => "application/vnd.blueice.multipass",
-
".mpn" => "application/vnd.mophun.application",
-
".mpp" => "application/vnd.ms-project",
-
".mpy" => "application/vnd.ibm.minipay",
-
".mqy" => "application/vnd.mobius.mqy",
-
".mrc" => "application/marc",
-
".ms" => "text/troff",
-
".mscml" => "application/mediaservercontrol+xml",
-
".mseq" => "application/vnd.mseq",
-
".msf" => "application/vnd.epson.msf",
-
".msh" => "model/mesh",
-
".msi" => "application/x-msdownload",
-
".msl" => "application/vnd.mobius.msl",
-
".msty" => "application/vnd.muvee.style",
-
".mts" => "model/vnd.mts",
-
".mus" => "application/vnd.musician",
-
".mvb" => "application/x-msmediaview",
-
".mwf" => "application/vnd.mfer",
-
".mxf" => "application/mxf",
-
".mxl" => "application/vnd.recordare.musicxml",
-
".mxml" => "application/xv+xml",
-
".mxs" => "application/vnd.triscape.mxs",
-
".mxu" => "video/vnd.mpegurl",
-
".n" => "application/vnd.nokia.n-gage.symbian.install",
-
".nc" => "application/x-netcdf",
-
".ngdat" => "application/vnd.nokia.n-gage.data",
-
".nlu" => "application/vnd.neurolanguage.nlu",
-
".nml" => "application/vnd.enliven",
-
".nnd" => "application/vnd.noblenet-directory",
-
".nns" => "application/vnd.noblenet-sealer",
-
".nnw" => "application/vnd.noblenet-web",
-
".npx" => "image/vnd.net-fpx",
-
".nsf" => "application/vnd.lotus-notes",
-
".oa2" => "application/vnd.fujitsu.oasys2",
-
".oa3" => "application/vnd.fujitsu.oasys3",
-
".oas" => "application/vnd.fujitsu.oasys",
-
".obd" => "application/x-msbinder",
-
".oda" => "application/oda",
-
".odc" => "application/vnd.oasis.opendocument.chart",
-
".odf" => "application/vnd.oasis.opendocument.formula",
-
".odg" => "application/vnd.oasis.opendocument.graphics",
-
".odi" => "application/vnd.oasis.opendocument.image",
-
".odp" => "application/vnd.oasis.opendocument.presentation",
-
".ods" => "application/vnd.oasis.opendocument.spreadsheet",
-
".odt" => "application/vnd.oasis.opendocument.text",
-
".oga" => "audio/ogg",
-
".ogg" => "application/ogg",
-
".ogv" => "video/ogg",
-
".ogx" => "application/ogg",
-
".org" => "application/vnd.lotus-organizer",
-
".otc" => "application/vnd.oasis.opendocument.chart-template",
-
".otf" => "application/vnd.oasis.opendocument.formula-template",
-
".otg" => "application/vnd.oasis.opendocument.graphics-template",
-
".oth" => "application/vnd.oasis.opendocument.text-web",
-
".oti" => "application/vnd.oasis.opendocument.image-template",
-
".otm" => "application/vnd.oasis.opendocument.text-master",
-
".ots" => "application/vnd.oasis.opendocument.spreadsheet-template",
-
".ott" => "application/vnd.oasis.opendocument.text-template",
-
".oxt" => "application/vnd.openofficeorg.extension",
-
".p" => "text/x-pascal",
-
".p10" => "application/pkcs10",
-
".p12" => "application/x-pkcs12",
-
".p7b" => "application/x-pkcs7-certificates",
-
".p7m" => "application/pkcs7-mime",
-
".p7r" => "application/x-pkcs7-certreqresp",
-
".p7s" => "application/pkcs7-signature",
-
".pas" => "text/x-pascal",
-
".pbd" => "application/vnd.powerbuilder6",
-
".pbm" => "image/x-portable-bitmap",
-
".pcl" => "application/vnd.hp-pcl",
-
".pclxl" => "application/vnd.hp-pclxl",
-
".pcx" => "image/x-pcx",
-
".pdb" => "chemical/x-pdb",
-
".pdf" => "application/pdf",
-
".pem" => "application/x-x509-ca-cert",
-
".pfr" => "application/font-tdpfr",
-
".pgm" => "image/x-portable-graymap",
-
".pgn" => "application/x-chess-pgn",
-
".pgp" => "application/pgp-encrypted",
-
".pic" => "image/x-pict",
-
".pict" => "image/pict",
-
".pkg" => "application/octet-stream",
-
".pki" => "application/pkixcmp",
-
".pkipath" => "application/pkix-pkipath",
-
".pl" => "text/x-script.perl",
-
".plb" => "application/vnd.3gpp.pic-bw-large",
-
".plc" => "application/vnd.mobius.plc",
-
".plf" => "application/vnd.pocketlearn",
-
".pls" => "application/pls+xml",
-
".pm" => "text/x-script.perl-module",
-
".pml" => "application/vnd.ctc-posml",
-
".png" => "image/png",
-
".pnm" => "image/x-portable-anymap",
-
".pntg" => "image/x-macpaint",
-
".portpkg" => "application/vnd.macports.portpkg",
-
".ppd" => "application/vnd.cups-ppd",
-
".ppm" => "image/x-portable-pixmap",
-
".pps" => "application/vnd.ms-powerpoint",
-
".ppt" => "application/vnd.ms-powerpoint",
-
".prc" => "application/vnd.palm",
-
".pre" => "application/vnd.lotus-freelance",
-
".prf" => "application/pics-rules",
-
".ps" => "application/postscript",
-
".psb" => "application/vnd.3gpp.pic-bw-small",
-
".psd" => "image/vnd.adobe.photoshop",
-
".ptid" => "application/vnd.pvi.ptid1",
-
".pub" => "application/x-mspublisher",
-
".pvb" => "application/vnd.3gpp.pic-bw-var",
-
".pwn" => "application/vnd.3m.post-it-notes",
-
".py" => "text/x-script.python",
-
".pya" => "audio/vnd.ms-playready.media.pya",
-
".pyv" => "video/vnd.ms-playready.media.pyv",
-
".qam" => "application/vnd.epson.quickanime",
-
".qbo" => "application/vnd.intu.qbo",
-
".qfx" => "application/vnd.intu.qfx",
-
".qps" => "application/vnd.publishare-delta-tree",
-
".qt" => "video/quicktime",
-
".qtif" => "image/x-quicktime",
-
".qxd" => "application/vnd.quark.quarkxpress",
-
".ra" => "audio/x-pn-realaudio",
-
".rake" => "text/x-script.ruby",
-
".ram" => "audio/x-pn-realaudio",
-
".rar" => "application/x-rar-compressed",
-
".ras" => "image/x-cmu-raster",
-
".rb" => "text/x-script.ruby",
-
".rcprofile" => "application/vnd.ipunplugged.rcprofile",
-
".rdf" => "application/rdf+xml",
-
".rdz" => "application/vnd.data-vision.rdz",
-
".rep" => "application/vnd.businessobjects",
-
".rgb" => "image/x-rgb",
-
".rif" => "application/reginfo+xml",
-
".rl" => "application/resource-lists+xml",
-
".rlc" => "image/vnd.fujixerox.edmics-rlc",
-
".rld" => "application/resource-lists-diff+xml",
-
".rm" => "application/vnd.rn-realmedia",
-
".rmp" => "audio/x-pn-realaudio-plugin",
-
".rms" => "application/vnd.jcp.javame.midlet-rms",
-
".rnc" => "application/relax-ng-compact-syntax",
-
".roff" => "text/troff",
-
".rpm" => "application/x-redhat-package-manager",
-
".rpss" => "application/vnd.nokia.radio-presets",
-
".rpst" => "application/vnd.nokia.radio-preset",
-
".rq" => "application/sparql-query",
-
".rs" => "application/rls-services+xml",
-
".rsd" => "application/rsd+xml",
-
".rss" => "application/rss+xml",
-
".rtf" => "application/rtf",
-
".rtx" => "text/richtext",
-
".ru" => "text/x-script.ruby",
-
".s" => "text/x-asm",
-
".saf" => "application/vnd.yamaha.smaf-audio",
-
".sbml" => "application/sbml+xml",
-
".sc" => "application/vnd.ibm.secure-container",
-
".scd" => "application/x-msschedule",
-
".scm" => "application/vnd.lotus-screencam",
-
".scq" => "application/scvp-cv-request",
-
".scs" => "application/scvp-cv-response",
-
".sdkm" => "application/vnd.solent.sdkm+xml",
-
".sdp" => "application/sdp",
-
".see" => "application/vnd.seemail",
-
".sema" => "application/vnd.sema",
-
".semd" => "application/vnd.semd",
-
".semf" => "application/vnd.semf",
-
".setpay" => "application/set-payment-initiation",
-
".setreg" => "application/set-registration-initiation",
-
".sfd" => "application/vnd.hydrostatix.sof-data",
-
".sfs" => "application/vnd.spotfire.sfs",
-
".sgm" => "text/sgml",
-
".sgml" => "text/sgml",
-
".sh" => "application/x-sh",
-
".shar" => "application/x-shar",
-
".shf" => "application/shf+xml",
-
".sig" => "application/pgp-signature",
-
".sit" => "application/x-stuffit",
-
".sitx" => "application/x-stuffitx",
-
".skp" => "application/vnd.koan",
-
".slt" => "application/vnd.epson.salt",
-
".smi" => "application/smil+xml",
-
".snd" => "audio/basic",
-
".so" => "application/octet-stream",
-
".spf" => "application/vnd.yamaha.smaf-phrase",
-
".spl" => "application/x-futuresplash",
-
".spot" => "text/vnd.in3d.spot",
-
".spp" => "application/scvp-vp-response",
-
".spq" => "application/scvp-vp-request",
-
".src" => "application/x-wais-source",
-
".srx" => "application/sparql-results+xml",
-
".sse" => "application/vnd.kodak-descriptor",
-
".ssf" => "application/vnd.epson.ssf",
-
".ssml" => "application/ssml+xml",
-
".stf" => "application/vnd.wt.stf",
-
".stk" => "application/hyperstudio",
-
".str" => "application/vnd.pg.format",
-
".sus" => "application/vnd.sus-calendar",
-
".sv4cpio" => "application/x-sv4cpio",
-
".sv4crc" => "application/x-sv4crc",
-
".svd" => "application/vnd.svd",
-
".svg" => "image/svg+xml",
-
".svgz" => "image/svg+xml",
-
".swf" => "application/x-shockwave-flash",
-
".swi" => "application/vnd.arastra.swi",
-
".t" => "text/troff",
-
".tao" => "application/vnd.tao.intent-module-archive",
-
".tar" => "application/x-tar",
-
".tbz" => "application/x-bzip-compressed-tar",
-
".tcap" => "application/vnd.3gpp2.tcap",
-
".tcl" => "application/x-tcl",
-
".tex" => "application/x-tex",
-
".texi" => "application/x-texinfo",
-
".texinfo" => "application/x-texinfo",
-
".text" => "text/plain",
-
".tif" => "image/tiff",
-
".tiff" => "image/tiff",
-
".tmo" => "application/vnd.tmobile-livetv",
-
".torrent" => "application/x-bittorrent",
-
".tpl" => "application/vnd.groove-tool-template",
-
".tpt" => "application/vnd.trid.tpt",
-
".tr" => "text/troff",
-
".tra" => "application/vnd.trueapp",
-
".trm" => "application/x-msterminal",
-
".tsv" => "text/tab-separated-values",
-
".ttf" => "application/octet-stream",
-
".twd" => "application/vnd.simtech-mindmapper",
-
".txd" => "application/vnd.genomatix.tuxedo",
-
".txf" => "application/vnd.mobius.txf",
-
".txt" => "text/plain",
-
".ufd" => "application/vnd.ufdl",
-
".umj" => "application/vnd.umajin",
-
".unityweb" => "application/vnd.unity",
-
".uoml" => "application/vnd.uoml+xml",
-
".uri" => "text/uri-list",
-
".ustar" => "application/x-ustar",
-
".utz" => "application/vnd.uiq.theme",
-
".uu" => "text/x-uuencode",
-
".vcd" => "application/x-cdlink",
-
".vcf" => "text/x-vcard",
-
".vcg" => "application/vnd.groove-vcard",
-
".vcs" => "text/x-vcalendar",
-
".vcx" => "application/vnd.vcx",
-
".vis" => "application/vnd.visionary",
-
".viv" => "video/vnd.vivo",
-
".vrml" => "model/vrml",
-
".vsd" => "application/vnd.visio",
-
".vsf" => "application/vnd.vsf",
-
".vtu" => "model/vnd.vtu",
-
".vxml" => "application/voicexml+xml",
-
".war" => "application/java-archive",
-
".wav" => "audio/x-wav",
-
".wax" => "audio/x-ms-wax",
-
".wbmp" => "image/vnd.wap.wbmp",
-
".wbs" => "application/vnd.criticaltools.wbs+xml",
-
".wbxml" => "application/vnd.wap.wbxml",
-
".webm" => "video/webm",
-
".wm" => "video/x-ms-wm",
-
".wma" => "audio/x-ms-wma",
-
".wmd" => "application/x-ms-wmd",
-
".wmf" => "application/x-msmetafile",
-
".wml" => "text/vnd.wap.wml",
-
".wmlc" => "application/vnd.wap.wmlc",
-
".wmls" => "text/vnd.wap.wmlscript",
-
".wmlsc" => "application/vnd.wap.wmlscriptc",
-
".wmv" => "video/x-ms-wmv",
-
".wmx" => "video/x-ms-wmx",
-
".wmz" => "application/x-ms-wmz",
-
".woff" => "application/font-woff",
-
".wpd" => "application/vnd.wordperfect",
-
".wpl" => "application/vnd.ms-wpl",
-
".wps" => "application/vnd.ms-works",
-
".wqd" => "application/vnd.wqd",
-
".wri" => "application/x-mswrite",
-
".wrl" => "model/vrml",
-
".wsdl" => "application/wsdl+xml",
-
".wspolicy" => "application/wspolicy+xml",
-
".wtb" => "application/vnd.webturbo",
-
".wvx" => "video/x-ms-wvx",
-
".x3d" => "application/vnd.hzn-3d-crossword",
-
".xar" => "application/vnd.xara",
-
".xbd" => "application/vnd.fujixerox.docuworks.binder",
-
".xbm" => "image/x-xbitmap",
-
".xdm" => "application/vnd.syncml.dm+xml",
-
".xdp" => "application/vnd.adobe.xdp+xml",
-
".xdw" => "application/vnd.fujixerox.docuworks",
-
".xenc" => "application/xenc+xml",
-
".xer" => "application/patch-ops-error+xml",
-
".xfdf" => "application/vnd.adobe.xfdf",
-
".xfdl" => "application/vnd.xfdl",
-
".xhtml" => "application/xhtml+xml",
-
".xif" => "image/vnd.xiff",
-
".xls" => "application/vnd.ms-excel",
-
".xlsx" => "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
-
".xml" => "application/xml",
-
".xo" => "application/vnd.olpc-sugar",
-
".xop" => "application/xop+xml",
-
".xpm" => "image/x-xpixmap",
-
".xpr" => "application/vnd.is-xpr",
-
".xps" => "application/vnd.ms-xpsdocument",
-
".xpw" => "application/vnd.intercon.formnet",
-
".xsl" => "application/xml",
-
".xslt" => "application/xslt+xml",
-
".xsm" => "application/vnd.syncml+xml",
-
".xspf" => "application/xspf+xml",
-
".xul" => "application/vnd.mozilla.xul+xml",
-
".xwd" => "image/x-xwindowdump",
-
".xyz" => "chemical/x-xyz",
-
".yaml" => "text/yaml",
-
".yml" => "text/yaml",
-
".zaz" => "application/vnd.zzazz.deck+xml",
-
".zip" => "application/zip",
-
".zmm" => "application/vnd.handheld-entertainment+xml",
-
}
-
end
-
end
-
2
require 'uri'
-
2
require 'stringio'
-
2
require 'rack'
-
2
require 'rack/lint'
-
2
require 'rack/utils'
-
2
require 'rack/response'
-
-
2
module Rack
-
# Rack::MockRequest helps testing your Rack application without
-
# actually using HTTP.
-
#
-
# After performing a request on a URL with get/post/put/patch/delete, it
-
# returns a MockResponse with useful helper methods for effective
-
# testing.
-
#
-
# You can pass a hash with additional configuration to the
-
# get/post/put/patch/delete.
-
# <tt>:input</tt>:: A String or IO-like to be used as rack.input.
-
# <tt>:fatal</tt>:: Raise a FatalWarning if the app writes to rack.errors.
-
# <tt>:lint</tt>:: If true, wrap the application in a Rack::Lint.
-
-
2
class MockRequest
-
2
class FatalWarning < RuntimeError
-
end
-
-
2
class FatalWarner
-
2
def puts(warning)
-
raise FatalWarning, warning
-
end
-
-
2
def write(warning)
-
raise FatalWarning, warning
-
end
-
-
2
def flush
-
end
-
-
2
def string
-
""
-
end
-
end
-
-
2
DEFAULT_ENV = {
-
"rack.version" => Rack::VERSION,
-
"rack.input" => StringIO.new,
-
"rack.errors" => StringIO.new,
-
"rack.multithread" => true,
-
"rack.multiprocess" => true,
-
"rack.run_once" => false,
-
}
-
-
2
def initialize(app)
-
@app = app
-
end
-
-
2
def get(uri, opts={}) request("GET", uri, opts) end
-
2
def post(uri, opts={}) request("POST", uri, opts) end
-
2
def put(uri, opts={}) request("PUT", uri, opts) end
-
2
def patch(uri, opts={}) request("PATCH", uri, opts) end
-
2
def delete(uri, opts={}) request("DELETE", uri, opts) end
-
2
def head(uri, opts={}) request("HEAD", uri, opts) end
-
-
2
def request(method="GET", uri="", opts={})
-
env = self.class.env_for(uri, opts.merge(:method => method))
-
-
if opts[:lint]
-
app = Rack::Lint.new(@app)
-
else
-
app = @app
-
end
-
-
errors = env["rack.errors"]
-
status, headers, body = app.call(env)
-
MockResponse.new(status, headers, body, errors)
-
ensure
-
body.close if body.respond_to?(:close)
-
end
-
-
# Return the Rack environment used for a request to +uri+.
-
2
def self.env_for(uri="", opts={})
-
15
uri = URI(uri)
-
15
uri.path = "/#{uri.path}" unless uri.path[0] == ?/
-
-
15
env = DEFAULT_ENV.dup
-
-
15
env["REQUEST_METHOD"] = opts[:method] ? opts[:method].to_s.upcase : "GET"
-
15
env["SERVER_NAME"] = uri.host || "example.org"
-
15
env["SERVER_PORT"] = uri.port ? uri.port.to_s : "80"
-
15
env["QUERY_STRING"] = uri.query.to_s
-
15
env["PATH_INFO"] = (!uri.path || uri.path.empty?) ? "/" : uri.path
-
15
env["rack.url_scheme"] = uri.scheme || "http"
-
15
env["HTTPS"] = env["rack.url_scheme"] == "https" ? "on" : "off"
-
-
15
env["SCRIPT_NAME"] = opts[:script_name] || ""
-
-
15
if opts[:fatal]
-
env["rack.errors"] = FatalWarner.new
-
else
-
15
env["rack.errors"] = StringIO.new
-
end
-
-
15
if params = opts[:params]
-
if env["REQUEST_METHOD"] == "GET"
-
params = Utils.parse_nested_query(params) if params.is_a?(String)
-
params.update(Utils.parse_nested_query(env["QUERY_STRING"]))
-
env["QUERY_STRING"] = Utils.build_nested_query(params)
-
elsif !opts.has_key?(:input)
-
opts["CONTENT_TYPE"] = "application/x-www-form-urlencoded"
-
if params.is_a?(Hash)
-
if data = Utils::Multipart.build_multipart(params)
-
opts[:input] = data
-
opts["CONTENT_LENGTH"] ||= data.length.to_s
-
opts["CONTENT_TYPE"] = "multipart/form-data; boundary=#{Utils::Multipart::MULTIPART_BOUNDARY}"
-
else
-
opts[:input] = Utils.build_nested_query(params)
-
end
-
else
-
opts[:input] = params
-
end
-
end
-
end
-
-
15
empty_str = ""
-
15
empty_str.force_encoding("ASCII-8BIT") if empty_str.respond_to? :force_encoding
-
15
opts[:input] ||= empty_str
-
15
if String === opts[:input]
-
15
rack_input = StringIO.new(opts[:input])
-
else
-
rack_input = opts[:input]
-
end
-
-
15
rack_input.set_encoding(Encoding::BINARY) if rack_input.respond_to?(:set_encoding)
-
15
env['rack.input'] = rack_input
-
-
15
env["CONTENT_LENGTH"] ||= env["rack.input"].length.to_s
-
-
15
opts.each { |field, value|
-
99
env[field] = value if String === field
-
}
-
-
15
env
-
end
-
end
-
-
# Rack::MockResponse provides useful helpers for testing your apps.
-
# Usually, you don't create the MockResponse on your own, but use
-
# MockRequest.
-
-
2
class MockResponse < Rack::Response
-
# Headers
-
2
attr_reader :original_headers
-
-
# Errors
-
2
attr_accessor :errors
-
-
2
def initialize(status, headers, body, errors=StringIO.new(""))
-
13
@original_headers = headers
-
13
@errors = errors.string if errors.respond_to?(:string)
-
13
@body_string = nil
-
-
13
super(body, status, headers)
-
end
-
-
2
def =~(other)
-
body =~ other
-
end
-
-
2
def match(other)
-
body.match other
-
end
-
-
2
def body
-
# FIXME: apparently users of MockResponse expect the return value of
-
# MockResponse#body to be a string. However, the real response object
-
# returns the body as a list.
-
#
-
# See spec_showstatus.rb:
-
#
-
# should "not replace existing messages" do
-
# ...
-
# res.body.should == "foo!"
-
# end
-
7
super.join
-
end
-
-
2
def empty?
-
[201, 204, 205, 304].include? status
-
end
-
end
-
end
-
2
module Rack
-
# A multipart form data parser, adapted from IOWA.
-
#
-
# Usually, Rack::Request#POST takes care of calling this.
-
2
module Multipart
-
2
autoload :UploadedFile, 'rack/multipart/uploaded_file'
-
2
autoload :Parser, 'rack/multipart/parser'
-
2
autoload :Generator, 'rack/multipart/generator'
-
-
2
EOL = "\r\n"
-
2
MULTIPART_BOUNDARY = "AaB03x"
-
2
MULTIPART = %r|\Amultipart/.*boundary=\"?([^\";,]+)\"?|n
-
2
TOKEN = /[^\s()<>,;:\\"\/\[\]?=]+/
-
2
CONDISP = /Content-Disposition:\s*#{TOKEN}\s*/i
-
2
DISPPARM = /;\s*(#{TOKEN})=("(?:\\"|[^"])*"|#{TOKEN})/
-
2
RFC2183 = /^#{CONDISP}(#{DISPPARM})+$/i
-
2
BROKEN_QUOTED = /^#{CONDISP}.*;\sfilename="(.*?)"(?:\s*$|\s*;\s*#{TOKEN}=)/i
-
2
BROKEN_UNQUOTED = /^#{CONDISP}.*;\sfilename=(#{TOKEN})/i
-
2
MULTIPART_CONTENT_TYPE = /Content-Type: (.*)#{EOL}/ni
-
2
MULTIPART_CONTENT_DISPOSITION = /Content-Disposition:.*\s+name="?([^\";]*)"?/ni
-
2
MULTIPART_CONTENT_ID = /Content-ID:\s*([^#{EOL}]*)/ni
-
-
2
class << self
-
2
def parse_multipart(env)
-
4
Parser.new(env).parse
-
end
-
-
2
def build_multipart(params, first = true)
-
Generator.new(params, first).dump
-
end
-
end
-
-
end
-
end
-
1
require 'rack/utils'
-
-
1
module Rack
-
1
module Multipart
-
1
class MultipartLimitError < Errno::EMFILE; end
-
-
1
class Parser
-
1
BUFSIZE = 16384
-
-
1
def initialize(env)
-
4
@env = env
-
end
-
-
1
def parse
-
4
return nil unless setup_parse
-
-
2
fast_forward_to_first_boundary
-
-
2
opened_files = 0
-
2
loop do
-
-
18
head, filename, content_type, name, body =
-
get_current_head_and_filename_and_content_type_and_name_and_body
-
-
18
if Utils.multipart_part_limit > 0
-
18
opened_files += 1 if filename
-
18
raise MultipartLimitError, 'Maximum file multiparts in content reached' if opened_files >= Utils.multipart_part_limit
-
end
-
-
# Save the rest.
-
18
if i = @buf.index(rx)
-
18
body << @buf.slice!(0, i)
-
18
@buf.slice!(0, @boundary_size+2)
-
-
18
@content_length = -1 if $1 == "--"
-
end
-
-
18
filename, data = get_data(filename, body, content_type, name, head)
-
-
18
Utils.normalize_params(@params, name, data) unless data.nil?
-
-
# break if we're at the end of a buffer, but not if it is the end of a field
-
18
break if (@buf.empty? && $1 != EOL) || @content_length == -1
-
end
-
-
2
@io.rewind
-
-
2
@params.to_params_hash
-
end
-
-
1
private
-
1
def setup_parse
-
4
return false unless @env['CONTENT_TYPE'] =~ MULTIPART
-
-
2
@boundary = "--#{$1}"
-
-
2
@buf = ""
-
2
@params = Utils::KeySpaceConstrainedParams.new
-
-
2
@io = @env['rack.input']
-
2
@io.rewind
-
-
2
@boundary_size = Utils.bytesize(@boundary) + EOL.size
-
-
2
if @content_length = @env['CONTENT_LENGTH']
-
2
@content_length = @content_length.to_i
-
2
@content_length -= @boundary_size
-
end
-
2
true
-
end
-
-
1
def full_boundary
-
2
@boundary + EOL
-
end
-
-
1
def rx
-
36
@rx ||= /(?:#{EOL})?#{Regexp.quote(@boundary)}(#{EOL}|--)/n
-
end
-
-
1
def fast_forward_to_first_boundary
-
2
loop do
-
2
content = @io.read(BUFSIZE)
-
2
raise EOFError, "bad content body" unless content
-
2
@buf << content
-
-
2
while @buf.gsub!(/\A([^\n]*\n)/, '')
-
2
read_buffer = $1
-
2
return if read_buffer == full_boundary
-
end
-
-
raise EOFError, "bad content body" if Utils.bytesize(@buf) >= BUFSIZE
-
end
-
end
-
-
1
def get_current_head_and_filename_and_content_type_and_name_and_body
-
18
head = nil
-
18
body = ''
-
18
filename = content_type = name = nil
-
18
content = nil
-
-
18
until head && @buf =~ rx
-
18
if !head && i = @buf.index(EOL+EOL)
-
18
head = @buf.slice!(0, i+2) # First \r\n
-
-
18
@buf.slice!(0, 2) # Second \r\n
-
-
18
content_type = head[MULTIPART_CONTENT_TYPE, 1]
-
18
name = head[MULTIPART_CONTENT_DISPOSITION, 1] || head[MULTIPART_CONTENT_ID, 1]
-
-
18
filename = get_filename(head)
-
-
18
if filename
-
2
body = Tempfile.new("RackMultipart")
-
2
body.binmode if body.respond_to?(:binmode)
-
end
-
-
18
next
-
end
-
-
# Save the read body part.
-
if head && (@boundary_size+4 < @buf.size)
-
body << @buf.slice!(0, @buf.size - (@boundary_size+4))
-
end
-
-
content = @io.read(@content_length && BUFSIZE >= @content_length ? @content_length : BUFSIZE)
-
raise EOFError, "bad content body" if content.nil? || content.empty?
-
-
@buf << content
-
@content_length -= content.size if @content_length
-
end
-
-
18
[head, filename, content_type, name, body]
-
end
-
-
1
def get_filename(head)
-
18
filename = nil
-
18
if head =~ RFC2183
-
filename = Hash[head.scan(DISPPARM)]['filename']
-
filename = $1 if filename and filename =~ /^"(.*)"$/
-
elsif head =~ BROKEN_QUOTED
-
2
filename = $1
-
elsif head =~ BROKEN_UNQUOTED
-
filename = $1
-
end
-
-
18
if filename && filename.scan(/%.?.?/).all? { |s| s =~ /%[0-9a-fA-F]{2}/ }
-
2
filename = Utils.unescape(filename)
-
end
-
18
if filename && filename !~ /\\[^\\"]/
-
2
filename = filename.gsub(/\\(.)/, '\1')
-
end
-
18
filename
-
end
-
-
1
def get_data(filename, body, content_type, name, head)
-
18
data = nil
-
18
if filename == ""
-
# filename is blank which means no file has been selected
-
2
return data
-
elsif filename
-
body.rewind
-
-
# Take the basename of the upload's original filename.
-
# This handles the full Windows paths given by Internet Explorer
-
# (and perhaps other broken user agents) without affecting
-
# those which give the lone filename.
-
filename = filename.split(/[\/\\]/).last
-
-
data = {:filename => filename, :type => content_type,
-
:name => name, :tempfile => body, :head => head}
-
elsif !filename && content_type && body.is_a?(IO)
-
body.rewind
-
-
# Generic multipart cases, not coming from a form
-
data = {:type => content_type,
-
:name => name, :tempfile => body, :head => head}
-
else
-
16
data = body
-
end
-
-
16
[filename, data]
-
end
-
end
-
end
-
end
-
2
require 'rack/utils'
-
-
2
module Rack
-
# Rack::Request provides a convenient interface to a Rack
-
# environment. It is stateless, the environment +env+ passed to the
-
# constructor will be directly modified.
-
#
-
# req = Rack::Request.new(env)
-
# req.post?
-
# req.params["data"]
-
#
-
# The environment hash passed will store a reference to the Request object
-
# instantiated so that it will only instantiate if an instance of the Request
-
# object doesn't already exist.
-
-
2
class Request
-
# The environment of the request.
-
2
attr_reader :env
-
-
2
def initialize(env)
-
99
@env = env
-
end
-
-
2
def body; @env["rack.input"] end
-
110
def script_name; @env["SCRIPT_NAME"].to_s end
-
90
def path_info; @env["PATH_INFO"].to_s end
-
2
def request_method; @env["REQUEST_METHOD"] end
-
85
def query_string; @env["QUERY_STRING"].to_s end
-
15
def content_length; @env['CONTENT_LENGTH'] end
-
-
2
def content_type
-
8
content_type = @env['CONTENT_TYPE']
-
8
content_type.nil? || content_type.empty? ? nil : content_type
-
end
-
-
109
def session; @env['rack.session'] ||= {} end
-
2
def session_options; @env['rack.session.options'] ||= {} end
-
2
def logger; @env['rack.logger'] end
-
-
# The media type (type/subtype) portion of the CONTENT_TYPE header
-
# without any media type parameters. e.g., when CONTENT_TYPE is
-
# "text/plain;charset=utf-8", the media-type is "text/plain".
-
#
-
# For more information on the use of media types in HTTP, see:
-
# http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.7
-
2
def media_type
-
4
content_type && content_type.split(/\s*[;,]\s*/, 2).first.downcase
-
end
-
-
# The media type parameters provided in CONTENT_TYPE as a Hash, or
-
# an empty Hash if no CONTENT_TYPE or media-type parameters were
-
# provided. e.g., when the CONTENT_TYPE is "text/plain;charset=utf-8",
-
# this method responds with the following Hash:
-
# { 'charset' => 'utf-8' }
-
2
def media_type_params
-
return {} if content_type.nil?
-
Hash[*content_type.split(/\s*[;,]\s*/)[1..-1].
-
collect { |s| s.split('=', 2) }.
-
map { |k,v| [k.downcase, v] }.flatten]
-
end
-
-
# The character set of the request body if a "charset" media type
-
# parameter was given, or nil if no "charset" was specified. Note
-
# that, per RFC2616, text/* media types that specify no explicit
-
# charset are to be considered ISO-8859-1.
-
2
def content_charset
-
media_type_params['charset']
-
end
-
-
2
def scheme
-
62
if @env['HTTPS'] == 'on'
-
'https'
-
62
elsif @env['HTTP_X_FORWARDED_SSL'] == 'on'
-
'https'
-
62
elsif @env['HTTP_X_FORWARDED_SCHEME']
-
@env['HTTP_X_FORWARDED_SCHEME']
-
62
elsif @env['HTTP_X_FORWARDED_PROTO']
-
@env['HTTP_X_FORWARDED_PROTO'].split(',')[0]
-
else
-
62
@env["rack.url_scheme"]
-
end
-
end
-
-
2
def ssl?
-
48
scheme == 'https'
-
end
-
-
2
def host_with_port
-
14
if forwarded = @env["HTTP_X_FORWARDED_HOST"]
-
forwarded.split(/,\s?/).last
-
else
-
14
@env['HTTP_HOST'] || "#{@env['SERVER_NAME'] || @env['SERVER_ADDR']}:#{@env['SERVER_PORT']}"
-
end
-
end
-
-
2
def port
-
7
if port = host_with_port.split(/:/)[1]
-
port.to_i
-
7
elsif port = @env['HTTP_X_FORWARDED_PORT']
-
port.to_i
-
7
elsif @env.has_key?("HTTP_X_FORWARDED_HOST")
-
DEFAULT_PORTS[scheme]
-
7
elsif @env.has_key?("HTTP_X_FORWARDED_PROTO")
-
DEFAULT_PORTS[@env['HTTP_X_FORWARDED_PROTO']]
-
else
-
7
@env["SERVER_PORT"].to_i
-
end
-
end
-
-
2
def host
-
# Remove port number.
-
7
host_with_port.to_s.gsub(/:\d+\z/, '')
-
end
-
-
2
def script_name=(s); @env["SCRIPT_NAME"] = s.to_s end
-
2
def path_info=(s); @env["PATH_INFO"] = s.to_s end
-
-
-
# Checks the HTTP request method (or verb) to see if it was of type DELETE
-
2
def delete?; request_method == "DELETE" end
-
-
# Checks the HTTP request method (or verb) to see if it was of type GET
-
2
def get?; request_method == "GET" end
-
-
# Checks the HTTP request method (or verb) to see if it was of type HEAD
-
2
def head?; request_method == "HEAD" end
-
-
# Checks the HTTP request method (or verb) to see if it was of type OPTIONS
-
2
def options?; request_method == "OPTIONS" end
-
-
# Checks the HTTP request method (or verb) to see if it was of type PATCH
-
2
def patch?; request_method == "PATCH" end
-
-
# Checks the HTTP request method (or verb) to see if it was of type POST
-
2
def post?; request_method == "POST" end
-
-
# Checks the HTTP request method (or verb) to see if it was of type PUT
-
2
def put?; request_method == "PUT" end
-
-
# Checks the HTTP request method (or verb) to see if it was of type TRACE
-
2
def trace?; request_method == "TRACE" end
-
-
-
# The set of form-data media-types. Requests that do not indicate
-
# one of the media types presents in this list will not be eligible
-
# for form-data / param parsing.
-
2
FORM_DATA_MEDIA_TYPES = [
-
'application/x-www-form-urlencoded',
-
'multipart/form-data'
-
]
-
-
# The set of media-types. Requests that do not indicate
-
# one of the media types presents in this list will not be eligible
-
# for param parsing like soap attachments or generic multiparts
-
2
PARSEABLE_DATA_MEDIA_TYPES = [
-
'multipart/related',
-
'multipart/mixed'
-
]
-
-
# Default ports depending on scheme. Used to decide whether or not
-
# to include the port in a generated URI.
-
2
DEFAULT_PORTS = { 'http' => 80, 'https' => 443, 'coffee' => 80 }
-
-
# Determine whether the request body contains form-data by checking
-
# the request Content-Type for one of the media-types:
-
# "application/x-www-form-urlencoded" or "multipart/form-data". The
-
# list of form-data media types can be modified through the
-
# +FORM_DATA_MEDIA_TYPES+ array.
-
#
-
# A request body is also assumed to contain form-data when no
-
# Content-Type header is provided and the request_method is POST.
-
2
def form_data?
-
4
type = media_type
-
4
meth = env["rack.methodoverride.original_method"] || env['REQUEST_METHOD']
-
4
(meth == 'POST' && type.nil?) || FORM_DATA_MEDIA_TYPES.include?(type)
-
end
-
-
# Determine whether the request body contains data by checking
-
# the request media_type against registered parse-data media-types
-
2
def parseable_data?
-
20
PARSEABLE_DATA_MEDIA_TYPES.include?(media_type)
-
end
-
-
# Returns the data received in the query string.
-
2
def GET
-
13
if @env["rack.request.query_string"] == query_string
-
@env["rack.request.query_hash"]
-
else
-
13
@env["rack.request.query_string"] = query_string
-
13
@env["rack.request.query_hash"] = parse_query(query_string)
-
end
-
end
-
-
# Returns the data received in the request body.
-
#
-
# This method support both application/x-www-form-urlencoded and
-
# multipart/form-data.
-
2
def POST
-
28
if @env["rack.input"].nil?
-
raise "Missing rack.input"
-
28
elsif @env["rack.request.form_input"].equal? @env["rack.input"]
-
4
@env["rack.request.form_hash"]
-
24
elsif form_data? || parseable_data?
-
4
@env["rack.request.form_input"] = @env["rack.input"]
-
4
unless @env["rack.request.form_hash"] = parse_multipart(env)
-
2
form_vars = @env["rack.input"].read
-
-
# Fix for Safari Ajax postings that always append \0
-
# form_vars.sub!(/\0\z/, '') # performance replacement:
-
2
form_vars.slice!(-1) if form_vars[-1] == ?\0
-
-
2
@env["rack.request.form_vars"] = form_vars
-
2
@env["rack.request.form_hash"] = parse_query(form_vars)
-
-
2
@env["rack.input"].rewind
-
end
-
4
@env["rack.request.form_hash"]
-
else
-
20
{}
-
end
-
end
-
-
# The union of GET and POST data.
-
#
-
# Note that modifications will not be persisted in the env. Use update_param or delete_param if you want to destructively modify params.
-
2
def params
-
@params ||= self.GET.merge(self.POST)
-
rescue EOFError
-
self.GET.dup
-
end
-
-
# Destructively update a parameter, whether it's in GET and/or POST. Returns nil.
-
#
-
# The parameter is updated wherever it was previous defined, so GET, POST, or both. If it wasn't previously defined, it's inserted into GET.
-
#
-
# env['rack.input'] is not touched.
-
2
def update_param(k, v)
-
found = false
-
if self.GET.has_key?(k)
-
found = true
-
self.GET[k] = v
-
end
-
if self.POST.has_key?(k)
-
found = true
-
self.POST[k] = v
-
end
-
unless found
-
self.GET[k] = v
-
end
-
@params = nil
-
nil
-
end
-
-
# Destructively delete a parameter, whether it's in GET or POST. Returns the value of the deleted parameter.
-
#
-
# If the parameter is in both GET and POST, the POST value takes precedence since that's how #params works.
-
#
-
# env['rack.input'] is not touched.
-
2
def delete_param(k)
-
v = [ self.POST.delete(k), self.GET.delete(k) ].compact.first
-
@params = nil
-
v
-
end
-
-
# shortcut for request.params[key]
-
2
def [](key)
-
params[key.to_s]
-
end
-
-
# shortcut for request.params[key] = value
-
#
-
# Note that modifications will not be persisted in the env. Use update_param or delete_param if you want to destructively modify params.
-
2
def []=(key, value)
-
params[key.to_s] = value
-
end
-
-
# like Hash#values_at
-
2
def values_at(*keys)
-
keys.map{|key| params[key] }
-
end
-
-
# the referer of the client
-
2
def referer
-
@env['HTTP_REFERER']
-
end
-
2
alias referrer referer
-
-
2
def user_agent
-
@env['HTTP_USER_AGENT']
-
end
-
-
2
def cookies
-
24
hash = @env["rack.request.cookie_hash"] ||= {}
-
24
string = @env["HTTP_COOKIE"]
-
-
24
return hash if string == @env["rack.request.cookie_string"]
-
13
hash.clear
-
-
# According to RFC 2109:
-
# If multiple cookies satisfy the criteria above, they are ordered in
-
# the Cookie header such that those with more specific Path attributes
-
# precede those with less specific. Ordering with respect to other
-
# attributes (e.g., Domain) is unspecified.
-
13
cookies = Utils.parse_query(string, ';,') { |s| Rack::Utils.unescape(s) rescue s }
-
13
cookies.each { |k,v| hash[k] = Array === v ? v.first : v }
-
13
@env["rack.request.cookie_string"] = string
-
13
hash
-
end
-
-
2
def xhr?
-
@env["HTTP_X_REQUESTED_WITH"] == "XMLHttpRequest"
-
end
-
-
2
def base_url
-
7
url = "#{scheme}://#{host}"
-
7
url << ":#{port}" if port != DEFAULT_PORTS[scheme]
-
7
url
-
end
-
-
# Tries to return a remake of the original request URL as a string.
-
2
def url
-
7
base_url + fullpath
-
end
-
-
2
def path
-
47
script_name + path_info
-
end
-
-
2
def fullpath
-
31
query_string.empty? ? path : "#{path}?#{query_string}"
-
end
-
-
2
def accept_encoding
-
@env["HTTP_ACCEPT_ENCODING"].to_s.split(/\s*,\s*/).map do |part|
-
encoding, parameters = part.split(/\s*;\s*/, 2)
-
quality = 1.0
-
if parameters and /\Aq=([\d.]+)/ =~ parameters
-
quality = $1.to_f
-
end
-
[encoding, quality]
-
end
-
end
-
-
2
def trusted_proxy?(ip)
-
13
ip =~ /\A127\.0\.0\.1\Z|\A(10|172\.(1[6-9]|2[0-9]|30|31)|192\.168)\.|\A::1\Z|\Afd[0-9a-f]{2}:.+|\Alocalhost\Z|\Aunix\Z|\Aunix:/i
-
end
-
-
2
def ip
-
13
remote_addrs = split_ip_addresses(@env['REMOTE_ADDR'])
-
13
remote_addrs = reject_trusted_ip_addresses(remote_addrs)
-
-
13
return remote_addrs.first if remote_addrs.any?
-
-
13
forwarded_ips = split_ip_addresses(@env['HTTP_X_FORWARDED_FOR'])
-
-
13
if client_ip = @env['HTTP_CLIENT_IP']
-
# If forwarded_ips doesn't include the client_ip, it might be an
-
# ip spoofing attempt, so we ignore HTTP_CLIENT_IP
-
return client_ip if forwarded_ips.include?(client_ip)
-
end
-
-
13
return reject_trusted_ip_addresses(forwarded_ips).last || @env["REMOTE_ADDR"]
-
end
-
-
2
protected
-
2
def split_ip_addresses(ip_addresses)
-
26
ip_addresses ? ip_addresses.strip.split(/[,\s]+/) : []
-
end
-
-
2
def reject_trusted_ip_addresses(ip_addresses)
-
39
ip_addresses.reject { |ip| trusted_proxy?(ip) }
-
end
-
-
2
def parse_query(qs)
-
15
Utils.parse_nested_query(qs)
-
end
-
-
2
def parse_multipart(env)
-
4
Rack::Multipart.parse_multipart(env)
-
end
-
end
-
end
-
2
require 'rack/request'
-
2
require 'rack/utils'
-
2
require 'time'
-
-
2
module Rack
-
# Rack::Response provides a convenient interface to create a Rack
-
# response.
-
#
-
# It allows setting of headers and cookies, and provides useful
-
# defaults (a OK response containing HTML).
-
#
-
# You can use Response#write to iteratively generate your response,
-
# but note that this is buffered by Rack::Response until you call
-
# +finish+. +finish+ however can take a block inside which calls to
-
# +write+ are synchronous with the Rack response.
-
#
-
# Your application's +call+ should end returning Response#finish.
-
-
2
class Response
-
2
attr_accessor :length
-
-
2
def initialize(body=[], status=200, header={})
-
13
@status = status.to_i
-
13
@header = Utils::HeaderHash.new.merge(header)
-
-
13
@chunked = "chunked" == @header['Transfer-Encoding']
-
26
@writer = lambda { |x| @body << x }
-
13
@block = nil
-
13
@length = 0
-
-
13
@body = []
-
-
13
if body.respond_to? :to_str
-
write body.to_str
-
elsif body.respond_to?(:each)
-
13
body.each { |part|
-
13
write part.to_s
-
}
-
else
-
raise TypeError, "stringable or iterable required"
-
end
-
-
13
yield self if block_given?
-
end
-
-
2
attr_reader :header
-
2
attr_accessor :status, :body
-
-
2
def [](key)
-
header[key]
-
end
-
-
2
def []=(key, value)
-
header[key] = value
-
end
-
-
2
def set_cookie(key, value)
-
Utils.set_cookie_header!(header, key, value)
-
end
-
-
2
def delete_cookie(key, value={})
-
Utils.delete_cookie_header!(header, key, value)
-
end
-
-
2
def redirect(target, status=302)
-
self.status = status
-
self["Location"] = target
-
end
-
-
2
def finish(&block)
-
13
@block = block
-
-
13
if [204, 205, 304].include?(status.to_i)
-
header.delete "Content-Type"
-
header.delete "Content-Length"
-
close
-
[status.to_i, header, []]
-
else
-
13
[status.to_i, header, BodyProxy.new(self){}]
-
end
-
end
-
2
alias to_a finish # For *response
-
2
alias to_ary finish # For implicit-splat on Ruby 1.9.2
-
-
2
def each(&callback)
-
@body.each(&callback)
-
@writer = callback
-
@block.call(self) if @block
-
end
-
-
# Append to body and update Content-Length.
-
#
-
# NOTE: Do not mix #write and direct #body access!
-
#
-
2
def write(str)
-
13
s = str.to_s
-
13
@length += Rack::Utils.bytesize(s) unless @chunked
-
13
@writer.call s
-
-
13
header["Content-Length"] = @length.to_s unless @chunked
-
13
str
-
end
-
-
2
def close
-
body.close if body.respond_to?(:close)
-
end
-
-
2
def empty?
-
@block == nil && @body.empty?
-
end
-
-
2
alias headers header
-
-
2
module Helpers
-
2
def invalid?; status < 100 || status >= 600; end
-
-
2
def informational?; status >= 100 && status < 200; end
-
13
def successful?; status >= 200 && status < 300; end
-
2
def redirection?; status >= 300 && status < 400; end
-
2
def client_error?; status >= 400 && status < 500; end
-
2
def server_error?; status >= 500 && status < 600; end
-
-
2
def ok?; status == 200; end
-
2
def bad_request?; status == 400; end
-
2
def forbidden?; status == 403; end
-
2
def not_found?; status == 404; end
-
2
def method_not_allowed?; status == 405; end
-
2
def unprocessable?; status == 422; end
-
-
80
def redirect?; [301, 302, 303, 307].include? status; end
-
-
# Headers
-
2
attr_reader :headers, :original_headers
-
-
2
def include?(header)
-
!!headers[header]
-
end
-
-
2
def content_type
-
headers["Content-Type"]
-
end
-
-
2
def content_length
-
cl = headers["Content-Length"]
-
cl ? cl.to_i : cl
-
end
-
-
2
def location
-
headers["Location"]
-
end
-
end
-
-
2
include Helpers
-
end
-
end
-
2
module Rack
-
# Sets an "X-Runtime" response header, indicating the response
-
# time of the request, in seconds
-
#
-
# You can put it right before the application to see the processing
-
# time, or before all the other middlewares to include time for them,
-
# too.
-
2
class Runtime
-
2
def initialize(app, name = nil)
-
2
@app = app
-
2
@header_name = "X-Runtime"
-
2
@header_name << "-#{name}" if name
-
end
-
-
2
def call(env)
-
13
start_time = Time.now
-
13
status, headers, body = @app.call(env)
-
13
request_time = Time.now - start_time
-
-
13
if !headers.has_key?(@header_name)
-
13
headers[@header_name] = "%0.6f" % request_time
-
end
-
-
13
[status, headers, body]
-
end
-
end
-
end
-
2
require 'rack/file'
-
-
2
module Rack
-
-
# = Sendfile
-
#
-
# The Sendfile middleware intercepts responses whose body is being
-
# served from a file and replaces it with a server specific X-Sendfile
-
# header. The web server is then responsible for writing the file contents
-
# to the client. This can dramatically reduce the amount of work required
-
# by the Ruby backend and takes advantage of the web server's optimized file
-
# delivery code.
-
#
-
# In order to take advantage of this middleware, the response body must
-
# respond to +to_path+ and the request must include an X-Sendfile-Type
-
# header. Rack::File and other components implement +to_path+ so there's
-
# rarely anything you need to do in your application. The X-Sendfile-Type
-
# header is typically set in your web servers configuration. The following
-
# sections attempt to document
-
#
-
# === Nginx
-
#
-
# Nginx supports the X-Accel-Redirect header. This is similar to X-Sendfile
-
# but requires parts of the filesystem to be mapped into a private URL
-
# hierarachy.
-
#
-
# The following example shows the Nginx configuration required to create
-
# a private "/files/" area, enable X-Accel-Redirect, and pass the special
-
# X-Sendfile-Type and X-Accel-Mapping headers to the backend:
-
#
-
# location ~ /files/(.*) {
-
# internal;
-
# alias /var/www/$1;
-
# }
-
#
-
# location / {
-
# proxy_redirect off;
-
#
-
# proxy_set_header Host $host;
-
# proxy_set_header X-Real-IP $remote_addr;
-
# proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
-
#
-
# proxy_set_header X-Sendfile-Type X-Accel-Redirect;
-
# proxy_set_header X-Accel-Mapping /var/www/=/files/;
-
#
-
# proxy_pass http://127.0.0.1:8080/;
-
# }
-
#
-
# Note that the X-Sendfile-Type header must be set exactly as shown above.
-
# The X-Accel-Mapping header should specify the location on the file system,
-
# followed by an equals sign (=), followed name of the private URL pattern
-
# that it maps to. The middleware performs a simple substitution on the
-
# resulting path.
-
#
-
# See Also: http://wiki.codemongers.com/NginxXSendfile
-
#
-
# === lighttpd
-
#
-
# Lighttpd has supported some variation of the X-Sendfile header for some
-
# time, although only recent version support X-Sendfile in a reverse proxy
-
# configuration.
-
#
-
# $HTTP["host"] == "example.com" {
-
# proxy-core.protocol = "http"
-
# proxy-core.balancer = "round-robin"
-
# proxy-core.backends = (
-
# "127.0.0.1:8000",
-
# "127.0.0.1:8001",
-
# ...
-
# )
-
#
-
# proxy-core.allow-x-sendfile = "enable"
-
# proxy-core.rewrite-request = (
-
# "X-Sendfile-Type" => (".*" => "X-Sendfile")
-
# )
-
# }
-
#
-
# See Also: http://redmine.lighttpd.net/wiki/lighttpd/Docs:ModProxyCore
-
#
-
# === Apache
-
#
-
# X-Sendfile is supported under Apache 2.x using a separate module:
-
#
-
# https://tn123.org/mod_xsendfile/
-
#
-
# Once the module is compiled and installed, you can enable it using
-
# XSendFile config directive:
-
#
-
# RequestHeader Set X-Sendfile-Type X-Sendfile
-
# ProxyPassReverse / http://localhost:8001/
-
# XSendFile on
-
#
-
# === Mapping parameter
-
#
-
# The third parameter allows for an overriding extension of the
-
# X-Accel-Mapping header. Mappings should be provided in tuples of internal to
-
# external. The internal values may contain regular expression syntax, they
-
# will be matched with case indifference.
-
-
2
class Sendfile
-
2
F = ::File
-
-
2
def initialize(app, variation=nil, mappings=[])
-
2
@app = app
-
2
@variation = variation
-
2
@mappings = mappings.map do |internal, external|
-
[/^#{internal}/i, external]
-
end
-
end
-
-
2
def call(env)
-
13
status, headers, body = @app.call(env)
-
13
if body.respond_to?(:to_path)
-
case type = variation(env)
-
when 'X-Accel-Redirect'
-
path = F.expand_path(body.to_path)
-
if url = map_accel_path(env, path)
-
headers['Content-Length'] = '0'
-
headers[type] = url
-
body.close if body.respond_to?(:close)
-
body = []
-
else
-
env['rack.errors'].puts "X-Accel-Mapping header missing"
-
end
-
when 'X-Sendfile', 'X-Lighttpd-Send-File'
-
path = F.expand_path(body.to_path)
-
headers['Content-Length'] = '0'
-
headers[type] = path
-
body.close if body.respond_to?(:close)
-
body = []
-
when '', nil
-
else
-
env['rack.errors'].puts "Unknown x-sendfile variation: '#{type}'.\n"
-
end
-
end
-
13
[status, headers, body]
-
end
-
-
2
private
-
2
def variation(env)
-
@variation ||
-
env['sendfile.type'] ||
-
env['HTTP_X_SENDFILE_TYPE']
-
end
-
-
2
def map_accel_path(env, path)
-
if mapping = @mappings.find { |internal,_| internal =~ path }
-
path.sub(*mapping)
-
elsif mapping = env['HTTP_X_ACCEL_MAPPING']
-
internal, external = mapping.split('=', 2).map{ |p| p.strip }
-
path.sub(/^#{internal}/i, external)
-
end
-
end
-
end
-
end
-
# AUTHOR: blink <blinketje@gmail.com>; blink#ruby-lang@irc.freenode.net
-
# bugrep: Andreas Zehnder
-
-
2
require 'time'
-
2
require 'rack/request'
-
2
require 'rack/response'
-
2
begin
-
2
require 'securerandom'
-
rescue LoadError
-
# We just won't get securerandom
-
end
-
-
2
module Rack
-
-
2
module Session
-
-
2
module Abstract
-
2
ENV_SESSION_KEY = 'rack.session'.freeze
-
2
ENV_SESSION_OPTIONS_KEY = 'rack.session.options'.freeze
-
-
# SessionHash is responsible to lazily load the session from store.
-
-
2
class SessionHash
-
2
include Enumerable
-
2
attr_writer :id
-
-
2
def self.find(env)
-
env[ENV_SESSION_KEY]
-
end
-
-
2
def self.set(env, session)
-
env[ENV_SESSION_KEY] = session
-
end
-
-
2
def self.set_options(env, options)
-
env[ENV_SESSION_OPTIONS_KEY] = options.dup
-
end
-
-
2
def initialize(store, env)
-
15
@store = store
-
15
@env = env
-
15
@loaded = false
-
end
-
-
2
def id
-
return @id if @loaded or instance_variable_defined?(:@id)
-
@id = @store.send(:extract_session_id, @env)
-
end
-
-
2
def options
-
@env[ENV_SESSION_OPTIONS_KEY]
-
end
-
-
2
def each(&block)
-
load_for_read!
-
@data.each(&block)
-
end
-
-
2
def [](key)
-
33
load_for_read!
-
33
@data[key.to_s]
-
end
-
2
alias :fetch :[]
-
-
2
def has_key?(key)
-
load_for_read!
-
@data.has_key?(key.to_s)
-
end
-
2
alias :key? :has_key?
-
2
alias :include? :has_key?
-
-
2
def []=(key, value)
-
11
load_for_write!
-
11
@data[key.to_s] = value
-
end
-
2
alias :store :[]=
-
-
2
def clear
-
load_for_write!
-
@data.clear
-
end
-
-
2
def destroy
-
clear
-
@id = @store.send(:destroy_session, @env, id, options)
-
end
-
-
2
def to_hash
-
load_for_read!
-
@data.dup
-
end
-
-
2
def update(hash)
-
load_for_write!
-
@data.update(stringify_keys(hash))
-
end
-
2
alias :merge! :update
-
-
2
def replace(hash)
-
load_for_write!
-
@data.replace(stringify_keys(hash))
-
end
-
-
2
def delete(key)
-
11
load_for_write!
-
11
@data.delete(key.to_s)
-
end
-
-
2
def inspect
-
if loaded?
-
@data.inspect
-
else
-
"#<#{self.class}:0x#{self.object_id.to_s(16)} not yet loaded>"
-
end
-
end
-
-
2
def exists?
-
return @exists if instance_variable_defined?(:@exists)
-
@data = {}
-
@exists = @store.send(:session_exists?, @env)
-
end
-
-
2
def loaded?
-
55
@loaded
-
end
-
-
2
def empty?
-
load_for_read!
-
@data.empty?
-
end
-
-
2
def keys
-
@data.keys
-
end
-
-
2
def values
-
@data.values
-
end
-
-
2
private
-
-
2
def load_for_read!
-
33
load! if !loaded? && exists?
-
end
-
-
2
def load_for_write!
-
22
load! unless loaded?
-
end
-
-
2
def load!
-
@id, session = @store.send(:load_session, @env)
-
@data = stringify_keys(session)
-
@loaded = true
-
end
-
-
2
def stringify_keys(other)
-
15
hash = {}
-
15
other.each do |key, value|
-
hash[key.to_s] = value
-
end
-
15
hash
-
end
-
end
-
-
# ID sets up a basic framework for implementing an id based sessioning
-
# service. Cookies sent to the client for maintaining sessions will only
-
# contain an id reference. Only #get_session and #set_session are
-
# required to be overwritten.
-
#
-
# All parameters are optional.
-
# * :key determines the name of the cookie, by default it is
-
# 'rack.session'
-
# * :path, :domain, :expire_after, :secure, and :httponly set the related
-
# cookie options as by Rack::Response#add_cookie
-
# * :skip will not a set a cookie in the response nor update the session state
-
# * :defer will not set a cookie in the response but still update the session
-
# state if it is used with a backend
-
# * :renew (implementation dependent) will prompt the generation of a new
-
# session id, and migration of data to be referenced at the new id. If
-
# :defer is set, it will be overridden and the cookie will be set.
-
# * :sidbits sets the number of bits in length that a generated session
-
# id will be.
-
#
-
# These options can be set on a per request basis, at the location of
-
# env['rack.session.options']. Additionally the id of the session can be
-
# found within the options hash at the key :id. It is highly not
-
# recommended to change its value.
-
#
-
# Is Rack::Utils::Context compatible.
-
#
-
# Not included by default; you must require 'rack/session/abstract/id'
-
# to use.
-
-
2
class ID
-
2
DEFAULT_OPTIONS = {
-
:key => 'rack.session',
-
:path => '/',
-
:domain => nil,
-
:expire_after => nil,
-
:secure => false,
-
:httponly => true,
-
:defer => false,
-
:renew => false,
-
:sidbits => 128,
-
:cookie_only => true,
-
2
:secure_random => (::SecureRandom rescue false)
-
}
-
-
2
attr_reader :key, :default_options
-
-
2
def initialize(app, options={})
-
2
@app = app
-
2
@default_options = self.class::DEFAULT_OPTIONS.merge(options)
-
2
@key = @default_options.delete(:key)
-
2
@cookie_only = @default_options.delete(:cookie_only)
-
2
initialize_sid
-
end
-
-
2
def call(env)
-
13
context(env)
-
end
-
-
2
def context(env, app=@app)
-
13
prepare_session(env)
-
13
status, headers, body = app.call(env)
-
13
commit_session(env, status, headers, body)
-
end
-
-
2
private
-
-
2
def initialize_sid
-
@sidbits = @default_options[:sidbits]
-
@sid_secure = @default_options[:secure_random]
-
@sid_length = @sidbits / 4
-
end
-
-
# Generate a new session id using Ruby #rand. The size of the
-
# session id is controlled by the :sidbits option.
-
# Monkey patch this to use custom methods for session id generation.
-
-
2
def generate_sid(secure = @sid_secure)
-
if secure
-
secure.hex(@sid_length)
-
else
-
"%0#{@sid_length}x" % Kernel.rand(2**@sidbits - 1)
-
end
-
rescue NotImplementedError
-
generate_sid(false)
-
end
-
-
# Sets the lazy session at 'rack.session' and places options and session
-
# metadata into 'rack.session.options'.
-
-
2
def prepare_session(env)
-
session_was = env[ENV_SESSION_KEY]
-
env[ENV_SESSION_KEY] = session_class.new(self, env)
-
env[ENV_SESSION_OPTIONS_KEY] = @default_options.dup
-
env[ENV_SESSION_KEY].merge! session_was if session_was
-
end
-
-
# Extracts the session id from provided cookies and passes it and the
-
# environment to #get_session.
-
-
2
def load_session(env)
-
sid = current_session_id(env)
-
sid, session = get_session(env, sid)
-
[sid, session || {}]
-
end
-
-
# Extract session id from request object.
-
-
2
def extract_session_id(env)
-
request = Rack::Request.new(env)
-
sid = request.cookies[@key]
-
sid ||= request.params[@key] unless @cookie_only
-
sid
-
end
-
-
# Returns the current session id from the SessionHash.
-
-
2
def current_session_id(env)
-
28
env[ENV_SESSION_KEY].id
-
end
-
-
# Check if the session exists or not.
-
-
2
def session_exists?(env)
-
28
value = current_session_id(env)
-
28
value && !value.empty?
-
end
-
-
# Session should be commited if it was loaded, any of specific options like :renew, :drop
-
# or :expire_after was given and the security permissions match. Skips if skip is given.
-
-
2
def commit_session?(env, session, options)
-
13
if options[:skip]
-
false
-
else
-
13
has_session = loaded_session?(session) || forced_session_update?(session, options)
-
13
has_session && security_matches?(env, options)
-
end
-
end
-
-
2
def loaded_session?(session)
-
!session.is_a?(session_class) || session.loaded?
-
end
-
-
2
def forced_session_update?(session, options)
-
11
force_options?(options) && session && !session.empty?
-
end
-
-
2
def force_options?(options)
-
11
options.values_at(:renew, :drop, :defer, :expire_after).any?
-
end
-
-
2
def security_matches?(env, options)
-
2
return true unless options[:secure]
-
request = Rack::Request.new(env)
-
request.ssl?
-
end
-
-
# Acquires the session from the environment and the session id from
-
# the session options and passes them to #set_session. If successful
-
# and the :defer option is not true, a cookie will be added to the
-
# response with the session's id.
-
-
2
def commit_session(env, status, headers, body)
-
13
session = env[ENV_SESSION_KEY]
-
13
options = session.options
-
-
13
if options[:drop] || options[:renew]
-
session_id = destroy_session(env, session.id || generate_sid, options)
-
return [status, headers, body] unless session_id
-
end
-
-
13
return [status, headers, body] unless commit_session?(env, session, options)
-
-
2
session.send(:load!) unless loaded_session?(session)
-
2
session_id ||= session.id
-
6
session_data = session.to_hash.delete_if { |k,v| v.nil? }
-
-
2
if not data = set_session(env, session_id, session_data, options)
-
env["rack.errors"].puts("Warning! #{self.class.name} failed to save session. Content dropped.")
-
elsif options[:defer] and not options[:renew]
-
env["rack.errors"].puts("Defering cookie for #{session_id}") if $VERBOSE
-
else
-
2
cookie = Hash.new
-
2
cookie[:value] = data
-
2
cookie[:expires] = Time.now + options[:expire_after] if options[:expire_after]
-
2
set_cookie(env, headers, cookie.merge!(options))
-
end
-
-
2
[status, headers, body]
-
end
-
-
# Sets the cookie back to the client with session id. We skip the cookie
-
# setting if the value didn't change (sid is the same) or expires was given.
-
-
2
def set_cookie(env, headers, cookie)
-
request = Rack::Request.new(env)
-
if request.cookies[@key] != cookie[:value] || cookie[:expires]
-
Utils.set_cookie_header!(headers, @key, cookie)
-
end
-
end
-
-
# Allow subclasses to prepare_session for different Session classes
-
-
2
def session_class
-
SessionHash
-
end
-
-
# All thread safety and session retrival proceedures should occur here.
-
# Should return [session_id, session].
-
# If nil is provided as the session id, generation of a new valid id
-
# should occur within.
-
-
2
def get_session(env, sid)
-
raise '#get_session not implemented.'
-
end
-
-
# All thread safety and session storage proceedures should occur here.
-
# Must return the session id if the session was saved successfully, or
-
# false if the session could not be saved.
-
-
2
def set_session(env, sid, session, options)
-
raise '#set_session not implemented.'
-
end
-
-
# All thread safety and session destroy proceedures should occur here.
-
# Should return a new session id or nil if options[:drop]
-
-
2
def destroy_session(env, sid, options)
-
raise '#destroy_session not implemented'
-
end
-
end
-
end
-
end
-
end
-
2
require 'openssl'
-
2
require 'rack/request'
-
2
require 'rack/response'
-
2
require 'rack/session/abstract/id'
-
-
2
module Rack
-
-
2
module Session
-
-
# Rack::Session::Cookie provides simple cookie based session management.
-
# By default, the session is a Ruby Hash stored as base64 encoded marshalled
-
# data set to :key (default: rack.session). The object that encodes the
-
# session data is configurable and must respond to +encode+ and +decode+.
-
# Both methods must take a string and return a string.
-
#
-
# When the secret key is set, cookie data is checked for data integrity.
-
# The old secret key is also accepted and allows graceful secret rotation.
-
#
-
# Example:
-
#
-
# use Rack::Session::Cookie, :key => 'rack.session',
-
# :domain => 'foo.com',
-
# :path => '/',
-
# :expire_after => 2592000,
-
# :secret => 'change_me',
-
# :old_secret => 'also_change_me'
-
#
-
# All parameters are optional.
-
#
-
# Example of a cookie with no encoding:
-
#
-
# Rack::Session::Cookie.new(application, {
-
# :coder => Rack::Session::Cookie::Identity.new
-
# })
-
#
-
# Example of a cookie with custom encoding:
-
#
-
# Rack::Session::Cookie.new(application, {
-
# :coder => Class.new {
-
# def encode(str); str.reverse; end
-
# def decode(str); str.reverse; end
-
# }.new
-
# })
-
#
-
-
2
class Cookie < Abstract::ID
-
# Encode session cookies as Base64
-
2
class Base64
-
2
def encode(str)
-
[str].pack('m')
-
end
-
-
2
def decode(str)
-
str.unpack('m').first
-
end
-
-
# Encode session cookies as Marshaled Base64 data
-
2
class Marshal < Base64
-
2
def encode(str)
-
super(::Marshal.dump(str))
-
end
-
-
2
def decode(str)
-
return unless str
-
::Marshal.load(super(str)) rescue nil
-
end
-
end
-
-
# N.B. Unlike other encoding methods, the contained objects must be a
-
# valid JSON composite type, either a Hash or an Array.
-
2
class JSON < Base64
-
2
def encode(obj)
-
super(::Rack::Utils::OkJson.encode(obj))
-
end
-
-
2
def decode(str)
-
return unless str
-
::Rack::Utils::OkJson.decode(super(str)) rescue nil
-
end
-
end
-
end
-
-
# Use no encoding for session cookies
-
2
class Identity
-
2
def encode(str); str; end
-
2
def decode(str); str; end
-
end
-
-
# Reverse string encoding. (trollface)
-
2
class Reverse
-
2
def encode(str); str.reverse; end
-
2
def decode(str); str.reverse; end
-
end
-
-
2
attr_reader :coder
-
-
2
def initialize(app, options={})
-
@secrets = options.values_at(:secret, :old_secret).compact
-
warn <<-MSG unless @secrets.size >= 1
-
SECURITY WARNING: No secret option provided to Rack::Session::Cookie.
-
This poses a security threat. It is strongly recommended that you
-
provide a secret to prevent exploits that may be possible from crafted
-
cookies. This will not be supported in future versions of Rack, and
-
future versions will even invalidate your existing user cookies.
-
-
Called from: #{caller[0]}.
-
MSG
-
@coder = options[:coder] ||= Base64::Marshal.new
-
super(app, options.merge!(:cookie_only => true))
-
end
-
-
2
private
-
-
2
def get_session(env, sid)
-
data = unpacked_cookie_data(env)
-
data = persistent_session_id!(data)
-
[data["session_id"], data]
-
end
-
-
2
def extract_session_id(env)
-
unpacked_cookie_data(env)["session_id"]
-
end
-
-
2
def unpacked_cookie_data(env)
-
env["rack.session.unpacked_cookie_data"] ||= begin
-
request = Rack::Request.new(env)
-
session_data = request.cookies[@key]
-
-
if @secrets.size > 0 && session_data
-
session_data, digest = session_data.split("--")
-
session_data = nil unless digest_match?(session_data, digest)
-
end
-
-
coder.decode(session_data) || {}
-
end
-
end
-
-
2
def persistent_session_id!(data, sid=nil)
-
data ||= {}
-
data["session_id"] ||= sid || generate_sid
-
data
-
end
-
-
2
def set_session(env, session_id, session, options)
-
session = session.merge("session_id" => session_id)
-
session_data = coder.encode(session)
-
-
if @secrets.first
-
session_data << "--#{generate_hmac(session_data, @secrets.first)}"
-
end
-
-
if session_data.size > (4096 - @key.size)
-
env["rack.errors"].puts("Warning! Rack::Session::Cookie data size exceeds 4K.")
-
nil
-
else
-
session_data
-
end
-
end
-
-
2
def destroy_session(env, session_id, options)
-
# Nothing to do here, data is in the client
-
generate_sid unless options[:drop]
-
end
-
-
2
def digest_match?(data, digest)
-
return unless data && digest
-
@secrets.any? do |secret|
-
Rack::Utils.secure_compare(digest, generate_hmac(data, secret))
-
end
-
end
-
-
2
def generate_hmac(data, secret)
-
OpenSSL::HMAC.hexdigest(OpenSSL::Digest::SHA1.new, secret, data)
-
end
-
-
end
-
end
-
end
-
2
module Rack
-
# Rack::URLMap takes a hash mapping urls or paths to apps, and
-
# dispatches accordingly. Support for HTTP/1.1 host names exists if
-
# the URLs start with <tt>http://</tt> or <tt>https://</tt>.
-
#
-
# URLMap modifies the SCRIPT_NAME and PATH_INFO such that the part
-
# relevant for dispatch is in the SCRIPT_NAME, and the rest in the
-
# PATH_INFO. This should be taken care of when you need to
-
# reconstruct the URL in order to create links.
-
#
-
# URLMap dispatches in such a way that the longest paths are tried
-
# first, since they are most specific.
-
-
2
class URLMap
-
2
NEGATIVE_INFINITY = -1.0 / 0.0
-
2
INFINITY = 1.0 / 0.0
-
-
2
def initialize(map = {})
-
2
remap(map)
-
end
-
-
2
def remap(map)
-
2
@mapping = map.map { |location, app|
-
2
if location =~ %r{\Ahttps?://(.*?)(/.*)}
-
host, location = $1, $2
-
else
-
2
host = nil
-
end
-
-
2
unless location[0] == ?/
-
raise ArgumentError, "paths need to start with /"
-
end
-
-
2
location = location.chomp('/')
-
2
match = Regexp.new("^#{Regexp.quote(location).gsub('/', '/+')}(.*)", nil, 'n')
-
-
2
[host, location, match, app]
-
}.sort_by do |(host, location, _, _)|
-
2
[host ? -host.size : INFINITY, -location.size]
-
end
-
end
-
-
2
def call(env)
-
13
path = env["PATH_INFO"]
-
13
script_name = env['SCRIPT_NAME']
-
13
hHost = env['HTTP_HOST']
-
13
sName = env['SERVER_NAME']
-
13
sPort = env['SERVER_PORT']
-
-
13
@mapping.each do |host, location, match, app|
-
unless hHost == host \
-
|| sName == host \
-
13
|| (!host && (hHost == sName || hHost == sName+':'+sPort))
-
next
-
end
-
-
13
next unless m = match.match(path.to_s)
-
-
13
rest = m[1]
-
13
next unless !rest || rest.empty? || rest[0] == ?/
-
-
13
env['SCRIPT_NAME'] = (script_name + location)
-
13
env['PATH_INFO'] = rest
-
-
13
return app.call(env)
-
end
-
-
[404, {"Content-Type" => "text/plain", "X-Cascade" => "pass"}, ["Not Found: #{path}"]]
-
-
ensure
-
13
env['PATH_INFO'] = path
-
13
env['SCRIPT_NAME'] = script_name
-
end
-
end
-
end
-
-
# -*- encoding: binary -*-
-
2
require 'fileutils'
-
2
require 'set'
-
2
require 'tempfile'
-
2
require 'rack/multipart'
-
2
require 'time'
-
-
8
major, minor, patch = RUBY_VERSION.split('.').map { |v| v.to_i }
-
-
2
if major == 1 && minor < 9
-
require 'rack/backports/uri/common_18'
-
elsif major == 1 && minor == 9 && patch == 2 && RUBY_PATCHLEVEL <= 320 && RUBY_ENGINE != 'jruby'
-
require 'rack/backports/uri/common_192'
-
elsif major == 1 && minor == 9 && patch == 3 && RUBY_PATCHLEVEL < 125
-
require 'rack/backports/uri/common_193'
-
else
-
2
require 'uri/common'
-
end
-
-
2
module Rack
-
# Rack::Utils contains a grab-bag of useful methods for writing web
-
# applications adopted from all kinds of Ruby libraries.
-
-
2
module Utils
-
# URI escapes. (CGI style space to +)
-
2
def escape(s)
-
32
URI.encode_www_form_component(s)
-
end
-
2
module_function :escape
-
-
# Like URI escaping, but with %20 instead of +. Strictly speaking this is
-
# true URI escaping.
-
2
def escape_path(s)
-
escape(s).gsub('+', '%20')
-
end
-
2
module_function :escape_path
-
-
# Unescapes a URI escaped string with +encoding+. +encoding+ will be the
-
# target encoding of the string returned, and it defaults to UTF-8
-
2
if defined?(::Encoding)
-
2
def unescape(s, encoding = Encoding::UTF_8)
-
44
URI.decode_www_form_component(s, encoding)
-
end
-
else
-
def unescape(s, encoding = nil)
-
URI.decode_www_form_component(s, encoding)
-
end
-
end
-
2
module_function :unescape
-
-
2
DEFAULT_SEP = /[&;] */n
-
-
2
class << self
-
2
attr_accessor :key_space_limit
-
2
attr_accessor :param_depth_limit
-
2
attr_accessor :multipart_part_limit
-
end
-
-
# The default number of bytes to allow parameter keys to take up.
-
# This helps prevent a rogue client from flooding a Request.
-
2
self.key_space_limit = 65536
-
-
# Default depth at which the parameter parser will raise an exception for
-
# being too deep. This helps prevent SystemStackErrors
-
2
self.param_depth_limit = 100
-
#
-
# The maximum number of parts a request can contain. Accepting to many part
-
# can lead to the server running out of file handles.
-
# Set to `0` for no limit.
-
2
self.multipart_part_limit = (ENV['RACK_MULTIPART_PART_LIMIT'] || 128).to_i
-
-
# Stolen from Mongrel, with some small modifications:
-
# Parses a query string by breaking it up at the '&'
-
# and ';' characters. You can also use this to parse
-
# cookies by changing the characters used in the second
-
# parameter (which defaults to '&;').
-
2
def parse_query(qs, d = nil, &unescaper)
-
25
unescaper ||= method(:unescape)
-
-
25
params = KeySpaceConstrainedParams.new
-
-
25
(qs || '').split(d ? /[#{d}] */n : DEFAULT_SEP).each do |p|
-
14
next if p.empty?
-
14
k, v = p.split('=', 2).map(&unescaper)
-
-
14
if cur = params[k]
-
if cur.class == Array
-
params[k] << v
-
else
-
params[k] = [cur, v]
-
end
-
else
-
14
params[k] = v
-
end
-
end
-
-
25
return params.to_params_hash
-
end
-
2
module_function :parse_query
-
-
2
def parse_nested_query(qs, d = nil)
-
24
params = KeySpaceConstrainedParams.new
-
-
24
(qs || '').split(d ? /[#{d}] */n : DEFAULT_SEP).each do |p|
-
24
k, v = p.split('=', 2).map { |s| unescape(s) }
-
-
8
normalize_params(params, k, v)
-
end
-
-
24
return params.to_params_hash
-
end
-
2
module_function :parse_nested_query
-
-
2
def normalize_params(params, name, v = nil, depth = Utils.param_depth_limit)
-
84
raise RangeError if depth <= 0
-
-
84
name =~ %r(\A[\[\]]*([^\[\]]+)\]*)
-
84
k = $1 || ''
-
84
after = $' || ''
-
-
84
return if k.empty?
-
-
84
if after == ""
-
50
params[k] = v
-
elsif after == "[]"
-
params[k] ||= []
-
raise TypeError, "expected Array (got #{params[k].class.name}) for param `#{k}'" unless params[k].is_a?(Array)
-
params[k] << v
-
elsif after =~ %r(^\[\]\[([^\[\]]+)\]$) || after =~ %r(^\[\](.+)$)
-
child_key = $1
-
params[k] ||= []
-
raise TypeError, "expected Array (got #{params[k].class.name}) for param `#{k}'" unless params[k].is_a?(Array)
-
if params_hash_type?(params[k].last) && !params[k].last.key?(child_key)
-
normalize_params(params[k].last, child_key, v, depth - 1)
-
else
-
params[k] << normalize_params(params.class.new, child_key, v, depth - 1)
-
end
-
else
-
34
params[k] ||= params.class.new
-
34
raise TypeError, "expected Hash (got #{params[k].class.name}) for param `#{k}'" unless params_hash_type?(params[k])
-
34
params[k] = normalize_params(params[k], after, v, depth - 1)
-
end
-
-
84
return params
-
end
-
2
module_function :normalize_params
-
-
2
def params_hash_type?(obj)
-
34
obj.kind_of?(KeySpaceConstrainedParams) || obj.kind_of?(Hash)
-
end
-
2
module_function :params_hash_type?
-
-
2
def build_query(params)
-
params.map { |k, v|
-
if v.class == Array
-
build_query(v.map { |x| [k, x] })
-
else
-
v.nil? ? escape(k) : "#{escape(k)}=#{escape(v)}"
-
end
-
}.join("&")
-
end
-
2
module_function :build_query
-
-
2
def build_nested_query(value, prefix = nil)
-
case value
-
when Array
-
value.map { |v|
-
build_nested_query(v, "#{prefix}[]")
-
}.join("&")
-
when Hash
-
value.map { |k, v|
-
build_nested_query(v, prefix ? "#{prefix}[#{escape(k)}]" : escape(k))
-
}.join("&")
-
when String
-
raise ArgumentError, "value must be a Hash" if prefix.nil?
-
"#{prefix}=#{escape(value)}"
-
else
-
prefix
-
end
-
end
-
2
module_function :build_nested_query
-
-
2
def q_values(q_value_header)
-
q_value_header.to_s.split(/\s*,\s*/).map do |part|
-
value, parameters = part.split(/\s*;\s*/, 2)
-
quality = 1.0
-
if md = /\Aq=([\d.]+)/.match(parameters)
-
quality = md[1].to_f
-
end
-
[value, quality]
-
end
-
end
-
2
module_function :q_values
-
-
2
def best_q_match(q_value_header, available_mimes)
-
values = q_values(q_value_header)
-
-
values.map do |req_mime, quality|
-
match = available_mimes.first { |am| Rack::Mime.match?(am, req_mime) }
-
next unless match
-
[match, quality]
-
end.compact.sort_by do |match, quality|
-
(match.split('/', 2).count('*') * -10) + quality
-
end.last.first
-
end
-
2
module_function :best_q_match
-
-
2
ESCAPE_HTML = {
-
"&" => "&",
-
"<" => "<",
-
">" => ">",
-
"'" => "'",
-
'"' => """,
-
"/" => "/"
-
}
-
2
if //.respond_to?(:encoding)
-
2
ESCAPE_HTML_PATTERN = Regexp.union(*ESCAPE_HTML.keys)
-
else
-
# On 1.8, there is a kcode = 'u' bug that allows for XSS otherwhise
-
# TODO doesn't apply to jruby, so a better condition above might be preferable?
-
ESCAPE_HTML_PATTERN = /#{Regexp.union(*ESCAPE_HTML.keys)}/n
-
end
-
-
# Escape ampersands, brackets and quotes to their HTML/XML entities.
-
2
def escape_html(string)
-
string.to_s.gsub(ESCAPE_HTML_PATTERN){|c| ESCAPE_HTML[c] }
-
end
-
2
module_function :escape_html
-
-
2
def select_best_encoding(available_encodings, accept_encoding)
-
# http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html
-
-
expanded_accept_encoding =
-
accept_encoding.map { |m, q|
-
if m == "*"
-
(available_encodings - accept_encoding.map { |m2, _| m2 }).map { |m2| [m2, q] }
-
else
-
[[m, q]]
-
end
-
}.inject([]) { |mem, list|
-
mem + list
-
}
-
-
encoding_candidates = expanded_accept_encoding.sort_by { |_, q| -q }.map { |m, _| m }
-
-
unless encoding_candidates.include?("identity")
-
encoding_candidates.push("identity")
-
end
-
-
expanded_accept_encoding.find_all { |m, q|
-
q == 0.0
-
}.each { |m, _|
-
encoding_candidates.delete(m)
-
}
-
-
return (encoding_candidates & available_encodings)[0]
-
end
-
2
module_function :select_best_encoding
-
-
2
def set_cookie_header!(header, key, value)
-
6
case value
-
when Hash
-
6
domain = "; domain=" + value[:domain] if value[:domain]
-
6
path = "; path=" + value[:path] if value[:path]
-
6
max_age = "; max-age=" + value[:max_age] if value[:max_age]
-
# There is an RFC mess in the area of date formatting for Cookies. Not
-
# only are there contradicting RFCs and examples within RFC text, but
-
# there are also numerous conflicting names of fields and partially
-
# cross-applicable specifications.
-
#
-
# These are best described in RFC 2616 3.3.1. This RFC text also
-
# specifies that RFC 822 as updated by RFC 1123 is preferred. That is a
-
# fixed length format with space-date delimeted fields.
-
#
-
# See also RFC 1123 section 5.2.14.
-
#
-
# RFC 6265 also specifies "sane-cookie-date" as RFC 1123 date, defined
-
# in RFC 2616 3.3.1. RFC 6265 also gives examples that clearly denote
-
# the space delimited format. These formats are compliant with RFC 2822.
-
#
-
# For reference, all involved RFCs are:
-
# RFC 822
-
# RFC 1123
-
# RFC 2109
-
# RFC 2616
-
# RFC 2822
-
# RFC 2965
-
# RFC 6265
-
expires = "; expires=" +
-
6
rfc2822(value[:expires].clone.gmtime) if value[:expires]
-
6
secure = "; secure" if value[:secure]
-
6
httponly = "; HttpOnly" if value[:httponly]
-
6
value = value[:value]
-
end
-
6
value = [value] unless Array === value
-
6
cookie = escape(key) + "=" +
-
6
value.map { |v| escape v }.join("&") +
-
"#{domain}#{path}#{max_age}#{expires}#{secure}#{httponly}"
-
-
6
case header["Set-Cookie"]
-
when nil, ''
-
4
header["Set-Cookie"] = cookie
-
when String
-
2
header["Set-Cookie"] = [header["Set-Cookie"], cookie].join("\n")
-
when Array
-
header["Set-Cookie"] = (header["Set-Cookie"] + [cookie]).join("\n")
-
end
-
-
nil
-
end
-
2
module_function :set_cookie_header!
-
-
2
def delete_cookie_header!(header, key, value = {})
-
case header["Set-Cookie"]
-
when nil, ''
-
cookies = []
-
when String
-
cookies = header["Set-Cookie"].split("\n")
-
when Array
-
cookies = header["Set-Cookie"]
-
end
-
-
cookies.reject! { |cookie|
-
if value[:domain]
-
cookie =~ /\A#{escape(key)}=.*domain=#{value[:domain]}/
-
elsif value[:path]
-
cookie =~ /\A#{escape(key)}=.*path=#{value[:path]}/
-
else
-
cookie =~ /\A#{escape(key)}=/
-
end
-
}
-
-
header["Set-Cookie"] = cookies.join("\n")
-
-
set_cookie_header!(header, key,
-
{:value => '', :path => nil, :domain => nil,
-
:max_age => '0',
-
:expires => Time.at(0) }.merge(value))
-
-
nil
-
end
-
2
module_function :delete_cookie_header!
-
-
# Return the bytesize of String; uses String#size under Ruby 1.8 and
-
# String#bytesize under 1.9.
-
2
if ''.respond_to?(:bytesize)
-
2
def bytesize(string)
-
19
string.bytesize
-
end
-
else
-
def bytesize(string)
-
string.size
-
end
-
end
-
2
module_function :bytesize
-
-
2
def rfc2822(time)
-
time.rfc2822
-
end
-
2
module_function :rfc2822
-
-
# Modified version of stdlib time.rb Time#rfc2822 to use '%d-%b-%Y' instead
-
# of '% %b %Y'.
-
# It assumes that the time is in GMT to comply to the RFC 2109.
-
#
-
# NOTE: I'm not sure the RFC says it requires GMT, but is ambigous enough
-
# that I'm certain someone implemented only that option.
-
# Do not use %a and %b from Time.strptime, it would use localized names for
-
# weekday and month.
-
#
-
2
def rfc2109(time)
-
wday = Time::RFC2822_DAY_NAME[time.wday]
-
mon = Time::RFC2822_MONTH_NAME[time.mon - 1]
-
time.strftime("#{wday}, %d-#{mon}-%Y %H:%M:%S GMT")
-
end
-
2
module_function :rfc2109
-
-
# Parses the "Range:" header, if present, into an array of Range objects.
-
# Returns nil if the header is missing or syntactically invalid.
-
# Returns an empty array if none of the ranges are satisfiable.
-
2
def byte_ranges(env, size)
-
# See <http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35>
-
http_range = env['HTTP_RANGE']
-
return nil unless http_range && http_range =~ /bytes=([^;]+)/
-
ranges = []
-
$1.split(/,\s*/).each do |range_spec|
-
return nil unless range_spec =~ /(\d*)-(\d*)/
-
r0,r1 = $1, $2
-
if r0.empty?
-
return nil if r1.empty?
-
# suffix-byte-range-spec, represents trailing suffix of file
-
r0 = size - r1.to_i
-
r0 = 0 if r0 < 0
-
r1 = size - 1
-
else
-
r0 = r0.to_i
-
if r1.empty?
-
r1 = size - 1
-
else
-
r1 = r1.to_i
-
return nil if r1 < r0 # backwards range is syntactically invalid
-
r1 = size-1 if r1 >= size
-
end
-
end
-
ranges << (r0..r1) if r0 <= r1
-
end
-
ranges
-
end
-
2
module_function :byte_ranges
-
-
# Constant time string comparison.
-
2
def secure_compare(a, b)
-
return false unless bytesize(a) == bytesize(b)
-
-
l = a.unpack("C*")
-
-
r, i = 0, -1
-
b.each_byte { |v| r |= v ^ l[i+=1] }
-
r == 0
-
end
-
2
module_function :secure_compare
-
-
# Context allows the use of a compatible middleware at different points
-
# in a request handling stack. A compatible middleware must define
-
# #context which should take the arguments env and app. The first of which
-
# would be the request environment. The second of which would be the rack
-
# application that the request would be forwarded to.
-
2
class Context
-
2
attr_reader :for, :app
-
-
2
def initialize(app_f, app_r)
-
raise 'running context does not respond to #context' unless app_f.respond_to? :context
-
@for, @app = app_f, app_r
-
end
-
-
2
def call(env)
-
@for.context(env, @app)
-
end
-
-
2
def recontext(app)
-
self.class.new(@for, app)
-
end
-
-
2
def context(env, app=@app)
-
recontext(app).call(env)
-
end
-
end
-
-
# A case-insensitive Hash that preserves the original case of a
-
# header when set.
-
2
class HeaderHash < Hash
-
2
def self.new(hash={})
-
22
HeaderHash === hash ? hash : super(hash)
-
end
-
-
2
def initialize(hash={})
-
22
super()
-
22
@names = {}
-
76
hash.each { |k, v| self[k] = v }
-
end
-
-
2
def each
-
9
super do |k, v|
-
72
yield(k, v.respond_to?(:to_ary) ? v.to_ary.join("\n") : v)
-
end
-
end
-
-
2
def to_hash
-
hash = {}
-
each { |k,v| hash[k] = v }
-
hash
-
end
-
-
2
def [](k)
-
44
super(k) || super(@names[k.downcase])
-
end
-
-
2
def []=(k, v)
-
193
canonical = k.downcase
-
193
delete k if @names[canonical] && @names[canonical] != k # .delete is expensive, don't invoke it unless necessary
-
193
@names[k] = @names[canonical] = k
-
193
super k, v
-
end
-
-
2
def delete(k)
-
canonical = k.downcase
-
result = super @names.delete(canonical)
-
@names.delete_if { |name,| name.downcase == canonical }
-
result
-
end
-
-
2
def include?(k)
-
9
@names.include?(k) || @names.include?(k.downcase)
-
end
-
-
2
alias_method :has_key?, :include?
-
2
alias_method :member?, :include?
-
2
alias_method :key?, :include?
-
-
2
def merge!(other)
-
121
other.each { |k, v| self[k] = v }
-
13
self
-
end
-
-
2
def merge(other)
-
13
hash = dup
-
13
hash.merge! other
-
end
-
-
2
def replace(other)
-
clear
-
other.each { |k, v| self[k] = v }
-
self
-
end
-
end
-
-
2
class KeySpaceConstrainedParams
-
2
def initialize(limit = Utils.key_space_limit)
-
55
@limit = limit
-
55
@size = 0
-
55
@params = {}
-
end
-
-
2
def [](key)
-
62
@params[key]
-
end
-
-
2
def []=(key, value)
-
58
@size += key.size if key && !@params.key?(key)
-
58
raise RangeError, 'exceeded available parameter key space' if @size > @limit
-
58
@params[key] = value
-
end
-
-
2
def key?(key)
-
@params.key?(key)
-
end
-
-
2
def to_params_hash
-
55
hash = @params
-
55
hash.keys.each do |key|
-
42
value = hash[key]
-
42
if value.kind_of?(self.class)
-
4
hash[key] = value.to_params_hash
-
elsif value.kind_of?(Array)
-
value.map! {|x| x.kind_of?(self.class) ? x.to_params_hash : x}
-
end
-
end
-
55
hash
-
end
-
end
-
-
# Every standard HTTP code mapped to the appropriate message.
-
# Generated with:
-
# irb -ropen-uri -rnokogiri
-
# > Nokogiri::XML(open("http://www.iana.org/assignments/http-status-codes/http-status-codes.xml")).css("record").each{|r|
-
# puts "#{r.css('value').text} => '#{r.css('description').text}'"}
-
2
HTTP_STATUS_CODES = {
-
100 => 'Continue',
-
101 => 'Switching Protocols',
-
102 => 'Processing',
-
200 => 'OK',
-
201 => 'Created',
-
202 => 'Accepted',
-
203 => 'Non-Authoritative Information',
-
204 => 'No Content',
-
205 => 'Reset Content',
-
206 => 'Partial Content',
-
207 => 'Multi-Status',
-
208 => 'Already Reported',
-
226 => 'IM Used',
-
300 => 'Multiple Choices',
-
301 => 'Moved Permanently',
-
302 => 'Found',
-
303 => 'See Other',
-
304 => 'Not Modified',
-
305 => 'Use Proxy',
-
306 => 'Reserved',
-
307 => 'Temporary Redirect',
-
308 => 'Permanent Redirect',
-
400 => 'Bad Request',
-
401 => 'Unauthorized',
-
402 => 'Payment Required',
-
403 => 'Forbidden',
-
404 => 'Not Found',
-
405 => 'Method Not Allowed',
-
406 => 'Not Acceptable',
-
407 => 'Proxy Authentication Required',
-
408 => 'Request Timeout',
-
409 => 'Conflict',
-
410 => 'Gone',
-
411 => 'Length Required',
-
412 => 'Precondition Failed',
-
413 => 'Request Entity Too Large',
-
414 => 'Request-URI Too Long',
-
415 => 'Unsupported Media Type',
-
416 => 'Requested Range Not Satisfiable',
-
417 => 'Expectation Failed',
-
422 => 'Unprocessable Entity',
-
423 => 'Locked',
-
424 => 'Failed Dependency',
-
425 => 'Reserved for WebDAV advanced collections expired proposal',
-
426 => 'Upgrade Required',
-
427 => 'Unassigned',
-
428 => 'Precondition Required',
-
429 => 'Too Many Requests',
-
430 => 'Unassigned',
-
431 => 'Request Header Fields Too Large',
-
500 => 'Internal Server Error',
-
501 => 'Not Implemented',
-
502 => 'Bad Gateway',
-
503 => 'Service Unavailable',
-
504 => 'Gateway Timeout',
-
505 => 'HTTP Version Not Supported',
-
506 => 'Variant Also Negotiates (Experimental)',
-
507 => 'Insufficient Storage',
-
508 => 'Loop Detected',
-
509 => 'Unassigned',
-
510 => 'Not Extended',
-
511 => 'Network Authentication Required'
-
}
-
-
# Responses with HTTP status codes that should not have an entity body
-
2
STATUS_WITH_NO_ENTITY_BODY = Set.new((100..199).to_a << 204 << 205 << 304)
-
-
2
SYMBOL_TO_STATUS_CODE = Hash[*HTTP_STATUS_CODES.map { |code, message|
-
124
[message.downcase.gsub(/\s|-/, '_').to_sym, code]
-
}.flatten]
-
-
2
def status_code(status)
-
39
if status.is_a?(Symbol)
-
SYMBOL_TO_STATUS_CODE[status] || 500
-
else
-
39
status.to_i
-
end
-
end
-
2
module_function :status_code
-
-
2
Multipart = Rack::Multipart
-
-
end
-
end
-
2
module Rack
-
-
2
class MockSession # :nodoc:
-
2
attr_writer :cookie_jar
-
2
attr_reader :default_host
-
-
2
def initialize(app, default_host = Rack::Test::DEFAULT_HOST)
-
6
@app = app
-
6
@after_request = []
-
6
@default_host = default_host
-
6
@last_request = nil
-
6
@last_response = nil
-
end
-
-
2
def after_request(&block)
-
@after_request << block
-
end
-
-
2
def clear_cookies
-
@cookie_jar = Rack::Test::CookieJar.new([], @default_host)
-
end
-
-
2
def set_cookie(cookie, uri = nil)
-
cookie_jar.merge(cookie, uri)
-
end
-
-
2
def request(uri, env)
-
13
env["HTTP_COOKIE"] ||= cookie_jar.for(uri)
-
13
@last_request = Rack::Request.new(env)
-
13
status, headers, body = @app.call(@last_request.env)
-
-
13
@last_response = MockResponse.new(status, headers, body, env["rack.errors"].flush)
-
13
body.close if body.respond_to?(:close)
-
-
13
cookie_jar.merge(last_response.headers["Set-Cookie"], uri)
-
-
13
@after_request.each { |hook| hook.call }
-
-
13
if @last_response.respond_to?(:finish)
-
13
@last_response.finish
-
else
-
@last_response
-
end
-
end
-
-
# Return the last request issued in the session. Raises an error if no
-
# requests have been sent yet.
-
2
def last_request
-
10
raise Rack::Test::Error.new("No request yet. Request a page first.") unless @last_request
-
10
@last_request
-
end
-
-
# Return the last response received in the session. Raises an error if
-
# no requests have been sent yet.
-
2
def last_response
-
124
raise Rack::Test::Error.new("No response yet. Request a page first.") unless @last_response
-
124
@last_response
-
end
-
-
2
def cookie_jar
-
26
@cookie_jar ||= Rack::Test::CookieJar.new([], @default_host)
-
end
-
-
end
-
-
end
-
2
require "uri"
-
2
require "rack"
-
2
require "rack/mock_session"
-
2
require "rack/test/cookie_jar"
-
2
require "rack/test/mock_digest_request"
-
2
require "rack/test/utils"
-
2
require "rack/test/methods"
-
2
require "rack/test/uploaded_file"
-
-
2
module Rack
-
2
module Test
-
2
VERSION = "0.6.3"
-
-
2
DEFAULT_HOST = "example.org"
-
2
MULTIPART_BOUNDARY = "----------XnJLe9ZIbbGUYtzPQJ16u1"
-
-
# The common base class for exceptions raised by Rack::Test
-
2
class Error < StandardError; end
-
-
# This class represents a series of requests issued to a Rack app, sharing
-
# a single cookie jar
-
#
-
# Rack::Test::Session's methods are most often called through Rack::Test::Methods,
-
# which will automatically build a session when it's first used.
-
2
class Session
-
2
extend Forwardable
-
2
include Rack::Test::Utils
-
-
2
def_delegators :@rack_mock_session, :clear_cookies, :set_cookie, :last_response, :last_request
-
-
# Creates a Rack::Test::Session for a given Rack app or Rack::MockSession.
-
#
-
# Note: Generally, you won't need to initialize a Rack::Test::Session directly.
-
# Instead, you should include Rack::Test::Methods into your testing context.
-
# (See README.rdoc for an example)
-
2
def initialize(mock_session)
-
6
@headers = {}
-
6
@env = {}
-
-
6
if mock_session.is_a?(MockSession)
-
6
@rack_mock_session = mock_session
-
else
-
@rack_mock_session = MockSession.new(mock_session)
-
end
-
-
6
@default_host = @rack_mock_session.default_host
-
end
-
-
# Issue a GET request for the given URI with the given params and Rack
-
# environment. Stores the issues request object in #last_request and
-
# the app's response in #last_response. Yield #last_response to a block
-
# if given.
-
#
-
# Example:
-
# get "/"
-
2
def get(uri, params = {}, env = {}, &block)
-
9
env = env_for(uri, env.merge(:method => "GET", :params => params))
-
9
process_request(uri, env, &block)
-
end
-
-
# Issue a POST request for the given URI. See #get
-
#
-
# Example:
-
# post "/signup", "name" => "Bryan"
-
2
def post(uri, params = {}, env = {}, &block)
-
4
env = env_for(uri, env.merge(:method => "POST", :params => params))
-
4
process_request(uri, env, &block)
-
end
-
-
# Issue a PUT request for the given URI. See #get
-
#
-
# Example:
-
# put "/"
-
2
def put(uri, params = {}, env = {}, &block)
-
env = env_for(uri, env.merge(:method => "PUT", :params => params))
-
process_request(uri, env, &block)
-
end
-
-
# Issue a PATCH request for the given URI. See #get
-
#
-
# Example:
-
# patch "/"
-
2
def patch(uri, params = {}, env = {}, &block)
-
env = env_for(uri, env.merge(:method => "PATCH", :params => params))
-
process_request(uri, env, &block)
-
end
-
-
# Issue a DELETE request for the given URI. See #get
-
#
-
# Example:
-
# delete "/"
-
2
def delete(uri, params = {}, env = {}, &block)
-
env = env_for(uri, env.merge(:method => "DELETE", :params => params))
-
process_request(uri, env, &block)
-
end
-
-
# Issue an OPTIONS request for the given URI. See #get
-
#
-
# Example:
-
# options "/"
-
2
def options(uri, params = {}, env = {}, &block)
-
env = env_for(uri, env.merge(:method => "OPTIONS", :params => params))
-
process_request(uri, env, &block)
-
end
-
-
# Issue a HEAD request for the given URI. See #get
-
#
-
# Example:
-
# head "/"
-
2
def head(uri, params = {}, env = {}, &block)
-
env = env_for(uri, env.merge(:method => "HEAD", :params => params))
-
process_request(uri, env, &block)
-
end
-
-
# Issue a request to the Rack app for the given URI and optional Rack
-
# environment. Stores the issues request object in #last_request and
-
# the app's response in #last_response. Yield #last_response to a block
-
# if given.
-
#
-
# Example:
-
# request "/"
-
2
def request(uri, env = {}, &block)
-
env = env_for(uri, env)
-
process_request(uri, env, &block)
-
end
-
-
# Set a header to be included on all subsequent requests through the
-
# session. Use a value of nil to remove a previously configured header.
-
#
-
# In accordance with the Rack spec, headers will be included in the Rack
-
# environment hash in HTTP_USER_AGENT form.
-
#
-
# Example:
-
# header "User-Agent", "Firefox"
-
2
def header(name, value)
-
if value.nil?
-
@headers.delete(name)
-
else
-
@headers[name] = value
-
end
-
end
-
-
# Set an env var to be included on all subsequent requests through the
-
# session. Use a value of nil to remove a previously configured env.
-
#
-
# Example:
-
# env "rack.session", {:csrf => 'token'}
-
2
def env(name, value)
-
if value.nil?
-
@env.delete(name)
-
else
-
@env[name] = value
-
end
-
end
-
-
# Set the username and password for HTTP Basic authorization, to be
-
# included in subsequent requests in the HTTP_AUTHORIZATION header.
-
#
-
# Example:
-
# basic_authorize "bryan", "secret"
-
2
def basic_authorize(username, password)
-
encoded_login = ["#{username}:#{password}"].pack("m*")
-
header('Authorization', "Basic #{encoded_login}")
-
end
-
-
2
alias_method :authorize, :basic_authorize
-
-
# Set the username and password for HTTP Digest authorization, to be
-
# included in subsequent requests in the HTTP_AUTHORIZATION header.
-
#
-
# Example:
-
# digest_authorize "bryan", "secret"
-
2
def digest_authorize(username, password)
-
@digest_username = username
-
@digest_password = password
-
end
-
-
# Rack::Test will not follow any redirects automatically. This method
-
# will follow the redirect returned (including setting the Referer header
-
# on the new request) in the last response. If the last response was not
-
# a redirect, an error will be raised.
-
2
def follow_redirect!
-
unless last_response.redirect?
-
raise Error.new("Last response was not a redirect. Cannot follow_redirect!")
-
end
-
-
get(last_response["Location"], {}, { "HTTP_REFERER" => last_request.url })
-
end
-
-
2
private
-
-
2
def env_for(path, env)
-
13
uri = URI.parse(path)
-
13
uri.path = "/#{uri.path}" unless uri.path[0] == ?/
-
13
uri.host ||= @default_host
-
-
13
env = default_env.merge(env)
-
-
13
env["HTTP_HOST"] ||= [uri.host, (uri.port if uri.port != uri.default_port)].compact.join(":")
-
-
13
env.update("HTTPS" => "on") if URI::HTTPS === uri
-
13
env["HTTP_X_REQUESTED_WITH"] = "XMLHttpRequest" if env[:xhr]
-
-
# TODO: Remove this after Rack 1.1 has been released.
-
# Stringifying and upcasing methods has be commit upstream
-
13
env["REQUEST_METHOD"] ||= env[:method] ? env[:method].to_s.upcase : "GET"
-
-
13
if env["REQUEST_METHOD"] == "GET"
-
# merge :params with the query string
-
9
if params = env[:params]
-
9
params = parse_nested_query(params) if params.is_a?(String)
-
9
params.update(parse_nested_query(uri.query))
-
9
uri.query = build_nested_query(params)
-
end
-
elsif !env.has_key?(:input)
-
4
env["CONTENT_TYPE"] ||= "application/x-www-form-urlencoded"
-
-
4
if env[:params].is_a?(Hash)
-
4
if data = build_multipart(env[:params])
-
2
env[:input] = data
-
2
env["CONTENT_LENGTH"] ||= data.length.to_s
-
2
env["CONTENT_TYPE"] = "multipart/form-data; boundary=#{MULTIPART_BOUNDARY}"
-
else
-
2
env[:input] = params_to_string(env[:params])
-
end
-
else
-
env[:input] = env[:params]
-
end
-
end
-
-
13
env.delete(:params)
-
-
13
if env.has_key?(:cookie)
-
set_cookie(env.delete(:cookie), uri)
-
end
-
-
13
Rack::MockRequest.env_for(uri.to_s, env)
-
end
-
-
2
def process_request(uri, env)
-
13
uri = URI.parse(uri)
-
13
uri.host ||= @default_host
-
-
13
@rack_mock_session.request(uri, env)
-
-
13
if retry_with_digest_auth?(env)
-
auth_env = env.merge({
-
"HTTP_AUTHORIZATION" => digest_auth_header,
-
"rack-test.digest_auth_retry" => true
-
})
-
auth_env.delete('rack.request')
-
process_request(uri.path, auth_env)
-
else
-
13
yield last_response if block_given?
-
-
13
last_response
-
end
-
end
-
-
2
def digest_auth_header
-
challenge = last_response["WWW-Authenticate"].split(" ", 2).last
-
params = Rack::Auth::Digest::Params.parse(challenge)
-
-
params.merge!({
-
"username" => @digest_username,
-
"nc" => "00000001",
-
"cnonce" => "nonsensenonce",
-
"uri" => last_request.fullpath,
-
"method" => last_request.env["REQUEST_METHOD"],
-
})
-
-
params["response"] = MockDigestRequest.new(params).response(@digest_password)
-
-
"Digest #{params}"
-
end
-
-
2
def retry_with_digest_auth?(env)
-
last_response.status == 401 &&
-
13
digest_auth_configured? &&
-
!env["rack-test.digest_auth_retry"]
-
end
-
-
2
def digest_auth_configured?
-
@digest_username
-
end
-
-
2
def default_env
-
13
{ "rack.test" => true, "REMOTE_ADDR" => "127.0.0.1" }.merge(@env).merge(headers_for_env)
-
end
-
-
2
def headers_for_env
-
13
converted_headers = {}
-
-
13
@headers.each do |name, value|
-
env_key = name.upcase.gsub("-", "_")
-
env_key = "HTTP_" + env_key unless "CONTENT_TYPE" == env_key
-
converted_headers[env_key] = value
-
end
-
-
13
converted_headers
-
end
-
-
2
def params_to_string(params)
-
2
case params
-
2
when Hash then build_nested_query(params)
-
when nil then ""
-
else params
-
end
-
end
-
-
end
-
-
2
def self.encoding_aware_strings?
-
16
defined?(Encoding) && "".respond_to?(:encode)
-
end
-
-
end
-
end
-
2
require 'rails/ruby_version_check'
-
-
2
require 'pathname'
-
-
2
require 'active_support'
-
2
require 'active_support/dependencies/autoload'
-
2
require 'active_support/core_ext/kernel/reporting'
-
2
require 'active_support/core_ext/module/delegation'
-
2
require 'active_support/core_ext/array/extract_options'
-
-
2
require 'rails/application'
-
2
require 'rails/version'
-
-
2
require 'active_support/railtie'
-
2
require 'action_dispatch/railtie'
-
-
# For Ruby 1.9, UTF-8 is the default internal and external encoding.
-
2
silence_warnings do
-
2
Encoding.default_external = Encoding::UTF_8
-
2
Encoding.default_internal = Encoding::UTF_8
-
end
-
-
2
module Rails
-
2
extend ActiveSupport::Autoload
-
-
2
autoload :Info
-
2
autoload :InfoController
-
2
autoload :MailersController
-
2
autoload :WelcomeController
-
-
2
class << self
-
2
attr_accessor :application, :cache, :logger
-
-
2
delegate :initialize!, :initialized?, to: :application
-
-
# The Configuration instance used to configure the Rails environment
-
2
def configuration
-
application.config
-
end
-
-
2
def backtrace_cleaner
-
@backtrace_cleaner ||= begin
-
# Relies on Active Support, so we have to lazy load to postpone definition until AS has been loaded
-
2
require 'rails/backtrace_cleaner'
-
2
Rails::BacktraceCleaner.new
-
5
end
-
end
-
-
2
def root
-
39
application && application.config.root
-
end
-
-
2
def env
-
76
@_env ||= ActiveSupport::StringInquirer.new(ENV["RAILS_ENV"] || ENV["RACK_ENV"] || "development")
-
end
-
-
2
def env=(environment)
-
@_env = ActiveSupport::StringInquirer.new(environment)
-
end
-
-
# Returns all rails groups for loading based on:
-
#
-
# * The Rails environment;
-
# * The environment variable RAILS_GROUPS;
-
# * The optional envs given as argument and the hash with group dependencies;
-
#
-
# groups assets: [:development, :test]
-
#
-
# # Returns
-
# # => [:default, :development, :assets] for Rails.env == "development"
-
# # => [:default, :production] for Rails.env == "production"
-
2
def groups(*groups)
-
2
hash = groups.extract_options!
-
2
env = Rails.env
-
2
groups.unshift(:default, env)
-
2
groups.concat ENV["RAILS_GROUPS"].to_s.split(",")
-
2
groups.concat hash.map { |k, v| k if v.map(&:to_s).include?(env) }
-
2
groups.compact!
-
2
groups.uniq!
-
2
groups
-
end
-
-
2
def public_path
-
4
application && Pathname.new(application.paths["public"].first)
-
end
-
end
-
end
-
2
require "rails"
-
-
%w(
-
active_record
-
action_controller
-
action_view
-
action_mailer
-
rails/test_unit
-
sprockets
-
2
).each do |framework|
-
12
begin
-
12
require "#{framework}/railtie"
-
rescue LoadError
-
end
-
end
-
2
require 'fileutils'
-
2
require 'active_support/core_ext/hash/keys'
-
2
require 'active_support/core_ext/object/blank'
-
2
require 'active_support/key_generator'
-
2
require 'active_support/message_verifier'
-
2
require 'rails/engine'
-
-
2
module Rails
-
# In Rails 3.0, a Rails::Application object was introduced which is nothing more than
-
# an Engine but with the responsibility of coordinating the whole boot process.
-
#
-
# == Initialization
-
#
-
# Rails::Application is responsible for executing all railties and engines
-
# initializers. It also executes some bootstrap initializers (check
-
# Rails::Application::Bootstrap) and finishing initializers, after all the others
-
# are executed (check Rails::Application::Finisher).
-
#
-
# == Configuration
-
#
-
# Besides providing the same configuration as Rails::Engine and Rails::Railtie,
-
# the application object has several specific configurations, for example
-
# "cache_classes", "consider_all_requests_local", "filter_parameters",
-
# "logger" and so forth.
-
#
-
# Check Rails::Application::Configuration to see them all.
-
#
-
# == Routes
-
#
-
# The application object is also responsible for holding the routes and reloading routes
-
# whenever the files change in development.
-
#
-
# == Middlewares
-
#
-
# The Application is also responsible for building the middleware stack.
-
#
-
# == Booting process
-
#
-
# The application is also responsible for setting up and executing the booting
-
# process. From the moment you require "config/application.rb" in your app,
-
# the booting process goes like this:
-
#
-
# 1) require "config/boot.rb" to setup load paths
-
# 2) require railties and engines
-
# 3) Define Rails.application as "class MyApp::Application < Rails::Application"
-
# 4) Run config.before_configuration callbacks
-
# 5) Load config/environments/ENV.rb
-
# 6) Run config.before_initialize callbacks
-
# 7) Run Railtie#initializer defined by railties, engines and application.
-
# One by one, each engine sets up its load paths, routes and runs its config/initializers/* files.
-
# 8) Custom Railtie#initializers added by railties, engines and applications are executed
-
# 9) Build the middleware stack and run to_prepare callbacks
-
# 10) Run config.before_eager_load and eager_load! if eager_load is true
-
# 11) Run config.after_initialize callbacks
-
#
-
# == Multiple Applications
-
#
-
# If you decide to define multiple applications, then the first application
-
# that is initialized will be set to +Rails.application+, unless you override
-
# it with a different application.
-
#
-
# To create a new application, you can instantiate a new instance of a class
-
# that has already been created:
-
#
-
# class Application < Rails::Application
-
# end
-
#
-
# first_application = Application.new
-
# second_application = Application.new(config: first_application.config)
-
#
-
# In the above example, the configuration from the first application was used
-
# to initialize the second application. You can also use the +initialize_copy+
-
# on one of the applications to create a copy of the application which shares
-
# the configuration.
-
#
-
# If you decide to define rake tasks, runners, or initializers in an
-
# application other than +Rails.application+, then you must run those
-
# these manually.
-
2
class Application < Engine
-
2
autoload :Bootstrap, 'rails/application/bootstrap'
-
2
autoload :Configuration, 'rails/application/configuration'
-
2
autoload :DefaultMiddlewareStack, 'rails/application/default_middleware_stack'
-
2
autoload :Finisher, 'rails/application/finisher'
-
2
autoload :Railties, 'rails/engine/railties'
-
2
autoload :RoutesReloader, 'rails/application/routes_reloader'
-
-
2
class << self
-
2
def inherited(base)
-
2
super
-
2
base.instance
-
end
-
-
# Makes the +new+ method public.
-
#
-
# Note that Rails::Application inherits from Rails::Engine, which
-
# inherits from Rails::Railtie and the +new+ method on Rails::Railtie is
-
# private
-
2
public :new
-
end
-
-
2
attr_accessor :assets, :sandbox
-
2
alias_method :sandbox?, :sandbox
-
2
attr_reader :reloaders
-
-
2
delegate :default_url_options, :default_url_options=, to: :routes
-
-
2
INITIAL_VARIABLES = [:config, :railties, :routes_reloader, :reloaders,
-
:routes, :helpers, :app_env_config, :secrets] # :nodoc:
-
-
2
def initialize(initial_variable_values = {}, &block)
-
2
super()
-
2
@initialized = false
-
2
@reloaders = []
-
2
@routes_reloader = nil
-
2
@app_env_config = nil
-
2
@ordered_railties = nil
-
2
@railties = nil
-
2
@message_verifiers = {}
-
-
2
Rails.application ||= self
-
-
2
add_lib_to_load_path!
-
2
ActiveSupport.run_load_hooks(:before_configuration, self)
-
-
2
initial_variable_values.each do |variable_name, value|
-
if INITIAL_VARIABLES.include?(variable_name)
-
instance_variable_set("@#{variable_name}", value)
-
end
-
end
-
-
2
instance_eval(&block) if block_given?
-
end
-
-
# Returns true if the application is initialized.
-
2
def initialized?
-
@initialized
-
end
-
-
# Implements call according to the Rack API. It simply
-
# dispatches the request to the underlying middleware stack.
-
2
def call(env)
-
13
env["ORIGINAL_FULLPATH"] = build_original_fullpath(env)
-
13
env["ORIGINAL_SCRIPT_NAME"] = env["SCRIPT_NAME"]
-
13
super(env)
-
end
-
-
# Reload application routes regardless if they changed or not.
-
2
def reload_routes!
-
routes_reloader.reload!
-
end
-
-
# Return the application's KeyGenerator
-
2
def key_generator
-
# number of iterations selected based on consultation with the google security
-
# team. Details at https://github.com/rails/rails/pull/6952#issuecomment-7661220
-
@caching_key_generator ||= begin
-
2
if secrets.secret_key_base
-
2
key_generator = ActiveSupport::KeyGenerator.new(secrets.secret_key_base, iterations: 1000)
-
2
ActiveSupport::CachingKeyGenerator.new(key_generator)
-
else
-
ActiveSupport::LegacyKeyGenerator.new(config.secret_token)
-
end
-
2
end
-
end
-
-
# Returns a message verifier object.
-
#
-
# This verifier can be used to generate and verify signed messages in the application.
-
#
-
# It is recommended not to use the same verifier for different things, so you can get different
-
# verifiers passing the +verifier_name+ argument.
-
#
-
# ==== Parameters
-
#
-
# * +verifier_name+ - the name of the message verifier.
-
#
-
# ==== Examples
-
#
-
# message = Rails.application.message_verifier('sensitive_data').generate('my sensible data')
-
# Rails.application.message_verifier('sensitive_data').verify(message)
-
# # => 'my sensible data'
-
#
-
# See the +ActiveSupport::MessageVerifier+ documentation for more information.
-
2
def message_verifier(verifier_name)
-
@message_verifiers[verifier_name] ||= begin
-
secret = key_generator.generate_key(verifier_name.to_s)
-
ActiveSupport::MessageVerifier.new(secret)
-
end
-
end
-
-
# Stores some of the Rails initial environment parameters which
-
# will be used by middlewares and engines to configure themselves.
-
2
def env_config
-
@app_env_config ||= begin
-
2
validate_secret_key_config!
-
-
2
super.merge({
-
"action_dispatch.parameter_filter" => config.filter_parameters,
-
"action_dispatch.redirect_filter" => config.filter_redirect,
-
"action_dispatch.secret_token" => config.secret_token,
-
"action_dispatch.secret_key_base" => secrets.secret_key_base,
-
"action_dispatch.show_exceptions" => config.action_dispatch.show_exceptions,
-
"action_dispatch.show_detailed_exceptions" => config.consider_all_requests_local,
-
"action_dispatch.logger" => Rails.logger,
-
"action_dispatch.backtrace_cleaner" => Rails.backtrace_cleaner,
-
"action_dispatch.key_generator" => key_generator,
-
"action_dispatch.http_auth_salt" => config.action_dispatch.http_auth_salt,
-
"action_dispatch.signed_cookie_salt" => config.action_dispatch.signed_cookie_salt,
-
"action_dispatch.encrypted_cookie_salt" => config.action_dispatch.encrypted_cookie_salt,
-
"action_dispatch.encrypted_signed_cookie_salt" => config.action_dispatch.encrypted_signed_cookie_salt,
-
"action_dispatch.cookies_serializer" => config.action_dispatch.cookies_serializer
-
})
-
28
end
-
end
-
-
# If you try to define a set of rake tasks on the instance, these will get
-
# passed up to the rake tasks defined on the application's class.
-
2
def rake_tasks(&block)
-
self.class.rake_tasks(&block)
-
end
-
-
# Sends the initializers to the +initializer+ method defined in the
-
# Rails::Initializable module. Each Rails::Application class has its own
-
# set of initializers, as defined by the Initializable module.
-
2
def initializer(name, opts={}, &block)
-
self.class.initializer(name, opts, &block)
-
end
-
-
# Sends any runner called in the instance of a new application up
-
# to the +runner+ method defined in Rails::Railtie.
-
2
def runner(&blk)
-
self.class.runner(&blk)
-
end
-
-
# Sends any console called in the instance of a new application up
-
# to the +console+ method defined in Rails::Railtie.
-
2
def console(&blk)
-
self.class.console(&blk)
-
end
-
-
# Sends any generators called in the instance of a new application up
-
# to the +generators+ method defined in Rails::Railtie.
-
2
def generators(&blk)
-
self.class.generators(&blk)
-
end
-
-
# Sends the +isolate_namespace+ method up to the class method.
-
2
def isolate_namespace(mod)
-
self.class.isolate_namespace(mod)
-
end
-
-
## Rails internal API
-
-
# This method is called just after an application inherits from Rails::Application,
-
# allowing the developer to load classes in lib and use them during application
-
# configuration.
-
#
-
# class MyApplication < Rails::Application
-
# require "my_backend" # in lib/my_backend
-
# config.i18n.backend = MyBackend
-
# end
-
#
-
# Notice this method takes into consideration the default root path. So if you
-
# are changing config.root inside your application definition or having a custom
-
# Rails application, you will need to add lib to $LOAD_PATH on your own in case
-
# you need to load files in lib/ during the application configuration as well.
-
2
def add_lib_to_load_path! #:nodoc:
-
2
path = File.join config.root, 'lib'
-
2
if File.exist?(path) && !$LOAD_PATH.include?(path)
-
1
$LOAD_PATH.unshift(path)
-
end
-
end
-
-
2
def require_environment! #:nodoc:
-
environment = paths["config/environment"].existent.first
-
require environment if environment
-
end
-
-
2
def routes_reloader #:nodoc:
-
6
@routes_reloader ||= RoutesReloader.new
-
end
-
-
# Returns an array of file paths appended with a hash of
-
# directories-extensions suitable for ActiveSupport::FileUpdateChecker
-
# API.
-
2
def watchable_args #:nodoc:
-
2
files, dirs = config.watchable_files.dup, config.watchable_dirs.dup
-
-
2
ActiveSupport::Dependencies.autoload_paths.each do |path|
-
26
dirs[path.to_s] = [:rb]
-
end
-
-
2
[files, dirs]
-
end
-
-
# Initialize the application passing the given group. By default, the
-
# group is :default
-
2
def initialize!(group=:default) #:nodoc:
-
2
raise "Application has been already initialized." if @initialized
-
2
run_initializers(group, self)
-
2
@initialized = true
-
2
self
-
end
-
-
2
def initializers #:nodoc:
-
Bootstrap.initializers_for(self) +
-
railties_initializers(super) +
-
2
Finisher.initializers_for(self)
-
end
-
-
2
def config #:nodoc:
-
421
@config ||= Application::Configuration.new(find_root_with_flag("config.ru", Dir.pwd))
-
end
-
-
2
def config=(configuration) #:nodoc:
-
@config = configuration
-
end
-
-
2
def secrets #:nodoc:
-
@secrets ||= begin
-
2
secrets = ActiveSupport::OrderedOptions.new
-
2
yaml = config.paths["config/secrets"].first
-
2
if File.exist?(yaml)
-
2
require "erb"
-
2
all_secrets = YAML.load(ERB.new(IO.read(yaml)).result) || {}
-
2
env_secrets = all_secrets[Rails.env]
-
2
secrets.merge!(env_secrets.symbolize_keys) if env_secrets
-
end
-
-
# Fallback to config.secret_key_base if secrets.secret_key_base isn't set
-
2
secrets.secret_key_base ||= config.secret_key_base
-
-
2
secrets
-
10
end
-
end
-
-
2
def secrets=(secrets) #:nodoc:
-
@secrets = secrets
-
end
-
-
2
def to_app #:nodoc:
-
self
-
end
-
-
2
def helpers_paths #:nodoc:
-
2
config.helpers_paths
-
end
-
-
2
console do
-
require "pp"
-
end
-
-
2
console do
-
unless ::Kernel.private_method_defined?(:y)
-
if RUBY_VERSION >= '2.0'
-
require "psych/y"
-
else
-
module ::Kernel
-
def y(*objects)
-
puts ::Psych.dump_stream(*objects)
-
end
-
private :y
-
end
-
end
-
end
-
end
-
-
# Return an array of railties respecting the order they're loaded
-
# and the order specified by the +railties_order+ config.
-
#
-
# While when running initializers we need engines in reverse
-
# order here when copying migrations from railties we need then in the same
-
# order as given by +railties_order+
-
2
def migration_railties # :nodoc:
-
ordered_railties.flatten - [self]
-
end
-
-
2
protected
-
-
2
alias :build_middleware_stack :app
-
-
2
def run_tasks_blocks(app) #:nodoc:
-
railties.each { |r| r.run_tasks_blocks(app) }
-
super
-
require "rails/tasks"
-
task :environment do
-
ActiveSupport.on_load(:before_initialize) { config.eager_load = false }
-
-
require_environment!
-
end
-
end
-
-
2
def run_generators_blocks(app) #:nodoc:
-
railties.each { |r| r.run_generators_blocks(app) }
-
super
-
end
-
-
2
def run_runner_blocks(app) #:nodoc:
-
railties.each { |r| r.run_runner_blocks(app) }
-
super
-
end
-
-
2
def run_console_blocks(app) #:nodoc:
-
railties.each { |r| r.run_console_blocks(app) }
-
super
-
end
-
-
# Returns the ordered railties for this application considering railties_order.
-
2
def ordered_railties #:nodoc:
-
@ordered_railties ||= begin
-
2
order = config.railties_order.map do |railtie|
-
2
if railtie == :main_app
-
self
-
elsif railtie.respond_to?(:instance)
-
railtie.instance
-
else
-
2
railtie
-
end
-
end
-
-
2
all = (railties - order)
-
2
all.push(self) unless (all + order).include?(self)
-
2
order.push(:all) unless order.include?(:all)
-
-
2
index = order.index(:all)
-
2
order[index] = all
-
2
order
-
2
end
-
end
-
-
2
def railties_initializers(current) #:nodoc:
-
2
initializers = []
-
2
ordered_railties.reverse.flatten.each do |r|
-
64
if r == self
-
2
initializers += current
-
else
-
62
initializers += r.initializers
-
end
-
end
-
2
initializers
-
end
-
-
2
def default_middleware_stack #:nodoc:
-
2
default_stack = DefaultMiddlewareStack.new(self, config, paths)
-
2
default_stack.build_stack
-
end
-
-
2
def build_original_fullpath(env) #:nodoc:
-
13
path_info = env["PATH_INFO"]
-
13
query_string = env["QUERY_STRING"]
-
13
script_name = env["SCRIPT_NAME"]
-
-
13
if query_string.present?
-
"#{script_name}#{path_info}?#{query_string}"
-
else
-
13
"#{script_name}#{path_info}"
-
end
-
end
-
-
2
def validate_secret_key_config! #:nodoc:
-
2
if secrets.secret_key_base.blank? && config.secret_token.blank?
-
raise "Missing `secret_key_base` for '#{Rails.env}' environment, set this value in `config/secrets.yml`"
-
end
-
end
-
end
-
end
-
2
require "active_support/notifications"
-
2
require "active_support/dependencies"
-
2
require "active_support/descendants_tracker"
-
-
2
module Rails
-
2
class Application
-
2
module Bootstrap
-
2
include Initializable
-
-
2
initializer :load_environment_hook, group: :all do end
-
-
2
initializer :load_active_support, group: :all do
-
2
require "active_support/all" unless config.active_support.bare
-
end
-
-
2
initializer :set_eager_load, group: :all do
-
2
if config.eager_load.nil?
-
warn <<-INFO
-
config.eager_load is set to nil. Please update your config/environments/*.rb files accordingly:
-
-
* development - set it to false
-
* test - set it to false (unless you use a tool that preloads your test environment)
-
* production - set it to true
-
-
INFO
-
config.eager_load = config.cache_classes
-
end
-
end
-
-
# Initialize the logger early in the stack in case we need to log some deprecation.
-
2
initializer :initialize_logger, group: :all do
-
2
Rails.logger ||= config.logger || begin
-
2
path = config.paths["log"].first
-
2
unless File.exist? File.dirname path
-
FileUtils.mkdir_p File.dirname path
-
end
-
-
2
f = File.open path, 'a'
-
2
f.binmode
-
2
f.sync = config.autoflush_log # if true make sure every write flushes
-
-
2
logger = ActiveSupport::Logger.new f
-
2
logger.formatter = config.log_formatter
-
2
logger = ActiveSupport::TaggedLogging.new(logger)
-
2
logger
-
rescue StandardError
-
logger = ActiveSupport::TaggedLogging.new(ActiveSupport::Logger.new(STDERR))
-
logger.level = ActiveSupport::Logger::WARN
-
logger.warn(
-
"Rails Error: Unable to access log file. Please ensure that #{path} exists and is chmod 0666. " +
-
"The log level has been raised to WARN and the output directed to STDERR until the problem is fixed."
-
)
-
logger
-
end
-
-
2
Rails.logger.level = ActiveSupport::Logger.const_get(config.log_level.to_s.upcase)
-
end
-
-
# Initialize cache early in the stack so railties can make use of it.
-
2
initializer :initialize_cache, group: :all do
-
2
unless Rails.cache
-
2
Rails.cache = ActiveSupport::Cache.lookup_store(config.cache_store)
-
-
2
if Rails.cache.respond_to?(:middleware)
-
2
config.middleware.insert_before("Rack::Runtime", Rails.cache.middleware)
-
end
-
end
-
end
-
-
# Sets the dependency loading mechanism.
-
2
initializer :initialize_dependency_mechanism, group: :all do
-
2
ActiveSupport::Dependencies.mechanism = config.cache_classes ? :require : :load
-
end
-
-
2
initializer :bootstrap_hook, group: :all do |app|
-
2
ActiveSupport.run_load_hooks(:before_initialize, app)
-
end
-
end
-
end
-
end
-
2
require 'active_support/core_ext/kernel/reporting'
-
2
require 'active_support/file_update_checker'
-
2
require 'rails/engine/configuration'
-
-
2
module Rails
-
2
class Application
-
2
class Configuration < ::Rails::Engine::Configuration
-
2
attr_accessor :allow_concurrency, :asset_host, :assets, :autoflush_log,
-
:cache_classes, :cache_store, :consider_all_requests_local, :console,
-
:eager_load, :exceptions_app, :file_watcher, :filter_parameters,
-
:force_ssl, :helpers_paths, :logger, :log_formatter, :log_tags,
-
:railties_order, :relative_url_root, :secret_key_base, :secret_token,
-
:serve_static_assets, :ssl_options, :static_cache_control, :session_options,
-
:time_zone, :reload_classes_only_on_change,
-
:beginning_of_week, :filter_redirect
-
-
2
attr_writer :log_level
-
2
attr_reader :encoding
-
-
2
def initialize(*)
-
2
super
-
2
self.encoding = "utf-8"
-
2
@allow_concurrency = nil
-
2
@consider_all_requests_local = false
-
2
@filter_parameters = []
-
2
@filter_redirect = []
-
2
@helpers_paths = []
-
2
@serve_static_assets = true
-
2
@static_cache_control = nil
-
2
@force_ssl = false
-
2
@ssl_options = {}
-
2
@session_store = :cookie_store
-
2
@session_options = {}
-
2
@time_zone = "UTC"
-
2
@beginning_of_week = :monday
-
2
@log_level = nil
-
2
@middleware = app_middleware
-
2
@generators = app_generators
-
2
@cache_store = [ :file_store, "#{root}/tmp/cache/" ]
-
2
@railties_order = [:all]
-
2
@relative_url_root = ENV["RAILS_RELATIVE_URL_ROOT"]
-
2
@reload_classes_only_on_change = true
-
2
@file_watcher = ActiveSupport::FileUpdateChecker
-
2
@exceptions_app = nil
-
2
@autoflush_log = true
-
2
@log_formatter = ActiveSupport::Logger::SimpleFormatter.new
-
2
@eager_load = nil
-
2
@secret_token = nil
-
2
@secret_key_base = nil
-
-
2
@assets = ActiveSupport::OrderedOptions.new
-
2
@assets.enabled = true
-
2
@assets.paths = []
-
2
@assets.precompile = [ Proc.new { |path, fn| fn =~ /app\/assets/ && !%w(.js .css).include?(File.extname(path)) },
-
/(?:\/|\\|\A)application\.(css|js)$/ ]
-
2
@assets.prefix = "/assets"
-
2
@assets.version = '1.0'
-
2
@assets.debug = false
-
2
@assets.compile = true
-
2
@assets.digest = false
-
2
@assets.cache_store = [ :file_store, "#{root}/tmp/cache/assets/#{Rails.env}/" ]
-
2
@assets.js_compressor = nil
-
2
@assets.css_compressor = nil
-
2
@assets.logger = nil
-
end
-
-
2
def encoding=(value)
-
2
@encoding = value
-
2
silence_warnings do
-
2
Encoding.default_external = value
-
2
Encoding.default_internal = value
-
end
-
end
-
-
2
def paths
-
@paths ||= begin
-
2
paths = super
-
2
paths.add "config/database", with: "config/database.yml"
-
2
paths.add "config/secrets", with: "config/secrets.yml"
-
2
paths.add "config/environment", with: "config/environment.rb"
-
2
paths.add "lib/templates"
-
2
paths.add "log", with: "log/#{Rails.env}.log"
-
2
paths.add "public"
-
2
paths.add "public/javascripts"
-
2
paths.add "public/stylesheets"
-
2
paths.add "tmp"
-
2
paths
-
52
end
-
end
-
-
# Loads and returns the entire raw configuration of database from
-
# values stored in `config/database.yml`.
-
2
def database_configuration
-
2
yaml = Pathname.new(paths["config/database"].existent.first || "")
-
-
2
config = if yaml.exist?
-
2
require "yaml"
-
2
require "erb"
-
2
YAML.load(ERB.new(yaml.read).result) || {}
-
elsif ENV['DATABASE_URL']
-
# Value from ENV['DATABASE_URL'] is set to default database connection
-
# by Active Record.
-
{}
-
else
-
raise "Could not load database configuration. No such file - #{yaml}"
-
end
-
-
2
config
-
rescue Psych::SyntaxError => e
-
raise "YAML syntax error occurred while parsing #{paths["config/database"].first}. " \
-
"Please note that YAML must be consistently indented using spaces. Tabs are not allowed. " \
-
"Error: #{e.message}"
-
rescue => e
-
raise e, "Cannot load `Rails.application.database_configuration`:\n#{e.message}", e.backtrace
-
end
-
-
2
def log_level
-
2
@log_level ||= Rails.env.production? ? :info : :debug
-
end
-
-
2
def colorize_logging
-
ActiveSupport::LogSubscriber.colorize_logging
-
end
-
-
2
def colorize_logging=(val)
-
ActiveSupport::LogSubscriber.colorize_logging = val
-
self.generators.colorize_logging = val
-
end
-
-
2
def session_store(*args)
-
6
if args.empty?
-
4
case @session_store
-
when :disabled
-
nil
-
when :active_record_store
-
begin
-
ActionDispatch::Session::ActiveRecordStore
-
rescue NameError
-
raise "`ActiveRecord::SessionStore` is extracted out of Rails into a gem. " \
-
"Please add `activerecord-session_store` to your Gemfile to use it."
-
end
-
when Symbol
-
4
ActionDispatch::Session.const_get(@session_store.to_s.camelize)
-
else
-
@session_store
-
end
-
else
-
2
@session_store = args.shift
-
2
@session_options = args.shift || {}
-
end
-
end
-
-
end
-
end
-
end
-
2
module Rails
-
2
class Application
-
2
class DefaultMiddlewareStack
-
2
attr_reader :config, :paths, :app
-
-
2
def initialize(app, config, paths)
-
2
@app = app
-
2
@config = config
-
2
@paths = paths
-
end
-
-
2
def build_stack
-
2
ActionDispatch::MiddlewareStack.new.tap do |middleware|
-
2
if config.force_ssl
-
middleware.use ::ActionDispatch::SSL, config.ssl_options
-
end
-
-
2
middleware.use ::Rack::Sendfile, config.action_dispatch.x_sendfile_header
-
-
2
if config.serve_static_assets
-
2
middleware.use ::ActionDispatch::Static, paths["public"].first, config.static_cache_control
-
end
-
-
2
if rack_cache = load_rack_cache
-
require "action_dispatch/http/rack_cache"
-
middleware.use ::Rack::Cache, rack_cache
-
end
-
-
2
middleware.use ::Rack::Lock unless allow_concurrency?
-
2
middleware.use ::Rack::Runtime
-
2
middleware.use ::Rack::MethodOverride
-
2
middleware.use ::ActionDispatch::RequestId
-
-
# Must come after Rack::MethodOverride to properly log overridden methods
-
2
middleware.use ::Rails::Rack::Logger, config.log_tags
-
2
middleware.use ::ActionDispatch::ShowExceptions, show_exceptions_app
-
2
middleware.use ::ActionDispatch::DebugExceptions, app
-
2
middleware.use ::ActionDispatch::RemoteIp, config.action_dispatch.ip_spoofing_check, config.action_dispatch.trusted_proxies
-
-
2
unless config.cache_classes
-
middleware.use ::ActionDispatch::Reloader, lambda { reload_dependencies? }
-
end
-
-
2
middleware.use ::ActionDispatch::Callbacks
-
2
middleware.use ::ActionDispatch::Cookies
-
-
2
if config.session_store
-
2
if config.force_ssl && !config.session_options.key?(:secure)
-
config.session_options[:secure] = true
-
end
-
2
middleware.use config.session_store, config.session_options
-
2
middleware.use ::ActionDispatch::Flash
-
end
-
-
2
middleware.use ::ActionDispatch::ParamsParser
-
2
middleware.use ::Rack::Head
-
2
middleware.use ::Rack::ConditionalGet
-
2
middleware.use ::Rack::ETag, "no-cache"
-
end
-
end
-
-
2
private
-
-
2
def reload_dependencies?
-
config.reload_classes_only_on_change != true || app.reloaders.map(&:updated?).any?
-
end
-
-
2
def allow_concurrency?
-
2
config.allow_concurrency.nil? ? config.cache_classes : config.allow_concurrency
-
end
-
-
2
def load_rack_cache
-
2
rack_cache = config.action_dispatch.rack_cache
-
2
return unless rack_cache
-
-
begin
-
require 'rack/cache'
-
rescue LoadError => error
-
error.message << ' Be sure to add rack-cache to your Gemfile'
-
raise
-
end
-
-
if rack_cache == true
-
{
-
metastore: "rails:/",
-
entitystore: "rails:/",
-
verbose: false
-
}
-
else
-
rack_cache
-
end
-
end
-
-
2
def show_exceptions_app
-
2
config.exceptions_app || ActionDispatch::PublicExceptions.new(Rails.public_path)
-
end
-
end
-
end
-
end
-
2
module Rails
-
2
class Application
-
2
module Finisher
-
2
include Initializable
-
-
2
initializer :add_generator_templates do
-
2
config.generators.templates.unshift(*paths["lib/templates"].existent)
-
end
-
-
2
initializer :ensure_autoload_once_paths_as_subset do
-
2
extra = ActiveSupport::Dependencies.autoload_once_paths -
-
ActiveSupport::Dependencies.autoload_paths
-
-
2
unless extra.empty?
-
abort <<-end_error
-
autoload_once_paths must be a subset of the autoload_paths.
-
Extra items in autoload_once_paths: #{extra * ','}
-
end_error
-
end
-
end
-
-
2
initializer :add_builtin_route do |app|
-
2
if Rails.env.development?
-
app.routes.append do
-
get '/rails/mailers' => "rails/mailers#index"
-
get '/rails/mailers/*path' => "rails/mailers#preview"
-
get '/rails/info/properties' => "rails/info#properties"
-
get '/rails/info/routes' => "rails/info#routes"
-
get '/rails/info' => "rails/info#index"
-
get '/' => "rails/welcome#index"
-
end
-
end
-
end
-
-
2
initializer :build_middleware_stack do
-
2
build_middleware_stack
-
end
-
-
2
initializer :define_main_app_helper do |app|
-
2
app.routes.define_mounted_helper(:main_app)
-
end
-
-
2
initializer :add_to_prepare_blocks do
-
2
config.to_prepare_blocks.each do |block|
-
12
ActionDispatch::Reloader.to_prepare(&block)
-
end
-
end
-
-
# This needs to happen before eager load so it happens
-
# in exactly the same point regardless of config.cache_classes
-
2
initializer :run_prepare_callbacks do
-
2
ActionDispatch::Reloader.prepare!
-
end
-
-
2
initializer :eager_load! do
-
2
if config.eager_load
-
ActiveSupport.run_load_hooks(:before_eager_load, self)
-
config.eager_load_namespaces.each(&:eager_load!)
-
end
-
end
-
-
# All initialization is done, including eager loading in production
-
2
initializer :finisher_hook do
-
2
ActiveSupport.run_load_hooks(:after_initialize, self)
-
end
-
-
# Set routes reload after the finisher hook to ensure routes added in
-
# the hook are taken into account.
-
2
initializer :set_routes_reloader_hook do
-
2
reloader = routes_reloader
-
2
reloader.execute_if_updated
-
2
self.reloaders << reloader
-
2
ActionDispatch::Reloader.to_prepare do
-
# We configure #execute rather than #execute_if_updated because if
-
# autoloaded constants are cleared we need to reload routes also in
-
# case any was used there, as in
-
#
-
# mount MailPreview => 'mail_view'
-
#
-
# This means routes are also reloaded if i18n is updated, which
-
# might not be necessary, but in order to be more precise we need
-
# some sort of reloaders dependency support, to be added.
-
reloader.execute
-
end
-
end
-
-
# Set clearing dependencies after the finisher hook to ensure paths
-
# added in the hook are taken into account.
-
2
initializer :set_clear_dependencies_hook, group: :all do
-
2
callback = lambda do
-
ActiveSupport::DescendantsTracker.clear
-
ActiveSupport::Dependencies.clear
-
end
-
-
2
if config.reload_classes_only_on_change
-
2
reloader = config.file_watcher.new(*watchable_args, &callback)
-
2
self.reloaders << reloader
-
-
# Prepend this callback to have autoloaded constants cleared before
-
# any other possible reloading, in case they need to autoload fresh
-
# constants.
-
2
ActionDispatch::Reloader.to_prepare(prepend: true) do
-
# In addition to changes detected by the file watcher, if routes
-
# or i18n have been updated we also need to clear constants,
-
# that's why we run #execute rather than #execute_if_updated, this
-
# callback has to clear autoloaded constants after any update.
-
reloader.execute
-
end
-
else
-
ActionDispatch::Reloader.to_cleanup(&callback)
-
end
-
end
-
end
-
end
-
end
-
2
require "active_support/core_ext/module/delegation"
-
-
2
module Rails
-
2
class Application
-
2
class RoutesReloader
-
2
attr_reader :route_sets, :paths
-
2
delegate :execute_if_updated, :execute, :updated?, to: :updater
-
-
2
def initialize
-
2
@paths = []
-
2
@route_sets = []
-
end
-
-
2
def reload!
-
2
clear!
-
2
load_paths
-
2
finalize!
-
ensure
-
2
revert
-
end
-
-
2
private
-
-
2
def updater
-
@updater ||= begin
-
4
updater = ActiveSupport::FileUpdateChecker.new(paths) { reload! }
-
2
updater.execute
-
2
updater
-
2
end
-
end
-
-
2
def clear!
-
2
route_sets.each do |routes|
-
2
routes.disable_clear_and_finalize = true
-
2
routes.clear!
-
end
-
end
-
-
2
def load_paths
-
4
paths.each { |path| load(path) }
-
end
-
-
2
def finalize!
-
2
route_sets.each do |routes|
-
2
routes.finalize!
-
end
-
end
-
-
2
def revert
-
2
route_sets.each do |routes|
-
2
routes.disable_clear_and_finalize = false
-
end
-
end
-
end
-
end
-
end
-
2
require 'active_support/backtrace_cleaner'
-
-
2
module Rails
-
2
class BacktraceCleaner < ActiveSupport::BacktraceCleaner
-
2
APP_DIRS_PATTERN = /^\/?(app|config|lib|test)/
-
2
RENDER_TEMPLATE_PATTERN = /:in `_render_template_\w*'/
-
-
2
def initialize
-
2
super
-
2
add_filter { |line| line.sub("#{Rails.root}/", '') }
-
2
add_filter { |line| line.sub(RENDER_TEMPLATE_PATTERN, '') }
-
2
add_filter { |line| line.sub('./', '/') } # for tests
-
-
2
add_gem_filters
-
2
add_silencer { |line| line !~ APP_DIRS_PATTERN }
-
end
-
-
2
private
-
2
def add_gem_filters
-
6
gems_paths = (Gem.path | [Gem.default_dir]).map { |p| Regexp.escape(p) }
-
2
return if gems_paths.empty?
-
-
2
gems_regexp = %r{(#{gems_paths.join('|')})/gems/([^/]+)-([\w.]+)/(.*)}
-
2
add_filter { |line| line.sub(gems_regexp, '\2 (\3) \4') }
-
end
-
end
-
end
-
2
require 'active_support/ordered_options'
-
2
require 'active_support/core_ext/object'
-
2
require 'rails/paths'
-
2
require 'rails/rack'
-
-
2
module Rails
-
2
module Configuration
-
# MiddlewareStackProxy is a proxy for the Rails middleware stack that allows
-
# you to configure middlewares in your application. It works basically as a
-
# command recorder, saving each command to be applied after initialization
-
# over the default middleware stack, so you can add, swap, or remove any
-
# middleware in Rails.
-
#
-
# You can add your own middlewares by using the +config.middleware.use+ method:
-
#
-
# config.middleware.use Magical::Unicorns
-
#
-
# This will put the <tt>Magical::Unicorns</tt> middleware on the end of the stack.
-
# You can use +insert_before+ if you wish to add a middleware before another:
-
#
-
# config.middleware.insert_before ActionDispatch::Head, Magical::Unicorns
-
#
-
# There's also +insert_after+ which will insert a middleware after another:
-
#
-
# config.middleware.insert_after ActionDispatch::Head, Magical::Unicorns
-
#
-
# Middlewares can also be completely swapped out and replaced with others:
-
#
-
# config.middleware.swap ActionDispatch::Flash, Magical::Unicorns
-
#
-
# And finally they can also be removed from the stack completely:
-
#
-
# config.middleware.delete ActionDispatch::Flash
-
#
-
2
class MiddlewareStackProxy
-
2
def initialize
-
2
@operations = []
-
end
-
-
2
def insert_before(*args, &block)
-
2
@operations << [__method__, args, block]
-
end
-
-
2
alias :insert :insert_before
-
-
2
def insert_after(*args, &block)
-
4
@operations << [__method__, args, block]
-
end
-
-
2
def swap(*args, &block)
-
@operations << [__method__, args, block]
-
end
-
-
2
def use(*args, &block)
-
2
@operations << [__method__, args, block]
-
end
-
-
2
def delete(*args, &block)
-
@operations << [__method__, args, block]
-
end
-
-
2
def unshift(*args, &block)
-
@operations << [__method__, args, block]
-
end
-
-
2
def merge_into(other) #:nodoc:
-
2
@operations.each do |operation, args, block|
-
8
other.send(operation, *args, &block)
-
end
-
2
other
-
end
-
end
-
-
2
class Generators #:nodoc:
-
2
attr_accessor :aliases, :options, :templates, :fallbacks, :colorize_logging
-
2
attr_reader :hidden_namespaces
-
-
2
def initialize
-
2
@aliases = Hash.new { |h,k| h[k] = {} }
-
8
@options = Hash.new { |h,k| h[k] = {} }
-
2
@fallbacks = {}
-
2
@templates = []
-
2
@colorize_logging = true
-
2
@hidden_namespaces = []
-
end
-
-
2
def initialize_copy(source)
-
22
@aliases = @aliases.deep_dup
-
22
@options = @options.deep_dup
-
22
@fallbacks = @fallbacks.deep_dup
-
22
@templates = @templates.dup
-
end
-
-
2
def hide_namespace(namespace)
-
2
@hidden_namespaces << namespace
-
end
-
-
2
def method_missing(method, *args)
-
20
method = method.to_s.sub(/=$/, '').to_sym
-
-
20
return @options[method] if args.empty?
-
-
20
if method == :rails || args.first.is_a?(Hash)
-
namespace, configuration = method, args.shift
-
else
-
20
namespace, configuration = args.shift, args.shift
-
20
namespace = namespace.to_sym if namespace.respond_to?(:to_sym)
-
20
@options[:rails][method] = namespace
-
end
-
-
20
if configuration
-
4
aliases = configuration.delete(:aliases)
-
4
@aliases[namespace].merge!(aliases) if aliases
-
4
@options[namespace].merge!(configuration)
-
end
-
end
-
end
-
end
-
end
-
2
require 'rails/railtie'
-
2
require 'rails/engine/railties'
-
2
require 'active_support/core_ext/module/delegation'
-
2
require 'pathname'
-
-
2
module Rails
-
# <tt>Rails::Engine</tt> allows you to wrap a specific Rails application or subset of
-
# functionality and share it with other applications or within a larger packaged application.
-
# Since Rails 3.0, every <tt>Rails::Application</tt> is just an engine, which allows for simple
-
# feature and application sharing.
-
#
-
# Any <tt>Rails::Engine</tt> is also a <tt>Rails::Railtie</tt>, so the same
-
# methods (like <tt>rake_tasks</tt> and +generators+) and configuration
-
# options that are available in railties can also be used in engines.
-
#
-
# == Creating an Engine
-
#
-
# In Rails versions prior to 3.0, your gems automatically behaved as engines, however,
-
# this coupled Rails to Rubygems. Since Rails 3.0, if you want a gem to automatically
-
# behave as an engine, you have to specify an +Engine+ for it somewhere inside
-
# your plugin's +lib+ folder (similar to how we specify a +Railtie+):
-
#
-
# # lib/my_engine.rb
-
# module MyEngine
-
# class Engine < Rails::Engine
-
# end
-
# end
-
#
-
# Then ensure that this file is loaded at the top of your <tt>config/application.rb</tt>
-
# (or in your +Gemfile+) and it will automatically load models, controllers and helpers
-
# inside +app+, load routes at <tt>config/routes.rb</tt>, load locales at
-
# <tt>config/locales/*</tt>, and load tasks at <tt>lib/tasks/*</tt>.
-
#
-
# == Configuration
-
#
-
# Besides the +Railtie+ configuration which is shared across the application, in a
-
# <tt>Rails::Engine</tt> you can access <tt>autoload_paths</tt>, <tt>eager_load_paths</tt>
-
# and <tt>autoload_once_paths</tt>, which, differently from a <tt>Railtie</tt>, are scoped to
-
# the current engine.
-
#
-
# class MyEngine < Rails::Engine
-
# # Add a load path for this specific Engine
-
# config.autoload_paths << File.expand_path("../lib/some/path", __FILE__)
-
#
-
# initializer "my_engine.add_middleware" do |app|
-
# app.middleware.use MyEngine::Middleware
-
# end
-
# end
-
#
-
# == Generators
-
#
-
# You can set up generators for engines with <tt>config.generators</tt> method:
-
#
-
# class MyEngine < Rails::Engine
-
# config.generators do |g|
-
# g.orm :active_record
-
# g.template_engine :erb
-
# g.test_framework :test_unit
-
# end
-
# end
-
#
-
# You can also set generators for an application by using <tt>config.app_generators</tt>:
-
#
-
# class MyEngine < Rails::Engine
-
# # note that you can also pass block to app_generators in the same way you
-
# # can pass it to generators method
-
# config.app_generators.orm :datamapper
-
# end
-
#
-
# == Paths
-
#
-
# Since Rails 3.0, applications and engines have more flexible path configuration (as
-
# opposed to the previous hardcoded path configuration). This means that you are not
-
# required to place your controllers at <tt>app/controllers</tt>, but in any place
-
# which you find convenient.
-
#
-
# For example, let's suppose you want to place your controllers in <tt>lib/controllers</tt>.
-
# You can set that as an option:
-
#
-
# class MyEngine < Rails::Engine
-
# paths["app/controllers"] = "lib/controllers"
-
# end
-
#
-
# You can also have your controllers loaded from both <tt>app/controllers</tt> and
-
# <tt>lib/controllers</tt>:
-
#
-
# class MyEngine < Rails::Engine
-
# paths["app/controllers"] << "lib/controllers"
-
# end
-
#
-
# The available paths in an engine are:
-
#
-
# class MyEngine < Rails::Engine
-
# paths["app"] # => ["app"]
-
# paths["app/controllers"] # => ["app/controllers"]
-
# paths["app/helpers"] # => ["app/helpers"]
-
# paths["app/models"] # => ["app/models"]
-
# paths["app/views"] # => ["app/views"]
-
# paths["lib"] # => ["lib"]
-
# paths["lib/tasks"] # => ["lib/tasks"]
-
# paths["config"] # => ["config"]
-
# paths["config/initializers"] # => ["config/initializers"]
-
# paths["config/locales"] # => ["config/locales"]
-
# paths["config/routes.rb"] # => ["config/routes.rb"]
-
# end
-
#
-
# The <tt>Application</tt> class adds a couple more paths to this set. And as in your
-
# <tt>Application</tt>, all folders under +app+ are automatically added to the load path.
-
# If you have an <tt>app/services</tt> folder for example, it will be added by default.
-
#
-
# == Endpoint
-
#
-
# An engine can be also a rack application. It can be useful if you have a rack application that
-
# you would like to wrap with +Engine+ and provide some of the +Engine+'s features.
-
#
-
# To do that, use the +endpoint+ method:
-
#
-
# module MyEngine
-
# class Engine < Rails::Engine
-
# endpoint MyRackApplication
-
# end
-
# end
-
#
-
# Now you can mount your engine in application's routes just like that:
-
#
-
# Rails.application.routes.draw do
-
# mount MyEngine::Engine => "/engine"
-
# end
-
#
-
# == Middleware stack
-
#
-
# As an engine can now be a rack endpoint, it can also have a middleware
-
# stack. The usage is exactly the same as in <tt>Application</tt>:
-
#
-
# module MyEngine
-
# class Engine < Rails::Engine
-
# middleware.use SomeMiddleware
-
# end
-
# end
-
#
-
# == Routes
-
#
-
# If you don't specify an endpoint, routes will be used as the default
-
# endpoint. You can use them just like you use an application's routes:
-
#
-
# # ENGINE/config/routes.rb
-
# MyEngine::Engine.routes.draw do
-
# get "/" => "posts#index"
-
# end
-
#
-
# == Mount priority
-
#
-
# Note that now there can be more than one router in your application, and it's better to avoid
-
# passing requests through many routers. Consider this situation:
-
#
-
# Rails.application.routes.draw do
-
# mount MyEngine::Engine => "/blog"
-
# get "/blog/omg" => "main#omg"
-
# end
-
#
-
# +MyEngine+ is mounted at <tt>/blog</tt>, and <tt>/blog/omg</tt> points to application's
-
# controller. In such a situation, requests to <tt>/blog/omg</tt> will go through +MyEngine+,
-
# and if there is no such route in +Engine+'s routes, it will be dispatched to <tt>main#omg</tt>.
-
# It's much better to swap that:
-
#
-
# Rails.application.routes.draw do
-
# get "/blog/omg" => "main#omg"
-
# mount MyEngine::Engine => "/blog"
-
# end
-
#
-
# Now, +Engine+ will get only requests that were not handled by +Application+.
-
#
-
# == Engine name
-
#
-
# There are some places where an Engine's name is used:
-
#
-
# * routes: when you mount an Engine with <tt>mount(MyEngine::Engine => '/my_engine')</tt>,
-
# it's used as default <tt>:as</tt> option
-
# * rake task for installing migrations <tt>my_engine:install:migrations</tt>
-
#
-
# Engine name is set by default based on class name. For <tt>MyEngine::Engine</tt> it will be
-
# <tt>my_engine_engine</tt>. You can change it manually using the <tt>engine_name</tt> method:
-
#
-
# module MyEngine
-
# class Engine < Rails::Engine
-
# engine_name "my_engine"
-
# end
-
# end
-
#
-
# == Isolated Engine
-
#
-
# Normally when you create controllers, helpers and models inside an engine, they are treated
-
# as if they were created inside the application itself. This means that all helpers and
-
# named routes from the application will be available to your engine's controllers as well.
-
#
-
# However, sometimes you want to isolate your engine from the application, especially if your engine
-
# has its own router. To do that, you simply need to call +isolate_namespace+. This method requires
-
# you to pass a module where all your controllers, helpers and models should be nested to:
-
#
-
# module MyEngine
-
# class Engine < Rails::Engine
-
# isolate_namespace MyEngine
-
# end
-
# end
-
#
-
# With such an engine, everything that is inside the +MyEngine+ module will be isolated from
-
# the application.
-
#
-
# Consider such controller:
-
#
-
# module MyEngine
-
# class FooController < ActionController::Base
-
# end
-
# end
-
#
-
# If an engine is marked as isolated, +FooController+ has access only to helpers from +Engine+ and
-
# <tt>url_helpers</tt> from <tt>MyEngine::Engine.routes</tt>.
-
#
-
# The next thing that changes in isolated engines is the behavior of routes. Normally, when you namespace
-
# your controllers, you also need to do namespace all your routes. With an isolated engine,
-
# the namespace is applied by default, so you can ignore it in routes:
-
#
-
# MyEngine::Engine.routes.draw do
-
# resources :articles
-
# end
-
#
-
# The routes above will automatically point to <tt>MyEngine::ArticlesController</tt>. Furthermore, you don't
-
# need to use longer url helpers like <tt>my_engine_articles_path</tt>. Instead, you should simply use
-
# <tt>articles_path</tt> as you would do with your application.
-
#
-
# To make that behavior consistent with other parts of the framework, an isolated engine also has influence on
-
# <tt>ActiveModel::Naming</tt>. When you use a namespaced model, like <tt>MyEngine::Article</tt>, it will normally
-
# use the prefix "my_engine". In an isolated engine, the prefix will be omitted in url helpers and
-
# form fields for convenience.
-
#
-
# polymorphic_url(MyEngine::Article.new) # => "articles_path"
-
#
-
# form_for(MyEngine::Article.new) do
-
# text_field :title # => <input type="text" name="article[title]" id="article_title" />
-
# end
-
#
-
# Additionally, an isolated engine will set its name according to namespace, so
-
# MyEngine::Engine.engine_name will be "my_engine". It will also set MyEngine.table_name_prefix
-
# to "my_engine_", changing the MyEngine::Article model to use the my_engine_articles table.
-
#
-
# == Using Engine's routes outside Engine
-
#
-
# Since you can now mount an engine inside application's routes, you do not have direct access to +Engine+'s
-
# <tt>url_helpers</tt> inside +Application+. When you mount an engine in an application's routes, a special helper is
-
# created to allow you to do that. Consider such a scenario:
-
#
-
# # config/routes.rb
-
# Rails.application.routes.draw do
-
# mount MyEngine::Engine => "/my_engine", as: "my_engine"
-
# get "/foo" => "foo#index"
-
# end
-
#
-
# Now, you can use the <tt>my_engine</tt> helper inside your application:
-
#
-
# class FooController < ApplicationController
-
# def index
-
# my_engine.root_url # => /my_engine/
-
# end
-
# end
-
#
-
# There is also a <tt>main_app</tt> helper that gives you access to application's routes inside Engine:
-
#
-
# module MyEngine
-
# class BarController
-
# def index
-
# main_app.foo_path # => /foo
-
# end
-
# end
-
# end
-
#
-
# Note that the <tt>:as</tt> option given to mount takes the <tt>engine_name</tt> as default, so most of the time
-
# you can simply omit it.
-
#
-
# Finally, if you want to generate a url to an engine's route using
-
# <tt>polymorphic_url</tt>, you also need to pass the engine helper. Let's
-
# say that you want to create a form pointing to one of the engine's routes.
-
# All you need to do is pass the helper as the first element in array with
-
# attributes for url:
-
#
-
# form_for([my_engine, @user])
-
#
-
# This code will use <tt>my_engine.user_path(@user)</tt> to generate the proper route.
-
#
-
# == Isolated engine's helpers
-
#
-
# Sometimes you may want to isolate engine, but use helpers that are defined for it.
-
# If you want to share just a few specific helpers you can add them to application's
-
# helpers in ApplicationController:
-
#
-
# class ApplicationController < ActionController::Base
-
# helper MyEngine::SharedEngineHelper
-
# end
-
#
-
# If you want to include all of the engine's helpers, you can use #helper method on an engine's
-
# instance:
-
#
-
# class ApplicationController < ActionController::Base
-
# helper MyEngine::Engine.helpers
-
# end
-
#
-
# It will include all of the helpers from engine's directory. Take into account that this does
-
# not include helpers defined in controllers with helper_method or other similar solutions,
-
# only helpers defined in the helpers directory will be included.
-
#
-
# == Migrations & seed data
-
#
-
# Engines can have their own migrations. The default path for migrations is exactly the same
-
# as in application: <tt>db/migrate</tt>
-
#
-
# To use engine's migrations in application you can use rake task, which copies them to
-
# application's dir:
-
#
-
# rake ENGINE_NAME:install:migrations
-
#
-
# Note that some of the migrations may be skipped if a migration with the same name already exists
-
# in application. In such a situation you must decide whether to leave that migration or rename the
-
# migration in the application and rerun copying migrations.
-
#
-
# If your engine has migrations, you may also want to prepare data for the database in
-
# the <tt>db/seeds.rb</tt> file. You can load that data using the <tt>load_seed</tt> method, e.g.
-
#
-
# MyEngine::Engine.load_seed
-
#
-
# == Loading priority
-
#
-
# In order to change engine's priority you can use +config.railties_order+ in main application.
-
# It will affect the priority of loading views, helpers, assets and all the other files
-
# related to engine or application.
-
#
-
# # load Blog::Engine with highest priority, followed by application and other railties
-
# config.railties_order = [Blog::Engine, :main_app, :all]
-
2
class Engine < Railtie
-
2
autoload :Configuration, "rails/engine/configuration"
-
-
2
class << self
-
2
attr_accessor :called_from, :isolated
-
-
2
alias :isolated? :isolated
-
2
alias :engine_name :railtie_name
-
-
2
delegate :eager_load!, to: :instance
-
-
2
def inherited(base)
-
24
unless base.abstract_railtie?
-
22
Rails::Railtie::Configuration.eager_load_namespaces << base
-
-
22
base.called_from = begin
-
22
call_stack = if Kernel.respond_to?(:caller_locations)
-
22
caller_locations.map(&:path)
-
else
-
# Remove the line number from backtraces making sure we don't leave anything behind
-
caller.map { |p| p.sub(/:\d+.*/, '') }
-
end
-
-
46
File.dirname(call_stack.detect { |p| p !~ %r[railties[\w.-]*/lib/rails|rack[\w.-]*/lib/rack] })
-
end
-
end
-
-
24
super
-
end
-
-
2
def endpoint(endpoint = nil)
-
2
@endpoint ||= nil
-
2
@endpoint = endpoint if endpoint
-
2
@endpoint
-
end
-
-
2
def isolate_namespace(mod)
-
engine_name(generate_railtie_name(mod))
-
-
self.routes.default_scope = { module: ActiveSupport::Inflector.underscore(mod.name) }
-
self.isolated = true
-
-
unless mod.respond_to?(:railtie_namespace)
-
name, railtie = engine_name, self
-
-
mod.singleton_class.instance_eval do
-
define_method(:railtie_namespace) { railtie }
-
-
unless mod.respond_to?(:table_name_prefix)
-
define_method(:table_name_prefix) { "#{name}_" }
-
end
-
-
unless mod.respond_to?(:use_relative_model_naming?)
-
class_eval "def use_relative_model_naming?; true; end", __FILE__, __LINE__
-
end
-
-
unless mod.respond_to?(:railtie_helpers_paths)
-
define_method(:railtie_helpers_paths) { railtie.helpers_paths }
-
end
-
-
unless mod.respond_to?(:railtie_routes_url_helpers)
-
define_method(:railtie_routes_url_helpers) { railtie.routes.url_helpers }
-
end
-
end
-
end
-
end
-
-
# Finds engine with given path
-
2
def find(path)
-
expanded_path = File.expand_path path
-
Rails::Engine.subclasses.each do |klass|
-
engine = klass.instance
-
return engine if File.expand_path(engine.root) == expanded_path
-
end
-
nil
-
end
-
end
-
-
2
delegate :middleware, :root, :paths, to: :config
-
2
delegate :engine_name, :isolated?, to: :class
-
-
2
def initialize
-
22
@_all_autoload_paths = nil
-
22
@_all_load_paths = nil
-
22
@app = nil
-
22
@config = nil
-
22
@env_config = nil
-
22
@helpers = nil
-
22
@routes = nil
-
22
super
-
end
-
-
# Load console and invoke the registered hooks.
-
# Check <tt>Rails::Railtie.console</tt> for more info.
-
2
def load_console(app=self)
-
require "rails/console/app"
-
require "rails/console/helpers"
-
run_console_blocks(app)
-
self
-
end
-
-
# Load Rails runner and invoke the registered hooks.
-
# Check <tt>Rails::Railtie.runner</tt> for more info.
-
2
def load_runner(app=self)
-
run_runner_blocks(app)
-
self
-
end
-
-
# Load Rake, railties tasks and invoke the registered hooks.
-
# Check <tt>Rails::Railtie.rake_tasks</tt> for more info.
-
2
def load_tasks(app=self)
-
require "rake"
-
run_tasks_blocks(app)
-
self
-
end
-
-
# Load Rails generators and invoke the registered hooks.
-
# Check <tt>Rails::Railtie.generators</tt> for more info.
-
2
def load_generators(app=self)
-
require "rails/generators"
-
run_generators_blocks(app)
-
Rails::Generators.configure!(app.config.generators)
-
self
-
end
-
-
# Eager load the application by loading all ruby
-
# files inside eager_load paths.
-
2
def eager_load!
-
config.eager_load_paths.each do |load_path|
-
matcher = /\A#{Regexp.escape(load_path.to_s)}\/(.*)\.rb\Z/
-
Dir.glob("#{load_path}/**/*.rb").sort.each do |file|
-
require_dependency file.sub(matcher, '\1')
-
end
-
end
-
end
-
-
2
def railties
-
2
@railties ||= Railties.new
-
end
-
-
# Returns a module with all the helpers defined for the engine.
-
2
def helpers
-
@helpers ||= begin
-
helpers = Module.new
-
all = ActionController::Base.all_helpers_from_path(helpers_paths)
-
ActionController::Base.modules_for_helpers(all).each do |mod|
-
helpers.send(:include, mod)
-
end
-
helpers
-
end
-
end
-
-
# Returns all registered helpers paths.
-
2
def helpers_paths
-
paths["app/helpers"].existent
-
end
-
-
# Returns the underlying rack application for this engine.
-
2
def app
-
@app ||= begin
-
2
config.middleware = config.middleware.merge_into(default_middleware_stack)
-
2
config.middleware.build(endpoint)
-
15
end
-
end
-
-
# Returns the endpoint for this engine. If none is registered,
-
# defaults to an ActionDispatch::Routing::RouteSet.
-
2
def endpoint
-
2
self.class.endpoint || routes
-
end
-
-
# Define the Rack API for this engine.
-
2
def call(env)
-
13
env.merge!(env_config)
-
13
if env['SCRIPT_NAME']
-
13
env.merge! "ROUTES_#{routes.object_id}_SCRIPT_NAME" => env['SCRIPT_NAME'].dup
-
end
-
13
app.call(env)
-
end
-
-
# Defines additional Rack env configuration that is added on each call.
-
2
def env_config
-
@env_config ||= {
-
'action_dispatch.routes' => routes
-
2
}
-
end
-
-
# Defines the routes for this engine. If a block is given to
-
# routes, it is appended to the engine.
-
2
def routes
-
86
@routes ||= ActionDispatch::Routing::RouteSet.new
-
86
@routes.append(&Proc.new) if block_given?
-
86
@routes
-
end
-
-
# Define the configuration object for the engine.
-
2
def config
-
378
@config ||= Engine::Configuration.new(find_root_with_flag("lib"))
-
end
-
-
# Load data from db/seeds.rb file. It can be used in to load engines'
-
# seeds, e.g.:
-
#
-
# Blog::Engine.load_seed
-
2
def load_seed
-
seed_file = paths["db/seeds.rb"].existent.first
-
load(seed_file) if seed_file
-
end
-
-
# Add configured load paths to ruby load paths and remove duplicates.
-
2
initializer :set_load_path, before: :bootstrap_hook do
-
22
_all_load_paths.reverse_each do |path|
-
62
$LOAD_PATH.unshift(path) if File.directory?(path)
-
end
-
22
$LOAD_PATH.uniq!
-
end
-
-
# Set the paths from which Rails will automatically load source files,
-
# and the load_once paths.
-
#
-
# This needs to be an initializer, since it needs to run once
-
# per engine and get the engine as a block parameter
-
2
initializer :set_autoload_paths, before: :bootstrap_hook do
-
22
ActiveSupport::Dependencies.autoload_paths.unshift(*_all_autoload_paths)
-
22
ActiveSupport::Dependencies.autoload_once_paths.unshift(*_all_autoload_once_paths)
-
-
# Freeze so future modifications will fail rather than do nothing mysteriously
-
22
config.autoload_paths.freeze
-
22
config.eager_load_paths.freeze
-
22
config.autoload_once_paths.freeze
-
end
-
-
2
initializer :add_routing_paths do |app|
-
22
paths = self.paths["config/routes.rb"].existent
-
-
22
if routes? || paths.any?
-
2
app.routes_reloader.paths.unshift(*paths)
-
2
app.routes_reloader.route_sets << routes
-
end
-
end
-
-
# I18n load paths are a special case since the ones added
-
# later have higher priority.
-
2
initializer :add_locales do
-
22
config.i18n.railties_load_path.concat(paths["config/locales"].existent)
-
end
-
-
2
initializer :add_view_paths do
-
22
views = paths["app/views"].existent
-
22
unless views.empty?
-
12
ActiveSupport.on_load(:action_controller){ prepend_view_path(views) if respond_to?(:prepend_view_path) }
-
12
ActiveSupport.on_load(:action_mailer){ prepend_view_path(views) }
-
end
-
end
-
-
2
initializer :load_environment_config, before: :load_environment_hook, group: :all do
-
22
paths["config/environments"].existent.each do |environment|
-
2
require environment
-
end
-
end
-
-
2
initializer :append_assets_path, group: :all do |app|
-
22
app.config.assets.paths.unshift(*paths["vendor/assets"].existent_directories)
-
22
app.config.assets.paths.unshift(*paths["lib/assets"].existent_directories)
-
22
app.config.assets.paths.unshift(*paths["app/assets"].existent_directories)
-
end
-
-
2
initializer :prepend_helpers_path do |app|
-
22
if !isolated? || (app == self)
-
22
app.config.helpers_paths.unshift(*paths["app/helpers"].existent)
-
end
-
end
-
-
2
initializer :load_config_initializers do
-
22
config.paths["config/initializers"].existent.sort.each do |initializer|
-
22
load_config_initializer(initializer)
-
end
-
end
-
-
2
initializer :engines_blank_point do
-
# We need this initializer so all extra initializers added in engines are
-
# consistently executed after all the initializers above across all engines.
-
end
-
-
2
rake_tasks do
-
next if self.is_a?(Rails::Application)
-
next unless has_migrations?
-
-
namespace railtie_name do
-
namespace :install do
-
desc "Copy migrations from #{railtie_name} to application"
-
task :migrations do
-
ENV["FROM"] = railtie_name
-
if Rake::Task.task_defined?("railties:install:migrations")
-
Rake::Task["railties:install:migrations"].invoke
-
else
-
Rake::Task["app:railties:install:migrations"].invoke
-
end
-
end
-
end
-
end
-
end
-
-
2
def routes? #:nodoc:
-
22
@routes
-
end
-
-
2
protected
-
-
2
def load_config_initializer(initializer)
-
22
ActiveSupport::Notifications.instrument('load_config_initializer.railties', initializer: initializer) do
-
22
load(initializer)
-
end
-
end
-
-
2
def run_tasks_blocks(*) #:nodoc:
-
super
-
paths["lib/tasks"].existent.sort.each { |ext| load(ext) }
-
end
-
-
2
def has_migrations? #:nodoc:
-
paths["db/migrate"].existent.any?
-
end
-
-
2
def find_root_with_flag(flag, default=nil) #:nodoc:
-
22
root_path = self.class.called_from
-
-
22
while root_path && File.directory?(root_path) && !File.exist?("#{root_path}/#{flag}")
-
46
parent = File.dirname(root_path)
-
46
root_path = parent != root_path && parent
-
end
-
-
22
root = File.exist?("#{root_path}/#{flag}") ? root_path : default
-
22
raise "Could not find root path for #{self}" unless root
-
-
22
Pathname.new File.realpath root
-
end
-
-
2
def default_middleware_stack #:nodoc:
-
ActionDispatch::MiddlewareStack.new
-
end
-
-
2
def _all_autoload_once_paths #:nodoc:
-
22
config.autoload_once_paths
-
end
-
-
2
def _all_autoload_paths #:nodoc:
-
44
@_all_autoload_paths ||= (config.autoload_paths + config.eager_load_paths + config.autoload_once_paths).uniq
-
end
-
-
2
def _all_load_paths #:nodoc:
-
22
@_all_load_paths ||= (config.paths.load_paths + _all_autoload_paths).uniq
-
end
-
end
-
end
-
2
require 'rails/railtie/configuration'
-
-
2
module Rails
-
2
class Engine
-
2
class Configuration < ::Rails::Railtie::Configuration
-
2
attr_reader :root
-
2
attr_writer :middleware, :eager_load_paths, :autoload_once_paths, :autoload_paths
-
-
2
def initialize(root=nil)
-
22
super()
-
22
@root = root
-
22
@generators = app_generators.dup
-
end
-
-
# Returns the middleware stack for the engine.
-
2
def middleware
-
6
@middleware ||= Rails::Configuration::MiddlewareStackProxy.new
-
end
-
-
# Holds generators configuration:
-
#
-
# config.generators do |g|
-
# g.orm :data_mapper, migration: true
-
# g.template_engine :haml
-
# g.test_framework :rspec
-
# end
-
#
-
# If you want to disable color in console, do:
-
#
-
# config.generators.colorize_logging = false
-
#
-
2
def generators #:nodoc:
-
4
@generators ||= Rails::Configuration::Generators.new
-
4
yield(@generators) if block_given?
-
4
@generators
-
end
-
-
2
def paths
-
@paths ||= begin
-
22
paths = Rails::Paths::Root.new(@root)
-
-
22
paths.add "app", eager_load: true, glob: "*"
-
22
paths.add "app/assets", glob: "*"
-
22
paths.add "app/controllers", eager_load: true
-
22
paths.add "app/helpers", eager_load: true
-
22
paths.add "app/models", eager_load: true
-
22
paths.add "app/mailers", eager_load: true
-
22
paths.add "app/views"
-
-
22
paths.add "app/controllers/concerns", eager_load: true
-
22
paths.add "app/models/concerns", eager_load: true
-
-
22
paths.add "lib", load_path: true
-
22
paths.add "lib/assets", glob: "*"
-
22
paths.add "lib/tasks", glob: "**/*.rake"
-
-
22
paths.add "config"
-
22
paths.add "config/environments", glob: "#{Rails.env}.rb"
-
22
paths.add "config/initializers", glob: "**/*.rb"
-
22
paths.add "config/locales", glob: "*.{rb,yml}"
-
22
paths.add "config/routes.rb"
-
-
22
paths.add "db"
-
22
paths.add "db/migrate"
-
22
paths.add "db/seeds.rb"
-
-
22
paths.add "vendor", load_path: true
-
22
paths.add "vendor/assets", glob: "*"
-
-
22
paths
-
262
end
-
end
-
-
2
def root=(value)
-
@root = paths.path = Pathname.new(value).expand_path
-
end
-
-
2
def eager_load_paths
-
44
@eager_load_paths ||= paths.eager_load
-
end
-
-
2
def autoload_once_paths
-
66
@autoload_once_paths ||= paths.autoload_once
-
end
-
-
2
def autoload_paths
-
44
@autoload_paths ||= paths.autoload_paths
-
end
-
end
-
end
-
end
-
2
module Rails
-
2
class Engine < Railtie
-
2
class Railties
-
2
include Enumerable
-
2
attr_reader :_all
-
-
2
def initialize
-
@_all ||= ::Rails::Railtie.subclasses.map(&:instance) +
-
2
::Rails::Engine.subclasses.map(&:instance)
-
end
-
-
2
def each(*args, &block)
-
_all.each(*args, &block)
-
end
-
-
2
def -(others)
-
2
_all - others
-
end
-
end
-
end
-
end
-
2
module Rails
-
# Returns the version of the currently loaded Rails as a <tt>Gem::Version</tt>
-
2
def self.gem_version
-
Gem::Version.new VERSION::STRING
-
end
-
-
2
module VERSION
-
2
MAJOR = 4
-
2
MINOR = 1
-
2
TINY = 8
-
2
PRE = nil
-
-
2
STRING = [MAJOR, MINOR, TINY, PRE].compact.join(".")
-
end
-
end
-
1
activesupport_path = File.expand_path('../../../../activesupport/lib', __FILE__)
-
1
$:.unshift(activesupport_path) if File.directory?(activesupport_path) && !$:.include?(activesupport_path)
-
-
1
require 'thor/group'
-
-
1
require 'active_support'
-
1
require 'active_support/core_ext/object/blank'
-
1
require 'active_support/core_ext/kernel/singleton_class'
-
1
require 'active_support/core_ext/array/extract_options'
-
1
require 'active_support/core_ext/hash/deep_merge'
-
1
require 'active_support/core_ext/module/attribute_accessors'
-
1
require 'active_support/core_ext/string/inflections'
-
-
1
module Rails
-
1
module Generators
-
1
autoload :Actions, 'rails/generators/actions'
-
1
autoload :ActiveModel, 'rails/generators/active_model'
-
1
autoload :Base, 'rails/generators/base'
-
1
autoload :Migration, 'rails/generators/migration'
-
1
autoload :NamedBase, 'rails/generators/named_base'
-
1
autoload :ResourceHelpers, 'rails/generators/resource_helpers'
-
1
autoload :TestCase, 'rails/generators/test_case'
-
-
1
mattr_accessor :namespace
-
-
1
DEFAULT_ALIASES = {
-
rails: {
-
actions: '-a',
-
orm: '-o',
-
javascripts: '-j',
-
javascript_engine: '-je',
-
resource_controller: '-c',
-
scaffold_controller: '-c',
-
stylesheets: '-y',
-
stylesheet_engine: '-se',
-
template_engine: '-e',
-
test_framework: '-t'
-
},
-
-
test_unit: {
-
fixture_replacement: '-r',
-
}
-
}
-
-
1
DEFAULT_OPTIONS = {
-
rails: {
-
assets: true,
-
force_plural: false,
-
helper: true,
-
integration_tool: nil,
-
javascripts: true,
-
javascript_engine: :js,
-
orm: false,
-
resource_controller: :controller,
-
resource_route: true,
-
scaffold_controller: :scaffold_controller,
-
stylesheets: true,
-
stylesheet_engine: :css,
-
test_framework: false,
-
template_engine: :erb
-
}
-
}
-
-
1
def self.configure!(config) #:nodoc:
-
no_color! unless config.colorize_logging
-
aliases.deep_merge! config.aliases
-
options.deep_merge! config.options
-
fallbacks.merge! config.fallbacks
-
templates_path.concat config.templates
-
templates_path.uniq!
-
hide_namespaces(*config.hidden_namespaces)
-
end
-
-
1
def self.templates_path #:nodoc:
-
@templates_path ||= []
-
end
-
-
1
def self.aliases #:nodoc:
-
@aliases ||= DEFAULT_ALIASES.dup
-
end
-
-
1
def self.options #:nodoc:
-
@options ||= DEFAULT_OPTIONS.dup
-
end
-
-
# Hold configured generators fallbacks. If a plugin developer wants a
-
# generator group to fallback to another group in case of missing generators,
-
# they can add a fallback.
-
#
-
# For example, shoulda is considered a test_framework and is an extension
-
# of test_unit. However, most part of shoulda generators are similar to
-
# test_unit ones.
-
#
-
# Shoulda then can tell generators to search for test_unit generators when
-
# some of them are not available by adding a fallback:
-
#
-
# Rails::Generators.fallbacks[:shoulda] = :test_unit
-
1
def self.fallbacks
-
@fallbacks ||= {}
-
end
-
-
# Remove the color from output.
-
1
def self.no_color!
-
1
Thor::Base.shell = Thor::Shell::Basic
-
end
-
-
# Track all generators subclasses.
-
1
def self.subclasses
-
@subclasses ||= []
-
end
-
-
# Rails finds namespaces similar to thor, it only adds one rule:
-
#
-
# Generators names must end with "_generator.rb". This is required because Rails
-
# looks in load paths and loads the generator just before it's going to be used.
-
#
-
# find_by_namespace :webrat, :rails, :integration
-
#
-
# Will search for the following generators:
-
#
-
# "rails:webrat", "webrat:integration", "webrat"
-
#
-
# Notice that "rails:generators:webrat" could be loaded as well, what
-
# Rails looks for is the first and last parts of the namespace.
-
1
def self.find_by_namespace(name, base=nil, context=nil) #:nodoc:
-
lookups = []
-
lookups << "#{base}:#{name}" if base
-
lookups << "#{name}:#{context}" if context
-
-
unless base || context
-
unless name.to_s.include?(?:)
-
lookups << "#{name}:#{name}"
-
lookups << "rails:#{name}"
-
end
-
lookups << "#{name}"
-
end
-
-
lookup(lookups)
-
-
namespaces = Hash[subclasses.map { |klass| [klass.namespace, klass] }]
-
-
lookups.each do |namespace|
-
klass = namespaces[namespace]
-
return klass if klass
-
end
-
-
invoke_fallbacks_for(name, base) || invoke_fallbacks_for(context, name)
-
end
-
-
# Receives a namespace, arguments and the behavior to invoke the generator.
-
# It's used as the default entry point for generate, destroy and update
-
# commands.
-
1
def self.invoke(namespace, args=ARGV, config={})
-
names = namespace.to_s.split(':')
-
if klass = find_by_namespace(names.pop, names.any? && names.join(':'))
-
args << "--help" if args.empty? && klass.arguments.any? { |a| a.required? }
-
klass.start(args, config)
-
else
-
puts "Could not find generator #{namespace}."
-
end
-
end
-
-
1
def self.hidden_namespaces
-
@hidden_namespaces ||= begin
-
orm = options[:rails][:orm]
-
test = options[:rails][:test_framework]
-
template = options[:rails][:template_engine]
-
css = options[:rails][:stylesheet_engine]
-
-
[
-
"rails",
-
"resource_route",
-
"#{orm}:migration",
-
"#{orm}:model",
-
"#{test}:controller",
-
"#{test}:helper",
-
"#{test}:integration",
-
"#{test}:mailer",
-
"#{test}:model",
-
"#{test}:scaffold",
-
"#{test}:view",
-
"#{template}:controller",
-
"#{template}:scaffold",
-
"#{template}:mailer",
-
"#{css}:scaffold",
-
"#{css}:assets",
-
"css:assets",
-
"css:scaffold"
-
]
-
end
-
end
-
-
1
class << self
-
1
def hide_namespaces(*namespaces)
-
hidden_namespaces.concat(namespaces)
-
end
-
1
alias hide_namespace hide_namespaces
-
end
-
-
# Show help message with available generators.
-
1
def self.help(command = 'generate')
-
lookup!
-
-
namespaces = subclasses.map{ |k| k.namespace }
-
namespaces.sort!
-
-
groups = Hash.new { |h,k| h[k] = [] }
-
namespaces.each do |namespace|
-
base = namespace.split(':').first
-
groups[base] << namespace
-
end
-
-
puts "Usage: rails #{command} GENERATOR [args] [options]"
-
puts
-
puts "General options:"
-
puts " -h, [--help] # Print generator's options and usage"
-
puts " -p, [--pretend] # Run but do not make any changes"
-
puts " -f, [--force] # Overwrite files that already exist"
-
puts " -s, [--skip] # Skip files that already exist"
-
puts " -q, [--quiet] # Suppress status output"
-
puts
-
puts "Please choose a generator below."
-
puts
-
-
# Print Rails defaults first.
-
rails = groups.delete("rails")
-
rails.map! { |n| n.sub(/^rails:/, '') }
-
rails.delete("app")
-
rails.delete("plugin")
-
print_list("rails", rails)
-
-
hidden_namespaces.each { |n| groups.delete(n.to_s) }
-
-
groups.sort.each { |b, n| print_list(b, n) }
-
end
-
-
1
protected
-
-
# Prints a list of generators.
-
1
def self.print_list(base, namespaces) #:nodoc:
-
namespaces = namespaces.reject do |n|
-
hidden_namespaces.include?(n)
-
end
-
-
return if namespaces.empty?
-
puts "#{base.camelize}:"
-
-
namespaces.each do |namespace|
-
puts(" #{namespace}")
-
end
-
-
puts
-
end
-
-
# Try fallbacks for the given base.
-
1
def self.invoke_fallbacks_for(name, base) #:nodoc:
-
return nil unless base && fallbacks[base.to_sym]
-
invoked_fallbacks = []
-
-
Array(fallbacks[base.to_sym]).each do |fallback|
-
next if invoked_fallbacks.include?(fallback)
-
invoked_fallbacks << fallback
-
-
klass = find_by_namespace(name, fallback)
-
return klass if klass
-
end
-
-
nil
-
end
-
-
# Receives namespaces in an array and tries to find matching generators
-
# in the load path.
-
1
def self.lookup(namespaces) #:nodoc:
-
paths = namespaces_to_paths(namespaces)
-
-
paths.each do |raw_path|
-
["rails/generators", "generators"].each do |base|
-
path = "#{base}/#{raw_path}_generator"
-
-
begin
-
require path
-
return
-
rescue LoadError => e
-
raise unless e.message =~ /#{Regexp.escape(path)}$/
-
rescue Exception => e
-
warn "[WARNING] Could not load generator #{path.inspect}. Error: #{e.message}.\n#{e.backtrace.join("\n")}"
-
end
-
end
-
end
-
end
-
-
# This will try to load any generator in the load path to show in help.
-
1
def self.lookup! #:nodoc:
-
$LOAD_PATH.each do |base|
-
Dir[File.join(base, "{rails/generators,generators}", "**", "*_generator.rb")].each do |path|
-
begin
-
path = path.sub("#{base}/", "")
-
require path
-
rescue Exception
-
# No problem
-
end
-
end
-
end
-
end
-
-
# Convert namespaces to paths by replacing ":" for "/" and adding
-
# an extra lookup. For example, "rails:model" should be searched
-
# in both: "rails/model/model_generator" and "rails/model_generator".
-
1
def self.namespaces_to_paths(namespaces) #:nodoc:
-
paths = []
-
namespaces.each do |namespace|
-
pieces = namespace.split(":")
-
paths << pieces.dup.push(pieces.last).join("/")
-
paths << pieces.join("/")
-
end
-
paths.uniq!
-
paths
-
end
-
end
-
end
-
1
require 'rails/generators'
-
1
require 'rails/generators/testing/behaviour'
-
1
require 'rails/generators/testing/setup_and_teardown'
-
1
require 'rails/generators/testing/assertions'
-
1
require 'fileutils'
-
-
1
module Rails
-
1
module Generators
-
# Disable color in output. Easier to debug.
-
1
no_color!
-
-
# This class provides a TestCase for testing generators. To setup, you need
-
# just to configure the destination and set which generator is being tested:
-
#
-
# class AppGeneratorTest < Rails::Generators::TestCase
-
# tests AppGenerator
-
# destination File.expand_path("../tmp", File.dirname(__FILE__))
-
# end
-
#
-
# If you want to ensure your destination root is clean before running each test,
-
# you can set a setup callback:
-
#
-
# class AppGeneratorTest < Rails::Generators::TestCase
-
# tests AppGenerator
-
# destination File.expand_path("../tmp", File.dirname(__FILE__))
-
# setup :prepare_destination
-
# end
-
1
class TestCase < ActiveSupport::TestCase
-
1
include Rails::Generators::Testing::Behaviour
-
1
include Rails::Generators::Testing::SetupAndTeardown
-
1
include Rails::Generators::Testing::Assertions
-
1
include FileUtils
-
-
end
-
end
-
end
-
1
require 'shellwords'
-
-
1
module Rails
-
1
module Generators
-
1
module Testing
-
1
module Assertions
-
# Asserts a given file exists. You need to supply an absolute path or a path relative
-
# to the configured destination:
-
#
-
# assert_file "config/environment.rb"
-
#
-
# You can also give extra arguments. If the argument is a regexp, it will check if the
-
# regular expression matches the given file content. If it's a string, it compares the
-
# file with the given string:
-
#
-
# assert_file "config/environment.rb", /initialize/
-
#
-
# Finally, when a block is given, it yields the file content:
-
#
-
# assert_file "app/controllers/products_controller.rb" do |controller|
-
# assert_instance_method :index, controller do |index|
-
# assert_match(/Product\.all/, index)
-
# end
-
# end
-
1
def assert_file(relative, *contents)
-
absolute = File.expand_path(relative, destination_root).shellescape
-
assert File.exist?(absolute), "Expected file #{relative.inspect} to exist, but does not"
-
-
read = File.read(absolute) if block_given? || !contents.empty?
-
yield read if block_given?
-
-
contents.each do |content|
-
case content
-
when String
-
assert_equal content, read
-
when Regexp
-
assert_match content, read
-
end
-
end
-
end
-
1
alias :assert_directory :assert_file
-
-
# Asserts a given file does not exist. You need to supply an absolute path or a
-
# path relative to the configured destination:
-
#
-
# assert_no_file "config/random.rb"
-
1
def assert_no_file(relative)
-
absolute = File.expand_path(relative, destination_root)
-
assert !File.exist?(absolute), "Expected file #{relative.inspect} to not exist, but does"
-
end
-
1
alias :assert_no_directory :assert_no_file
-
-
# Asserts a given migration exists. You need to supply an absolute path or a
-
# path relative to the configured destination:
-
#
-
# assert_migration "db/migrate/create_products.rb"
-
#
-
# This method manipulates the given path and tries to find any migration which
-
# matches the migration name. For example, the call above is converted to:
-
#
-
# assert_file "db/migrate/003_create_products.rb"
-
#
-
# Consequently, assert_migration accepts the same arguments has assert_file.
-
1
def assert_migration(relative, *contents, &block)
-
file_name = migration_file_name(relative)
-
assert file_name, "Expected migration #{relative} to exist, but was not found"
-
assert_file file_name, *contents, &block
-
end
-
-
# Asserts a given migration does not exist. You need to supply an absolute path or a
-
# path relative to the configured destination:
-
#
-
# assert_no_migration "db/migrate/create_products.rb"
-
1
def assert_no_migration(relative)
-
file_name = migration_file_name(relative)
-
assert_nil file_name, "Expected migration #{relative} to not exist, but found #{file_name}"
-
end
-
-
# Asserts the given class method exists in the given content. This method does not detect
-
# class methods inside (class << self), only class methods which starts with "self.".
-
# When a block is given, it yields the content of the method.
-
#
-
# assert_migration "db/migrate/create_products.rb" do |migration|
-
# assert_class_method :up, migration do |up|
-
# assert_match(/create_table/, up)
-
# end
-
# end
-
1
def assert_class_method(method, content, &block)
-
assert_instance_method "self.#{method}", content, &block
-
end
-
-
# Asserts the given method exists in the given content. When a block is given,
-
# it yields the content of the method.
-
#
-
# assert_file "app/controllers/products_controller.rb" do |controller|
-
# assert_instance_method :index, controller do |index|
-
# assert_match(/Product\.all/, index)
-
# end
-
# end
-
1
def assert_instance_method(method, content)
-
assert content =~ /(\s+)def #{method}(\(.+\))?(.*?)\n\1end/m, "Expected to have method #{method}"
-
yield $3.strip if block_given?
-
end
-
1
alias :assert_method :assert_instance_method
-
-
# Asserts the given attribute type gets translated to a field type
-
# properly:
-
#
-
# assert_field_type :date, :date_select
-
1
def assert_field_type(attribute_type, field_type)
-
assert_equal(field_type, create_generated_attribute(attribute_type).field_type)
-
end
-
-
# Asserts the given attribute type gets a proper default value:
-
#
-
# assert_field_default_value :string, "MyString"
-
1
def assert_field_default_value(attribute_type, value)
-
assert_equal(value, create_generated_attribute(attribute_type).default)
-
end
-
end
-
end
-
end
-
end
-
1
require 'active_support/core_ext/class/attribute'
-
1
require 'active_support/core_ext/module/delegation'
-
1
require 'active_support/core_ext/hash/reverse_merge'
-
1
require 'active_support/core_ext/kernel/reporting'
-
1
require 'active_support/concern'
-
1
require 'rails/generators'
-
-
1
module Rails
-
1
module Generators
-
1
module Testing
-
1
module Behaviour
-
1
extend ActiveSupport::Concern
-
-
1
included do
-
1
class_attribute :destination_root, :current_path, :generator_class, :default_arguments
-
-
# Generators frequently change the current path using +FileUtils.cd+.
-
# So we need to store the path at file load and revert back to it after each test.
-
1
self.current_path = File.expand_path(Dir.pwd)
-
1
self.default_arguments = []
-
end
-
-
1
module ClassMethods
-
# Sets which generator should be tested:
-
#
-
# tests AppGenerator
-
1
def tests(klass)
-
self.generator_class = klass
-
end
-
-
# Sets default arguments on generator invocation. This can be overwritten when
-
# invoking it.
-
#
-
# arguments %w(app_name --skip-active-record)
-
1
def arguments(array)
-
self.default_arguments = array
-
end
-
-
# Sets the destination of generator files:
-
#
-
# destination File.expand_path("../tmp", File.dirname(__FILE__))
-
1
def destination(path)
-
self.destination_root = path
-
end
-
end
-
-
# Runs the generator configured for this class. The first argument is an array like
-
# command line arguments:
-
#
-
# class AppGeneratorTest < Rails::Generators::TestCase
-
# tests AppGenerator
-
# destination File.expand_path("../tmp", File.dirname(__FILE__))
-
# teardown :cleanup_destination_root
-
#
-
# test "database.yml is not created when skipping Active Record" do
-
# run_generator %w(myapp --skip-active-record)
-
# assert_no_file "config/database.yml"
-
# end
-
# end
-
#
-
# You can provide a configuration hash as second argument. This method returns the output
-
# printed by the generator.
-
1
def run_generator(args=self.default_arguments, config={})
-
capture(:stdout) do
-
args += ['--skip-bundle'] unless args.include? '--dev'
-
self.generator_class.start(args, config.reverse_merge(destination_root: destination_root))
-
end
-
end
-
-
# Instantiate the generator.
-
1
def generator(args=self.default_arguments, options={}, config={})
-
@generator ||= self.generator_class.new(args, options, config.reverse_merge(destination_root: destination_root))
-
end
-
-
# Create a Rails::Generators::GeneratedAttribute by supplying the
-
# attribute type and, optionally, the attribute name:
-
#
-
# create_generated_attribute(:string, 'name')
-
1
def create_generated_attribute(attribute_type, name = 'test', index = nil)
-
Rails::Generators::GeneratedAttribute.parse([name, attribute_type, index].compact.join(':'))
-
end
-
-
1
protected
-
-
1
def destination_root_is_set? # :nodoc:
-
raise "You need to configure your Rails::Generators::TestCase destination root." unless destination_root
-
end
-
-
1
def ensure_current_path # :nodoc:
-
cd current_path
-
end
-
-
1
def prepare_destination # :nodoc:
-
rm_rf(destination_root)
-
mkdir_p(destination_root)
-
end
-
-
1
def migration_file_name(relative) # :nodoc:
-
absolute = File.expand_path(relative, destination_root)
-
dirname, file_name = File.dirname(absolute), File.basename(absolute).sub(/\.rb$/, '')
-
Dir.glob("#{dirname}/[0-9]*_*.rb").grep(/\d+_#{file_name}.rb$/).first
-
end
-
end
-
end
-
end
-
end
-
1
module Rails
-
1
module Generators
-
1
module Testing
-
1
module SetupAndTeardown
-
1
def setup # :nodoc:
-
destination_root_is_set?
-
ensure_current_path
-
super
-
end
-
-
1
def teardown # :nodoc:
-
ensure_current_path
-
super
-
end
-
end
-
end
-
end
-
end
-
2
require 'tsort'
-
-
2
module Rails
-
2
module Initializable
-
2
def self.included(base) #:nodoc:
-
6
base.extend ClassMethods
-
end
-
-
2
class Initializer
-
2
attr_reader :name, :block
-
-
2
def initialize(name, context, options, &block)
-
504
options[:group] ||= :default
-
504
@name, @context, @options, @block = name, context, options, block
-
end
-
-
2
def before
-
61952
@options[:before]
-
end
-
-
2
def after
-
61882
@options[:after]
-
end
-
-
2
def belongs_to?(group)
-
352
@options[:group] == group || @options[:group] == :all
-
end
-
-
2
def run(*args)
-
352
@context.instance_exec(*args, &block)
-
end
-
-
2
def bind(context)
-
352
return self if @context
-
352
Initializer.new(@name, context, @options, &block)
-
end
-
end
-
-
2
class Collection < Array
-
2
include TSort
-
-
2
alias :tsort_each_node :each
-
2
def tsort_each_child(initializer, &block)
-
62304
select { |i| i.before == initializer.name || i.name == initializer.after }.each(&block)
-
end
-
-
2
def +(other)
-
160
Collection.new(to_a + other.to_a)
-
end
-
end
-
-
2
def run_initializers(group=:default, *args)
-
2
return if instance_variable_defined?(:@ran)
-
2
initializers.tsort_each do |initializer|
-
352
initializer.run(*args) if initializer.belongs_to?(group)
-
end
-
2
@ran = true
-
end
-
-
2
def initializers
-
64
@initializers ||= self.class.initializers_for(self)
-
end
-
-
2
module ClassMethods
-
2
def initializers
-
668
@initializers ||= Collection.new
-
end
-
-
2
def initializers_chain
-
68
initializers = Collection.new
-
68
ancestors.reverse_each do |klass|
-
608
next unless klass.respond_to?(:initializers)
-
156
initializers = initializers + klass.initializers
-
end
-
68
initializers
-
end
-
-
2
def initializers_for(binding)
-
420
Collection.new(initializers_chain.map { |i| i.bind(binding) })
-
end
-
-
2
def initializer(name, opts = {}, &blk)
-
152
raise ArgumentError, "A block must be passed when defining an initializer" unless blk
-
542
opts[:after] ||= initializers.last.name unless initializers.empty? || initializers.find { |i| i.name == opts[:before] }
-
152
initializers << Initializer.new(name, nil, opts, &blk)
-
end
-
end
-
end
-
end
-
2
module Rails
-
2
module Paths
-
# This object is an extended hash that behaves as root of the <tt>Rails::Paths</tt> system.
-
# It allows you to collect information about how you want to structure your application
-
# paths by a Hash like API. It requires you to give a physical path on initialization.
-
#
-
# root = Root.new "/rails"
-
# root.add "app/controllers", eager_load: true
-
#
-
# The command above creates a new root object and add "app/controllers" as a path.
-
# This means we can get a <tt>Rails::Paths::Path</tt> object back like below:
-
#
-
# path = root["app/controllers"]
-
# path.eager_load? # => true
-
# path.is_a?(Rails::Paths::Path) # => true
-
#
-
# The +Path+ object is simply an enumerable and allows you to easily add extra paths:
-
#
-
# path.is_a?(Enumerable) # => true
-
# path.to_ary.inspect # => ["app/controllers"]
-
#
-
# path << "lib/controllers"
-
# path.to_ary.inspect # => ["app/controllers", "lib/controllers"]
-
#
-
# Notice that when you add a path using +add+, the path object created already
-
# contains the path with the same path value given to +add+. In some situations,
-
# you may not want this behavior, so you can give <tt>:with</tt> as option.
-
#
-
# root.add "config/routes", with: "config/routes.rb"
-
# root["config/routes"].inspect # => ["config/routes.rb"]
-
#
-
# The +add+ method accepts the following options as arguments:
-
# eager_load, autoload, autoload_once and glob.
-
#
-
# Finally, the +Path+ object also provides a few helpers:
-
#
-
# root = Root.new "/rails"
-
# root.add "app/controllers"
-
#
-
# root["app/controllers"].expanded # => ["/rails/app/controllers"]
-
# root["app/controllers"].existent # => ["/rails/app/controllers"]
-
#
-
# Check the <tt>Rails::Paths::Path</tt> documentation for more information.
-
2
class Root
-
2
attr_accessor :path
-
-
2
def initialize(path)
-
22
@current = nil
-
22
@path = path
-
22
@root = {}
-
end
-
-
2
def []=(path, value)
-
glob = self[path] ? self[path].glob : nil
-
add(path, with: value, glob: glob)
-
end
-
-
2
def add(path, options = {})
-
502
with = Array(options.fetch(:with, path))
-
502
@root[path] = Path.new(self, path, with, options)
-
end
-
-
2
def [](path)
-
230
@root[path]
-
end
-
-
2
def values
-
88
@root.values
-
end
-
-
2
def keys
-
198
@root.keys
-
end
-
-
2
def values_at(*list)
-
198
@root.values_at(*list)
-
end
-
-
2
def all_paths
-
176
values.tap { |v| v.uniq! }
-
end
-
-
2
def autoload_once
-
524
filter_by { |p| p.autoload_once? }
-
end
-
-
2
def eager_load
-
744
filter_by { |p| p.eager_load? }
-
end
-
-
2
def autoload_paths
-
524
filter_by { |p| p.autoload? }
-
end
-
-
2
def load_paths
-
592
filter_by { |p| p.load_path? }
-
end
-
-
2
private
-
-
2
def filter_by(&block)
-
all_paths.find_all(&block).flat_map { |path|
-
198
paths = path.existent
-
486
paths - path.children.map { |p| yield(p) ? [] : p.existent }.flatten
-
88
}.uniq
-
end
-
end
-
-
2
class Path
-
2
include Enumerable
-
-
2
attr_accessor :glob
-
-
2
def initialize(root, current, paths, options = {})
-
502
@paths = paths
-
502
@current = current
-
502
@root = root
-
502
@glob = options[:glob]
-
-
502
options[:autoload_once] ? autoload_once! : skip_autoload_once!
-
502
options[:eager_load] ? eager_load! : skip_eager_load!
-
502
options[:autoload] ? autoload! : skip_autoload!
-
502
options[:load_path] ? load_path! : skip_load_path!
-
end
-
-
2
def children
-
198
keys = @root.keys.find_all { |k|
-
4518
k.start_with?(@current) && k != @current
-
}
-
198
@root.values_at(*keys.sort)
-
end
-
-
2
def first
-
28
expanded.first
-
end
-
-
2
def last
-
expanded.last
-
end
-
-
2
%w(autoload_once eager_load autoload load_path).each do |m|
-
8
class_eval <<-RUBY, __FILE__, __LINE__ + 1
-
def #{m}! # def eager_load!
-
@#{m} = true # @eager_load = true
-
end # end
-
#
-
def skip_#{m}! # def skip_eager_load!
-
@#{m} = false # @eager_load = false
-
end # end
-
#
-
def #{m}? # def eager_load?
-
@#{m} # @eager_load
-
end # end
-
RUBY
-
end
-
-
2
def each(&block)
-
540
@paths.each(&block)
-
end
-
-
2
def <<(path)
-
@paths << path
-
end
-
2
alias :push :<<
-
-
2
def concat(paths)
-
@paths.concat paths
-
end
-
-
2
def unshift(path)
-
@paths.unshift path
-
end
-
-
2
def to_ary
-
@paths
-
end
-
-
# Expands all paths against the root and return all unique values.
-
2
def expanded
-
540
raise "You need to set a path root" unless @root.path
-
540
result = []
-
-
540
each do |p|
-
540
path = File.expand_path(p, @root.path)
-
-
540
if @glob && File.directory?(path)
-
64
Dir.chdir(path) do
-
216
result.concat(Dir.glob(@glob).map { |file| File.join path, file }.sort)
-
end
-
else
-
476
result << path
-
end
-
end
-
-
540
result.uniq!
-
540
result
-
end
-
-
# Returns all expanded paths but only if they exist in the filesystem.
-
2
def existent
-
960
expanded.select { |f| File.exist?(f) }
-
end
-
-
2
def existent_directories
-
152
expanded.select { |d| File.directory?(d) }
-
end
-
-
2
alias to_a expanded
-
end
-
end
-
end
-
2
module Rails
-
2
module Rack
-
2
autoload :Debugger, "rails/rack/debugger"
-
2
autoload :Logger, "rails/rack/logger"
-
2
autoload :LogTailer, "rails/rack/log_tailer"
-
end
-
end
-
2
require 'active_support/core_ext/time/conversions'
-
2
require 'active_support/core_ext/object/blank'
-
2
require 'active_support/log_subscriber'
-
2
require 'action_dispatch/http/request'
-
2
require 'rack/body_proxy'
-
-
2
module Rails
-
2
module Rack
-
# Sets log tags, logs the request, calls the app, and flushes the logs.
-
2
class Logger < ActiveSupport::LogSubscriber
-
2
def initialize(app, taggers = nil)
-
2
@app = app
-
2
@taggers = taggers || []
-
end
-
-
2
def call(env)
-
13
request = ActionDispatch::Request.new(env)
-
-
13
if logger.respond_to?(:tagged)
-
26
logger.tagged(compute_tags(request)) { call_app(request, env) }
-
else
-
call_app(request, env)
-
end
-
end
-
-
2
protected
-
-
2
def call_app(request, env)
-
# Put some space between requests in development logs.
-
13
if development?
-
logger.debug ''
-
logger.debug ''
-
end
-
-
13
instrumenter = ActiveSupport::Notifications.instrumenter
-
13
instrumenter.start 'request.action_dispatch', request: request
-
13
logger.info started_request_message(request)
-
13
resp = @app.call(env)
-
26
resp[2] = ::Rack::BodyProxy.new(resp[2]) { finish(request) }
-
13
resp
-
rescue Exception
-
finish(request)
-
raise
-
ensure
-
13
ActiveSupport::LogSubscriber.flush_all!
-
end
-
-
# Started GET "/session/new" for 127.0.0.1 at 2012-09-26 14:51:42 -0700
-
2
def started_request_message(request)
-
'Started %s "%s" for %s at %s' % [
-
request.request_method,
-
request.filtered_path,
-
request.ip,
-
13
Time.now.to_default_s ]
-
end
-
-
2
def compute_tags(request)
-
13
@taggers.collect do |tag|
-
case tag
-
when Proc
-
tag.call(request)
-
when Symbol
-
request.send(tag)
-
else
-
tag
-
end
-
end
-
end
-
-
2
private
-
-
2
def finish(request)
-
13
instrumenter = ActiveSupport::Notifications.instrumenter
-
13
instrumenter.finish 'request.action_dispatch', request: request
-
end
-
-
2
def development?
-
13
Rails.env.development?
-
end
-
-
2
def logger
-
39
Rails.logger
-
end
-
end
-
end
-
end
-
2
require 'rails/initializable'
-
2
require 'rails/configuration'
-
2
require 'active_support/inflector'
-
2
require 'active_support/core_ext/module/introspection'
-
2
require 'active_support/core_ext/module/delegation'
-
-
2
module Rails
-
# Railtie is the core of the Rails framework and provides several hooks to extend
-
# Rails and/or modify the initialization process.
-
#
-
# Every major component of Rails (Action Mailer, Action Controller,
-
# Action View and Active Record) is a Railtie. Each of
-
# them is responsible for their own initialization. This makes Rails itself
-
# absent of any component hooks, allowing other components to be used in
-
# place of any of the Rails defaults.
-
#
-
# Developing a Rails extension does _not_ require any implementation of
-
# Railtie, but if you need to interact with the Rails framework during
-
# or after boot, then Railtie is needed.
-
#
-
# For example, an extension doing any of the following would require Railtie:
-
#
-
# * creating initializers
-
# * configuring a Rails framework for the application, like setting a generator
-
# * adding <tt>config.*</tt> keys to the environment
-
# * setting up a subscriber with ActiveSupport::Notifications
-
# * adding rake tasks
-
#
-
# == Creating your Railtie
-
#
-
# To extend Rails using Railtie, create a Railtie class which inherits
-
# from Rails::Railtie within your extension's namespace. This class must be
-
# loaded during the Rails boot process.
-
#
-
# The following example demonstrates an extension which can be used with or without Rails.
-
#
-
# # lib/my_gem/railtie.rb
-
# module MyGem
-
# class Railtie < Rails::Railtie
-
# end
-
# end
-
#
-
# # lib/my_gem.rb
-
# require 'my_gem/railtie' if defined?(Rails)
-
#
-
# == Initializers
-
#
-
# To add an initialization step from your Railtie to Rails boot process, you just need
-
# to create an initializer block:
-
#
-
# class MyRailtie < Rails::Railtie
-
# initializer "my_railtie.configure_rails_initialization" do
-
# # some initialization behavior
-
# end
-
# end
-
#
-
# If specified, the block can also receive the application object, in case you
-
# need to access some application specific configuration, like middleware:
-
#
-
# class MyRailtie < Rails::Railtie
-
# initializer "my_railtie.configure_rails_initialization" do |app|
-
# app.middleware.use MyRailtie::Middleware
-
# end
-
# end
-
#
-
# Finally, you can also pass <tt>:before</tt> and <tt>:after</tt> as option to initializer,
-
# in case you want to couple it with a specific step in the initialization process.
-
#
-
# == Configuration
-
#
-
# Inside the Railtie class, you can access a config object which contains configuration
-
# shared by all railties and the application:
-
#
-
# class MyRailtie < Rails::Railtie
-
# # Customize the ORM
-
# config.app_generators.orm :my_railtie_orm
-
#
-
# # Add a to_prepare block which is executed once in production
-
# # and before each request in development
-
# config.to_prepare do
-
# MyRailtie.setup!
-
# end
-
# end
-
#
-
# == Loading rake tasks and generators
-
#
-
# If your railtie has rake tasks, you can tell Rails to load them through the method
-
# rake_tasks:
-
#
-
# class MyRailtie < Rails::Railtie
-
# rake_tasks do
-
# load "path/to/my_railtie.tasks"
-
# end
-
# end
-
#
-
# By default, Rails load generators from your load path. However, if you want to place
-
# your generators at a different location, you can specify in your Railtie a block which
-
# will load them during normal generators lookup:
-
#
-
# class MyRailtie < Rails::Railtie
-
# generators do
-
# require "path/to/my_railtie_generator"
-
# end
-
# end
-
#
-
# == Application and Engine
-
#
-
# A Rails::Engine is nothing more than a Railtie with some initializers already set.
-
# And since Rails::Application is an engine, the same configuration described here
-
# can be used in both.
-
#
-
# Be sure to look at the documentation of those specific classes for more information.
-
#
-
2
class Railtie
-
2
autoload :Configuration, "rails/railtie/configuration"
-
-
2
include Initializable
-
-
2
ABSTRACT_RAILTIES = %w(Rails::Railtie Rails::Engine Rails::Application)
-
-
2
class << self
-
2
private :new
-
2
delegate :config, to: :instance
-
-
2
def subclasses
-
68
@subclasses ||= []
-
end
-
-
2
def inherited(base)
-
68
unless base.abstract_railtie?
-
64
subclasses << base
-
end
-
end
-
-
2
def rake_tasks(&blk)
-
16
@rake_tasks ||= []
-
16
@rake_tasks << blk if blk
-
16
@rake_tasks
-
end
-
-
2
def console(&blk)
-
6
@load_console ||= []
-
6
@load_console << blk if blk
-
6
@load_console
-
end
-
-
2
def runner(&blk)
-
2
@load_runner ||= []
-
2
@load_runner << blk if blk
-
2
@load_runner
-
end
-
-
2
def generators(&blk)
-
4
@generators ||= []
-
4
@generators << blk if blk
-
4
@generators
-
end
-
-
2
def abstract_railtie?
-
156
ABSTRACT_RAILTIES.include?(name)
-
end
-
-
2
def railtie_name(name = nil)
-
@railtie_name = name.to_s if name
-
@railtie_name ||= generate_railtie_name(self.name)
-
end
-
-
# Since Rails::Railtie cannot be instantiated, any methods that call
-
# +instance+ are intended to be called only on subclasses of a Railtie.
-
2
def instance
-
234
@instance ||= new
-
end
-
-
2
def respond_to_missing?(*args)
-
instance.respond_to?(*args) || super
-
end
-
-
# Allows you to configure the railtie. This is the same method seen in
-
# Railtie::Configurable, but this module is no longer required for all
-
# subclasses of Railtie so we provide the class method here.
-
2
def configure(&block)
-
instance.configure(&block)
-
end
-
-
2
protected
-
2
def generate_railtie_name(class_or_module)
-
ActiveSupport::Inflector.underscore(class_or_module).tr("/", "_")
-
end
-
-
# If the class method does not have a method, then send the method call
-
# to the Railtie instance.
-
2
def method_missing(name, *args, &block)
-
if instance.respond_to?(name)
-
instance.public_send(name, *args, &block)
-
else
-
super
-
end
-
end
-
end
-
-
2
delegate :railtie_name, to: :class
-
-
2
def initialize
-
64
if self.class.abstract_railtie?
-
raise "#{self.class.name} is abstract, you cannot instantiate it directly."
-
end
-
end
-
-
2
def configure(&block)
-
2
instance_eval(&block)
-
end
-
-
2
def config
-
180
@config ||= Railtie::Configuration.new
-
end
-
-
2
def railtie_namespace
-
@railtie_namespace ||= self.class.parents.detect { |n| n.respond_to?(:railtie_namespace) }
-
end
-
-
2
protected
-
-
2
def run_console_blocks(app) #:nodoc:
-
each_registered_block(:console) { |block| block.call(app) }
-
end
-
-
2
def run_generators_blocks(app) #:nodoc:
-
each_registered_block(:generators) { |block| block.call(app) }
-
end
-
-
2
def run_runner_blocks(app) #:nodoc:
-
each_registered_block(:runner) { |block| block.call(app) }
-
end
-
-
2
def run_tasks_blocks(app) #:nodoc:
-
extend Rake::DSL
-
each_registered_block(:rake_tasks) { |block| instance_exec(app, &block) }
-
end
-
-
2
private
-
-
2
def each_registered_block(type, &block)
-
klass = self.class
-
while klass.respond_to?(type)
-
klass.public_send(type).each(&block)
-
klass = klass.superclass
-
end
-
end
-
end
-
end
-
2
require 'rails/configuration'
-
-
2
module Rails
-
2
class Railtie
-
2
class Configuration
-
2
def initialize
-
54
@@options ||= {}
-
end
-
-
# Expose the eager_load_namespaces at "module" level for convenience.
-
2
def self.eager_load_namespaces #:nodoc:
-
22
@@eager_load_namespaces ||= []
-
end
-
-
# All namespaces that are eager loaded
-
2
def eager_load_namespaces
-
16
@@eager_load_namespaces ||= []
-
end
-
-
# Add files that should be watched for change.
-
2
def watchable_files
-
4
@@watchable_files ||= []
-
end
-
-
# Add directories that should be watched for change.
-
# The key of the hashes should be directories and the values should
-
# be an array of extensions to match in each directory.
-
2
def watchable_dirs
-
2
@@watchable_dirs ||= {}
-
end
-
-
# This allows you to modify the application's middlewares from Engines.
-
#
-
# All operations you run on the app_middleware will be replayed on the
-
# application once it is defined and the default_middlewares are
-
# created
-
2
def app_middleware
-
8
@@app_middleware ||= Rails::Configuration::MiddlewareStackProxy.new
-
end
-
-
# This allows you to modify application's generators from Railties.
-
#
-
# Values set on app_generators will become defaults for application, unless
-
# application overwrites them.
-
2
def app_generators
-
40
@@app_generators ||= Rails::Configuration::Generators.new
-
40
yield(@@app_generators) if block_given?
-
40
@@app_generators
-
end
-
-
# First configurable block to run. Called before any initializers are run.
-
2
def before_configuration(&block)
-
4
ActiveSupport.on_load(:before_configuration, yield: true, &block)
-
end
-
-
# Third configurable block to run. Does not run if +config.cache_classes+
-
# set to false.
-
2
def before_eager_load(&block)
-
4
ActiveSupport.on_load(:before_eager_load, yield: true, &block)
-
end
-
-
# Second configurable block to run. Called before frameworks initialize.
-
2
def before_initialize(&block)
-
ActiveSupport.on_load(:before_initialize, yield: true, &block)
-
end
-
-
# Last configurable block to run. Called after frameworks initialize.
-
2
def after_initialize(&block)
-
12
ActiveSupport.on_load(:after_initialize, yield: true, &block)
-
end
-
-
# Array of callbacks defined by #to_prepare.
-
2
def to_prepare_blocks
-
14
@@to_prepare_blocks ||= []
-
end
-
-
# Defines generic callbacks to run before #after_initialize. Useful for
-
# Rails::Railtie subclasses.
-
2
def to_prepare(&blk)
-
12
to_prepare_blocks << blk if blk
-
end
-
-
2
def respond_to?(name, include_private = false)
-
14
super || @@options.key?(name.to_sym)
-
end
-
-
2
private
-
-
2
def method_missing(name, *args, &blk)
-
379
if name.to_s =~ /=$/
-
22
@@options[$`.to_sym] = args.first
-
357
elsif @@options.key?(name)
-
357
@@options[name]
-
else
-
super
-
end
-
end
-
end
-
end
-
end
-
2
if RUBY_VERSION < '1.9.3'
-
desc = defined?(RUBY_DESCRIPTION) ? RUBY_DESCRIPTION : "ruby #{RUBY_VERSION} (#{RUBY_RELEASE_DATE})"
-
abort <<-end_message
-
-
Rails 4 prefers to run on Ruby 2.0.
-
-
You're running
-
#{desc}
-
-
Please upgrade to Ruby 1.9.3 or newer to continue.
-
-
end_message
-
end
-
# Make double-sure the RAILS_ENV is not set to production,
-
# so fixtures aren't loaded into that environment
-
1
abort("Abort testing: Your Rails environment is running in production mode!") if Rails.env.production?
-
-
1
require 'active_support/testing/autorun'
-
1
require 'active_support/test_case'
-
1
require 'action_controller'
-
1
require 'action_controller/test_case'
-
1
require 'action_dispatch/testing/integration'
-
1
require 'rails/generators/test_case'
-
-
# Config Rails backtrace in tests.
-
1
require 'rails/backtrace_cleaner'
-
1
if ENV["BACKTRACE"].nil?
-
1
Minitest.backtrace_filter = Rails.backtrace_cleaner
-
end
-
-
1
if defined?(ActiveRecord::Base)
-
1
ActiveRecord::Migration.maintain_test_schema!
-
-
1
class ActiveSupport::TestCase
-
1
include ActiveRecord::TestFixtures
-
1
self.fixture_path = "#{Rails.root}/test/fixtures/"
-
end
-
-
1
ActionDispatch::IntegrationTest.fixture_path = ActiveSupport::TestCase.fixture_path
-
-
1
def create_fixtures(*fixture_set_names, &block)
-
FixtureSet.create_fixtures(ActiveSupport::TestCase.fixture_path, fixture_set_names, {}, &block)
-
end
-
end
-
-
1
class ActionController::TestCase
-
1
setup do
-
@routes = Rails.application.routes
-
end
-
end
-
-
1
class ActionDispatch::IntegrationTest
-
1
setup do
-
@routes = Rails.application.routes
-
end
-
end
-
2
if defined?(Rake.application) && Rake.application.top_level_tasks.grep(/^(default$|test(:|$))/).any?
-
ENV['RAILS_ENV'] ||= 'test'
-
end
-
-
2
module Rails
-
2
class TestUnitRailtie < Rails::Railtie
-
2
config.app_generators do |c|
-
2
c.test_framework :test_unit, fixture: true,
-
fixture_replacement: nil
-
-
2
c.integration_tool :test_unit
-
end
-
-
2
rake_tasks do
-
load "rails/test_unit/testing.rake"
-
end
-
end
-
end
-
2
require_relative 'gem_version'
-
-
2
module Rails
-
# Returns the version of the currently loaded Rails as a string.
-
2
def self.version
-
13
VERSION::STRING
-
end
-
end
-
#--
-
# Copyright 2003-2010 by Jim Weirich (jim.weirich@gmail.com)
-
#
-
# Permission is hereby granted, free of charge, to any person obtaining a copy
-
# of this software and associated documentation files (the "Software"), to
-
# deal in the Software without restriction, including without limitation the
-
# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
-
# sell copies of the Software, and to permit persons to whom the Software is
-
# furnished to do so, subject to the following conditions:
-
#
-
# The above copyright notice and this permission notice shall be included in
-
# all copies or substantial portions of the Software.
-
#
-
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
-
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
-
# IN THE SOFTWARE.
-
#++
-
-
2
module Rake
-
2
VERSION = '11.0.1'
-
end
-
-
2
require 'rake/version'
-
-
2
require 'rbconfig'
-
2
require 'fileutils'
-
2
require 'singleton'
-
2
require 'monitor'
-
2
require 'optparse'
-
2
require 'ostruct'
-
-
2
require 'rake/ext/string'
-
2
require 'rake/ext/fixnum'
-
-
2
require 'rake/win32'
-
-
2
require 'rake/linked_list'
-
2
require 'rake/cpu_counter'
-
2
require 'rake/scope'
-
2
require 'rake/task_argument_error'
-
2
require 'rake/rule_recursion_overflow_error'
-
2
require 'rake/rake_module'
-
2
require 'rake/trace_output'
-
2
require 'rake/pseudo_status'
-
2
require 'rake/task_arguments'
-
2
require 'rake/invocation_chain'
-
2
require 'rake/task'
-
2
require 'rake/file_task'
-
2
require 'rake/file_creation_task'
-
2
require 'rake/multi_task'
-
2
require 'rake/dsl_definition'
-
2
require 'rake/file_utils_ext'
-
2
require 'rake/file_list'
-
2
require 'rake/default_loader'
-
2
require 'rake/early_time'
-
2
require 'rake/late_time'
-
2
require 'rake/name_space'
-
2
require 'rake/task_manager'
-
2
require 'rake/application'
-
2
require 'rake/backtrace'
-
-
2
$trace = false
-
-
# :stopdoc:
-
#
-
# Some top level Constants.
-
-
2
FileList = Rake::FileList
-
2
RakeFileUtils = Rake::FileUtilsExt
-
2
require 'shellwords'
-
2
require 'optparse'
-
-
2
require 'rake/task_manager'
-
2
require 'rake/file_list'
-
2
require 'rake/thread_pool'
-
2
require 'rake/thread_history_display'
-
2
require 'rake/trace_output'
-
2
require 'rake/win32'
-
-
2
module Rake
-
-
2
CommandLineOptionError = Class.new(StandardError)
-
-
##
-
# Rake main application object. When invoking +rake+ from the
-
# command line, a Rake::Application object is created and run.
-
-
2
class Application
-
2
include TaskManager
-
2
include TraceOutput
-
-
# The name of the application (typically 'rake')
-
2
attr_reader :name
-
-
# The original directory where rake was invoked.
-
2
attr_reader :original_dir
-
-
# Name of the actual rakefile used.
-
2
attr_reader :rakefile
-
-
# Number of columns on the terminal
-
2
attr_accessor :terminal_columns
-
-
# List of the top level task names (task names from the command line).
-
2
attr_reader :top_level_tasks
-
-
2
DEFAULT_RAKEFILES = [
-
'rakefile',
-
'Rakefile',
-
'rakefile.rb',
-
'Rakefile.rb'
-
].freeze
-
-
# Initialize a Rake::Application object.
-
2
def initialize
-
super
-
@name = 'rake'
-
@rakefiles = DEFAULT_RAKEFILES.dup
-
@rakefile = nil
-
@pending_imports = []
-
@imported = []
-
@loaders = {}
-
@default_loader = Rake::DefaultLoader.new
-
@original_dir = Dir.pwd
-
@top_level_tasks = []
-
add_loader('rb', DefaultLoader.new)
-
add_loader('rf', DefaultLoader.new)
-
add_loader('rake', DefaultLoader.new)
-
@tty_output = STDOUT.tty?
-
@terminal_columns = ENV['RAKE_COLUMNS'].to_i
-
end
-
-
# Run the Rake application. The run method performs the following
-
# three steps:
-
#
-
# * Initialize the command line options (+init+).
-
# * Define the tasks (+load_rakefile+).
-
# * Run the top level tasks (+top_level+).
-
#
-
# If you wish to build a custom rake command, you should call
-
# +init+ on your application. Then define any tasks. Finally,
-
# call +top_level+ to run your top level tasks.
-
2
def run
-
standard_exception_handling do
-
init
-
load_rakefile
-
top_level
-
end
-
end
-
-
# Initialize the command line parameters and app name.
-
2
def init(app_name='rake')
-
standard_exception_handling do
-
@name = app_name
-
args = handle_options
-
collect_command_line_tasks(args)
-
end
-
end
-
-
# Find the rakefile and then load it and any pending imports.
-
2
def load_rakefile
-
standard_exception_handling do
-
raw_load_rakefile
-
end
-
end
-
-
# Run the top level tasks of a Rake application.
-
2
def top_level
-
run_with_threads do
-
if options.show_tasks
-
display_tasks_and_comments
-
elsif options.show_prereqs
-
display_prerequisites
-
else
-
top_level_tasks.each { |task_name| invoke_task(task_name) }
-
end
-
end
-
end
-
-
# Run the given block with the thread startup and shutdown.
-
2
def run_with_threads
-
thread_pool.gather_history if options.job_stats == :history
-
-
yield
-
-
thread_pool.join
-
if options.job_stats
-
stats = thread_pool.statistics
-
puts "Maximum active threads: #{stats[:max_active_threads]} + main"
-
puts "Total threads in play: #{stats[:total_threads_in_play]} + main"
-
end
-
ThreadHistoryDisplay.new(thread_pool.history).show if
-
options.job_stats == :history
-
end
-
-
# Add a loader to handle imported files ending in the extension
-
# +ext+.
-
2
def add_loader(ext, loader)
-
ext = ".#{ext}" unless ext =~ /^\./
-
@loaders[ext] = loader
-
end
-
-
# Application options from the command line
-
2
def options
-
@options ||= OpenStruct.new
-
end
-
-
# Return the thread pool used for multithreaded processing.
-
2
def thread_pool # :nodoc:
-
@thread_pool ||= ThreadPool.new(options.thread_pool_size || Rake.suggested_thread_count-1)
-
end
-
-
# internal ----------------------------------------------------------------
-
-
# Invokes a task with arguments that are extracted from +task_string+
-
2
def invoke_task(task_string) # :nodoc:
-
name, args = parse_task_string(task_string)
-
t = self[name]
-
t.invoke(*args)
-
end
-
-
2
def parse_task_string(string) # :nodoc:
-
/^([^\[]+)(?:\[(.*)\])$/ =~ string.to_s
-
-
name = $1
-
remaining_args = $2
-
-
return string, [] unless name
-
return name, [] if remaining_args.empty?
-
-
args = []
-
-
begin
-
/((?:[^\\,]|\\.)*?)\s*(?:,\s*(.*))?$/ =~ remaining_args
-
-
remaining_args = $2
-
args << $1.gsub(/\\(.)/, '\1')
-
end while remaining_args
-
-
return name, args
-
end
-
-
# Provide standard exception handling for the given block.
-
2
def standard_exception_handling # :nodoc:
-
yield
-
rescue SystemExit
-
# Exit silently with current status
-
raise
-
rescue OptionParser::InvalidOption => ex
-
$stderr.puts ex.message
-
exit(false)
-
rescue Exception => ex
-
# Exit with error message
-
display_error_message(ex)
-
exit_because_of_exception(ex)
-
end
-
-
# Exit the program because of an unhandled exception.
-
# (may be overridden by subclasses)
-
2
def exit_because_of_exception(ex) # :nodoc:
-
exit(false)
-
end
-
-
# Display the error message that caused the exception.
-
2
def display_error_message(ex) # :nodoc:
-
trace "#{name} aborted!"
-
display_exception_details(ex)
-
trace "Tasks: #{ex.chain}" if has_chain?(ex)
-
trace "(See full trace by running task with --trace)" unless
-
options.backtrace
-
end
-
-
2
def display_exception_details(ex) # :nodoc:
-
seen = Thread.current[:rake_display_exception_details_seen] ||= []
-
return if seen.include? ex
-
seen << ex
-
-
display_exception_message_details(ex)
-
display_exception_backtrace(ex)
-
display_exception_details(ex.cause) if has_cause?(ex)
-
end
-
-
2
def has_cause?(ex) # :nodoc:
-
ex.respond_to?(:cause) && ex.cause
-
end
-
-
2
def display_exception_message_details(ex) # :nodoc:
-
if ex.instance_of?(RuntimeError)
-
trace ex.message
-
else
-
trace "#{ex.class.name}: #{ex.message}"
-
end
-
end
-
-
2
def display_exception_backtrace(ex) # :nodoc:
-
if options.backtrace
-
trace ex.backtrace.join("\n")
-
else
-
trace Backtrace.collapse(ex.backtrace).join("\n")
-
end
-
end
-
-
# Warn about deprecated usage.
-
#
-
# Example:
-
# Rake.application.deprecate("import", "Rake.import", caller.first)
-
#
-
2
def deprecate(old_usage, new_usage, call_site) # :nodoc:
-
unless options.ignore_deprecate
-
$stderr.puts "WARNING: '#{old_usage}' is deprecated. " +
-
"Please use '#{new_usage}' instead.\n" +
-
" at #{call_site}"
-
end
-
end
-
-
# Does the exception have a task invocation chain?
-
2
def has_chain?(exception) # :nodoc:
-
exception.respond_to?(:chain) && exception.chain
-
end
-
2
private :has_chain?
-
-
# True if one of the files in RAKEFILES is in the current directory.
-
# If a match is found, it is copied into @rakefile.
-
2
def have_rakefile # :nodoc:
-
@rakefiles.each do |fn|
-
if File.exist?(fn)
-
others = FileList.glob(fn, File::FNM_CASEFOLD)
-
return others.size == 1 ? others.first : fn
-
elsif fn == ''
-
return fn
-
end
-
end
-
return nil
-
end
-
-
# True if we are outputting to TTY, false otherwise
-
2
def tty_output? # :nodoc:
-
@tty_output
-
end
-
-
# Override the detected TTY output state (mostly for testing)
-
2
def tty_output=(tty_output_state) # :nodoc:
-
@tty_output = tty_output_state
-
end
-
-
# We will truncate output if we are outputting to a TTY or if we've been
-
# given an explicit column width to honor
-
2
def truncate_output? # :nodoc:
-
tty_output? || @terminal_columns.nonzero?
-
end
-
-
# Display the tasks and comments.
-
2
def display_tasks_and_comments # :nodoc:
-
displayable_tasks = tasks.select { |t|
-
(options.show_all_tasks || t.comment) &&
-
t.name =~ options.show_task_pattern
-
}
-
case options.show_tasks
-
when :tasks
-
width = displayable_tasks.map { |t| t.name_with_args.length }.max || 10
-
if truncate_output?
-
max_column = terminal_width - name.size - width - 7
-
else
-
max_column = nil
-
end
-
-
displayable_tasks.each do |t|
-
printf("#{name} %-#{width}s # %s\n",
-
t.name_with_args,
-
max_column ? truncate(t.comment, max_column) : t.comment)
-
end
-
when :describe
-
displayable_tasks.each do |t|
-
puts "#{name} #{t.name_with_args}"
-
comment = t.full_comment || ""
-
comment.split("\n").each do |line|
-
puts " #{line}"
-
end
-
puts
-
end
-
when :lines
-
displayable_tasks.each do |t|
-
t.locations.each do |loc|
-
printf "#{name} %-30s %s\n", t.name_with_args, loc
-
end
-
end
-
else
-
fail "Unknown show task mode: '#{options.show_tasks}'"
-
end
-
end
-
-
2
def terminal_width # :nodoc:
-
if @terminal_columns.nonzero?
-
result = @terminal_columns
-
else
-
result = unix? ? dynamic_width : 80
-
end
-
(result < 10) ? 80 : result
-
rescue
-
80
-
end
-
-
# Calculate the dynamic width of the
-
2
def dynamic_width # :nodoc:
-
@dynamic_width ||= (dynamic_width_stty.nonzero? || dynamic_width_tput)
-
end
-
-
2
def dynamic_width_stty # :nodoc:
-
%x{stty size 2>/dev/null}.split[1].to_i
-
end
-
-
2
def dynamic_width_tput # :nodoc:
-
%x{tput cols 2>/dev/null}.to_i
-
end
-
-
2
def unix? # :nodoc:
-
RbConfig::CONFIG['host_os'] =~
-
/(aix|darwin|linux|(net|free|open)bsd|cygwin|solaris|irix|hpux)/i
-
end
-
-
2
def windows? # :nodoc:
-
Win32.windows?
-
end
-
-
2
def truncate(string, width) # :nodoc:
-
if string.nil?
-
""
-
elsif string.length <= width
-
string
-
else
-
(string[0, width - 3] || "") + "..."
-
end
-
end
-
-
# Display the tasks and prerequisites
-
2
def display_prerequisites # :nodoc:
-
tasks.each do |t|
-
puts "#{name} #{t.name}"
-
t.prerequisites.each { |pre| puts " #{pre}" }
-
end
-
end
-
-
2
def trace(*strings) # :nodoc:
-
options.trace_output ||= $stderr
-
trace_on(options.trace_output, *strings)
-
end
-
-
2
def sort_options(options) # :nodoc:
-
options.sort_by { |opt|
-
opt.select { |o| o =~ /^-/ }.map { |o| o.downcase }.sort.reverse
-
}
-
end
-
2
private :sort_options
-
-
# A list of all the standard options used in rake, suitable for
-
# passing to OptionParser.
-
2
def standard_rake_options # :nodoc:
-
sort_options(
-
[
-
['--all', '-A',
-
"Show all tasks, even uncommented ones (in combination with -T or -D)",
-
lambda { |value|
-
options.show_all_tasks = value
-
}
-
],
-
['--backtrace=[OUT]',
-
"Enable full backtrace. OUT can be stderr (default) or stdout.",
-
lambda { |value|
-
options.backtrace = true
-
select_trace_output(options, 'backtrace', value)
-
}
-
],
-
['--build-all', '-B',
-
"Build all prerequisites, including those which are up-to-date.",
-
lambda { |value|
-
options.build_all = true
-
}
-
],
-
['--comments',
-
"Show commented tasks only",
-
lambda { |value|
-
options.show_all_tasks = !value
-
}
-
],
-
['--describe', '-D [PATTERN]',
-
"Describe the tasks (matching optional PATTERN), then exit.",
-
lambda { |value|
-
select_tasks_to_show(options, :describe, value)
-
}
-
],
-
['--dry-run', '-n',
-
"Do a dry run without executing actions.",
-
lambda { |value|
-
Rake.verbose(true)
-
Rake.nowrite(true)
-
options.dryrun = true
-
options.trace = true
-
}
-
],
-
['--execute', '-e CODE',
-
"Execute some Ruby code and exit.",
-
lambda { |value|
-
eval(value)
-
exit
-
}
-
],
-
['--execute-print', '-p CODE',
-
"Execute some Ruby code, print the result, then exit.",
-
lambda { |value|
-
puts eval(value)
-
exit
-
}
-
],
-
['--execute-continue', '-E CODE',
-
"Execute some Ruby code, " +
-
"then continue with normal task processing.",
-
lambda { |value| eval(value) }
-
],
-
['--jobs', '-j [NUMBER]',
-
"Specifies the maximum number of tasks to execute in parallel. " +
-
"(default is number of CPU cores + 4)",
-
lambda { |value|
-
if value.nil? || value == ''
-
value = Fixnum::MAX
-
elsif value =~ /^\d+$/
-
value = value.to_i
-
else
-
value = Rake.suggested_thread_count
-
end
-
value = 1 if value < 1
-
options.thread_pool_size = value - 1
-
}
-
],
-
['--job-stats [LEVEL]',
-
"Display job statistics. " +
-
"LEVEL=history displays a complete job list",
-
lambda { |value|
-
if value =~ /^history/i
-
options.job_stats = :history
-
else
-
options.job_stats = true
-
end
-
}
-
],
-
['--libdir', '-I LIBDIR',
-
"Include LIBDIR in the search path for required modules.",
-
lambda { |value| $:.push(value) }
-
],
-
['--multitask', '-m',
-
"Treat all tasks as multitasks.",
-
lambda { |value| options.always_multitask = true }
-
],
-
['--no-search', '--nosearch',
-
'-N', "Do not search parent directories for the Rakefile.",
-
lambda { |value| options.nosearch = true }
-
],
-
['--prereqs', '-P',
-
"Display the tasks and dependencies, then exit.",
-
lambda { |value| options.show_prereqs = true }
-
],
-
['--quiet', '-q',
-
"Do not log messages to standard output.",
-
lambda { |value| Rake.verbose(false) }
-
],
-
['--rakefile', '-f [FILENAME]',
-
"Use FILENAME as the rakefile to search for.",
-
lambda { |value|
-
value ||= ''
-
@rakefiles.clear
-
@rakefiles << value
-
}
-
],
-
['--rakelibdir', '--rakelib', '-R RAKELIBDIR',
-
"Auto-import any .rake files in RAKELIBDIR. " +
-
"(default is 'rakelib')",
-
lambda { |value|
-
options.rakelib = value.split(File::PATH_SEPARATOR)
-
}
-
],
-
['--require', '-r MODULE',
-
"Require MODULE before executing rakefile.",
-
lambda { |value|
-
begin
-
require value
-
rescue LoadError => ex
-
begin
-
rake_require value
-
rescue LoadError
-
raise ex
-
end
-
end
-
}
-
],
-
['--rules',
-
"Trace the rules resolution.",
-
lambda { |value| options.trace_rules = true }
-
],
-
['--silent', '-s',
-
"Like --quiet, but also suppresses the " +
-
"'in directory' announcement.",
-
lambda { |value|
-
Rake.verbose(false)
-
options.silent = true
-
}
-
],
-
['--suppress-backtrace PATTERN',
-
"Suppress backtrace lines matching regexp PATTERN. " +
-
"Ignored if --trace is on.",
-
lambda { |value|
-
options.suppress_backtrace_pattern = Regexp.new(value)
-
}
-
],
-
['--system', '-g',
-
"Using system wide (global) rakefiles " +
-
"(usually '~/.rake/*.rake').",
-
lambda { |value| options.load_system = true }
-
],
-
['--no-system', '--nosystem', '-G',
-
"Use standard project Rakefile search paths, " +
-
"ignore system wide rakefiles.",
-
lambda { |value| options.ignore_system = true }
-
],
-
['--tasks', '-T [PATTERN]',
-
"Display the tasks (matching optional PATTERN) " +
-
"with descriptions, then exit.",
-
lambda { |value|
-
select_tasks_to_show(options, :tasks, value)
-
}
-
],
-
['--trace=[OUT]', '-t',
-
"Turn on invoke/execute tracing, enable full backtrace. " +
-
"OUT can be stderr (default) or stdout.",
-
lambda { |value|
-
options.trace = true
-
options.backtrace = true
-
select_trace_output(options, 'trace', value)
-
Rake.verbose(true)
-
}
-
],
-
['--verbose', '-v',
-
"Log message to standard output.",
-
lambda { |value| Rake.verbose(true) }
-
],
-
['--version', '-V',
-
"Display the program version.",
-
lambda { |value|
-
puts "rake, version #{Rake::VERSION}"
-
exit
-
}
-
],
-
['--where', '-W [PATTERN]',
-
"Describe the tasks (matching optional PATTERN), then exit.",
-
lambda { |value|
-
select_tasks_to_show(options, :lines, value)
-
options.show_all_tasks = true
-
}
-
],
-
['--no-deprecation-warnings', '-X',
-
"Disable the deprecation warnings.",
-
lambda { |value|
-
options.ignore_deprecate = true
-
}
-
],
-
])
-
end
-
-
2
def select_tasks_to_show(options, show_tasks, value) # :nodoc:
-
options.show_tasks = show_tasks
-
options.show_task_pattern = Regexp.new(value || '')
-
Rake::TaskManager.record_task_metadata = true
-
end
-
2
private :select_tasks_to_show
-
-
2
def select_trace_output(options, trace_option, value) # :nodoc:
-
value = value.strip unless value.nil?
-
case value
-
when 'stdout'
-
options.trace_output = $stdout
-
when 'stderr', nil
-
options.trace_output = $stderr
-
else
-
fail CommandLineOptionError,
-
"Unrecognized --#{trace_option} option '#{value}'"
-
end
-
end
-
2
private :select_trace_output
-
-
# Read and handle the command line options. Returns the command line
-
# arguments that we didn't understand, which should (in theory) be just
-
# task names and env vars.
-
2
def handle_options # :nodoc:
-
options.rakelib = ['rakelib']
-
options.trace_output = $stderr
-
-
OptionParser.new do |opts|
-
opts.banner = "#{Rake.application.name} [-f rakefile] {options} targets..."
-
opts.separator ""
-
opts.separator "Options are ..."
-
-
opts.on_tail("-h", "--help", "-H", "Display this help message.") do
-
puts opts
-
exit
-
end
-
-
standard_rake_options.each { |args| opts.on(*args) }
-
opts.environment('RAKEOPT')
-
end.parse(ARGV)
-
end
-
-
# Similar to the regular Ruby +require+ command, but will check
-
# for *.rake files in addition to *.rb files.
-
2
def rake_require(file_name, paths=$LOAD_PATH, loaded=$") # :nodoc:
-
fn = file_name + ".rake"
-
return false if loaded.include?(fn)
-
paths.each do |path|
-
full_path = File.join(path, fn)
-
if File.exist?(full_path)
-
Rake.load_rakefile(full_path)
-
loaded << fn
-
return true
-
end
-
end
-
fail LoadError, "Can't find #{file_name}"
-
end
-
-
2
def find_rakefile_location # :nodoc:
-
here = Dir.pwd
-
until (fn = have_rakefile)
-
Dir.chdir("..")
-
return nil if Dir.pwd == here || options.nosearch
-
here = Dir.pwd
-
end
-
[fn, here]
-
ensure
-
Dir.chdir(Rake.original_dir)
-
end
-
-
2
def print_rakefile_directory(location) # :nodoc:
-
$stderr.puts "(in #{Dir.pwd})" unless
-
options.silent or original_dir == location
-
end
-
-
2
def raw_load_rakefile # :nodoc:
-
rakefile, location = find_rakefile_location
-
if (! options.ignore_system) &&
-
(options.load_system || rakefile.nil?) &&
-
system_dir && File.directory?(system_dir)
-
print_rakefile_directory(location)
-
glob("#{system_dir}/*.rake") do |name|
-
add_import name
-
end
-
else
-
fail "No Rakefile found (looking for: #{@rakefiles.join(', ')})" if
-
rakefile.nil?
-
@rakefile = rakefile
-
Dir.chdir(location)
-
print_rakefile_directory(location)
-
Rake.load_rakefile(File.expand_path(@rakefile)) if
-
@rakefile && @rakefile != ''
-
options.rakelib.each do |rlib|
-
glob("#{rlib}/*.rake") do |name|
-
add_import name
-
end
-
end
-
end
-
load_imports
-
end
-
-
2
def glob(path, &block) # :nodoc:
-
FileList.glob(path.gsub("\\", '/')).each(&block)
-
end
-
2
private :glob
-
-
# The directory path containing the system wide rakefiles.
-
2
def system_dir # :nodoc:
-
@system_dir ||=
-
begin
-
if ENV['RAKE_SYSTEM']
-
ENV['RAKE_SYSTEM']
-
else
-
standard_system_dir
-
end
-
end
-
end
-
-
# The standard directory containing system wide rake files.
-
2
if Win32.windows?
-
def standard_system_dir #:nodoc:
-
Win32.win32_system_dir
-
end
-
else
-
2
def standard_system_dir #:nodoc:
-
File.join(File.expand_path('~'), '.rake')
-
end
-
end
-
2
private :standard_system_dir
-
-
# Collect the list of tasks on the command line. If no tasks are
-
# given, return a list containing only the default task.
-
# Environmental assignments are processed at this time as well.
-
#
-
# `args` is the list of arguments to peruse to get the list of tasks.
-
# It should be the command line that was given to rake, less any
-
# recognised command-line options, which OptionParser.parse will
-
# have taken care of already.
-
2
def collect_command_line_tasks(args) # :nodoc:
-
@top_level_tasks = []
-
args.each do |arg|
-
if arg =~ /^(\w+)=(.*)$/m
-
ENV[$1] = $2
-
else
-
@top_level_tasks << arg unless arg =~ /^-/
-
end
-
end
-
@top_level_tasks.push(default_task_name) if @top_level_tasks.empty?
-
end
-
-
# Default task name ("default").
-
# (May be overridden by subclasses)
-
2
def default_task_name # :nodoc:
-
"default"
-
end
-
-
# Add a file to the list of files to be imported.
-
2
def add_import(fn) # :nodoc:
-
@pending_imports << fn
-
end
-
-
# Load the pending list of imported files.
-
2
def load_imports # :nodoc:
-
while fn = @pending_imports.shift
-
next if @imported.member?(fn)
-
fn_task = lookup(fn) and fn_task.invoke
-
ext = File.extname(fn)
-
loader = @loaders[ext] || @default_loader
-
loader.load(fn)
-
if fn_task = lookup(fn) and fn_task.needed?
-
fn_task.reenable
-
fn_task.invoke
-
loader.load(fn)
-
end
-
@imported << fn
-
end
-
end
-
-
2
def rakefile_location(backtrace=caller) # :nodoc:
-
backtrace.map { |t| t[/([^:]+):/, 1] }
-
-
re = /^#{@rakefile}$/
-
re = /#{re.source}/i if windows?
-
-
backtrace.find { |str| str =~ re } || ''
-
end
-
-
end
-
end
-
2
module Rake
-
2
module Backtrace # :nodoc: all
-
2
SYS_KEYS = RbConfig::CONFIG.keys.grep(/(?:[a-z]prefix|libdir)\z/)
-
2
SYS_PATHS = RbConfig::CONFIG.values_at(*SYS_KEYS).uniq +
-
[ File.join(File.dirname(__FILE__), "..") ]
-
-
2
SUPPRESSED_PATHS = SYS_PATHS.
-
16
map { |s| s.gsub("\\", "/") }.
-
16
map { |f| File.expand_path(f) }.
-
16
reject { |s| s.nil? || s =~ /^ *$/ }
-
18
SUPPRESSED_PATHS_RE = SUPPRESSED_PATHS.map { |f| Regexp.quote(f) }.join("|")
-
SUPPRESSED_PATHS_RE << "|^org\\/jruby\\/\\w+\\.java" if
-
2
Object.const_defined?(:RUBY_ENGINE) and RUBY_ENGINE == 'jruby'
-
-
2
SUPPRESS_PATTERN = %r!(\A(#{SUPPRESSED_PATHS_RE})|bin/rake:\d+)!i
-
-
2
def self.collapse(backtrace)
-
pattern = Rake.application.options.suppress_backtrace_pattern ||
-
SUPPRESS_PATTERN
-
backtrace.reject { |elem| elem =~ pattern }
-
end
-
end
-
end
-
2
module Rake
-
##
-
# Mixin for creating easily cloned objects.
-
-
2
module Cloneable # :nodoc:
-
# The hook that is invoked by 'clone' and 'dup' methods.
-
2
def initialize_copy(source)
-
super
-
source.instance_variables.each do |var|
-
src_value = source.instance_variable_get(var)
-
value = src_value.clone rescue src_value
-
instance_variable_set(var, value)
-
end
-
end
-
end
-
end
-
2
module Rake
-
-
# Based on a script at:
-
# http://stackoverflow.com/questions/891537/ruby-detect-number-of-cpus-installed
-
2
class CpuCounter # :nodoc: all
-
2
def self.count
-
new.count_with_default
-
end
-
-
2
def count_with_default(default=4)
-
count || default
-
rescue StandardError
-
default
-
end
-
-
2
begin
-
2
require 'etc'
-
rescue LoadError
-
else
-
2
if Etc.respond_to?(:nprocessors)
-
2
def count
-
return Etc.nprocessors
-
end
-
end
-
end
-
end
-
end
-
-
2
unless Rake::CpuCounter.method_defined?(:count)
-
Rake::CpuCounter.class_eval <<-'end;', __FILE__, __LINE__+1
-
require 'rbconfig'
-
-
def count
-
if defined?(Java::Java)
-
count_via_java_runtime
-
else
-
case RbConfig::CONFIG['host_os']
-
when /darwin9/
-
count_via_hwprefs_cpu_count
-
when /darwin/
-
count_via_hwprefs_thread_count || count_via_sysctl
-
when /linux/
-
count_via_cpuinfo
-
when /bsd/
-
count_via_sysctl
-
when /mswin|mingw/
-
count_via_win32
-
else
-
# Try everything
-
count_via_win32 ||
-
count_via_sysctl ||
-
count_via_hwprefs_thread_count ||
-
count_via_hwprefs_cpu_count ||
-
count_via_cpuinfo
-
end
-
end
-
end
-
-
def count_via_java_runtime
-
Java::Java.lang.Runtime.getRuntime.availableProcessors
-
rescue StandardError
-
nil
-
end
-
-
def count_via_win32
-
require 'win32ole'
-
wmi = WIN32OLE.connect("winmgmts://")
-
cpu = wmi.ExecQuery("select NumberOfCores from Win32_Processor") # TODO count hyper-threaded in this
-
cpu.to_enum.first.NumberOfCores
-
rescue StandardError, LoadError
-
nil
-
end
-
-
def count_via_cpuinfo
-
open('/proc/cpuinfo') { |f| f.readlines }.grep(/processor/).size
-
rescue StandardError
-
nil
-
end
-
-
def count_via_hwprefs_thread_count
-
run 'hwprefs', 'thread_count'
-
end
-
-
def count_via_hwprefs_cpu_count
-
run 'hwprefs', 'cpu_count'
-
end
-
-
def count_via_sysctl
-
run 'sysctl', '-n', 'hw.ncpu'
-
end
-
-
def run(command, *args)
-
cmd = resolve_command(command)
-
if cmd
-
IO.popen [cmd, *args] do |io|
-
io.read.to_i
-
end
-
else
-
nil
-
end
-
end
-
-
def resolve_command(command)
-
look_for_command("/usr/sbin", command) ||
-
look_for_command("/sbin", command) ||
-
in_path_command(command)
-
end
-
-
def look_for_command(dir, command)
-
path = File.join(dir, command)
-
File.exist?(path) ? path : nil
-
end
-
-
def in_path_command(command)
-
IO.popen ['which', command] do |io|
-
io.eof? ? nil : command
-
end
-
end
-
end;
-
end
-
2
module Rake
-
-
# Default Rakefile loader used by +import+.
-
2
class DefaultLoader
-
-
##
-
# Loads a rakefile into the current application from +fn+
-
-
2
def load(fn)
-
Rake.load_rakefile(File.expand_path(fn))
-
end
-
end
-
-
end
-
# Rake DSL functions.
-
2
require 'rake/file_utils_ext'
-
-
2
module Rake
-
-
##
-
# DSL is a module that provides #task, #desc, #namespace, etc. Use this
-
# when you'd like to use rake outside the top level scope.
-
#
-
# For a Rakefile you run from the command line this module is automatically
-
# included.
-
-
2
module DSL
-
-
#--
-
# Include the FileUtils file manipulation functions in the top
-
# level module, but mark them private so that they don't
-
# unintentionally define methods on other objects.
-
#++
-
-
2
include FileUtilsExt
-
2
private(*FileUtils.instance_methods(false))
-
2
private(*FileUtilsExt.instance_methods(false))
-
-
2
private
-
-
# :call-seq:
-
# task task_name
-
# task task_name: dependencies
-
# task task_name, arguments => dependencies
-
#
-
# Declare a basic task. The +task_name+ is always the first argument. If
-
# the task name contains a ":" it is defined in that namespace.
-
#
-
# The +dependencies+ may be a single task name or an Array of task names.
-
# The +argument+ (a single name) or +arguments+ (an Array of names) define
-
# the arguments provided to the task.
-
#
-
# The task, argument and dependency names may be either symbols or
-
# strings.
-
#
-
# A task with a single dependency:
-
#
-
# task clobber: %w[clean] do
-
# rm_rf "html"
-
# end
-
#
-
# A task with an argument and a dependency:
-
#
-
# task :package, [:version] => :test do |t, args|
-
# # ...
-
# end
-
#
-
# To invoke this task from the command line:
-
#
-
# $ rake package[1.2.3]
-
#
-
2
def task(*args, &block) # :doc:
-
Rake::Task.define_task(*args, &block)
-
end
-
-
# Declare a file task.
-
#
-
# Example:
-
# file "config.cfg" => ["config.template"] do
-
# open("config.cfg", "w") do |outfile|
-
# open("config.template") do |infile|
-
# while line = infile.gets
-
# outfile.puts line
-
# end
-
# end
-
# end
-
# end
-
#
-
2
def file(*args, &block) # :doc:
-
Rake::FileTask.define_task(*args, &block)
-
end
-
-
# Declare a file creation task.
-
# (Mainly used for the directory command).
-
2
def file_create(*args, &block)
-
Rake::FileCreationTask.define_task(*args, &block)
-
end
-
-
# Declare a set of files tasks to create the given directories on
-
# demand.
-
#
-
# Example:
-
# directory "testdata/doc"
-
#
-
2
def directory(*args, &block) # :doc:
-
result = file_create(*args, &block)
-
dir, _ = *Rake.application.resolve_args(args)
-
dir = Rake.from_pathname(dir)
-
Rake.each_dir_parent(dir) do |d|
-
file_create d do |t|
-
mkdir_p t.name unless File.exist?(t.name)
-
end
-
end
-
result
-
end
-
-
# Declare a task that performs its prerequisites in
-
# parallel. Multitasks does *not* guarantee that its prerequisites
-
# will execute in any given order (which is obvious when you think
-
# about it)
-
#
-
# Example:
-
# multitask deploy: %w[deploy_gem deploy_rdoc]
-
#
-
2
def multitask(*args, &block) # :doc:
-
Rake::MultiTask.define_task(*args, &block)
-
end
-
-
# Create a new rake namespace and use it for evaluating the given
-
# block. Returns a NameSpace object that can be used to lookup
-
# tasks defined in the namespace.
-
#
-
# Example:
-
#
-
# ns = namespace "nested" do
-
# # the "nested:run" task
-
# task :run
-
# end
-
# task_run = ns[:run] # find :run in the given namespace.
-
#
-
# Tasks can also be defined in a namespace by using a ":" in the task
-
# name:
-
#
-
# task "nested:test" do
-
# # ...
-
# end
-
#
-
2
def namespace(name=nil, &block) # :doc:
-
name = name.to_s if name.kind_of?(Symbol)
-
name = name.to_str if name.respond_to?(:to_str)
-
unless name.kind_of?(String) || name.nil?
-
raise ArgumentError, "Expected a String or Symbol for a namespace name"
-
end
-
Rake.application.in_namespace(name, &block)
-
end
-
-
# Declare a rule for auto-tasks.
-
#
-
# Example:
-
# rule '.o' => '.c' do |t|
-
# sh 'cc', '-o', t.name, t.source
-
# end
-
#
-
2
def rule(*args, &block) # :doc:
-
Rake::Task.create_rule(*args, &block)
-
end
-
-
# Describes the next rake task. Duplicate descriptions are discarded.
-
# Descriptions are shown with <code>rake -T</code> (up to the first
-
# sentence) and <code>rake -D</code> (the entire description).
-
#
-
# Example:
-
# desc "Run the Unit Tests"
-
# task test: [:build]
-
# # ... run tests
-
# end
-
#
-
2
def desc(description) # :doc:
-
Rake.application.last_description = description
-
end
-
-
# Import the partial Rakefiles +fn+. Imported files are loaded
-
# _after_ the current file is completely loaded. This allows the
-
# import statement to appear anywhere in the importing file, and yet
-
# allowing the imported files to depend on objects defined in the
-
# importing file.
-
#
-
# A common use of the import statement is to include files
-
# containing dependency declarations.
-
#
-
# See also the --rakelibdir command line option.
-
#
-
# Example:
-
# import ".depend", "my_rules"
-
#
-
2
def import(*fns) # :doc:
-
fns.each do |fn|
-
Rake.application.add_import(fn)
-
end
-
end
-
end
-
2
extend FileUtilsExt
-
end
-
-
# Extend the main object with the DSL commands. This allows top-level
-
# calls to task, etc. to work from a Rakefile without polluting the
-
# object inheritance tree.
-
2
self.extend Rake::DSL
-
2
module Rake
-
-
# EarlyTime is a fake timestamp that occurs _before_ any other time value.
-
2
class EarlyTime
-
2
include Comparable
-
2
include Singleton
-
-
##
-
# The EarlyTime always comes before +other+!
-
-
2
def <=>(other)
-
-1
-
end
-
-
2
def to_s # :nodoc:
-
"<EARLY TIME>"
-
end
-
end
-
-
2
EARLY = EarlyTime.instance
-
end
-
2
class Module
-
# Check for an existing method in the current class before extending. If
-
# the method already exists, then a warning is printed and the extension is
-
# not added. Otherwise the block is yielded and any definitions in the
-
# block will take effect.
-
#
-
# Usage:
-
#
-
# class String
-
# rake_extension("xyz") do
-
# def xyz
-
# ...
-
# end
-
# end
-
# end
-
#
-
2
def rake_extension(method) # :nodoc:
-
4
if method_defined?(method)
-
$stderr.puts "WARNING: Possible conflict with Rake extension: " +
-
"#{self}##{method} already exists"
-
else
-
4
yield
-
end
-
end
-
end
-
#--
-
# Extensions to fixnum to define some constants missing from Ruby itself
-
-
2
class Fixnum
-
-
2
unless constants.include? :MAX
-
-
# future versions of Ruby may end up defining this constant
-
# in a more portable way, as documented by Matz himself in:
-
#
-
# https://bugs.ruby-lang.org/issues/7517
-
#
-
# ... but until such time, we define the constant ourselves
-
2
MAX = (2**(0.size * 8 - 2) - 1) # :nodoc:
-
-
end
-
-
end
-
2
require 'rake/ext/core'
-
-
2
class String
-
-
2
rake_extension("ext") do
-
# Replace the file extension with +newext+. If there is no extension on
-
# the string, append the new extension to the end. If the new extension
-
# is not given, or is the empty string, remove any existing extension.
-
#
-
# +ext+ is a user added method for the String class.
-
#
-
# This String extension comes from Rake
-
2
def ext(newext='')
-
return self.dup if ['.', '..'].include? self
-
if newext != ''
-
newext = "." + newext unless newext =~ /^\./
-
end
-
self.chomp(File.extname(self)) << newext
-
end
-
end
-
-
2
rake_extension("pathmap") do
-
# Explode a path into individual components. Used by +pathmap+.
-
#
-
# This String extension comes from Rake
-
2
def pathmap_explode
-
head, tail = File.split(self)
-
return [self] if head == self
-
return [tail] if head == '.' || tail == '/'
-
return [head, tail] if head == '/'
-
return head.pathmap_explode + [tail]
-
end
-
2
protected :pathmap_explode
-
-
# Extract a partial path from the path. Include +n+ directories from the
-
# front end (left hand side) if +n+ is positive. Include |+n+|
-
# directories from the back end (right hand side) if +n+ is negative.
-
#
-
# This String extension comes from Rake
-
2
def pathmap_partial(n)
-
dirs = File.dirname(self).pathmap_explode
-
partial_dirs =
-
if n > 0
-
dirs[0...n]
-
elsif n < 0
-
dirs.reverse[0...-n].reverse
-
else
-
"."
-
end
-
File.join(partial_dirs)
-
end
-
2
protected :pathmap_partial
-
-
# Perform the pathmap replacement operations on the given path. The
-
# patterns take the form 'pat1,rep1;pat2,rep2...'.
-
#
-
# This String extension comes from Rake
-
2
def pathmap_replace(patterns, &block)
-
result = self
-
patterns.split(';').each do |pair|
-
pattern, replacement = pair.split(',')
-
pattern = Regexp.new(pattern)
-
if replacement == '*' && block_given?
-
result = result.sub(pattern, &block)
-
elsif replacement
-
result = result.sub(pattern, replacement)
-
else
-
result = result.sub(pattern, '')
-
end
-
end
-
result
-
end
-
2
protected :pathmap_replace
-
-
# Map the path according to the given specification. The specification
-
# controls the details of the mapping. The following special patterns are
-
# recognized:
-
#
-
# <tt>%p</tt> :: The complete path.
-
# <tt>%f</tt> :: The base file name of the path, with its file extension,
-
# but without any directories.
-
# <tt>%n</tt> :: The file name of the path without its file extension.
-
# <tt>%d</tt> :: The directory list of the path.
-
# <tt>%x</tt> :: The file extension of the path. An empty string if there
-
# is no extension.
-
# <tt>%X</tt> :: Everything *but* the file extension.
-
# <tt>%s</tt> :: The alternate file separator if defined, otherwise use #
-
# the standard file separator.
-
# <tt>%%</tt> :: A percent sign.
-
#
-
# The <tt>%d</tt> specifier can also have a numeric prefix (e.g. '%2d').
-
# If the number is positive, only return (up to) +n+ directories in the
-
# path, starting from the left hand side. If +n+ is negative, return (up
-
# to) +n+ directories from the right hand side of the path.
-
#
-
# Examples:
-
#
-
# 'a/b/c/d/file.txt'.pathmap("%2d") => 'a/b'
-
# 'a/b/c/d/file.txt'.pathmap("%-2d") => 'c/d'
-
#
-
# Also the <tt>%d</tt>, <tt>%p</tt>, <tt>%f</tt>, <tt>%n</tt>,
-
# <tt>%x</tt>, and <tt>%X</tt> operators can take a pattern/replacement
-
# argument to perform simple string substitutions on a particular part of
-
# the path. The pattern and replacement are separated by a comma and are
-
# enclosed by curly braces. The replacement spec comes after the %
-
# character but before the operator letter. (e.g. "%{old,new}d").
-
# Multiple replacement specs should be separated by semi-colons (e.g.
-
# "%{old,new;src,bin}d").
-
#
-
# Regular expressions may be used for the pattern, and back refs may be
-
# used in the replacement text. Curly braces, commas and semi-colons are
-
# excluded from both the pattern and replacement text (let's keep parsing
-
# reasonable).
-
#
-
# For example:
-
#
-
# "src/org/onestepback/proj/A.java".pathmap("%{^src,class}X.class")
-
#
-
# returns:
-
#
-
# "class/org/onestepback/proj/A.class"
-
#
-
# If the replacement text is '*', then a block may be provided to perform
-
# some arbitrary calculation for the replacement.
-
#
-
# For example:
-
#
-
# "/path/to/file.TXT".pathmap("%X%{.*,*}x") { |ext|
-
# ext.downcase
-
# }
-
#
-
# Returns:
-
#
-
# "/path/to/file.txt"
-
#
-
# This String extension comes from Rake
-
2
def pathmap(spec=nil, &block)
-
return self if spec.nil?
-
result = ''
-
spec.scan(/%\{[^}]*\}-?\d*[sdpfnxX%]|%-?\d+d|%.|[^%]+/) do |frag|
-
case frag
-
when '%f'
-
result << File.basename(self)
-
when '%n'
-
result << File.basename(self).ext
-
when '%d'
-
result << File.dirname(self)
-
when '%x'
-
result << File.extname(self)
-
when '%X'
-
result << self.ext
-
when '%p'
-
result << self
-
when '%s'
-
result << (File::ALT_SEPARATOR || File::SEPARATOR)
-
when '%-'
-
# do nothing
-
when '%%'
-
result << "%"
-
when /%(-?\d+)d/
-
result << pathmap_partial($1.to_i)
-
when /^%\{([^}]*)\}(\d*[dpfnxX])/
-
patterns, operator = $1, $2
-
result << pathmap('%' + operator).pathmap_replace(patterns, &block)
-
when /^%/
-
fail ArgumentError, "Unknown pathmap specifier #{frag} in '#{spec}'"
-
else
-
result << frag
-
end
-
end
-
result
-
end
-
end
-
-
end
-
2
require 'rake/file_task'
-
2
require 'rake/early_time'
-
-
2
module Rake
-
-
# A FileCreationTask is a file task that when used as a dependency will be
-
# needed if and only if the file has not been created. Once created, it is
-
# not re-triggered if any of its dependencies are newer, nor does trigger
-
# any rebuilds of tasks that depend on it whenever it is updated.
-
#
-
2
class FileCreationTask < FileTask
-
# Is this file task needed? Yes if it doesn't exist.
-
2
def needed?
-
! File.exist?(name)
-
end
-
-
# Time stamp for file creation task. This time stamp is earlier
-
# than any other time stamp.
-
2
def timestamp
-
Rake::EARLY
-
end
-
end
-
-
end
-
2
require 'rake/cloneable'
-
2
require 'rake/file_utils_ext'
-
2
require 'rake/ext/string'
-
-
2
module Rake
-
-
##
-
# A FileList is essentially an array with a few helper methods defined to
-
# make file manipulation a bit easier.
-
#
-
# FileLists are lazy. When given a list of glob patterns for possible files
-
# to be included in the file list, instead of searching the file structures
-
# to find the files, a FileList holds the pattern for latter use.
-
#
-
# This allows us to define a number of FileList to match any number of
-
# files, but only search out the actual files when then FileList itself is
-
# actually used. The key is that the first time an element of the
-
# FileList/Array is requested, the pending patterns are resolved into a real
-
# list of file names.
-
#
-
2
class FileList
-
-
2
include Cloneable
-
-
# == Method Delegation
-
#
-
# The lazy evaluation magic of FileLists happens by implementing all the
-
# array specific methods to call +resolve+ before delegating the heavy
-
# lifting to an embedded array object (@items).
-
#
-
# In addition, there are two kinds of delegation calls. The regular kind
-
# delegates to the @items array and returns the result directly. Well,
-
# almost directly. It checks if the returned value is the @items object
-
# itself, and if so will return the FileList object instead.
-
#
-
# The second kind of delegation call is used in methods that normally
-
# return a new Array object. We want to capture the return value of these
-
# methods and wrap them in a new FileList object. We enumerate these
-
# methods in the +SPECIAL_RETURN+ list below.
-
-
# List of array methods (that are not in +Object+) that need to be
-
# delegated.
-
2
ARRAY_METHODS = (Array.instance_methods - Object.instance_methods).
-
280
map { |n| n.to_s }
-
-
# List of additional methods that must be delegated.
-
2
MUST_DEFINE = %w[inspect <=>]
-
-
# List of methods that should not be delegated here (we define special
-
# versions of them explicitly below).
-
2
MUST_NOT_DEFINE = %w[to_a to_ary partition * <<]
-
-
# List of delegated methods that return new array values which need
-
# wrapping.
-
2
SPECIAL_RETURN = %w[
-
map collect sort sort_by select find_all reject grep
-
compact flatten uniq values_at
-
+ - & |
-
]
-
-
2
DELEGATING_METHODS = (ARRAY_METHODS + MUST_DEFINE - MUST_NOT_DEFINE).
-
274
map { |s| s.to_s }.sort.uniq
-
-
# Now do the delegation.
-
2
DELEGATING_METHODS.each do |sym|
-
274
if SPECIAL_RETURN.include?(sym)
-
32
ln = __LINE__ + 1
-
32
class_eval %{
-
def #{sym}(*args, &block)
-
resolve
-
result = @items.send(:#{sym}, *args, &block)
-
self.class.new.import(result)
-
end
-
}, __FILE__, ln
-
else
-
242
ln = __LINE__ + 1
-
242
class_eval %{
-
def #{sym}(*args, &block)
-
resolve
-
result = @items.send(:#{sym}, *args, &block)
-
result.object_id == @items.object_id ? self : result
-
end
-
}, __FILE__, ln
-
end
-
end
-
-
2
GLOB_PATTERN = %r{[*?\[\{]}
-
-
# Create a file list from the globbable patterns given. If you wish to
-
# perform multiple includes or excludes at object build time, use the
-
# "yield self" pattern.
-
#
-
# Example:
-
# file_list = FileList.new('lib/**/*.rb', 'test/test*.rb')
-
#
-
# pkg_files = FileList.new('lib/**/*') do |fl|
-
# fl.exclude(/\bCVS\b/)
-
# end
-
#
-
2
def initialize(*patterns)
-
@pending_add = []
-
@pending = false
-
@exclude_patterns = DEFAULT_IGNORE_PATTERNS.dup
-
@exclude_procs = DEFAULT_IGNORE_PROCS.dup
-
@items = []
-
patterns.each { |pattern| include(pattern) }
-
yield self if block_given?
-
end
-
-
# Add file names defined by glob patterns to the file list. If an array
-
# is given, add each element of the array.
-
#
-
# Example:
-
# file_list.include("*.java", "*.cfg")
-
# file_list.include %w( math.c lib.h *.o )
-
#
-
2
def include(*filenames)
-
# TODO: check for pending
-
filenames.each do |fn|
-
if fn.respond_to? :to_ary
-
include(*fn.to_ary)
-
else
-
@pending_add << Rake.from_pathname(fn)
-
end
-
end
-
@pending = true
-
self
-
end
-
2
alias :add :include
-
-
# Register a list of file name patterns that should be excluded from the
-
# list. Patterns may be regular expressions, glob patterns or regular
-
# strings. In addition, a block given to exclude will remove entries that
-
# return true when given to the block.
-
#
-
# Note that glob patterns are expanded against the file system. If a file
-
# is explicitly added to a file list, but does not exist in the file
-
# system, then an glob pattern in the exclude list will not exclude the
-
# file.
-
#
-
# Examples:
-
# FileList['a.c', 'b.c'].exclude("a.c") => ['b.c']
-
# FileList['a.c', 'b.c'].exclude(/^a/) => ['b.c']
-
#
-
# If "a.c" is a file, then ...
-
# FileList['a.c', 'b.c'].exclude("a.*") => ['b.c']
-
#
-
# If "a.c" is not a file, then ...
-
# FileList['a.c', 'b.c'].exclude("a.*") => ['a.c', 'b.c']
-
#
-
2
def exclude(*patterns, &block)
-
patterns.each do |pat|
-
if pat.respond_to? :to_ary
-
exclude(*pat.to_ary)
-
else
-
@exclude_patterns << Rake.from_pathname(pat)
-
end
-
end
-
@exclude_procs << block if block_given?
-
resolve_exclude unless @pending
-
self
-
end
-
-
# Clear all the exclude patterns so that we exclude nothing.
-
2
def clear_exclude
-
@exclude_patterns = []
-
@exclude_procs = []
-
self
-
end
-
-
# A FileList is equal through array equality.
-
2
def ==(array)
-
to_ary == array
-
end
-
-
# Return the internal array object.
-
2
def to_a
-
resolve
-
@items
-
end
-
-
# Return the internal array object.
-
2
def to_ary
-
to_a
-
end
-
-
# Lie about our class.
-
2
def is_a?(klass)
-
klass == Array || super(klass)
-
end
-
2
alias kind_of? is_a?
-
-
# Redefine * to return either a string or a new file list.
-
2
def *(other)
-
result = @items * other
-
case result
-
when Array
-
self.class.new.import(result)
-
else
-
result
-
end
-
end
-
-
2
def <<(obj)
-
resolve
-
@items << Rake.from_pathname(obj)
-
self
-
end
-
-
# Resolve all the pending adds now.
-
2
def resolve
-
if @pending
-
@pending = false
-
@pending_add.each do |fn| resolve_add(fn) end
-
@pending_add = []
-
resolve_exclude
-
end
-
self
-
end
-
-
2
def resolve_add(fn) # :nodoc:
-
case fn
-
when GLOB_PATTERN
-
add_matching(fn)
-
else
-
self << fn
-
end
-
end
-
2
private :resolve_add
-
-
2
def resolve_exclude # :nodoc:
-
reject! { |fn| excluded_from_list?(fn) }
-
self
-
end
-
2
private :resolve_exclude
-
-
# Return a new FileList with the results of running +sub+ against each
-
# element of the original list.
-
#
-
# Example:
-
# FileList['a.c', 'b.c'].sub(/\.c$/, '.o') => ['a.o', 'b.o']
-
#
-
2
def sub(pat, rep)
-
inject(self.class.new) { |res, fn| res << fn.sub(pat, rep) }
-
end
-
-
# Return a new FileList with the results of running +gsub+ against each
-
# element of the original list.
-
#
-
# Example:
-
# FileList['lib/test/file', 'x/y'].gsub(/\//, "\\")
-
# => ['lib\\test\\file', 'x\\y']
-
#
-
2
def gsub(pat, rep)
-
inject(self.class.new) { |res, fn| res << fn.gsub(pat, rep) }
-
end
-
-
# Same as +sub+ except that the original file list is modified.
-
2
def sub!(pat, rep)
-
each_with_index { |fn, i| self[i] = fn.sub(pat, rep) }
-
self
-
end
-
-
# Same as +gsub+ except that the original file list is modified.
-
2
def gsub!(pat, rep)
-
each_with_index { |fn, i| self[i] = fn.gsub(pat, rep) }
-
self
-
end
-
-
# Apply the pathmap spec to each of the included file names, returning a
-
# new file list with the modified paths. (See String#pathmap for
-
# details.)
-
2
def pathmap(spec=nil, &block)
-
collect { |fn| fn.pathmap(spec, &block) }
-
end
-
-
# Return a new FileList with <tt>String#ext</tt> method applied to
-
# each member of the array.
-
#
-
# This method is a shortcut for:
-
#
-
# array.collect { |item| item.ext(newext) }
-
#
-
# +ext+ is a user added method for the Array class.
-
2
def ext(newext='')
-
collect { |fn| fn.ext(newext) }
-
end
-
-
# Grep each of the files in the filelist using the given pattern. If a
-
# block is given, call the block on each matching line, passing the file
-
# name, line number, and the matching line of text. If no block is given,
-
# a standard emacs style file:linenumber:line message will be printed to
-
# standard out. Returns the number of matched items.
-
2
def egrep(pattern, *options)
-
matched = 0
-
each do |fn|
-
begin
-
open(fn, "r", *options) do |inf|
-
count = 0
-
inf.each do |line|
-
count += 1
-
if pattern.match(line)
-
matched += 1
-
if block_given?
-
yield fn, count, line
-
else
-
puts "#{fn}:#{count}:#{line}"
-
end
-
end
-
end
-
end
-
rescue StandardError => ex
-
$stderr.puts "Error while processing '#{fn}': #{ex}"
-
end
-
end
-
matched
-
end
-
-
# Return a new file list that only contains file names from the current
-
# file list that exist on the file system.
-
2
def existing
-
select { |fn| File.exist?(fn) }
-
end
-
-
# Modify the current file list so that it contains only file name that
-
# exist on the file system.
-
2
def existing!
-
resolve
-
@items = @items.select { |fn| File.exist?(fn) }
-
self
-
end
-
-
# FileList version of partition. Needed because the nested arrays should
-
# be FileLists in this version.
-
2
def partition(&block) # :nodoc:
-
resolve
-
result = @items.partition(&block)
-
[
-
self.class.new.import(result[0]),
-
self.class.new.import(result[1]),
-
]
-
end
-
-
# Convert a FileList to a string by joining all elements with a space.
-
2
def to_s
-
resolve
-
self.join(' ')
-
end
-
-
# Add matching glob patterns.
-
2
def add_matching(pattern)
-
self.class.glob(pattern).each do |fn|
-
self << fn unless excluded_from_list?(fn)
-
end
-
end
-
2
private :add_matching
-
-
# Should the given file name be excluded from the list?
-
#
-
# NOTE: This method was formerly named "exclude?", but Rails
-
# introduced an exclude? method as an array method and setup a
-
# conflict with file list. We renamed the method to avoid
-
# confusion. If you were using "FileList#exclude?" in your user
-
# code, you will need to update.
-
2
def excluded_from_list?(fn)
-
return true if @exclude_patterns.any? do |pat|
-
case pat
-
when Regexp
-
fn =~ pat
-
when GLOB_PATTERN
-
flags = File::FNM_PATHNAME
-
# Ruby <= 1.9.3 does not support File::FNM_EXTGLOB
-
flags |= File::FNM_EXTGLOB if defined? File::FNM_EXTGLOB
-
File.fnmatch?(pat, fn, flags)
-
else
-
fn == pat
-
end
-
end
-
@exclude_procs.any? { |p| p.call(fn) }
-
end
-
-
2
DEFAULT_IGNORE_PATTERNS = [
-
/(^|[\/\\])CVS([\/\\]|$)/,
-
/(^|[\/\\])\.svn([\/\\]|$)/,
-
/\.bak$/,
-
/~$/
-
]
-
2
DEFAULT_IGNORE_PROCS = [
-
proc { |fn| fn =~ /(^|[\/\\])core$/ && ! File.directory?(fn) }
-
]
-
-
2
def import(array) # :nodoc:
-
@items = array
-
self
-
end
-
-
2
class << self
-
# Create a new file list including the files listed. Similar to:
-
#
-
# FileList.new(*args)
-
2
def [](*args)
-
new(*args)
-
end
-
-
# Get a sorted list of files matching the pattern. This method
-
# should be preferred to Dir[pattern] and Dir.glob(pattern) because
-
# the files returned are guaranteed to be sorted.
-
2
def glob(pattern, *args)
-
Dir.glob(pattern, *args).sort
-
end
-
end
-
end
-
end
-
-
2
module Rake
-
2
class << self
-
-
# Yield each file or directory component.
-
2
def each_dir_parent(dir) # :nodoc:
-
old_length = nil
-
while dir != '.' && dir.length != old_length
-
yield(dir)
-
old_length = dir.length
-
dir = File.dirname(dir)
-
end
-
end
-
-
# Convert Pathname and Pathname-like objects to strings;
-
# leave everything else alone
-
2
def from_pathname(path) # :nodoc:
-
path = path.to_path if path.respond_to?(:to_path)
-
path = path.to_str if path.respond_to?(:to_str)
-
path
-
end
-
end
-
end # module Rake
-
2
require 'rake/task.rb'
-
2
require 'rake/early_time'
-
-
2
module Rake
-
-
# A FileTask is a task that includes time based dependencies. If any of a
-
# FileTask's prerequisites have a timestamp that is later than the file
-
# represented by this task, then the file must be rebuilt (using the
-
# supplied actions).
-
#
-
2
class FileTask < Task
-
-
# Is this file task needed? Yes if it doesn't exist, or if its time stamp
-
# is out of date.
-
2
def needed?
-
! File.exist?(name) || out_of_date?(timestamp) || @application.options.build_all
-
end
-
-
# Time stamp for file task.
-
2
def timestamp
-
if File.exist?(name)
-
File.mtime(name.to_s)
-
else
-
Rake::LATE
-
end
-
end
-
-
2
private
-
-
# Are there any prerequisites with a later time than the given time stamp?
-
2
def out_of_date?(stamp)
-
@prerequisites.any? { |n| application[n, @scope].timestamp > stamp }
-
end
-
-
# ----------------------------------------------------------------
-
# Task class methods.
-
#
-
2
class << self
-
# Apply the scope to the task name according to the rules for this kind
-
# of task. File based tasks ignore the scope when creating the name.
-
2
def scope_name(scope, task_name)
-
Rake.from_pathname(task_name)
-
end
-
end
-
end
-
end
-
2
require 'rbconfig'
-
2
require 'fileutils'
-
-
#--
-
# This a FileUtils extension that defines several additional commands to be
-
# added to the FileUtils utility functions.
-
2
module FileUtils
-
# Path to the currently running Ruby program
-
2
RUBY = ENV['RUBY'] || File.join(
-
RbConfig::CONFIG['bindir'],
-
RbConfig::CONFIG['ruby_install_name'] + RbConfig::CONFIG['EXEEXT']).
-
sub(/.*\s.*/m, '"\&"')
-
-
2
OPT_TABLE['sh'] = %w(noop verbose)
-
2
OPT_TABLE['ruby'] = %w(noop verbose)
-
-
# Run the system command +cmd+. If multiple arguments are given the command
-
# is run directly (without the shell, same semantics as Kernel::exec and
-
# Kernel::system).
-
#
-
# It is recommended you use the multiple argument form over interpolating
-
# user input for both usability and security reasons. With the multiple
-
# argument form you can easily process files with spaces or other shell
-
# reserved characters in them. With the multiple argument form your rake
-
# tasks are not vulnerable to users providing an argument like
-
# <code>; rm # -rf /</code>.
-
#
-
# If a block is given, upon command completion the block is called with an
-
# OK flag (true on a zero exit status) and a Process::Status object.
-
# Without a block a RuntimeError is raised when the command exits non-zero.
-
#
-
# Examples:
-
#
-
# sh 'ls -ltr'
-
#
-
# sh 'ls', 'file with spaces'
-
#
-
# # check exit status after command runs
-
# sh %{grep pattern file} do |ok, res|
-
# if ! ok
-
# puts "pattern not found (status = #{res.exitstatus})"
-
# end
-
# end
-
#
-
2
def sh(*cmd, &block)
-
options = (Hash === cmd.last) ? cmd.pop : {}
-
shell_runner = block_given? ? block : create_shell_runner(cmd)
-
set_verbose_option(options)
-
options[:noop] ||= Rake::FileUtilsExt.nowrite_flag
-
Rake.rake_check_options options, :noop, :verbose
-
Rake.rake_output_message cmd.join(" ") if options[:verbose]
-
-
unless options[:noop]
-
res = system(*cmd)
-
status = $?
-
status = Rake::PseudoStatus.new(1) if !res && status.nil?
-
shell_runner.call(res, status)
-
end
-
end
-
-
2
def create_shell_runner(cmd) # :nodoc:
-
show_command = cmd.join(" ")
-
show_command = show_command[0, 42] + "..." unless $trace
-
lambda do |ok, status|
-
ok or
-
fail "Command failed with status (#{status.exitstatus}): " +
-
"[#{show_command}]"
-
end
-
end
-
2
private :create_shell_runner
-
-
2
def set_verbose_option(options) # :nodoc:
-
unless options.key? :verbose
-
options[:verbose] =
-
(Rake::FileUtilsExt.verbose_flag == Rake::FileUtilsExt::DEFAULT) ||
-
Rake::FileUtilsExt.verbose_flag
-
end
-
end
-
2
private :set_verbose_option
-
-
# Run a Ruby interpreter with the given arguments.
-
#
-
# Example:
-
# ruby %{-pe '$_.upcase!' <README}
-
#
-
2
def ruby(*args, &block)
-
options = (Hash === args.last) ? args.pop : {}
-
if args.length > 1
-
sh(*([RUBY] + args + [options]), &block)
-
else
-
sh("#{RUBY} #{args.first}", options, &block)
-
end
-
end
-
-
2
LN_SUPPORTED = [true]
-
-
# Attempt to do a normal file link, but fall back to a copy if the link
-
# fails.
-
2
def safe_ln(*args)
-
if ! LN_SUPPORTED[0]
-
cp(*args)
-
else
-
begin
-
ln(*args)
-
rescue StandardError, NotImplementedError
-
LN_SUPPORTED[0] = false
-
cp(*args)
-
end
-
end
-
end
-
-
# Split a file path into individual directory names.
-
#
-
# Example:
-
# split_all("a/b/c") => ['a', 'b', 'c']
-
#
-
2
def split_all(path)
-
head, tail = File.split(path)
-
return [tail] if head == '.' || tail == '/'
-
return [head, tail] if head == '/'
-
return split_all(head) + [tail]
-
end
-
end
-
2
require 'rake/file_utils'
-
-
2
module Rake
-
#
-
# FileUtilsExt provides a custom version of the FileUtils methods
-
# that respond to the <tt>verbose</tt> and <tt>nowrite</tt>
-
# commands.
-
#
-
2
module FileUtilsExt
-
2
include FileUtils
-
-
2
class << self
-
2
attr_accessor :verbose_flag, :nowrite_flag
-
end
-
-
2
DEFAULT = Object.new
-
-
2
FileUtilsExt.verbose_flag = DEFAULT
-
2
FileUtilsExt.nowrite_flag = false
-
-
2
FileUtils.commands.each do |name|
-
64
opts = FileUtils.options_of name
-
64
default_options = []
-
64
if opts.include?("verbose")
-
64
default_options << ':verbose => FileUtilsExt.verbose_flag'
-
end
-
64
if opts.include?("noop")
-
60
default_options << ':noop => FileUtilsExt.nowrite_flag'
-
end
-
-
64
next if default_options.empty?
-
64
module_eval(<<-EOS, __FILE__, __LINE__ + 1)
-
def #{name}( *args, &block )
-
super(
-
*rake_merge_option(args,
-
#{default_options.join(', ')}
-
), &block)
-
end
-
EOS
-
end
-
-
# Get/set the verbose flag controlling output from the FileUtils
-
# utilities. If verbose is true, then the utility method is
-
# echoed to standard output.
-
#
-
# Examples:
-
# verbose # return the current value of the
-
# # verbose flag
-
# verbose(v) # set the verbose flag to _v_.
-
# verbose(v) { code } # Execute code with the verbose flag set
-
# # temporarily to _v_. Return to the
-
# # original value when code is done.
-
2
def verbose(value=nil)
-
oldvalue = FileUtilsExt.verbose_flag
-
FileUtilsExt.verbose_flag = value unless value.nil?
-
if block_given?
-
begin
-
yield
-
ensure
-
FileUtilsExt.verbose_flag = oldvalue
-
end
-
end
-
FileUtilsExt.verbose_flag
-
end
-
-
# Get/set the nowrite flag controlling output from the FileUtils
-
# utilities. If verbose is true, then the utility method is
-
# echoed to standard output.
-
#
-
# Examples:
-
# nowrite # return the current value of the
-
# # nowrite flag
-
# nowrite(v) # set the nowrite flag to _v_.
-
# nowrite(v) { code } # Execute code with the nowrite flag set
-
# # temporarily to _v_. Return to the
-
# # original value when code is done.
-
2
def nowrite(value=nil)
-
oldvalue = FileUtilsExt.nowrite_flag
-
FileUtilsExt.nowrite_flag = value unless value.nil?
-
if block_given?
-
begin
-
yield
-
ensure
-
FileUtilsExt.nowrite_flag = oldvalue
-
end
-
end
-
oldvalue
-
end
-
-
# Use this function to prevent potentially destructive ruby code
-
# from running when the :nowrite flag is set.
-
#
-
# Example:
-
#
-
# when_writing("Building Project") do
-
# project.build
-
# end
-
#
-
# The following code will build the project under normal
-
# conditions. If the nowrite(true) flag is set, then the example
-
# will print:
-
#
-
# DRYRUN: Building Project
-
#
-
# instead of actually building the project.
-
#
-
2
def when_writing(msg=nil)
-
if FileUtilsExt.nowrite_flag
-
$stderr.puts "DRYRUN: #{msg}" if msg
-
else
-
yield
-
end
-
end
-
-
# Merge the given options with the default values.
-
2
def rake_merge_option(args, defaults)
-
if Hash === args.last
-
defaults.update(args.last)
-
args.pop
-
end
-
args.push defaults
-
args
-
end
-
-
# Send the message to the default rake output (which is $stderr).
-
2
def rake_output_message(message)
-
$stderr.puts(message)
-
end
-
-
# Check that the options do not contain options not listed in
-
# +optdecl+. An ArgumentError exception is thrown if non-declared
-
# options are found.
-
2
def rake_check_options(options, *optdecl)
-
h = options.dup
-
optdecl.each do |name|
-
h.delete name
-
end
-
raise ArgumentError, "no such option: #{h.keys.join(' ')}" unless
-
h.empty?
-
end
-
-
2
extend self
-
end
-
end
-
2
module Rake
-
-
# InvocationChain tracks the chain of task invocations to detect
-
# circular dependencies.
-
2
class InvocationChain < LinkedList
-
-
# Is the invocation already in the chain?
-
2
def member?(invocation)
-
head == invocation || tail.member?(invocation)
-
end
-
-
# Append an invocation to the chain of invocations. It is an error
-
# if the invocation already listed.
-
2
def append(invocation)
-
if member?(invocation)
-
fail RuntimeError, "Circular dependency detected: #{to_s} => #{invocation}"
-
end
-
conj(invocation)
-
end
-
-
# Convert to string, ie: TOP => invocation => invocation
-
2
def to_s
-
"#{prefix}#{head}"
-
end
-
-
# Class level append.
-
2
def self.append(invocation, chain)
-
chain.append(invocation)
-
end
-
-
2
private
-
-
2
def prefix
-
"#{tail} => "
-
end
-
-
# Null object for an empty chain.
-
2
class EmptyInvocationChain < LinkedList::EmptyLinkedList
-
2
@parent = InvocationChain
-
-
2
def member?(obj)
-
false
-
end
-
-
2
def append(invocation)
-
conj(invocation)
-
end
-
-
2
def to_s
-
"TOP"
-
end
-
end
-
-
2
EMPTY = EmptyInvocationChain.new
-
end
-
end
-
2
module Rake
-
2
module InvocationExceptionMixin
-
# Return the invocation chain (list of Rake tasks) that were in
-
# effect when this exception was detected by rake. May be null if
-
# no tasks were active.
-
2
def chain
-
@rake_invocation_chain ||= nil
-
end
-
-
# Set the invocation chain in effect when this exception was
-
# detected.
-
2
def chain=(value)
-
@rake_invocation_chain = value
-
end
-
end
-
end
-
2
module Rake
-
# LateTime is a fake timestamp that occurs _after_ any other time value.
-
2
class LateTime
-
2
include Comparable
-
2
include Singleton
-
-
2
def <=>(other)
-
1
-
end
-
-
2
def to_s
-
'<LATE TIME>'
-
end
-
end
-
-
2
LATE = LateTime.instance
-
end
-
2
module Rake
-
-
# Polylithic linked list structure used to implement several data
-
# structures in Rake.
-
2
class LinkedList
-
2
include Enumerable
-
2
attr_reader :head, :tail
-
-
# Polymorphically add a new element to the head of a list. The
-
# type of head node will be the same list type as the tail.
-
2
def conj(item)
-
self.class.cons(item, self)
-
end
-
-
# Is the list empty?
-
# .make guards against a list being empty making any instantiated LinkedList
-
# object not empty by default
-
# You should consider overriding this method if you implement your own .make method
-
2
def empty?
-
false
-
end
-
-
# Lists are structurally equivalent.
-
2
def ==(other)
-
current = self
-
while !current.empty? && !other.empty?
-
return false if current.head != other.head
-
current = current.tail
-
other = other.tail
-
end
-
current.empty? && other.empty?
-
end
-
-
# Convert to string: LL(item, item...)
-
2
def to_s
-
items = map(&:to_s).join(", ")
-
"LL(#{items})"
-
end
-
-
# Same as +to_s+, but with inspected items.
-
2
def inspect
-
items = map(&:inspect).join(", ")
-
"LL(#{items})"
-
end
-
-
# For each item in the list.
-
2
def each
-
current = self
-
while !current.empty?
-
yield(current.head)
-
current = current.tail
-
end
-
self
-
end
-
-
# Make a list out of the given arguments. This method is
-
# polymorphic
-
2
def self.make(*args)
-
# return an EmptyLinkedList if there are no arguments
-
return empty if !args || args.empty?
-
-
# build a LinkedList by starting at the tail and iterating
-
# through each argument
-
# inject takes an EmptyLinkedList to start
-
args.reverse.inject(empty) do |list, item|
-
list = cons(item, list)
-
list # return the newly created list for each item in the block
-
end
-
end
-
-
# Cons a new head onto the tail list.
-
2
def self.cons(head, tail)
-
new(head, tail)
-
end
-
-
# The standard empty list class for the given LinkedList class.
-
2
def self.empty
-
self::EMPTY
-
end
-
-
2
protected
-
-
2
def initialize(head, tail=EMPTY)
-
@head = head
-
@tail = tail
-
end
-
-
# Represent an empty list, using the Null Object Pattern.
-
#
-
# When inheriting from the LinkedList class, you should implement
-
# a type specific Empty class as well. Make sure you set the class
-
# instance variable @parent to the associated list class (this
-
# allows conj, cons and make to work polymorphically).
-
2
class EmptyLinkedList < LinkedList
-
2
@parent = LinkedList
-
-
2
def initialize
-
end
-
-
2
def empty?
-
true
-
end
-
-
2
def self.cons(head, tail)
-
@parent.cons(head, tail)
-
end
-
end
-
-
2
EMPTY = EmptyLinkedList.new
-
end
-
end
-
2
module Rake
-
-
# Same as a regular task, but the immediate prerequisites are done in
-
# parallel using Ruby threads.
-
#
-
2
class MultiTask < Task
-
2
private
-
2
def invoke_prerequisites(task_args, invocation_chain) # :nodoc:
-
invoke_prerequisites_concurrently(task_args, invocation_chain)
-
end
-
end
-
-
end
-
##
-
# The NameSpace class will lookup task names in the scope defined by a
-
# +namespace+ command.
-
-
2
class Rake::NameSpace
-
-
##
-
# Create a namespace lookup object using the given task manager
-
# and the list of scopes.
-
-
2
def initialize(task_manager, scope_list)
-
@task_manager = task_manager
-
@scope = scope_list.dup
-
end
-
-
##
-
# Lookup a task named +name+ in the namespace.
-
-
2
def [](name)
-
@task_manager.lookup(name, @scope)
-
end
-
-
##
-
# The scope of the namespace (a LinkedList)
-
-
2
def scope
-
@scope.dup
-
end
-
-
##
-
# Return the list of tasks defined in this and nested namespaces.
-
-
2
def tasks
-
@task_manager.tasks_in_scope(@scope)
-
end
-
-
end
-
-
2
module Rake
-
-
# Include PrivateReader to use +private_reader+.
-
2
module PrivateReader # :nodoc: all
-
-
2
def self.included(base)
-
2
base.extend(ClassMethods)
-
end
-
-
2
module ClassMethods
-
-
# Declare a list of private accessors
-
2
def private_reader(*names)
-
2
attr_reader(*names)
-
2
private(*names)
-
end
-
end
-
-
end
-
end
-
2
module Rake
-
-
# A Promise object represents a promise to do work (a chore) in the
-
# future. The promise is created with a block and a list of
-
# arguments for the block. Calling value will return the value of
-
# the promised chore.
-
#
-
# Used by ThreadPool.
-
#
-
2
class Promise # :nodoc: all
-
2
NOT_SET = Object.new.freeze # :nodoc:
-
-
2
attr_accessor :recorder
-
-
# Create a promise to do the chore specified by the block.
-
2
def initialize(args, &block)
-
@mutex = Mutex.new
-
@result = NOT_SET
-
@error = NOT_SET
-
@args = args
-
@block = block
-
end
-
-
# Return the value of this promise.
-
#
-
# If the promised chore is not yet complete, then do the work
-
# synchronously. We will wait.
-
2
def value
-
unless complete?
-
stat :sleeping_on, :item_id => object_id
-
@mutex.synchronize do
-
stat :has_lock_on, :item_id => object_id
-
chore
-
stat :releasing_lock_on, :item_id => object_id
-
end
-
end
-
error? ? raise(@error) : @result
-
end
-
-
# If no one else is working this promise, go ahead and do the chore.
-
2
def work
-
stat :attempting_lock_on, :item_id => object_id
-
if @mutex.try_lock
-
stat :has_lock_on, :item_id => object_id
-
chore
-
stat :releasing_lock_on, :item_id => object_id
-
@mutex.unlock
-
else
-
stat :bailed_on, :item_id => object_id
-
end
-
end
-
-
2
private
-
-
# Perform the chore promised
-
2
def chore
-
if complete?
-
stat :found_completed, :item_id => object_id
-
return
-
end
-
stat :will_execute, :item_id => object_id
-
begin
-
@result = @block.call(*@args)
-
rescue Exception => e
-
@error = e
-
end
-
stat :did_execute, :item_id => object_id
-
discard
-
end
-
-
# Do we have a result for the promise
-
2
def result?
-
! @result.equal?(NOT_SET)
-
end
-
-
# Did the promise throw an error
-
2
def error?
-
! @error.equal?(NOT_SET)
-
end
-
-
# Are we done with the promise
-
2
def complete?
-
result? || error?
-
end
-
-
# free up these items for the GC
-
2
def discard
-
@args = nil
-
@block = nil
-
end
-
-
# Record execution statistics if there is a recorder
-
2
def stat(*args)
-
@recorder.call(*args) if @recorder
-
end
-
-
end
-
-
end
-
2
module Rake
-
-
##
-
# Exit status class for times the system just gives us a nil.
-
2
class PseudoStatus # :nodoc: all
-
2
attr_reader :exitstatus
-
-
2
def initialize(code=0)
-
@exitstatus = code
-
end
-
-
2
def to_i
-
@exitstatus << 8
-
end
-
-
2
def >>(n)
-
to_i >> n
-
end
-
-
2
def stopped?
-
false
-
end
-
-
2
def exited?
-
true
-
end
-
end
-
-
end
-
2
require 'rake/application'
-
-
2
module Rake
-
-
2
class << self
-
# Current Rake Application
-
2
def application
-
@application ||= Rake::Application.new
-
end
-
-
# Set the current Rake application object.
-
2
def application=(app)
-
@application = app
-
end
-
-
2
def suggested_thread_count # :nodoc:
-
@cpu_count ||= Rake::CpuCounter.count
-
@cpu_count + 4
-
end
-
-
# Return the original directory where the Rake application was started.
-
2
def original_dir
-
application.original_dir
-
end
-
-
# Load a rakefile.
-
2
def load_rakefile(path)
-
load(path)
-
end
-
-
# Add files to the rakelib list
-
2
def add_rakelib(*files)
-
application.options.rakelib ||= []
-
application.options.rakelib.concat(files)
-
end
-
end
-
-
end
-
-
2
module Rake
-
-
# Error indicating a recursion overflow error in task selection.
-
2
class RuleRecursionOverflowError < StandardError
-
2
def initialize(*args)
-
super
-
@targets = []
-
end
-
-
2
def add_target(target)
-
@targets << target
-
end
-
-
2
def message
-
super + ": [" + @targets.reverse.join(' => ') + "]"
-
end
-
end
-
-
end
-
2
module Rake
-
2
class Scope < LinkedList # :nodoc: all
-
-
# Path for the scope.
-
2
def path
-
map { |item| item.to_s }.reverse.join(":")
-
end
-
-
# Path for the scope + the named path.
-
2
def path_with_task_name(task_name)
-
"#{path}:#{task_name}"
-
end
-
-
# Trim +n+ innermost scope levels from the scope. In no case will
-
# this trim beyond the toplevel scope.
-
2
def trim(n)
-
result = self
-
while n > 0 && ! result.empty?
-
result = result.tail
-
n -= 1
-
end
-
result
-
end
-
-
# Scope lists always end with an EmptyScope object. See Null
-
# Object Pattern)
-
2
class EmptyScope < EmptyLinkedList
-
2
@parent = Scope
-
-
2
def path
-
""
-
end
-
-
2
def path_with_task_name(task_name)
-
task_name
-
end
-
end
-
-
# Singleton null object for an empty scope.
-
2
EMPTY = EmptyScope.new
-
end
-
end
-
2
require 'rake/invocation_exception_mixin'
-
-
2
module Rake
-
-
##
-
# A Task is the basic unit of work in a Rakefile. Tasks have associated
-
# actions (possibly more than one) and a list of prerequisites. When
-
# invoked, a task will first ensure that all of its prerequisites have an
-
# opportunity to run and then it will execute its own actions.
-
#
-
# Tasks are not usually created directly using the new method, but rather
-
# use the +file+ and +task+ convenience methods.
-
#
-
2
class Task
-
# List of prerequisites for a task.
-
2
attr_reader :prerequisites
-
-
# List of actions attached to a task.
-
2
attr_reader :actions
-
-
# Application owning this task.
-
2
attr_accessor :application
-
-
# Array of nested namespaces names used for task lookup by this task.
-
2
attr_reader :scope
-
-
# File/Line locations of each of the task definitions for this
-
# task (only valid if the task was defined with the detect
-
# location option set).
-
2
attr_reader :locations
-
-
# Has this task already been invoked? Already invoked tasks
-
# will be skipped unless you reenable them.
-
2
attr_reader :already_invoked
-
-
# Return task name
-
2
def to_s
-
name
-
end
-
-
2
def inspect # :nodoc:
-
"<#{self.class} #{name} => [#{prerequisites.join(', ')}]>"
-
end
-
-
# List of sources for task.
-
2
attr_writer :sources
-
2
def sources
-
if defined?(@sources)
-
@sources
-
else
-
prerequisites
-
end
-
end
-
-
# List of prerequisite tasks
-
2
def prerequisite_tasks
-
prerequisites.map { |pre| lookup_prerequisite(pre) }
-
end
-
-
2
def lookup_prerequisite(prerequisite_name) # :nodoc:
-
scoped_prerequisite_task = application[prerequisite_name, @scope]
-
if scoped_prerequisite_task == self
-
unscoped_prerequisite_task = application[prerequisite_name]
-
end
-
unscoped_prerequisite_task || scoped_prerequisite_task
-
end
-
2
private :lookup_prerequisite
-
-
# List of all unique prerequisite tasks including prerequisite tasks'
-
# prerequisites.
-
# Includes self when cyclic dependencies are found.
-
2
def all_prerequisite_tasks
-
seen = {}
-
collect_prerequisites(seen)
-
seen.values
-
end
-
-
2
def collect_prerequisites(seen) # :nodoc:
-
prerequisite_tasks.each do |pre|
-
next if seen[pre.name]
-
seen[pre.name] = pre
-
pre.collect_prerequisites(seen)
-
end
-
end
-
2
protected :collect_prerequisites
-
-
# First source from a rule (nil if no sources)
-
2
def source
-
sources.first
-
end
-
-
# Create a task named +task_name+ with no actions or prerequisites. Use
-
# +enhance+ to add actions and prerequisites.
-
2
def initialize(task_name, app)
-
@name = task_name.to_s
-
@prerequisites = []
-
@actions = []
-
@already_invoked = false
-
@comments = []
-
@lock = Monitor.new
-
@application = app
-
@scope = app.current_scope
-
@arg_names = nil
-
@locations = []
-
end
-
-
# Enhance a task with prerequisites or actions. Returns self.
-
2
def enhance(deps=nil, &block)
-
@prerequisites |= deps if deps
-
@actions << block if block_given?
-
self
-
end
-
-
# Name of the task, including any namespace qualifiers.
-
2
def name
-
@name.to_s
-
end
-
-
# Name of task with argument list description.
-
2
def name_with_args # :nodoc:
-
if arg_description
-
"#{name}#{arg_description}"
-
else
-
name
-
end
-
end
-
-
# Argument description (nil if none).
-
2
def arg_description # :nodoc:
-
@arg_names ? "[#{arg_names.join(',')}]" : nil
-
end
-
-
# Name of arguments for this task.
-
2
def arg_names
-
@arg_names || []
-
end
-
-
# Reenable the task, allowing its tasks to be executed if the task
-
# is invoked again.
-
2
def reenable
-
@already_invoked = false
-
end
-
-
# Clear the existing prerequisites and actions of a rake task.
-
2
def clear
-
clear_prerequisites
-
clear_actions
-
clear_comments
-
self
-
end
-
-
# Clear the existing prerequisites of a rake task.
-
2
def clear_prerequisites
-
prerequisites.clear
-
self
-
end
-
-
# Clear the existing actions on a rake task.
-
2
def clear_actions
-
actions.clear
-
self
-
end
-
-
# Clear the existing comments on a rake task.
-
2
def clear_comments
-
@comments = []
-
self
-
end
-
-
# Invoke the task if it is needed. Prerequisites are invoked first.
-
2
def invoke(*args)
-
task_args = TaskArguments.new(arg_names, args)
-
invoke_with_call_chain(task_args, InvocationChain::EMPTY)
-
end
-
-
# Same as invoke, but explicitly pass a call chain to detect
-
# circular dependencies.
-
2
def invoke_with_call_chain(task_args, invocation_chain) # :nodoc:
-
new_chain = InvocationChain.append(self, invocation_chain)
-
@lock.synchronize do
-
if application.options.trace
-
application.trace "** Invoke #{name} #{format_trace_flags}"
-
end
-
return if @already_invoked
-
@already_invoked = true
-
invoke_prerequisites(task_args, new_chain)
-
execute(task_args) if needed?
-
end
-
rescue Exception => ex
-
add_chain_to(ex, new_chain)
-
raise ex
-
end
-
2
protected :invoke_with_call_chain
-
-
2
def add_chain_to(exception, new_chain) # :nodoc:
-
exception.extend(InvocationExceptionMixin) unless
-
exception.respond_to?(:chain)
-
exception.chain = new_chain if exception.chain.nil?
-
end
-
2
private :add_chain_to
-
-
# Invoke all the prerequisites of a task.
-
2
def invoke_prerequisites(task_args, invocation_chain) # :nodoc:
-
if application.options.always_multitask
-
invoke_prerequisites_concurrently(task_args, invocation_chain)
-
else
-
prerequisite_tasks.each { |p|
-
prereq_args = task_args.new_scope(p.arg_names)
-
p.invoke_with_call_chain(prereq_args, invocation_chain)
-
}
-
end
-
end
-
-
# Invoke all the prerequisites of a task in parallel.
-
2
def invoke_prerequisites_concurrently(task_args, invocation_chain)# :nodoc:
-
futures = prerequisite_tasks.map do |p|
-
prereq_args = task_args.new_scope(p.arg_names)
-
application.thread_pool.future(p) do |r|
-
r.invoke_with_call_chain(prereq_args, invocation_chain)
-
end
-
end
-
futures.each { |f| f.value }
-
end
-
-
# Format the trace flags for display.
-
2
def format_trace_flags
-
flags = []
-
flags << "first_time" unless @already_invoked
-
flags << "not_needed" unless needed?
-
flags.empty? ? "" : "(" + flags.join(", ") + ")"
-
end
-
2
private :format_trace_flags
-
-
# Execute the actions associated with this task.
-
2
def execute(args=nil)
-
args ||= EMPTY_TASK_ARGS
-
if application.options.dryrun
-
application.trace "** Execute (dry run) #{name}"
-
return
-
end
-
application.trace "** Execute #{name}" if application.options.trace
-
application.enhance_with_matching_rule(name) if @actions.empty?
-
@actions.each do |act|
-
case act.arity
-
when 1
-
act.call(self)
-
else
-
act.call(self, args)
-
end
-
end
-
end
-
-
# Is this task needed?
-
2
def needed?
-
true
-
end
-
-
# Timestamp for this task. Basic tasks return the current time for their
-
# time stamp. Other tasks can be more sophisticated.
-
2
def timestamp
-
Time.now
-
end
-
-
# Add a description to the task. The description can consist of an option
-
# argument list (enclosed brackets) and an optional comment.
-
2
def add_description(description)
-
return unless description
-
comment = description.strip
-
add_comment(comment) if comment && ! comment.empty?
-
end
-
-
2
def comment=(comment) # :nodoc:
-
add_comment(comment)
-
end
-
-
2
def add_comment(comment) # :nodoc:
-
return if comment.nil?
-
@comments << comment unless @comments.include?(comment)
-
end
-
2
private :add_comment
-
-
# Full collection of comments. Multiple comments are separated by
-
# newlines.
-
2
def full_comment
-
transform_comments("\n")
-
end
-
-
# First line (or sentence) of all comments. Multiple comments are
-
# separated by a "/".
-
2
def comment
-
transform_comments(" / ") { |c| first_sentence(c) }
-
end
-
-
# Transform the list of comments as specified by the block and
-
# join with the separator.
-
2
def transform_comments(separator, &block)
-
if @comments.empty?
-
nil
-
else
-
block ||= lambda { |c| c }
-
@comments.map(&block).join(separator)
-
end
-
end
-
2
private :transform_comments
-
-
# Get the first sentence in a string. The sentence is terminated
-
# by the first period or the end of the line. Decimal points do
-
# not count as periods.
-
2
def first_sentence(string)
-
string.split(/\.[ \t]|\.$|\n/).first
-
end
-
2
private :first_sentence
-
-
# Set the names of the arguments for this task. +args+ should be
-
# an array of symbols, one for each argument name.
-
2
def set_arg_names(args)
-
@arg_names = args.map { |a| a.to_sym }
-
end
-
-
# Return a string describing the internal state of a task. Useful for
-
# debugging.
-
2
def investigation
-
result = "------------------------------\n"
-
result << "Investigating #{name}\n"
-
result << "class: #{self.class}\n"
-
result << "task needed: #{needed?}\n"
-
result << "timestamp: #{timestamp}\n"
-
result << "pre-requisites: \n"
-
prereqs = prerequisite_tasks
-
prereqs.sort! { |a, b| a.timestamp <=> b.timestamp }
-
prereqs.each do |p|
-
result << "--#{p.name} (#{p.timestamp})\n"
-
end
-
latest_prereq = prerequisite_tasks.map { |pre| pre.timestamp }.max
-
result << "latest-prerequisite time: #{latest_prereq}\n"
-
result << "................................\n\n"
-
return result
-
end
-
-
# ----------------------------------------------------------------
-
# Rake Module Methods
-
#
-
2
class << self
-
-
# Clear the task list. This cause rake to immediately forget all the
-
# tasks that have been assigned. (Normally used in the unit tests.)
-
2
def clear
-
Rake.application.clear
-
end
-
-
# List of all defined tasks.
-
2
def tasks
-
Rake.application.tasks
-
end
-
-
# Return a task with the given name. If the task is not currently
-
# known, try to synthesize one from the defined rules. If no rules are
-
# found, but an existing file matches the task name, assume it is a file
-
# task with no dependencies or actions.
-
2
def [](task_name)
-
Rake.application[task_name]
-
end
-
-
# TRUE if the task name is already defined.
-
2
def task_defined?(task_name)
-
Rake.application.lookup(task_name) != nil
-
end
-
-
# Define a task given +args+ and an option block. If a rule with the
-
# given name already exists, the prerequisites and actions are added to
-
# the existing task. Returns the defined task.
-
2
def define_task(*args, &block)
-
Rake.application.define_task(self, *args, &block)
-
end
-
-
# Define a rule for synthesizing tasks.
-
2
def create_rule(*args, &block)
-
Rake.application.create_rule(*args, &block)
-
end
-
-
# Apply the scope to the task name according to the rules for
-
# this kind of task. Generic tasks will accept the scope as
-
# part of the name.
-
2
def scope_name(scope, task_name)
-
# (scope + [task_name]).join(':')
-
scope.path_with_task_name(task_name)
-
end
-
-
end # class << Rake::Task
-
end # class Rake::Task
-
end
-
2
module Rake
-
-
# Error indicating an ill-formed task declaration.
-
2
class TaskArgumentError < ArgumentError
-
end
-
-
end
-
2
module Rake
-
-
# The TaskManager module is a mixin for managing tasks.
-
2
module TaskManager
-
# Track the last comment made in the Rakefile.
-
2
attr_accessor :last_description
-
-
2
def initialize # :nodoc:
-
super
-
@tasks = Hash.new
-
@rules = Array.new
-
@scope = Scope.make
-
@last_description = nil
-
end
-
-
2
def create_rule(*args, &block) # :nodoc:
-
pattern, args, deps = resolve_args(args)
-
pattern = Regexp.new(Regexp.quote(pattern) + '$') if String === pattern
-
@rules << [pattern, args, deps, block]
-
end
-
-
2
def define_task(task_class, *args, &block) # :nodoc:
-
task_name, arg_names, deps = resolve_args(args)
-
-
original_scope = @scope
-
if String === task_name and
-
not task_class.ancestors.include? Rake::FileTask then
-
task_name, *definition_scope = *(task_name.split(":").reverse)
-
@scope = Scope.make(*(definition_scope + @scope.to_a))
-
end
-
-
task_name = task_class.scope_name(@scope, task_name)
-
deps = [deps] unless deps.respond_to?(:to_ary)
-
deps = deps.map { |d| Rake.from_pathname(d).to_s }
-
task = intern(task_class, task_name)
-
task.set_arg_names(arg_names) unless arg_names.empty?
-
if Rake::TaskManager.record_task_metadata
-
add_location(task)
-
task.add_description(get_description(task))
-
end
-
task.enhance(deps, &block)
-
ensure
-
@scope = original_scope
-
end
-
-
# Lookup a task. Return an existing task if found, otherwise
-
# create a task of the current type.
-
2
def intern(task_class, task_name)
-
@tasks[task_name.to_s] ||= task_class.new(task_name, self)
-
end
-
-
# Find a matching task for +task_name+.
-
2
def [](task_name, scopes=nil)
-
task_name = task_name.to_s
-
self.lookup(task_name, scopes) or
-
enhance_with_matching_rule(task_name) or
-
synthesize_file_task(task_name) or
-
fail "Don't know how to build task '#{task_name}' (see --tasks)"
-
end
-
-
2
def synthesize_file_task(task_name) # :nodoc:
-
return nil unless File.exist?(task_name)
-
define_task(Rake::FileTask, task_name)
-
end
-
-
# Resolve the arguments for a task/rule. Returns a triplet of
-
# [task_name, arg_name_list, prerequisites].
-
2
def resolve_args(args)
-
if args.last.is_a?(Hash)
-
deps = args.pop
-
resolve_args_with_dependencies(args, deps)
-
else
-
resolve_args_without_dependencies(args)
-
end
-
end
-
-
# Resolve task arguments for a task or rule when there are no
-
# dependencies declared.
-
#
-
# The patterns recognized by this argument resolving function are:
-
#
-
# task :t
-
# task :t, [:a]
-
#
-
2
def resolve_args_without_dependencies(args)
-
task_name = args.shift
-
if args.size == 1 && args.first.respond_to?(:to_ary)
-
arg_names = args.first.to_ary
-
else
-
arg_names = args
-
end
-
[task_name, arg_names, []]
-
end
-
2
private :resolve_args_without_dependencies
-
-
# Resolve task arguments for a task or rule when there are
-
# dependencies declared.
-
#
-
# The patterns recognized by this argument resolving function are:
-
#
-
# task :t => [:d]
-
# task :t, [a] => [:d]
-
#
-
2
def resolve_args_with_dependencies(args, hash) # :nodoc:
-
fail "Task Argument Error" if hash.size != 1
-
key, value = hash.map { |k, v| [k, v] }.first
-
if args.empty?
-
task_name = key
-
arg_names = []
-
deps = value || []
-
else
-
task_name = args.shift
-
arg_names = key
-
deps = value
-
end
-
deps = [deps] unless deps.respond_to?(:to_ary)
-
[task_name, arg_names, deps]
-
end
-
2
private :resolve_args_with_dependencies
-
-
# If a rule can be found that matches the task name, enhance the
-
# task with the prerequisites and actions from the rule. Set the
-
# source attribute of the task appropriately for the rule. Return
-
# the enhanced task or nil of no rule was found.
-
2
def enhance_with_matching_rule(task_name, level=0)
-
fail Rake::RuleRecursionOverflowError,
-
"Rule Recursion Too Deep" if level >= 16
-
@rules.each do |pattern, args, extensions, block|
-
if pattern.match(task_name)
-
task = attempt_rule(task_name, args, extensions, block, level)
-
return task if task
-
end
-
end
-
nil
-
rescue Rake::RuleRecursionOverflowError => ex
-
ex.add_target(task_name)
-
fail ex
-
end
-
-
# List of all defined tasks in this application.
-
2
def tasks
-
@tasks.values.sort_by { |t| t.name }
-
end
-
-
# List of all the tasks defined in the given scope (and its
-
# sub-scopes).
-
2
def tasks_in_scope(scope)
-
prefix = scope.path
-
tasks.select { |t|
-
/^#{prefix}:/ =~ t.name
-
}
-
end
-
-
# Clear all tasks in this application.
-
2
def clear
-
@tasks.clear
-
@rules.clear
-
end
-
-
# Lookup a task, using scope and the scope hints in the task name.
-
# This method performs straight lookups without trying to
-
# synthesize file tasks or rules. Special scope names (e.g. '^')
-
# are recognized. If no scope argument is supplied, use the
-
# current scope. Return nil if the task cannot be found.
-
2
def lookup(task_name, initial_scope=nil)
-
initial_scope ||= @scope
-
task_name = task_name.to_s
-
if task_name =~ /^rake:/
-
scopes = Scope.make
-
task_name = task_name.sub(/^rake:/, '')
-
elsif task_name =~ /^(\^+)/
-
scopes = initial_scope.trim($1.size)
-
task_name = task_name.sub(/^(\^+)/, '')
-
else
-
scopes = initial_scope
-
end
-
lookup_in_scope(task_name, scopes)
-
end
-
-
# Lookup the task name
-
2
def lookup_in_scope(name, scope)
-
loop do
-
tn = scope.path_with_task_name(name)
-
task = @tasks[tn]
-
return task if task
-
break if scope.empty?
-
scope = scope.tail
-
end
-
nil
-
end
-
2
private :lookup_in_scope
-
-
# Return the list of scope names currently active in the task
-
# manager.
-
2
def current_scope
-
@scope
-
end
-
-
# Evaluate the block in a nested namespace named +name+. Create
-
# an anonymous namespace if +name+ is nil.
-
2
def in_namespace(name)
-
name ||= generate_name
-
@scope = Scope.new(name, @scope)
-
ns = NameSpace.new(self, @scope)
-
yield(ns)
-
ns
-
ensure
-
@scope = @scope.tail
-
end
-
-
2
private
-
-
# Add a location to the locations field of the given task.
-
2
def add_location(task)
-
loc = find_location
-
task.locations << loc if loc
-
task
-
end
-
-
# Find the location that called into the dsl layer.
-
2
def find_location
-
locations = caller
-
i = 0
-
while locations[i]
-
return locations[i + 1] if locations[i] =~ /rake\/dsl_definition.rb/
-
i += 1
-
end
-
nil
-
end
-
-
# Generate an anonymous namespace name.
-
2
def generate_name
-
@seed ||= 0
-
@seed += 1
-
"_anon_#{@seed}"
-
end
-
-
2
def trace_rule(level, message) # :nodoc:
-
options.trace_output.puts "#{" " * level}#{message}" if
-
Rake.application.options.trace_rules
-
end
-
-
# Attempt to create a rule given the list of prerequisites.
-
2
def attempt_rule(task_name, args, extensions, block, level)
-
sources = make_sources(task_name, extensions)
-
prereqs = sources.map { |source|
-
trace_rule level, "Attempting Rule #{task_name} => #{source}"
-
if File.exist?(source) || Rake::Task.task_defined?(source)
-
trace_rule level, "(#{task_name} => #{source} ... EXIST)"
-
source
-
elsif parent = enhance_with_matching_rule(source, level + 1)
-
trace_rule level, "(#{task_name} => #{source} ... ENHANCE)"
-
parent.name
-
else
-
trace_rule level, "(#{task_name} => #{source} ... FAIL)"
-
return nil
-
end
-
}
-
task = FileTask.define_task(task_name, {args => prereqs}, &block)
-
task.sources = prereqs
-
task
-
end
-
-
# Make a list of sources from the list of file name extensions /
-
# translation procs.
-
2
def make_sources(task_name, extensions)
-
result = extensions.map { |ext|
-
case ext
-
when /%/
-
task_name.pathmap(ext)
-
when %r{/}
-
ext
-
when /^\./
-
task_name.ext(ext)
-
when String
-
ext
-
when Proc, Method
-
if ext.arity == 1
-
ext.call(task_name)
-
else
-
ext.call
-
end
-
else
-
fail "Don't know how to handle rule dependent: #{ext.inspect}"
-
end
-
}
-
result.flatten
-
end
-
-
# Return the current description, clearing it in the process.
-
2
def get_description(task)
-
desc = @last_description
-
@last_description = nil
-
desc
-
end
-
-
2
class << self
-
2
attr_accessor :record_task_metadata # :nodoc:
-
2
TaskManager.record_task_metadata = false
-
end
-
end
-
-
end
-
2
require 'rake/private_reader'
-
-
2
module Rake
-
-
2
class ThreadHistoryDisplay # :nodoc: all
-
2
include Rake::PrivateReader
-
-
2
private_reader :stats, :items, :threads
-
-
2
def initialize(stats)
-
@stats = stats
-
@items = { :_seq_ => 1 }
-
@threads = { :_seq_ => "A" }
-
end
-
-
2
def show
-
puts "Job History:"
-
stats.each do |stat|
-
stat[:data] ||= {}
-
rename(stat, :thread, threads)
-
rename(stat[:data], :item_id, items)
-
rename(stat[:data], :new_thread, threads)
-
rename(stat[:data], :deleted_thread, threads)
-
printf("%8d %2s %-20s %s\n",
-
(stat[:time] * 1_000_000).round,
-
stat[:thread],
-
stat[:event],
-
stat[:data].map do |k, v| "#{k}:#{v}" end.join(" "))
-
end
-
end
-
-
2
private
-
-
2
def rename(hash, key, renames)
-
if hash && hash[key]
-
original = hash[key]
-
value = renames[original]
-
unless value
-
value = renames[:_seq_]
-
renames[:_seq_] = renames[:_seq_].succ
-
renames[original] = value
-
end
-
hash[key] = value
-
end
-
end
-
end
-
-
end
-
2
require 'thread'
-
2
require 'set'
-
-
2
require 'rake/promise'
-
-
2
module Rake
-
-
2
class ThreadPool # :nodoc: all
-
-
# Creates a ThreadPool object. The +thread_count+ parameter is the size
-
# of the pool.
-
2
def initialize(thread_count)
-
@max_active_threads = [thread_count, 0].max
-
@threads = Set.new
-
@threads_mon = Monitor.new
-
@queue = Queue.new
-
@join_cond = @threads_mon.new_cond
-
-
@history_start_time = nil
-
@history = []
-
@history_mon = Monitor.new
-
@total_threads_in_play = 0
-
end
-
-
# Creates a future executed by the +ThreadPool+.
-
#
-
# The args are passed to the block when executing (similarly to
-
# Thread#new) The return value is an object representing
-
# a future which has been created and added to the queue in the
-
# pool. Sending #value to the object will sleep the
-
# current thread until the future is finished and will return the
-
# result (or raise an exception thrown from the future)
-
2
def future(*args, &block)
-
promise = Promise.new(args, &block)
-
promise.recorder = lambda { |*stats| stat(*stats) }
-
-
@queue.enq promise
-
stat :queued, :item_id => promise.object_id
-
start_thread
-
promise
-
end
-
-
# Waits until the queue of futures is empty and all threads have exited.
-
2
def join
-
@threads_mon.synchronize do
-
begin
-
stat :joining
-
@join_cond.wait unless @threads.empty?
-
stat :joined
-
rescue Exception => e
-
stat :joined
-
$stderr.puts e
-
$stderr.print "Queue contains #{@queue.size} items. " +
-
"Thread pool contains #{@threads.count} threads\n"
-
$stderr.print "Current Thread #{Thread.current} status = " +
-
"#{Thread.current.status}\n"
-
$stderr.puts e.backtrace.join("\n")
-
@threads.each do |t|
-
$stderr.print "Thread #{t} status = #{t.status}\n"
-
$stderr.puts t.backtrace.join("\n")
-
end
-
raise e
-
end
-
end
-
end
-
-
# Enable the gathering of history events.
-
2
def gather_history #:nodoc:
-
@history_start_time = Time.now if @history_start_time.nil?
-
end
-
-
# Return a array of history events for the thread pool.
-
#
-
# History gathering must be enabled to be able to see the events
-
# (see #gather_history). Best to call this when the job is
-
# complete (i.e. after ThreadPool#join is called).
-
2
def history # :nodoc:
-
@history_mon.synchronize { @history.dup }.
-
sort_by { |i| i[:time] }.
-
each { |i| i[:time] -= @history_start_time }
-
end
-
-
# Return a hash of always collected statistics for the thread pool.
-
2
def statistics # :nodoc:
-
{
-
:total_threads_in_play => @total_threads_in_play,
-
:max_active_threads => @max_active_threads,
-
}
-
end
-
-
2
private
-
-
# processes one item on the queue. Returns true if there was an
-
# item to process, false if there was no item
-
2
def process_queue_item #:nodoc:
-
return false if @queue.empty?
-
-
# Even though we just asked if the queue was empty, it
-
# still could have had an item which by this statement
-
# is now gone. For this reason we pass true to Queue#deq
-
# because we will sleep indefinitely if it is empty.
-
promise = @queue.deq(true)
-
stat :dequeued, :item_id => promise.object_id
-
promise.work
-
return true
-
-
rescue ThreadError # this means the queue is empty
-
false
-
end
-
-
2
def safe_thread_count
-
@threads_mon.synchronize do
-
@threads.count
-
end
-
end
-
-
2
def start_thread # :nodoc:
-
@threads_mon.synchronize do
-
next unless @threads.count < @max_active_threads
-
-
t = Thread.new do
-
begin
-
while safe_thread_count <= @max_active_threads
-
break unless process_queue_item
-
end
-
ensure
-
@threads_mon.synchronize do
-
@threads.delete Thread.current
-
stat :ended, :thread_count => @threads.count
-
@join_cond.broadcast if @threads.empty?
-
end
-
end
-
end
-
-
@threads << t
-
stat(
-
:spawned,
-
:new_thread => t.object_id,
-
:thread_count => @threads.count)
-
@total_threads_in_play = @threads.count if
-
@threads.count > @total_threads_in_play
-
end
-
end
-
-
2
def stat(event, data=nil) # :nodoc:
-
return if @history_start_time.nil?
-
info = {
-
:event => event,
-
:data => data,
-
:time => Time.now,
-
:thread => Thread.current.object_id,
-
}
-
@history_mon.synchronize { @history << info }
-
end
-
-
# for testing only
-
-
2
def __queue__ # :nodoc:
-
@queue
-
end
-
end
-
-
end
-
2
module Rake
-
2
module TraceOutput # :nodoc: all
-
-
# Write trace output to output stream +out+.
-
#
-
# The write is done as a single IO call (to print) to lessen the
-
# chance that the trace output is interrupted by other tasks also
-
# producing output.
-
2
def trace_on(out, *strings)
-
sep = $\ || "\n"
-
if strings.empty?
-
output = sep
-
else
-
output = strings.map { |s|
-
next if s.nil?
-
s.end_with?(sep) ? s : s + sep
-
}.join
-
end
-
out.print(output)
-
end
-
end
-
end
-
2
module Rake
-
2
module Version # :nodoc: all
-
2
MAJOR, MINOR, BUILD, *OTHER = Rake::VERSION.split '.'
-
-
2
NUMBERS = [MAJOR, MINOR, BUILD, *OTHER]
-
end
-
end
-
2
require 'rbconfig'
-
-
2
module Rake
-
# Win 32 interface methods for Rake. Windows specific functionality
-
# will be placed here to collect that knowledge in one spot.
-
2
module Win32 # :nodoc: all
-
-
# Error indicating a problem in locating the home directory on a
-
# Win32 system.
-
2
class Win32HomeError < RuntimeError
-
end
-
-
2
class << self
-
# True if running on a windows system.
-
2
def windows?
-
2
RbConfig::CONFIG["host_os"] =~ %r!(msdos|mswin|djgpp|mingw|[Ww]indows)!
-
end
-
-
# The standard directory containing system wide rake files on
-
# Win 32 systems. Try the following environment variables (in
-
# order):
-
#
-
# * HOME
-
# * HOMEDRIVE + HOMEPATH
-
# * APPDATA
-
# * USERPROFILE
-
#
-
# If the above are not defined, the return nil.
-
2
def win32_system_dir #:nodoc:
-
win32_shared_path = ENV['HOME']
-
if win32_shared_path.nil? && ENV['HOMEDRIVE'] && ENV['HOMEPATH']
-
win32_shared_path = ENV['HOMEDRIVE'] + ENV['HOMEPATH']
-
end
-
-
win32_shared_path ||= ENV['APPDATA']
-
win32_shared_path ||= ENV['USERPROFILE']
-
raise Win32HomeError,
-
"Unable to determine home path environment variable." if
-
win32_shared_path.nil? or win32_shared_path.empty?
-
normalize(File.join(win32_shared_path, 'Rake'))
-
end
-
-
# Normalize a win32 path so that the slashes are all forward slashes.
-
2
def normalize(path)
-
path.gsub(/\\/, '/')
-
end
-
-
end
-
end
-
end
-
2
require 'action_controller'
-
-
2
module Responders
-
2
autoload :FlashResponder, 'responders/flash_responder'
-
2
autoload :HttpCacheResponder, 'responders/http_cache_responder'
-
2
autoload :CollectionResponder, 'responders/collection_responder'
-
2
autoload :LocationResponder, 'responders/location_responder'
-
-
2
require 'responders/controller_method'
-
-
2
class Railtie < ::Rails::Railtie
-
2
config.responders = ActiveSupport::OrderedOptions.new
-
2
config.responders.flash_keys = [ :notice, :alert ]
-
2
config.responders.namespace_lookup = false
-
-
2
if config.respond_to?(:app_generators)
-
2
config.app_generators.scaffold_controller = :responders_controller
-
else
-
config.generators.scaffold_controller = :responders_controller
-
end
-
-
# Add load paths straight to I18n, so engines and application can overwrite it.
-
2
require 'active_support/i18n'
-
2
I18n.load_path << File.expand_path('../responders/locales/en.yml', __FILE__)
-
-
2
initializer "responders.flash_responder" do |app|
-
2
Responders::FlashResponder.flash_keys = app.config.responders.flash_keys
-
2
Responders::FlashResponder.namespace_lookup = app.config.responders.namespace_lookup
-
end
-
end
-
end
-
2
module Responders
-
2
module ControllerMethod
-
# Adds the given responders to the current controller's responder, allowing you to cherry-pick
-
# which responders you want per controller.
-
#
-
# class InvitationsController < ApplicationController
-
# responders :flash, :http_cache
-
# end
-
#
-
# Takes symbols and strings and translates them to VariableResponder (eg. :flash becomes FlashResponder).
-
# Also allows passing in the responders modules in directly, so you could do:
-
#
-
# responders FlashResponder, HttpCacheResponder
-
#
-
# Or a mix of both methods:
-
#
-
# responders :flash, MyCustomResponder
-
#
-
2
def responders(*responders)
-
self.responder = responders.inject(Class.new(responder)) do |klass, responder|
-
responder = case responder
-
when Module
-
responder
-
when String, Symbol
-
Responders.const_get("#{responder.to_s.camelize}Responder")
-
else
-
raise "responder has to be a string, a symbol or a module"
-
end
-
-
klass.send(:include, responder)
-
klass
-
end
-
end
-
end
-
end
-
-
2
ActionController::Base.extend Responders::ControllerMethod
-
2
module Responders
-
# Responder to automatically set flash messages based on I18n API. It checks for
-
# message based on the current action, but also allows defaults to be set, using
-
# the following order:
-
#
-
# flash.controller_name.action_name.status
-
# flash.actions.action_name.status
-
#
-
# So, if you have a CarsController, create action, it will check for:
-
#
-
# flash.cars.create.status
-
# flash.actions.create.status
-
#
-
# The statuses by default are :notice (when the object can be created, updated
-
# or destroyed with success) and :alert (when the object cannot be created
-
# or updated).
-
#
-
# On I18n, the resource_name given is available as interpolation option,
-
# this means you can set:
-
#
-
# flash:
-
# actions:
-
# create:
-
# notice: "Hooray! %{resource_name} was successfully created!"
-
#
-
# But sometimes, flash messages are not that simple. Going back
-
# to cars example, you might want to say the brand of the car when it's
-
# updated. Well, that's easy also:
-
#
-
# flash:
-
# cars:
-
# update:
-
# notice: "Hooray! You just tuned your %{car_brand}!"
-
#
-
# Since :car_name is not available for interpolation by default, you have
-
# to overwrite interpolation_options in your controller.
-
#
-
# def interpolation_options
-
# { :car_brand => @car.brand }
-
# end
-
#
-
# Then you will finally have:
-
#
-
# 'Hooray! You just tuned your Aston Martin!'
-
#
-
# If your controller is namespaced, for example Admin::CarsController,
-
# the messages will be checked in the following order:
-
#
-
# flash.admin.cars.create.status
-
# flash.admin.actions.create.status
-
# flash.cars.create.status
-
# flash.actions.create.status
-
#
-
# You can also have flash messages with embedded HTML. Just create a scope that
-
# ends with <tt>_html</tt> as the scopes below:
-
#
-
# flash.actions.create.notice_html
-
# flash.cars.create.notice_html
-
#
-
# == Options
-
#
-
# FlashResponder also accepts some options through respond_with API.
-
#
-
# * :flash - When set to false, no flash message is set.
-
#
-
# respond_with(@user, :flash => true)
-
#
-
# * :notice - Supply the message to be set if the record has no errors.
-
# * :alert - Supply the message to be set if the record has errors.
-
#
-
# respond_with(@user, :notice => "Hooray! Welcome!", :alert => "Woot! You failed.")
-
#
-
# * :flash_now - Sets the flash message using flash.now. Accepts true, :on_failure or :on_sucess.
-
#
-
# == Configure status keys
-
#
-
# As said previously, FlashResponder by default use :notice and :alert
-
# keys. You can change that by setting the status_keys:
-
#
-
# Responders::FlashResponder.flash_keys = [ :success, :failure ]
-
#
-
# However, the options :notice and :alert to respond_with are kept :notice
-
# and :alert.
-
#
-
2
module FlashResponder
-
2
class << self
-
2
attr_accessor :flash_keys, :namespace_lookup, :helper
-
end
-
-
2
self.flash_keys = [ :notice, :alert ]
-
2
self.namespace_lookup = false
-
2
self.helper = Object.new.extend(
-
ActionView::Helpers::TranslationHelper,
-
ActionView::Helpers::TagHelper
-
)
-
-
2
def initialize(controller, resources, options={})
-
super
-
@flash = options.delete(:flash)
-
@notice = options.delete(:notice)
-
@alert = options.delete(:alert)
-
@flash_now = options.delete(:flash_now) { :on_failure }
-
end
-
-
2
def to_html
-
set_flash_message! if set_flash_message?
-
super
-
end
-
-
2
def to_js
-
set_flash_message! if set_flash_message?
-
defined?(super) ? super : to_format
-
end
-
-
2
protected
-
-
2
def set_flash_message!
-
if has_errors?
-
status = Responders::FlashResponder.flash_keys.last
-
set_flash(status, @alert)
-
else
-
status = Responders::FlashResponder.flash_keys.first
-
set_flash(status, @notice)
-
end
-
-
return if controller.flash[status].present?
-
-
options = mount_i18n_options(status)
-
message = Responders::FlashResponder.helper.t options[:default].shift, options
-
set_flash(status, message)
-
end
-
-
2
def set_flash(key, value)
-
return if value.blank?
-
flash = controller.flash
-
flash = flash.now if set_flash_now?
-
flash[key] ||= value
-
end
-
-
2
def set_flash_now?
-
@flash_now == true || format == :js ||
-
(default_action && (has_errors? ? @flash_now == :on_failure : @flash_now == :on_success))
-
end
-
-
2
def set_flash_message? #:nodoc:
-
!get? && @flash != false
-
end
-
-
2
def mount_i18n_options(status) #:nodoc:
-
resource_name = if resource.class.respond_to?(:model_name)
-
resource.class.model_name.human
-
else
-
resource.class.name.underscore.humanize
-
end
-
-
options = {
-
:default => flash_defaults_by_namespace(status),
-
:resource_name => resource_name,
-
:downcase_resource_name => resource_name.downcase
-
}
-
-
if controller.respond_to?(:interpolation_options, true)
-
options.merge!(controller.send(:interpolation_options))
-
end
-
-
options
-
end
-
-
2
def flash_defaults_by_namespace(status) #:nodoc:
-
defaults = []
-
slices = controller.controller_path.split('/')
-
lookup = Responders::FlashResponder.namespace_lookup
-
-
begin
-
controller_scope = :"flash.#{slices.fill(controller.controller_name, -1).join('.')}.#{controller.action_name}.#{status}"
-
-
actions_scope = lookup ? slices.fill('actions', -1).join('.') : :actions
-
actions_scope = :"flash.#{actions_scope}.#{controller.action_name}.#{status}"
-
-
defaults << :"#{controller_scope}_html"
-
defaults << controller_scope
-
-
defaults << :"#{actions_scope}_html"
-
defaults << actions_scope
-
-
slices.shift
-
end while slices.size > 0 && lookup
-
-
defaults << ""
-
end
-
end
-
end
-
2
require 'rspec/core'
-
2
require 'rspec/version'
-
-
2
module RSpec # :nodoc:
-
2
module Version # :nodoc:
-
2
STRING = '3.4.0'
-
end
-
end
-
1
require 'rspec/core'
-
# Ensure the default config is loaded
-
1
RSpec::Core::Runner.autorun
-
# rubocop:disable Style/GlobalVars
-
1
$_rspec_core_load_started_at = Time.now
-
# rubocop:enable Style/GlobalVars
-
-
1
require "rspec/support"
-
1
RSpec::Support.require_rspec_support "caller_filter"
-
-
39
RSpec::Support.define_optimized_require_for_rspec(:core) { |f| require_relative f }
-
-
%w[
-
version
-
warnings
-
-
set
-
flat_map
-
filter_manager
-
dsl
-
notifications
-
reporter
-
-
hooks
-
memoized_helpers
-
metadata
-
metadata_filter
-
pending
-
formatters
-
ordering
-
-
world
-
configuration
-
option_parser
-
configuration_options
-
runner
-
example
-
shared_example_group
-
example_group
-
24
].each { |name| RSpec::Support.require_rspec_core name }
-
-
# Namespace for all core RSpec code.
-
1
module RSpec
-
1
autoload :SharedContext, 'rspec/core/shared_context'
-
-
1
extend RSpec::Core::Warnings
-
-
1
class << self
-
# Setters for shared global objects
-
# @api private
-
1
attr_writer :configuration, :world
-
end
-
-
# Used to ensure examples get reloaded and user configuration gets reset to
-
# defaults between multiple runs in the same process.
-
#
-
# Users must invoke this if they want to have the configuration reset when
-
# they use the runner multiple times within the same process. Users must deal
-
# themselves with re-configuration of RSpec before run.
-
1
def self.reset
-
@world = nil
-
@configuration = nil
-
end
-
-
# Used to ensure examples get reloaded between multiple runs in the same
-
# process and ensures user configuration is persisted.
-
#
-
# Users must invoke this if they want to clear all examples but preserve
-
# current configuration when they use the runner multiple times within the
-
# same process.
-
1
def self.clear_examples
-
world.reset
-
configuration.reporter.reset
-
configuration.start_time = ::RSpec::Core::Time.now
-
configuration.reset_filters
-
end
-
-
# Returns the global [Configuration](RSpec/Core/Configuration) object. While
-
# you _can_ use this method to access the configuration, the more common
-
# convention is to use [RSpec.configure](RSpec#configure-class_method).
-
#
-
# @example
-
# RSpec.configuration.drb_port = 1234
-
# @see RSpec.configure
-
# @see Core::Configuration
-
1
def self.configuration
-
3
@configuration ||= RSpec::Core::Configuration.new
-
end
-
1
configuration.expose_dsl_globally = true
-
-
# Yields the global configuration to a block.
-
# @yield [Configuration] global configuration
-
#
-
# @example
-
# RSpec.configure do |config|
-
# config.add_formatter 'documentation'
-
# end
-
# @see Core::Configuration
-
1
def self.configure
-
1
yield configuration if block_given?
-
end
-
-
# The example being executed.
-
#
-
# The primary audience for this method is library authors who need access
-
# to the example currently being executed and also want to support all
-
# versions of RSpec 2 and 3.
-
#
-
# @example
-
#
-
# RSpec.configure do |c|
-
# # context.example is deprecated, but RSpec.current_example is not
-
# # available until RSpec 3.0.
-
# fetch_current_example = RSpec.respond_to?(:current_example) ?
-
# proc { RSpec.current_example } : proc { |context| context.example }
-
#
-
# c.before(:example) do
-
# example = fetch_current_example.call(self)
-
#
-
# # ...
-
# end
-
# end
-
#
-
1
def self.current_example
-
RSpec::Support.thread_local_data[:current_example]
-
end
-
-
# Set the current example being executed.
-
# @api private
-
1
def self.current_example=(example)
-
RSpec::Support.thread_local_data[:current_example] = example
-
end
-
-
# @private
-
# Internal container for global non-configuration data.
-
1
def self.world
-
1
@world ||= RSpec::Core::World.new
-
end
-
-
# Namespace for the rspec-core code.
-
1
module Core
-
1
autoload :ExampleStatusPersister, "rspec/core/example_status_persister"
-
1
autoload :Profiler, "rspec/core/profiler"
-
-
# @private
-
# This avoids issues with reporting time caused by examples that
-
# change the value/meaning of Time.now without properly restoring
-
# it.
-
1
class Time
-
1
class << self
-
1
define_method(:now, &::Time.method(:now))
-
end
-
end
-
-
# @private path to executable file.
-
1
def self.path_to_executable
-
@path_to_executable ||= File.expand_path('../../../exe/rspec', __FILE__)
-
end
-
end
-
-
# @private
-
1
MODULES_TO_AUTOLOAD = {
-
:Matchers => "rspec/expectations",
-
:Expectations => "rspec/expectations",
-
:Mocks => "rspec/mocks"
-
}
-
-
# @private
-
1
def self.const_missing(name)
-
# Load rspec-expectations when RSpec::Matchers is referenced. This allows
-
# people to define custom matchers (using `RSpec::Matchers.define`) before
-
# rspec-core has loaded rspec-expectations (since it delays the loading of
-
# it to allow users to configure a different assertion/expectation
-
# framework). `autoload` can't be used since it works with ruby's built-in
-
# require (e.g. for files that are available relative to a load path dir),
-
# but not with rubygems' extended require.
-
#
-
# As of rspec 2.14.1, we no longer require `rspec/mocks` and
-
# `rspec/expectations` when `rspec` is required, so we want
-
# to make them available as an autoload.
-
require MODULES_TO_AUTOLOAD.fetch(name) { return super }
-
::RSpec.const_get(name)
-
end
-
end
-
1
module RSpec
-
1
module Core
-
# @private
-
1
class BacktraceFormatter
-
# @private
-
1
attr_accessor :exclusion_patterns, :inclusion_patterns
-
-
1
def initialize
-
1
@full_backtrace = false
-
-
1
patterns = %w[ /lib\d*/ruby/ bin/ exe/rspec ]
-
1
patterns << "org/jruby/" if RUBY_PLATFORM == 'java'
-
4
patterns.map! { |s| Regexp.new(s.gsub("/", File::SEPARATOR)) }
-
-
1
@exclusion_patterns = [Regexp.union(RSpec::CallerFilter::IGNORE_REGEX, *patterns)]
-
1
@inclusion_patterns = []
-
-
1
return unless matches?(@exclusion_patterns, File.join(Dir.getwd, "lib", "foo.rb:13"))
-
inclusion_patterns << Regexp.new(Dir.getwd)
-
end
-
-
1
attr_writer :full_backtrace
-
-
1
def full_backtrace?
-
@full_backtrace || exclusion_patterns.empty?
-
end
-
-
1
def filter_gem(gem_name)
-
sep = File::SEPARATOR
-
exclusion_patterns << /#{sep}#{gem_name}(-[^#{sep}]+)?#{sep}/
-
end
-
-
1
def format_backtrace(backtrace, options={})
-
return [] unless backtrace
-
return backtrace if options[:full_backtrace] || backtrace.empty?
-
-
backtrace.map { |l| backtrace_line(l) }.compact.
-
tap do |filtered|
-
if filtered.empty?
-
filtered.concat backtrace
-
filtered << ""
-
filtered << " Showing full backtrace because every line was filtered out."
-
filtered << " See docs for RSpec::Configuration#backtrace_exclusion_patterns and"
-
filtered << " RSpec::Configuration#backtrace_inclusion_patterns for more information."
-
end
-
end
-
end
-
-
1
def backtrace_line(line)
-
Metadata.relative_path(line) unless exclude?(line)
-
end
-
-
1
def exclude?(line)
-
return false if @full_backtrace
-
matches?(exclusion_patterns, line) && !matches?(inclusion_patterns, line)
-
end
-
-
1
private
-
-
1
def matches?(patterns, line)
-
2
patterns.any? { |p| line =~ p }
-
end
-
end
-
end
-
end
-
1
RSpec::Support.require_rspec_core "backtrace_formatter"
-
1
RSpec::Support.require_rspec_core "ruby_project"
-
1
RSpec::Support.require_rspec_core "formatters/deprecation_formatter"
-
-
1
module RSpec
-
1
module Core
-
# rubocop:disable Metrics/ClassLength
-
-
# Stores runtime configuration information.
-
#
-
# Configuration options are loaded from `~/.rspec`, `.rspec`,
-
# `.rspec-local`, command line switches, and the `SPEC_OPTS` environment
-
# variable (listed in lowest to highest precedence; for example, an option
-
# in `~/.rspec` can be overridden by an option in `.rspec-local`).
-
#
-
# @example Standard settings
-
# RSpec.configure do |c|
-
# c.drb = true
-
# c.drb_port = 1234
-
# c.default_path = 'behavior'
-
# end
-
#
-
# @example Hooks
-
# RSpec.configure do |c|
-
# c.before(:suite) { establish_connection }
-
# c.before(:example) { log_in_as :authorized }
-
# c.around(:example) { |ex| Database.transaction(&ex) }
-
# end
-
#
-
# @see RSpec.configure
-
# @see Hooks
-
1
class Configuration
-
1
include RSpec::Core::Hooks
-
-
# Module that holds `attr_reader` declarations. It's in a separate
-
# module to allow us to override those methods and use `super`.
-
# @private
-
1
Readers = Module.new
-
1
include Readers
-
-
# @private
-
1
class MustBeConfiguredBeforeExampleGroupsError < StandardError; end
-
-
# @private
-
1
def self.define_reader(name)
-
29
Readers.class_eval do
-
29
remove_method name if method_defined?(name)
-
29
attr_reader name
-
end
-
-
29
define_method(name) { value_for(name) { super() } }
-
end
-
-
# @private
-
1
def self.define_aliases(name, alias_name)
-
alias_method alias_name, name
-
alias_method "#{alias_name}=", "#{name}="
-
define_predicate_for alias_name
-
end
-
-
# @private
-
1
def self.define_predicate_for(*names)
-
42
names.each { |name| alias_method "#{name}?", name }
-
end
-
-
# @private
-
#
-
# Invoked by the `add_setting` instance method. Use that method on a
-
# `Configuration` instance rather than this class method.
-
1
def self.add_setting(name, opts={})
-
20
raise "Use the instance add_setting method if you want to set a default" if opts.key?(:default)
-
20
attr_writer name
-
20
add_read_only_setting name
-
-
20
Array(opts[:alias_with]).each do |alias_name|
-
define_aliases(name, alias_name)
-
end
-
end
-
-
# @private
-
#
-
# As `add_setting` but only add the reader.
-
1
def self.add_read_only_setting(name, opts={})
-
21
raise "Use the instance add_setting method if you want to set a default" if opts.key?(:default)
-
21
define_reader name
-
21
define_predicate_for name
-
end
-
-
# @macro [attach] add_setting
-
# @!attribute [rw] $1
-
# @!method $1=(value)
-
#
-
# @macro [attach] define_reader
-
# @!attribute [r] $1
-
-
# @macro add_setting
-
# Path to use if no path is provided to the `rspec` command (default:
-
# `"spec"`). Allows you to just type `rspec` instead of `rspec spec` to
-
# run all the examples in the `spec` directory.
-
#
-
# @note Other scripts invoking `rspec` indirectly will ignore this
-
# setting.
-
1
add_read_only_setting :default_path
-
1
def default_path=(path)
-
project_source_dirs << path
-
@default_path = path
-
end
-
-
# @macro add_setting
-
# Run examples over DRb (default: `false`). RSpec doesn't supply the DRb
-
# server, but you can use tools like spork.
-
1
add_setting :drb
-
-
# @macro add_setting
-
# The drb_port (default: nil).
-
1
add_setting :drb_port
-
-
# @macro add_setting
-
# Default: `$stderr`.
-
1
add_setting :error_stream
-
-
# Indicates if the DSL has been exposed off of modules and `main`.
-
# Default: true
-
1
def expose_dsl_globally?
-
Core::DSL.exposed_globally?
-
end
-
-
# Use this to expose the core RSpec DSL via `Module` and the `main`
-
# object. It will be set automatically but you can override it to
-
# remove the DSL.
-
# Default: true
-
1
def expose_dsl_globally=(value)
-
1
if value
-
1
Core::DSL.expose_globally!
-
1
Core::SharedExampleGroup::TopLevelDSL.expose_globally!
-
else
-
Core::DSL.remove_globally!
-
Core::SharedExampleGroup::TopLevelDSL.remove_globally!
-
end
-
end
-
-
# Determines where deprecation warnings are printed.
-
# Defaults to `$stderr`.
-
# @return [IO, String] IO to write to or filename to write to
-
1
define_reader :deprecation_stream
-
-
# Determines where deprecation warnings are printed.
-
# @param value [IO, String] IO to write to or filename to write to
-
1
def deprecation_stream=(value)
-
if @reporter && !value.equal?(@deprecation_stream)
-
warn "RSpec's reporter has already been initialized with " \
-
"#{deprecation_stream.inspect} as the deprecation stream, so your change to "\
-
"`deprecation_stream` will be ignored. You should configure it earlier for " \
-
"it to take effect, or use the `--deprecation-out` CLI option. " \
-
"(Called from #{CallerFilter.first_non_rspec_line})"
-
else
-
@deprecation_stream = value
-
end
-
end
-
-
# @macro define_reader
-
# The file path to use for persisting example statuses. Necessary for the
-
# `--only-failures` and `--next-failures` CLI options.
-
#
-
# @overload example_status_persistence_file_path
-
# @return [String] the file path
-
# @overload example_status_persistence_file_path=(value)
-
# @param value [String] the file path
-
1
define_reader :example_status_persistence_file_path
-
-
# Sets the file path to use for persisting example statuses. Necessary for the
-
# `--only-failures` and `--next-failures` CLI options.
-
1
def example_status_persistence_file_path=(value)
-
@example_status_persistence_file_path = value
-
clear_values_derived_from_example_status_persistence_file_path
-
end
-
-
# @macro define_reader
-
# Indicates if the `--only-failures` (or `--next-failure`) flag is being used.
-
1
define_reader :only_failures
-
1
alias_method :only_failures?, :only_failures
-
-
# @private
-
1
def only_failures_but_not_configured?
-
only_failures? && !example_status_persistence_file_path
-
end
-
-
# @macro add_setting
-
# If specified, indicates the number of failures required before cleaning
-
# up and exit (default: `nil`).
-
1
add_setting :fail_fast
-
-
# @macro add_setting
-
# Prints the formatter output of your suite without running any
-
# examples or hooks.
-
1
add_setting :dry_run
-
-
# @macro add_setting
-
# The exit code to return if there are any failures (default: 1).
-
1
add_setting :failure_exit_code
-
-
# @macro define_reader
-
# Indicates files configured to be required.
-
1
define_reader :requires
-
-
# @macro define_reader
-
# Returns dirs that have been prepended to the load path by the `-I`
-
# command line option.
-
1
define_reader :libs
-
-
# @macro add_setting
-
# Determines where RSpec will send its output.
-
# Default: `$stdout`.
-
1
define_reader :output_stream
-
-
# Set the output stream for reporter.
-
# @attr value [IO] value for output, defaults to $stdout
-
1
def output_stream=(value)
-
if @reporter && !value.equal?(@output_stream)
-
warn "RSpec's reporter has already been initialized with " \
-
"#{output_stream.inspect} as the output stream, so your change to "\
-
"`output_stream` will be ignored. You should configure it earlier for " \
-
"it to take effect. (Called from #{CallerFilter.first_non_rspec_line})"
-
else
-
@output_stream = value
-
end
-
end
-
-
# @macro define_reader
-
# Load files matching this pattern (default: `'**{,/*/**}/*_spec.rb'`).
-
1
define_reader :pattern
-
-
# Set pattern to match files to load.
-
# @attr value [String] the filename pattern to filter spec files by
-
1
def pattern=(value)
-
update_pattern_attr :pattern, value
-
end
-
-
# @macro define_reader
-
# Exclude files matching this pattern.
-
1
define_reader :exclude_pattern
-
-
# Set pattern to match files to exclude.
-
# @attr value [String] the filename pattern to exclude spec files by
-
1
def exclude_pattern=(value)
-
update_pattern_attr :exclude_pattern, value
-
end
-
-
# @macro add_setting
-
# Specifies which directories contain the source code for your project.
-
# When a failure occurs, RSpec looks through the backtrace to find a
-
# a line of source to print. It first looks for a line coming from
-
# one of the project source directories so that, for example, it prints
-
# the expectation or assertion call rather than the source code from
-
# the expectation or assertion framework.
-
# @return [Array<String>]
-
1
add_setting :project_source_dirs
-
-
# @macro add_setting
-
# Report the times for the slowest examples (default: `false`).
-
# Use this to specify the number of examples to include in the profile.
-
1
add_setting :profile_examples
-
-
# @macro add_setting
-
# Run all examples if none match the configured filters
-
# (default: `false`).
-
1
add_setting :run_all_when_everything_filtered
-
-
# @macro add_setting
-
# Color to use to indicate success.
-
# @param color [Symbol] defaults to `:green` but can be set to one of the
-
# following: `[:black, :white, :red, :green, :yellow, :blue, :magenta,
-
# :cyan]`
-
1
add_setting :success_color
-
-
# @macro add_setting
-
# Color to use to print pending examples.
-
# @param color [Symbol] defaults to `:yellow` but can be set to one of the
-
# following: `[:black, :white, :red, :green, :yellow, :blue, :magenta,
-
# :cyan]`
-
1
add_setting :pending_color
-
-
# @macro add_setting
-
# Color to use to indicate failure.
-
# @param color [Symbol] defaults to `:red` but can be set to one of the
-
# following: `[:black, :white, :red, :green, :yellow, :blue, :magenta,
-
# :cyan]`
-
1
add_setting :failure_color
-
-
# @macro add_setting
-
# The default output color.
-
# @param color [Symbol] defaults to `:white` but can be set to one of the
-
# following: `[:black, :white, :red, :green, :yellow, :blue, :magenta,
-
# :cyan]`
-
1
add_setting :default_color
-
-
# @macro add_setting
-
# Color used when a pending example is fixed.
-
# @param color [Symbol] defaults to `:blue` but can be set to one of the
-
# following: `[:black, :white, :red, :green, :yellow, :blue, :magenta,
-
# :cyan]`
-
1
add_setting :fixed_color
-
-
# @macro add_setting
-
# Color used to print details.
-
# @param color [Symbol] defaults to `:cyan` but can be set to one of the
-
# following: `[:black, :white, :red, :green, :yellow, :blue, :magenta,
-
# :cyan]`
-
1
add_setting :detail_color
-
-
# @macro add_setting
-
# Don't print filter info i.e. "Run options: include {:focus=>true}"
-
# (default `false`).
-
1
add_setting :silence_filter_announcements
-
-
# Deprecated. This config option was added in RSpec 2 to pave the way
-
# for this being the default behavior in RSpec 3. Now this option is
-
# a no-op.
-
1
def treat_symbols_as_metadata_keys_with_true_values=(_value)
-
RSpec.deprecate(
-
"RSpec::Core::Configuration#treat_symbols_as_metadata_keys_with_true_values=",
-
:message => "RSpec::Core::Configuration#treat_symbols_as_metadata_keys_with_true_values= " \
-
"is deprecated, it is now set to true as default and " \
-
"setting it to false has no effect."
-
)
-
end
-
-
# Record the start time of the spec suite to measure load time.
-
1
add_setting :start_time
-
-
# @macro add_setting
-
# Use threadsafe options where available.
-
# Currently this will place a mutex around memoized values such as let blocks.
-
1
add_setting :threadsafe
-
-
# @macro add_setting
-
# Maximum count of failed source lines to display in the failure reports.
-
# (default `10`).
-
1
add_setting :max_displayed_failure_line_count
-
-
# @private
-
1
add_setting :tty
-
# @private
-
1
attr_writer :files_to_run
-
# @private
-
1
attr_accessor :filter_manager
-
# @private
-
1
attr_accessor :static_config_filter_manager
-
# @private
-
1
attr_reader :backtrace_formatter, :ordering_manager, :loaded_spec_files
-
-
1
def initialize
-
# rubocop:disable Style/GlobalVars
-
1
@start_time = $_rspec_core_load_started_at || ::RSpec::Core::Time.now
-
# rubocop:enable Style/GlobalVars
-
1
@expectation_frameworks = []
-
1
@include_modules = FilterableItemRepository::QueryOptimized.new(:any?)
-
1
@extend_modules = FilterableItemRepository::QueryOptimized.new(:any?)
-
1
@prepend_modules = FilterableItemRepository::QueryOptimized.new(:any?)
-
-
1
@before_suite_hooks = []
-
1
@after_suite_hooks = []
-
-
1
@mock_framework = nil
-
1
@files_or_directories_to_run = []
-
1
@loaded_spec_files = Set.new
-
1
@color = false
-
1
@pattern = '**{,/*/**}/*_spec.rb'
-
1
@exclude_pattern = ''
-
1
@failure_exit_code = 1
-
1
@spec_files_loaded = false
-
-
1
@backtrace_formatter = BacktraceFormatter.new
-
-
1
@default_path = 'spec'
-
1
@project_source_dirs = %w[ spec lib app ]
-
1
@deprecation_stream = $stderr
-
1
@output_stream = $stdout
-
1
@reporter = nil
-
1
@reporter_buffer = nil
-
1
@filter_manager = FilterManager.new
-
1
@static_config_filter_manager = FilterManager.new
-
1
@ordering_manager = Ordering::ConfigurationManager.new
-
1
@preferred_options = {}
-
1
@failure_color = :red
-
1
@success_color = :green
-
1
@pending_color = :yellow
-
1
@default_color = :white
-
1
@fixed_color = :blue
-
1
@detail_color = :cyan
-
1
@profile_examples = false
-
1
@requires = []
-
1
@libs = []
-
1
@derived_metadata_blocks = FilterableItemRepository::QueryOptimized.new(:any?)
-
1
@threadsafe = true
-
1
@max_displayed_failure_line_count = 10
-
-
1
define_built_in_hooks
-
end
-
-
# @private
-
#
-
# Used to set higher priority option values from the command line.
-
1
def force(hash)
-
ordering_manager.force(hash)
-
@preferred_options.merge!(hash)
-
-
return unless hash.key?(:example_status_persistence_file_path)
-
clear_values_derived_from_example_status_persistence_file_path
-
end
-
-
# @private
-
1
def reset
-
@spec_files_loaded = false
-
@reporter = nil
-
@formatter_loader = nil
-
end
-
-
# @private
-
1
def reset_filters
-
self.filter_manager = FilterManager.new
-
filter_manager.include_only(
-
Metadata.deep_hash_dup(static_config_filter_manager.inclusions.rules)
-
)
-
filter_manager.exclude_only(
-
Metadata.deep_hash_dup(static_config_filter_manager.exclusions.rules)
-
)
-
end
-
-
# @overload add_setting(name)
-
# @overload add_setting(name, opts)
-
# @option opts [Symbol] :default
-
#
-
# Set a default value for the generated getter and predicate methods:
-
#
-
# add_setting(:foo, :default => "default value")
-
#
-
# @option opts [Symbol] :alias_with
-
#
-
# Use `:alias_with` to alias the setter, getter, and predicate to
-
# another name, or names:
-
#
-
# add_setting(:foo, :alias_with => :bar)
-
# add_setting(:foo, :alias_with => [:bar, :baz])
-
#
-
# Adds a custom setting to the RSpec.configuration object.
-
#
-
# RSpec.configuration.add_setting :foo
-
#
-
# Used internally and by extension frameworks like rspec-rails, so they
-
# can add config settings that are domain specific. For example:
-
#
-
# RSpec.configure do |c|
-
# c.add_setting :use_transactional_fixtures,
-
# :default => true,
-
# :alias_with => :use_transactional_examples
-
# end
-
#
-
# `add_setting` creates three methods on the configuration object, a
-
# setter, a getter, and a predicate:
-
#
-
# RSpec.configuration.foo=(value)
-
# RSpec.configuration.foo
-
# RSpec.configuration.foo? # Returns true if foo returns anything but nil or false.
-
1
def add_setting(name, opts={})
-
default = opts.delete(:default)
-
(class << self; self; end).class_exec do
-
add_setting(name, opts)
-
end
-
__send__("#{name}=", default) if default
-
end
-
-
# Returns the configured mock framework adapter module.
-
1
def mock_framework
-
if @mock_framework.nil?
-
begin
-
mock_with :rspec
-
rescue LoadError
-
mock_with :nothing
-
end
-
end
-
@mock_framework
-
end
-
-
# Delegates to mock_framework=(framework).
-
1
def mock_framework=(framework)
-
mock_with framework
-
end
-
-
# Regexps used to exclude lines from backtraces.
-
#
-
# Excludes lines from ruby (and jruby) source, installed gems, anything
-
# in any "bin" directory, and any of the RSpec libs (outside gem
-
# installs) by default.
-
#
-
# You can modify the list via the getter, or replace it with the setter.
-
#
-
# To override this behaviour and display a full backtrace, use
-
# `--backtrace` on the command line, in a `.rspec` file, or in the
-
# `rspec_options` attribute of RSpec's rake task.
-
1
def backtrace_exclusion_patterns
-
@backtrace_formatter.exclusion_patterns
-
end
-
-
# Set regular expressions used to exclude lines in backtrace.
-
# @param patterns [Regexp] set the backtrace exlusion pattern
-
1
def backtrace_exclusion_patterns=(patterns)
-
@backtrace_formatter.exclusion_patterns = patterns
-
end
-
-
# Regexps used to include lines in backtraces.
-
#
-
# Defaults to [Regexp.new Dir.getwd].
-
#
-
# Lines that match an exclusion _and_ an inclusion pattern
-
# will be included.
-
#
-
# You can modify the list via the getter, or replace it with the setter.
-
1
def backtrace_inclusion_patterns
-
@backtrace_formatter.inclusion_patterns
-
end
-
-
# Set regular expressions used to include lines in backtrace.
-
# @attr patterns [Regexp] set backtrace_formatter inclusion_patterns
-
1
def backtrace_inclusion_patterns=(patterns)
-
@backtrace_formatter.inclusion_patterns = patterns
-
end
-
-
# Adds {#backtrace_exclusion_patterns} that will filter lines from
-
# the named gems from backtraces.
-
#
-
# @param gem_names [Array<String>] Names of the gems to filter
-
#
-
# @example
-
# RSpec.configure do |config|
-
# config.filter_gems_from_backtrace "rack", "rake"
-
# end
-
#
-
# @note The patterns this adds will match the named gems in their common
-
# locations (e.g. system gems, vendored with bundler, installed as a
-
# :git dependency with bundler, etc) but is not guaranteed to work for
-
# all possible gem locations. For example, if you have the gem source
-
# in a directory with a completely unrelated name, and use bundler's
-
# :path option, this will not filter it.
-
1
def filter_gems_from_backtrace(*gem_names)
-
gem_names.each do |name|
-
@backtrace_formatter.filter_gem(name)
-
end
-
end
-
-
# @private
-
1
MOCKING_ADAPTERS = {
-
:rspec => :RSpec,
-
:flexmock => :Flexmock,
-
:rr => :RR,
-
:mocha => :Mocha,
-
:nothing => :Null
-
}
-
-
# Sets the mock framework adapter module.
-
#
-
# `framework` can be a Symbol or a Module.
-
#
-
# Given any of `:rspec`, `:mocha`, `:flexmock`, or `:rr`, configures the
-
# named framework.
-
#
-
# Given `:nothing`, configures no framework. Use this if you don't use
-
# any mocking framework to save a little bit of overhead.
-
#
-
# Given a Module, includes that module in every example group. The module
-
# should adhere to RSpec's mock framework adapter API:
-
#
-
# setup_mocks_for_rspec
-
# - called before each example
-
#
-
# verify_mocks_for_rspec
-
# - called after each example if the example hasn't yet failed.
-
# Framework should raise an exception when expectations fail
-
#
-
# teardown_mocks_for_rspec
-
# - called after verify_mocks_for_rspec (even if there are errors)
-
#
-
# If the module responds to `configuration` and `mock_with` receives a
-
# block, it will yield the configuration object to the block e.g.
-
#
-
# config.mock_with OtherMockFrameworkAdapter do |mod_config|
-
# mod_config.custom_setting = true
-
# end
-
1
def mock_with(framework)
-
framework_module =
-
if framework.is_a?(Module)
-
framework
-
else
-
const_name = MOCKING_ADAPTERS.fetch(framework) do
-
raise ArgumentError,
-
"Unknown mocking framework: #{framework.inspect}. " \
-
"Pass a module or one of #{MOCKING_ADAPTERS.keys.inspect}"
-
end
-
-
RSpec::Support.require_rspec_core "mocking_adapters/#{const_name.to_s.downcase}"
-
RSpec::Core::MockingAdapters.const_get(const_name)
-
end
-
-
new_name, old_name = [framework_module, @mock_framework].map do |mod|
-
mod.respond_to?(:framework_name) ? mod.framework_name : :unnamed
-
end
-
-
unless new_name == old_name
-
assert_no_example_groups_defined(:mock_framework)
-
end
-
-
if block_given?
-
raise "#{framework_module} must respond to `configuration` so that " \
-
"mock_with can yield it." unless framework_module.respond_to?(:configuration)
-
yield framework_module.configuration
-
end
-
-
@mock_framework = framework_module
-
end
-
-
# Returns the configured expectation framework adapter module(s)
-
1
def expectation_frameworks
-
if @expectation_frameworks.empty?
-
begin
-
expect_with :rspec
-
rescue LoadError
-
expect_with Module.new
-
end
-
end
-
@expectation_frameworks
-
end
-
-
# Delegates to expect_with(framework).
-
1
def expectation_framework=(framework)
-
expect_with(framework)
-
end
-
-
# Sets the expectation framework module(s) to be included in each example
-
# group.
-
#
-
# `frameworks` can be `:rspec`, `:test_unit`, `:minitest`, a custom
-
# module, or any combination thereof:
-
#
-
# config.expect_with :rspec
-
# config.expect_with :test_unit
-
# config.expect_with :minitest
-
# config.expect_with :rspec, :minitest
-
# config.expect_with OtherExpectationFramework
-
#
-
# RSpec will translate `:rspec`, `:minitest`, and `:test_unit` into the
-
# appropriate modules.
-
#
-
# ## Configuration
-
#
-
# If the module responds to `configuration`, `expect_with` will
-
# yield the `configuration` object if given a block:
-
#
-
# config.expect_with OtherExpectationFramework do |custom_config|
-
# custom_config.custom_setting = true
-
# end
-
1
def expect_with(*frameworks)
-
modules = frameworks.map do |framework|
-
case framework
-
when Module
-
framework
-
when :rspec
-
require 'rspec/expectations'
-
-
# Tag this exception class so our exception formatting logic knows
-
# that it satisfies the `MultipleExceptionError` interface.
-
::RSpec::Expectations::MultipleExpectationsNotMetError.__send__(
-
:include, MultipleExceptionError::InterfaceTag
-
)
-
-
::RSpec::Matchers
-
when :test_unit
-
require 'rspec/core/test_unit_assertions_adapter'
-
::RSpec::Core::TestUnitAssertionsAdapter
-
when :minitest
-
require 'rspec/core/minitest_assertions_adapter'
-
::RSpec::Core::MinitestAssertionsAdapter
-
else
-
raise ArgumentError, "#{framework.inspect} is not supported"
-
end
-
end
-
-
if (modules - @expectation_frameworks).any?
-
assert_no_example_groups_defined(:expect_with)
-
end
-
-
if block_given?
-
raise "expect_with only accepts a block with a single argument. " \
-
"Call expect_with #{modules.length} times, " \
-
"once with each argument, instead." if modules.length > 1
-
raise "#{modules.first} must respond to `configuration` so that " \
-
"expect_with can yield it." unless modules.first.respond_to?(:configuration)
-
yield modules.first.configuration
-
end
-
-
@expectation_frameworks.push(*modules)
-
end
-
-
# Check if full backtrace is enabled.
-
# @return [Boolean] is full backtrace enabled
-
1
def full_backtrace?
-
@backtrace_formatter.full_backtrace?
-
end
-
-
# Toggle full backtrace.
-
# @attr true_or_false [Boolean] toggle full backtrace display
-
1
def full_backtrace=(true_or_false)
-
@backtrace_formatter.full_backtrace = true_or_false
-
end
-
-
# Returns the configuration option for color, but should not
-
# be used to check if color is supported.
-
#
-
# @see color_enabled?
-
# @return [Boolean]
-
1
def color
-
value_for(:color) { @color }
-
end
-
-
# Check if color is enabled for a particular output.
-
# @param output [IO] an output stream to use, defaults to the current
-
# `output_stream`
-
# @return [Boolean]
-
1
def color_enabled?(output=output_stream)
-
output_to_tty?(output) && color
-
end
-
-
# Toggle output color.
-
1
attr_writer :color
-
-
# @private
-
1
def libs=(libs)
-
libs.map do |lib|
-
@libs.unshift lib
-
$LOAD_PATH.unshift lib
-
end
-
end
-
-
# Run examples matching on `description` in all files to run.
-
# @param description [String, Regexp] the pattern to filter on
-
1
def full_description=(description)
-
filter_run :full_description => Regexp.union(*Array(description).map { |d| Regexp.new(d) })
-
end
-
-
# @return [Array] full description filter
-
1
def full_description
-
filter.fetch :full_description, nil
-
end
-
-
# @overload add_formatter(formatter)
-
#
-
# Adds a formatter to the formatters collection. `formatter` can be a
-
# string representing any of the built-in formatters (see
-
# `built_in_formatter`), or a custom formatter class.
-
#
-
# ### Note
-
#
-
# For internal purposes, `add_formatter` also accepts the name of a class
-
# and paths to use for output streams, but you should consider that a
-
# private api that may change at any time without notice.
-
1
def add_formatter(formatter_to_use, *paths)
-
paths << output_stream if paths.empty?
-
formatter_loader.add formatter_to_use, *paths
-
end
-
1
alias_method :formatter=, :add_formatter
-
-
# The formatter that will be used if no formatter has been set.
-
# Defaults to 'progress'.
-
1
def default_formatter
-
formatter_loader.default_formatter
-
end
-
-
# Sets a fallback formatter to use if none other has been set.
-
#
-
# @example
-
#
-
# RSpec.configure do |rspec|
-
# rspec.default_formatter = 'doc'
-
# end
-
1
def default_formatter=(value)
-
formatter_loader.default_formatter = value
-
end
-
-
# Returns a duplicate of the formatters currently loaded in
-
# the `FormatterLoader` for introspection.
-
#
-
# Note as this is a duplicate, any mutations will be disregarded.
-
#
-
# @return [Array] the formatters currently loaded
-
1
def formatters
-
formatter_loader.formatters.dup
-
end
-
-
# @private
-
1
def formatter_loader
-
@formatter_loader ||= Formatters::Loader.new(Reporter.new(self))
-
end
-
-
# @private
-
#
-
# This buffer is used to capture all messages sent to the reporter during
-
# reporter initialization. It can then replay those messages after the
-
# formatter is correctly initialized. Otherwise, deprecation warnings
-
# during formatter initialization can cause an infinite loop.
-
1
class DeprecationReporterBuffer
-
1
def initialize
-
@calls = []
-
end
-
-
1
def deprecation(*args)
-
@calls << args
-
end
-
-
1
def play_onto(reporter)
-
@calls.each do |args|
-
reporter.deprecation(*args)
-
end
-
end
-
end
-
-
# @private
-
1
def reporter
-
# @reporter_buffer should only ever be set in this method to cover
-
# initialization of @reporter.
-
@reporter_buffer || @reporter ||=
-
begin
-
@reporter_buffer = DeprecationReporterBuffer.new
-
formatter_loader.setup_default output_stream, deprecation_stream
-
@reporter_buffer.play_onto(formatter_loader.reporter)
-
@reporter_buffer = nil
-
formatter_loader.reporter
-
end
-
end
-
-
# @api private
-
#
-
# Defaults `profile_examples` to 10 examples when `@profile_examples` is
-
# `true`.
-
1
def profile_examples
-
profile = value_for(:profile_examples) { @profile_examples }
-
if profile && !profile.is_a?(Integer)
-
10
-
else
-
profile
-
end
-
end
-
-
# @private
-
1
def files_or_directories_to_run=(*files)
-
files = files.flatten
-
-
if (command == 'rspec' || Runner.running_in_drb?) && default_path && files.empty?
-
files << default_path
-
end
-
-
@files_or_directories_to_run = files
-
@files_to_run = nil
-
end
-
-
# The spec files RSpec will run.
-
# @return [Array] specified files about to run
-
1
def files_to_run
-
@files_to_run ||= get_files_to_run(@files_or_directories_to_run)
-
end
-
-
# @private
-
1
def last_run_statuses
-
@last_run_statuses ||= Hash.new(UNKNOWN_STATUS).tap do |statuses|
-
if (path = example_status_persistence_file_path)
-
begin
-
ExampleStatusPersister.load_from(path).inject(statuses) do |hash, example|
-
hash[example.fetch(:example_id)] = example.fetch(:status)
-
hash
-
end
-
rescue SystemCallError => e
-
RSpec.warning "Could not read from #{path.inspect} (configured as " \
-
"`config.example_status_persistence_file_path`) due " \
-
"to a system error: #{e.inspect}. Please check that " \
-
"the config option is set to an accessible, valid " \
-
"file path", :call_site => nil
-
end
-
end
-
end
-
end
-
-
# @private
-
1
UNKNOWN_STATUS = "unknown".freeze
-
-
# @private
-
1
FAILED_STATUS = "failed".freeze
-
-
# @private
-
1
def spec_files_with_failures
-
@spec_files_with_failures ||= last_run_statuses.inject(Set.new) do |files, (id, status)|
-
files << Example.parse_id(id).first if status == FAILED_STATUS
-
files
-
end.to_a
-
end
-
-
# Creates a method that delegates to `example` including the submitted
-
# `args`. Used internally to add variants of `example` like `pending`:
-
# @param name [String] example name alias
-
# @param args [Array<Symbol>, Hash] metadata for the generated example
-
#
-
# @note The specific example alias below (`pending`) is already
-
# defined for you.
-
# @note Use with caution. This extends the language used in your
-
# specs, but does not add any additional documentation. We use this
-
# in RSpec to define methods like `focus` and `xit`, but we also add
-
# docs for those methods.
-
#
-
# @example
-
# RSpec.configure do |config|
-
# config.alias_example_to :pending, :pending => true
-
# end
-
#
-
# # This lets you do this:
-
#
-
# describe Thing do
-
# pending "does something" do
-
# thing = Thing.new
-
# end
-
# end
-
#
-
# # ... which is the equivalent of
-
#
-
# describe Thing do
-
# it "does something", :pending => true do
-
# thing = Thing.new
-
# end
-
# end
-
1
def alias_example_to(name, *args)
-
extra_options = Metadata.build_hash_from(args)
-
RSpec::Core::ExampleGroup.define_example_method(name, extra_options)
-
end
-
-
# Creates a method that defines an example group with the provided
-
# metadata. Can be used to define example group/metadata shortcuts.
-
#
-
# @example
-
# RSpec.configure do |config|
-
# config.alias_example_group_to :describe_model, :type => :model
-
# end
-
#
-
# shared_context_for "model tests", :type => :model do
-
# # define common model test helper methods, `let` declarations, etc
-
# end
-
#
-
# # This lets you do this:
-
#
-
# RSpec.describe_model User do
-
# end
-
#
-
# # ... which is the equivalent of
-
#
-
# RSpec.describe User, :type => :model do
-
# end
-
#
-
# @note The defined aliased will also be added to the top level
-
# (e.g. `main` and from within modules) if
-
# `expose_dsl_globally` is set to true.
-
# @see #alias_example_to
-
# @see #expose_dsl_globally=
-
1
def alias_example_group_to(new_name, *args)
-
extra_options = Metadata.build_hash_from(args)
-
RSpec::Core::ExampleGroup.define_example_group_method(new_name, extra_options)
-
end
-
-
# Define an alias for it_should_behave_like that allows different
-
# language (like "it_has_behavior" or "it_behaves_like") to be
-
# employed when including shared examples.
-
#
-
# @example
-
# RSpec.configure do |config|
-
# config.alias_it_behaves_like_to(:it_has_behavior, 'has behavior:')
-
# end
-
#
-
# # allows the user to include a shared example group like:
-
#
-
# describe Entity do
-
# it_has_behavior 'sortability' do
-
# let(:sortable) { Entity.new }
-
# end
-
# end
-
#
-
# # which is reported in the output as:
-
# # Entity
-
# # has behavior: sortability
-
# # ...sortability examples here
-
#
-
# @note Use with caution. This extends the language used in your
-
# specs, but does not add any additional documentation. We use this
-
# in RSpec to define `it_should_behave_like` (for backward
-
# compatibility), but we also add docs for that method.
-
1
def alias_it_behaves_like_to(new_name, report_label='')
-
RSpec::Core::ExampleGroup.define_nested_shared_group_method(new_name, report_label)
-
end
-
1
alias_method :alias_it_should_behave_like_to, :alias_it_behaves_like_to
-
-
# Adds key/value pairs to the `inclusion_filter`. If `args`
-
# includes any symbols that are not part of the hash, each symbol
-
# is treated as a key in the hash with the value `true`.
-
#
-
# ### Note
-
#
-
# Filters set using this method can be overridden from the command line
-
# or config files (e.g. `.rspec`).
-
#
-
# @example
-
# # Given this declaration.
-
# describe "something", :foo => 'bar' do
-
# # ...
-
# end
-
#
-
# # Any of the following will include that group.
-
# config.filter_run_including :foo => 'bar'
-
# config.filter_run_including :foo => /^ba/
-
# config.filter_run_including :foo => lambda {|v| v == 'bar'}
-
# config.filter_run_including :foo => lambda {|v,m| m[:foo] == 'bar'}
-
#
-
# # Given a proc with an arity of 1, the lambda is passed the value
-
# # related to the key, e.g.
-
# config.filter_run_including :foo => lambda {|v| v == 'bar'}
-
#
-
# # Given a proc with an arity of 2, the lambda is passed the value
-
# # related to the key, and the metadata itself e.g.
-
# config.filter_run_including :foo => lambda {|v,m| m[:foo] == 'bar'}
-
#
-
# filter_run_including :foo # same as filter_run_including :foo => true
-
1
def filter_run_including(*args)
-
meta = Metadata.build_hash_from(args, :warn_about_example_group_filtering)
-
filter_manager.include_with_low_priority meta
-
static_config_filter_manager.include_with_low_priority Metadata.deep_hash_dup(meta)
-
end
-
-
1
alias_method :filter_run, :filter_run_including
-
-
# Clears and reassigns the `inclusion_filter`. Set to `nil` if you don't
-
# want any inclusion filter at all.
-
#
-
# ### Warning
-
#
-
# This overrides any inclusion filters/tags set on the command line or in
-
# configuration files.
-
1
def inclusion_filter=(filter)
-
meta = Metadata.build_hash_from([filter], :warn_about_example_group_filtering)
-
filter_manager.include_only meta
-
end
-
-
1
alias_method :filter=, :inclusion_filter=
-
-
# Returns the `inclusion_filter`. If none has been set, returns an empty
-
# hash.
-
1
def inclusion_filter
-
filter_manager.inclusions
-
end
-
-
1
alias_method :filter, :inclusion_filter
-
-
# Adds key/value pairs to the `exclusion_filter`. If `args`
-
# includes any symbols that are not part of the hash, each symbol
-
# is treated as a key in the hash with the value `true`.
-
#
-
# ### Note
-
#
-
# Filters set using this method can be overridden from the command line
-
# or config files (e.g. `.rspec`).
-
#
-
# @example
-
# # Given this declaration.
-
# describe "something", :foo => 'bar' do
-
# # ...
-
# end
-
#
-
# # Any of the following will exclude that group.
-
# config.filter_run_excluding :foo => 'bar'
-
# config.filter_run_excluding :foo => /^ba/
-
# config.filter_run_excluding :foo => lambda {|v| v == 'bar'}
-
# config.filter_run_excluding :foo => lambda {|v,m| m[:foo] == 'bar'}
-
#
-
# # Given a proc with an arity of 1, the lambda is passed the value
-
# # related to the key, e.g.
-
# config.filter_run_excluding :foo => lambda {|v| v == 'bar'}
-
#
-
# # Given a proc with an arity of 2, the lambda is passed the value
-
# # related to the key, and the metadata itself e.g.
-
# config.filter_run_excluding :foo => lambda {|v,m| m[:foo] == 'bar'}
-
#
-
# filter_run_excluding :foo # same as filter_run_excluding :foo => true
-
1
def filter_run_excluding(*args)
-
meta = Metadata.build_hash_from(args, :warn_about_example_group_filtering)
-
filter_manager.exclude_with_low_priority meta
-
static_config_filter_manager.exclude_with_low_priority Metadata.deep_hash_dup(meta)
-
end
-
-
# Clears and reassigns the `exclusion_filter`. Set to `nil` if you don't
-
# want any exclusion filter at all.
-
#
-
# ### Warning
-
#
-
# This overrides any exclusion filters/tags set on the command line or in
-
# configuration files.
-
1
def exclusion_filter=(filter)
-
meta = Metadata.build_hash_from([filter], :warn_about_example_group_filtering)
-
filter_manager.exclude_only meta
-
end
-
-
# Returns the `exclusion_filter`. If none has been set, returns an empty
-
# hash.
-
1
def exclusion_filter
-
filter_manager.exclusions
-
end
-
-
# Tells RSpec to include `mod` in example groups. Methods defined in
-
# `mod` are exposed to examples (not example groups). Use `filters` to
-
# constrain the groups or examples in which to include the module.
-
#
-
# @example
-
#
-
# module AuthenticationHelpers
-
# def login_as(user)
-
# # ...
-
# end
-
# end
-
#
-
# module UserHelpers
-
# def users(username)
-
# # ...
-
# end
-
# end
-
#
-
# RSpec.configure do |config|
-
# config.include(UserHelpers) # included in all modules
-
# config.include(AuthenticationHelpers, :type => :request)
-
# end
-
#
-
# describe "edit profile", :type => :request do
-
# it "can be viewed by owning user" do
-
# login_as users(:jdoe)
-
# get "/profiles/jdoe"
-
# assert_select ".username", :text => 'jdoe'
-
# end
-
# end
-
#
-
# @note Filtered module inclusions can also be applied to
-
# individual examples that have matching metadata. Just like
-
# Ruby's object model is that every object has a singleton class
-
# which has only a single instance, RSpec's model is that every
-
# example has a singleton example group containing just the one
-
# example.
-
#
-
# @see #extend
-
# @see #prepend
-
1
def include(mod, *filters)
-
meta = Metadata.build_hash_from(filters, :warn_about_example_group_filtering)
-
@include_modules.append(mod, meta)
-
configure_existing_groups(mod, meta, :safe_include)
-
end
-
-
# Tells RSpec to extend example groups with `mod`. Methods defined in
-
# `mod` are exposed to example groups (not examples). Use `filters` to
-
# constrain the groups to extend.
-
#
-
# Similar to `include`, but behavior is added to example groups, which
-
# are classes, rather than the examples, which are instances of those
-
# classes.
-
#
-
# @example
-
#
-
# module UiHelpers
-
# def run_in_browser
-
# # ...
-
# end
-
# end
-
#
-
# RSpec.configure do |config|
-
# config.extend(UiHelpers, :type => :request)
-
# end
-
#
-
# describe "edit profile", :type => :request do
-
# run_in_browser
-
#
-
# it "does stuff in the client" do
-
# # ...
-
# end
-
# end
-
#
-
# @see #include
-
# @see #prepend
-
1
def extend(mod, *filters)
-
1
meta = Metadata.build_hash_from(filters, :warn_about_example_group_filtering)
-
1
@extend_modules.append(mod, meta)
-
1
configure_existing_groups(mod, meta, :safe_extend)
-
end
-
-
1
if RSpec::Support::RubyFeatures.module_prepends_supported?
-
# Tells RSpec to prepend example groups with `mod`. Methods defined in
-
# `mod` are exposed to examples (not example groups). Use `filters` to
-
# constrain the groups in which to prepend the module.
-
#
-
# Similar to `include`, but module is included before the example group's class
-
# in the ancestor chain.
-
#
-
# @example
-
#
-
# module OverrideMod
-
# def override_me
-
# "overridden"
-
# end
-
# end
-
#
-
# RSpec.configure do |config|
-
# config.prepend(OverrideMod, :method => :prepend)
-
# end
-
#
-
# describe "overriding example's class", :method => :prepend do
-
# it "finds the user" do
-
# self.class.class_eval do
-
# def override_me
-
# end
-
# end
-
# override_me # => "overridden"
-
# # ...
-
# end
-
# end
-
#
-
# @see #include
-
# @see #extend
-
1
def prepend(mod, *filters)
-
meta = Metadata.build_hash_from(filters, :warn_about_example_group_filtering)
-
@prepend_modules.append(mod, meta)
-
configure_existing_groups(mod, meta, :safe_prepend)
-
end
-
end
-
-
# @private
-
#
-
# Used internally to extend a group with modules using `include`, `prepend` and/or
-
# `extend`.
-
1
def configure_group(group)
-
configure_group_with group, @include_modules, :safe_include
-
configure_group_with group, @extend_modules, :safe_extend
-
configure_group_with group, @prepend_modules, :safe_prepend
-
end
-
-
# @private
-
1
def configure_group_with(group, module_list, application_method)
-
module_list.items_for(group.metadata).each do |mod|
-
__send__(application_method, mod, group)
-
end
-
end
-
-
# @private
-
1
def configure_existing_groups(mod, meta, application_method)
-
1
RSpec.world.all_example_groups.each do |group|
-
next unless meta.empty? || MetadataFilter.apply?(:any?, meta, group.metadata)
-
__send__(application_method, mod, group)
-
end
-
end
-
-
# @private
-
#
-
# Used internally to extend the singleton class of a single example's
-
# example group instance with modules using `include` and/or `extend`.
-
1
def configure_example(example)
-
singleton_group = example.example_group_instance.singleton_class
-
-
# We replace the metadata so that SharedExampleGroupModule#included
-
# has access to the example's metadata[:location].
-
singleton_group.with_replaced_metadata(example.metadata) do
-
modules = @include_modules.items_for(example.metadata)
-
modules.each do |mod|
-
safe_include(mod, example.example_group_instance.singleton_class)
-
end
-
-
MemoizedHelpers.define_helpers_on(singleton_group) unless modules.empty?
-
end
-
end
-
-
1
if RSpec::Support::RubyFeatures.module_prepends_supported?
-
# @private
-
1
def safe_prepend(mod, host)
-
host.__send__(:prepend, mod) unless host < mod
-
end
-
end
-
-
# @private
-
1
def requires=(paths)
-
directories = ['lib', default_path].select { |p| File.directory? p }
-
RSpec::Core::RubyProject.add_to_load_path(*directories)
-
paths.each { |path| require path }
-
@requires += paths
-
end
-
-
# @private
-
1
def in_project_source_dir_regex
-
regexes = project_source_dirs.map do |dir|
-
/\A#{Regexp.escape(File.expand_path(dir))}\//
-
end
-
-
Regexp.union(regexes)
-
end
-
-
# @private
-
1
if RUBY_VERSION.to_f >= 1.9
-
# @private
-
1
def safe_include(mod, host)
-
host.__send__(:include, mod) unless host < mod
-
end
-
-
# @private
-
1
def safe_extend(mod, host)
-
host.extend(mod) unless host.singleton_class < mod
-
end
-
else # for 1.8.7
-
# :nocov:
-
skipped
# @private
-
skipped
def safe_include(mod, host)
-
skipped
host.__send__(:include, mod) unless host.included_modules.include?(mod)
-
skipped
end
-
skipped
-
skipped
# @private
-
skipped
def safe_extend(mod, host)
-
skipped
host.extend(mod) unless (class << host; self; end).included_modules.include?(mod)
-
skipped
end
-
# :nocov:
-
end
-
-
# @private
-
1
def configure_mock_framework
-
RSpec::Core::ExampleGroup.__send__(:include, mock_framework)
-
conditionally_disable_mocks_monkey_patching
-
end
-
-
# @private
-
1
def configure_expectation_framework
-
expectation_frameworks.each do |framework|
-
RSpec::Core::ExampleGroup.__send__(:include, framework)
-
end
-
conditionally_disable_expectations_monkey_patching
-
end
-
-
# @private
-
1
def load_spec_files
-
# Note which spec files world is already aware of.
-
# This is generally only needed for when the user runs
-
# `ruby path/to/spec.rb` (and loads `rspec/autorun`) --
-
# in that case, the spec file was loaded by `ruby` and
-
# isn't loaded by us here so we only know about it because
-
# of an example group being registered in it.
-
RSpec.world.registered_example_group_files.each do |f|
-
loaded_spec_files << f # the registered files are already expended absolute paths
-
end
-
-
files_to_run.uniq.each do |f|
-
file = File.expand_path(f)
-
load file
-
loaded_spec_files << file
-
end
-
-
@spec_files_loaded = true
-
end
-
-
# @private
-
1
DEFAULT_FORMATTER = lambda { |string| string }
-
-
# Formats the docstring output using the block provided.
-
#
-
# @example
-
# # This will strip the descriptions of both examples and example
-
# # groups.
-
# RSpec.configure do |config|
-
# config.format_docstrings { |s| s.strip }
-
# end
-
1
def format_docstrings(&block)
-
@format_docstrings_block = block_given? ? block : DEFAULT_FORMATTER
-
end
-
-
# @private
-
1
def format_docstrings_block
-
@format_docstrings_block ||= DEFAULT_FORMATTER
-
end
-
-
# @private
-
# @macro [attach] delegate_to_ordering_manager
-
# @!method $1
-
1
def self.delegate_to_ordering_manager(*methods)
-
5
methods.each do |method|
-
6
define_method method do |*args, &block|
-
ordering_manager.__send__(method, *args, &block)
-
end
-
end
-
end
-
-
# @macro delegate_to_ordering_manager
-
#
-
# Sets the seed value and sets the default global ordering to random.
-
1
delegate_to_ordering_manager :seed=
-
-
# @macro delegate_to_ordering_manager
-
# Seed for random ordering (default: generated randomly each run).
-
#
-
# When you run specs with `--order random`, RSpec generates a random seed
-
# for the randomization and prints it to the `output_stream` (assuming
-
# you're using RSpec's built-in formatters). If you discover an ordering
-
# dependency (i.e. examples fail intermittently depending on order), set
-
# this (on Configuration or on the command line with `--seed`) to run
-
# using the same seed while you debug the issue.
-
#
-
# We recommend, actually, that you use the command line approach so you
-
# don't accidentally leave the seed encoded.
-
1
delegate_to_ordering_manager :seed
-
-
# @macro delegate_to_ordering_manager
-
#
-
# Sets the default global order and, if order is `'rand:<seed>'`, also
-
# sets the seed.
-
1
delegate_to_ordering_manager :order=
-
-
# @macro delegate_to_ordering_manager
-
# Registers a named ordering strategy that can later be
-
# used to order an example group's subgroups by adding
-
# `:order => <name>` metadata to the example group.
-
#
-
# @param name [Symbol] The name of the ordering.
-
# @yield Block that will order the given examples or example groups
-
# @yieldparam list [Array<RSpec::Core::Example>,
-
# Array<RSpec::Core::ExampleGroup>] The examples or groups to order
-
# @yieldreturn [Array<RSpec::Core::Example>,
-
# Array<RSpec::Core::ExampleGroup>] The re-ordered examples or groups
-
#
-
# @example
-
# RSpec.configure do |rspec|
-
# rspec.register_ordering :reverse do |list|
-
# list.reverse
-
# end
-
# end
-
#
-
# describe MyClass, :order => :reverse do
-
# # ...
-
# end
-
#
-
# @note Pass the symbol `:global` to set the ordering strategy that
-
# will be used to order the top-level example groups and any example
-
# groups that do not have declared `:order` metadata.
-
1
delegate_to_ordering_manager :register_ordering
-
-
# @private
-
1
delegate_to_ordering_manager :seed_used?, :ordering_registry
-
-
# Set Ruby warnings on or off.
-
1
def warnings=(value)
-
$VERBOSE = !!value
-
end
-
-
# @return [Boolean] Whether or not ruby warnings are enabled.
-
1
def warnings?
-
$VERBOSE
-
end
-
-
# @private
-
1
RAISE_ERROR_WARNING_NOTIFIER = lambda { |message| raise message }
-
-
# Turns warnings into errors. This can be useful when
-
# you want RSpec to run in a 'strict' no warning situation.
-
#
-
# @example
-
#
-
# RSpec.configure do |rspec|
-
# rspec.raise_on_warning = true
-
# end
-
1
def raise_on_warning=(value)
-
if value
-
RSpec::Support.warning_notifier = RAISE_ERROR_WARNING_NOTIFIER
-
else
-
RSpec::Support.warning_notifier = RSpec::Support::DEFAULT_WARNING_NOTIFIER
-
end
-
end
-
-
# Exposes the current running example via the named
-
# helper method. RSpec 2.x exposed this via `example`,
-
# but in RSpec 3.0, the example is instead exposed via
-
# an arg yielded to `it`, `before`, `let`, etc. However,
-
# some extension gems (such as Capybara) depend on the
-
# RSpec 2.x's `example` method, so this config option
-
# can be used to maintain compatibility.
-
#
-
# @param method_name [Symbol] the name of the helper method
-
#
-
# @example
-
#
-
# RSpec.configure do |rspec|
-
# rspec.expose_current_running_example_as :example
-
# end
-
#
-
# describe MyClass do
-
# before do
-
# # `example` can be used here because of the above config.
-
# do_something if example.metadata[:type] == "foo"
-
# end
-
# end
-
1
def expose_current_running_example_as(method_name)
-
ExposeCurrentExample.module_exec do
-
extend RSpec::SharedContext
-
let(method_name) { |ex| ex }
-
end
-
-
include ExposeCurrentExample
-
end
-
-
# @private
-
1
module ExposeCurrentExample; end
-
-
# Turns deprecation warnings into errors, in order to surface
-
# the full backtrace of the call site. This can be useful when
-
# you need more context to address a deprecation than the
-
# single-line call site normally provided.
-
#
-
# @example
-
#
-
# RSpec.configure do |rspec|
-
# rspec.raise_errors_for_deprecations!
-
# end
-
1
def raise_errors_for_deprecations!
-
self.deprecation_stream = Formatters::DeprecationFormatter::RaiseErrorStream.new
-
end
-
-
# Enables zero monkey patching mode for RSpec. It removes monkey
-
# patching of the top-level DSL methods (`describe`,
-
# `shared_examples_for`, etc) onto `main` and `Module`, instead
-
# requiring you to prefix these methods with `RSpec.`. It enables
-
# expect-only syntax for rspec-mocks and rspec-expectations. It
-
# simply disables monkey patching on whatever pieces of RSpec
-
# the user is using.
-
#
-
# @note It configures rspec-mocks and rspec-expectations only
-
# if the user is using those (either explicitly or implicitly
-
# by not setting `mock_with` or `expect_with` to anything else).
-
#
-
# @note If the user uses this options with `mock_with :mocha`
-
# (or similiar) they will still have monkey patching active
-
# in their test environment from mocha.
-
#
-
# @example
-
#
-
# # It disables all monkey patching.
-
# RSpec.configure do |config|
-
# config.disable_monkey_patching!
-
# end
-
#
-
# # Is an equivalent to
-
# RSpec.configure do |config|
-
# config.expose_dsl_globally = false
-
#
-
# config.mock_with :rspec do |mocks|
-
# mocks.syntax = :expect
-
# mocks.patch_marshal_to_support_partial_doubles = false
-
# end
-
#
-
# config.mock_with :rspec do |expectations|
-
# expectations.syntax = :expect
-
# end
-
# end
-
1
def disable_monkey_patching!
-
self.expose_dsl_globally = false
-
self.disable_monkey_patching = true
-
conditionally_disable_mocks_monkey_patching
-
conditionally_disable_expectations_monkey_patching
-
end
-
-
# @private
-
1
attr_accessor :disable_monkey_patching
-
-
# Defines a callback that can assign derived metadata values.
-
#
-
# @param filters [Array<Symbol>, Hash] metadata filters that determine
-
# which example or group metadata hashes the callback will be triggered
-
# for. If none are given, the callback will be run against the metadata
-
# hashes of all groups and examples.
-
# @yieldparam metadata [Hash] original metadata hash from an example or
-
# group. Mutate this in your block as needed.
-
#
-
# @example
-
# RSpec.configure do |config|
-
# # Tag all groups and examples in the spec/unit directory with
-
# # :type => :unit
-
# config.define_derived_metadata(:file_path => %r{/spec/unit/}) do |metadata|
-
# metadata[:type] = :unit
-
# end
-
# end
-
1
def define_derived_metadata(*filters, &block)
-
meta = Metadata.build_hash_from(filters, :warn_about_example_group_filtering)
-
@derived_metadata_blocks.append(block, meta)
-
end
-
-
# @private
-
1
def apply_derived_metadata_to(metadata)
-
@derived_metadata_blocks.items_for(metadata).each do |block|
-
block.call(metadata)
-
end
-
end
-
-
# Defines a `before` hook. See {Hooks#before} for full docs.
-
#
-
# This method differs from {Hooks#before} in only one way: it supports
-
# the `:suite` scope. Hooks with the `:suite` scope will be run once before
-
# the first example of the entire suite is executed.
-
#
-
# @see #prepend_before
-
# @see #after
-
# @see #append_after
-
1
def before(*args, &block)
-
handle_suite_hook(args, @before_suite_hooks, :push,
-
Hooks::BeforeHook, block) || super(*args, &block)
-
end
-
1
alias_method :append_before, :before
-
-
# Adds `block` to the start of the list of `before` blocks in the same
-
# scope (`:example`, `:context`, or `:suite`), in contrast to {#before},
-
# which adds the hook to the end of the list.
-
#
-
# See {Hooks#before} for full `before` hook docs.
-
#
-
# This method differs from {Hooks#prepend_before} in only one way: it supports
-
# the `:suite` scope. Hooks with the `:suite` scope will be run once before
-
# the first example of the entire suite is executed.
-
#
-
# @see #before
-
# @see #after
-
# @see #append_after
-
1
def prepend_before(*args, &block)
-
handle_suite_hook(args, @before_suite_hooks, :unshift,
-
Hooks::BeforeHook, block) || super(*args, &block)
-
end
-
-
# Defines a `after` hook. See {Hooks#after} for full docs.
-
#
-
# This method differs from {Hooks#after} in only one way: it supports
-
# the `:suite` scope. Hooks with the `:suite` scope will be run once after
-
# the last example of the entire suite is executed.
-
#
-
# @see #append_after
-
# @see #before
-
# @see #prepend_before
-
1
def after(*args, &block)
-
handle_suite_hook(args, @after_suite_hooks, :unshift,
-
Hooks::AfterHook, block) || super(*args, &block)
-
end
-
1
alias_method :prepend_after, :after
-
-
# Adds `block` to the end of the list of `after` blocks in the same
-
# scope (`:example`, `:context`, or `:suite`), in contrast to {#after},
-
# which adds the hook to the start of the list.
-
#
-
# See {Hooks#after} for full `after` hook docs.
-
#
-
# This method differs from {Hooks#append_after} in only one way: it supports
-
# the `:suite` scope. Hooks with the `:suite` scope will be run once after
-
# the last example of the entire suite is executed.
-
#
-
# @see #append_after
-
# @see #before
-
# @see #prepend_before
-
1
def append_after(*args, &block)
-
handle_suite_hook(args, @after_suite_hooks, :push,
-
Hooks::AfterHook, block) || super(*args, &block)
-
end
-
-
# @private
-
1
def with_suite_hooks
-
return yield if dry_run?
-
-
hook_context = SuiteHookContext.new
-
begin
-
run_hooks_with(@before_suite_hooks, hook_context)
-
yield
-
ensure
-
run_hooks_with(@after_suite_hooks, hook_context)
-
end
-
end
-
-
# @private
-
# Holds the various registered hooks. Here we use a FilterableItemRepository
-
# implementation that is specifically optimized for the read/write patterns
-
# of the config object.
-
1
def hooks
-
1
@hooks ||= HookCollections.new(self, FilterableItemRepository::QueryOptimized)
-
end
-
-
# Invokes block before defining an example group
-
1
def on_example_group_definition(&block)
-
on_example_group_definition_callbacks << block
-
end
-
-
# @api private
-
# Returns an array of blocks to call before defining an example group
-
1
def on_example_group_definition_callbacks
-
@on_example_group_definition_callbacks ||= []
-
end
-
-
1
private
-
-
1
def handle_suite_hook(args, collection, append_or_prepend, hook_type, block)
-
scope, meta = *args
-
return nil unless scope == :suite
-
-
if meta
-
# TODO: in RSpec 4, consider raising an error here.
-
# We warn only for backwards compatibility.
-
RSpec.warn_with "WARNING: `:suite` hooks do not support metadata since " \
-
"they apply to the suite as a whole rather than " \
-
"any individual example or example group that has metadata. " \
-
"The metadata you have provided (#{meta.inspect}) will be ignored."
-
end
-
-
collection.__send__(append_or_prepend, hook_type.new(block, {}))
-
end
-
-
1
def run_hooks_with(hooks, hook_context)
-
hooks.each { |h| h.run(hook_context) }
-
end
-
-
1
def get_files_to_run(paths)
-
files = FlatMap.flat_map(paths_to_check(paths)) do |path|
-
path = path.gsub(File::ALT_SEPARATOR, File::SEPARATOR) if File::ALT_SEPARATOR
-
File.directory?(path) ? gather_directories(path) : extract_location(path)
-
end.sort.uniq
-
-
return files unless only_failures?
-
relative_files = files.map { |f| Metadata.relative_path(File.expand_path f) }
-
intersection = (relative_files & spec_files_with_failures.to_a)
-
intersection.empty? ? files : intersection
-
end
-
-
1
def paths_to_check(paths)
-
return paths if pattern_might_load_specs_from_vendored_dirs?
-
paths + [Dir.getwd]
-
end
-
-
1
def pattern_might_load_specs_from_vendored_dirs?
-
pattern.split(File::SEPARATOR).first.include?('**')
-
end
-
-
1
def gather_directories(path)
-
include_files = get_matching_files(path, pattern)
-
exclude_files = get_matching_files(path, exclude_pattern)
-
(include_files - exclude_files).sort.uniq
-
end
-
-
1
def get_matching_files(path, pattern)
-
Dir[file_glob_from(path, pattern)].map { |file| File.expand_path(file) }
-
end
-
-
1
def file_glob_from(path, pattern)
-
stripped = "{#{pattern.gsub(/\s*,\s*/, ',')}}"
-
return stripped if pattern =~ /^(\.\/)?#{Regexp.escape path}/ || absolute_pattern?(pattern)
-
File.join(path, stripped)
-
end
-
-
1
if RSpec::Support::OS.windows?
-
# :nocov:
-
skipped
def absolute_pattern?(pattern)
-
skipped
pattern =~ /\A[A-Z]:\\/ || windows_absolute_network_path?(pattern)
-
skipped
end
-
skipped
-
skipped
def windows_absolute_network_path?(pattern)
-
skipped
return false unless ::File::ALT_SEPARATOR
-
skipped
pattern.start_with?(::File::ALT_SEPARATOR + ::File::ALT_SEPARATOR)
-
skipped
end
-
# :nocov:
-
else
-
1
def absolute_pattern?(pattern)
-
pattern.start_with?(File::Separator)
-
end
-
end
-
-
1
def extract_location(path)
-
match = /^(.*?)((?:\:\d+)+)$/.match(path)
-
-
if match
-
captures = match.captures
-
path = captures[0]
-
lines = captures[1][1..-1].split(":").map(&:to_i)
-
filter_manager.add_location path, lines
-
else
-
path, scoped_ids = Example.parse_id(path)
-
filter_manager.add_ids(path, scoped_ids.split(/\s*,\s*/)) if scoped_ids
-
end
-
-
return [] if path == default_path
-
path
-
end
-
-
1
def command
-
$0.split(File::SEPARATOR).last
-
end
-
-
1
def value_for(key)
-
@preferred_options.fetch(key) { yield }
-
end
-
-
1
def define_built_in_hooks
-
1
around(:example, :aggregate_failures => true) do |procsy|
-
begin
-
aggregate_failures(nil, :hide_backtrace => true, &procsy)
-
rescue Support::AllExceptionsExceptOnesWeMustNotRescue => exception
-
procsy.example.set_aggregate_failures_exception(exception)
-
end
-
end
-
end
-
-
1
def assert_no_example_groups_defined(config_option)
-
return unless RSpec.world.example_groups.any?
-
-
raise MustBeConfiguredBeforeExampleGroupsError.new(
-
"RSpec's #{config_option} configuration option must be configured before " \
-
"any example groups are defined, but you have already defined a group."
-
)
-
end
-
-
1
def output_to_tty?(output=output_stream)
-
tty? || (output.respond_to?(:tty?) && output.tty?)
-
end
-
-
1
def conditionally_disable_mocks_monkey_patching
-
return unless disable_monkey_patching && rspec_mocks_loaded?
-
-
RSpec::Mocks.configuration.tap do |config|
-
config.syntax = :expect
-
config.patch_marshal_to_support_partial_doubles = false
-
end
-
end
-
-
1
def conditionally_disable_expectations_monkey_patching
-
return unless disable_monkey_patching && rspec_expectations_loaded?
-
-
RSpec::Expectations.configuration.syntax = :expect
-
end
-
-
1
def rspec_mocks_loaded?
-
defined?(RSpec::Mocks.configuration)
-
end
-
-
1
def rspec_expectations_loaded?
-
defined?(RSpec::Expectations.configuration)
-
end
-
-
1
def update_pattern_attr(name, value)
-
if @spec_files_loaded
-
RSpec.warning "Configuring `#{name}` to #{value} has no effect since " \
-
"RSpec has already loaded the spec files."
-
end
-
-
instance_variable_set(:"@#{name}", value)
-
@files_to_run = nil
-
end
-
-
1
def clear_values_derived_from_example_status_persistence_file_path
-
@last_run_statuses = nil
-
@spec_files_with_failures = nil
-
end
-
end
-
# rubocop:enable Metrics/ClassLength
-
end
-
end
-
1
require 'erb'
-
1
require 'shellwords'
-
-
1
module RSpec
-
1
module Core
-
# Responsible for utilizing externally provided configuration options,
-
# whether via the command line, `.rspec`, `~/.rspec`, `.rspec-local`
-
# or a custom options file.
-
1
class ConfigurationOptions
-
# @param args [Array<String>] command line arguments
-
1
def initialize(args)
-
@args = args.dup
-
organize_options
-
end
-
-
# Updates the provided {Configuration} instance based on the provided
-
# external configuration options.
-
#
-
# @param config [Configuration] the configuration instance to update
-
1
def configure(config)
-
process_options_into config
-
configure_filter_manager config.filter_manager
-
load_formatters_into config
-
end
-
-
# @api private
-
# Updates the provided {FilterManager} based on the filter options.
-
# @param filter_manager [FilterManager] instance to update
-
1
def configure_filter_manager(filter_manager)
-
@filter_manager_options.each do |command, value|
-
filter_manager.__send__ command, value
-
end
-
end
-
-
# @return [Hash] the final merged options, drawn from all external sources
-
1
attr_reader :options
-
-
1
private
-
-
1
def organize_options
-
@filter_manager_options = []
-
-
@options = (file_options << command_line_options << env_options).each do |opts|
-
@filter_manager_options << [:include, opts.delete(:inclusion_filter)] if opts.key?(:inclusion_filter)
-
@filter_manager_options << [:exclude, opts.delete(:exclusion_filter)] if opts.key?(:exclusion_filter)
-
end
-
-
@options = @options.inject(:libs => [], :requires => []) do |hash, opts|
-
hash.merge(opts) do |key, oldval, newval|
-
[:libs, :requires].include?(key) ? oldval + newval : newval
-
end
-
end
-
end
-
-
1
UNFORCED_OPTIONS = Set.new([
-
:requires, :profile, :drb, :libs, :files_or_directories_to_run,
-
:full_description, :full_backtrace, :tty
-
])
-
-
1
UNPROCESSABLE_OPTIONS = Set.new([:formatters])
-
-
1
def force?(key)
-
!UNFORCED_OPTIONS.include?(key)
-
end
-
-
1
def order(keys)
-
OPTIONS_ORDER.reverse_each do |key|
-
keys.unshift(key) if keys.delete(key)
-
end
-
keys
-
end
-
-
1
OPTIONS_ORDER = [
-
# It's important to set this before anything that might issue a
-
# deprecation (or otherwise access the reporter).
-
:deprecation_stream,
-
-
# load paths depend on nothing, but must be set before `requires`
-
# to support load-path-relative requires.
-
:libs,
-
-
# `files_or_directories_to_run` uses `default_path` so it must be
-
# set before it.
-
:default_path, :only_failures,
-
-
# These must be set before `requires` to support checking
-
# `config.files_to_run` from within `spec_helper.rb` when a
-
# `-rspec_helper` option is used.
-
:files_or_directories_to_run, :pattern, :exclude_pattern,
-
-
# Necessary so that the `--seed` option is applied before requires,
-
# in case required files do something with the provided seed.
-
# (such as seed global randomization with it).
-
:order,
-
-
# In general, we want to require the specified files as early as
-
# possible. The `--require` option is specifically intended to allow
-
# early requires. For later requires, they can just put the require in
-
# their spec files, but `--require` provides a unique opportunity for
-
# users to instruct RSpec to load an extension file early for maximum
-
# flexibility.
-
:requires
-
]
-
-
1
def process_options_into(config)
-
opts = options.reject { |k, _| UNPROCESSABLE_OPTIONS.include? k }
-
-
order(opts.keys).each do |key|
-
force?(key) ? config.force(key => opts[key]) : config.__send__("#{key}=", opts[key])
-
end
-
end
-
-
1
def load_formatters_into(config)
-
options[:formatters].each { |pair| config.add_formatter(*pair) } if options[:formatters]
-
end
-
-
1
def file_options
-
custom_options_file ? [custom_options] : [global_options, project_options, local_options]
-
end
-
-
1
def env_options
-
return {} unless ENV['SPEC_OPTS']
-
-
parse_args_ignoring_files_or_dirs_to_run(
-
Shellwords.split(ENV["SPEC_OPTS"]),
-
"ENV['SPEC_OPTS']"
-
)
-
end
-
-
1
def command_line_options
-
@command_line_options ||= Parser.parse(@args)
-
end
-
-
1
def custom_options
-
options_from(custom_options_file)
-
end
-
-
1
def local_options
-
@local_options ||= options_from(local_options_file)
-
end
-
-
1
def project_options
-
@project_options ||= options_from(project_options_file)
-
end
-
-
1
def global_options
-
@global_options ||= options_from(global_options_file)
-
end
-
-
1
def options_from(path)
-
args = args_from_options_file(path)
-
parse_args_ignoring_files_or_dirs_to_run(args, path)
-
end
-
-
1
def parse_args_ignoring_files_or_dirs_to_run(args, source)
-
options = Parser.parse(args, source)
-
options.delete(:files_or_directories_to_run)
-
options
-
end
-
-
1
def args_from_options_file(path)
-
return [] unless path && File.exist?(path)
-
config_string = options_file_as_erb_string(path)
-
FlatMap.flat_map(config_string.split(/\n+/), &:shellsplit)
-
end
-
-
1
def options_file_as_erb_string(path)
-
ERB.new(File.read(path), nil, '-').result(binding)
-
end
-
-
1
def custom_options_file
-
command_line_options[:custom_options_file]
-
end
-
-
1
def project_options_file
-
"./.rspec"
-
end
-
-
1
def local_options_file
-
"./.rspec-local"
-
end
-
-
1
def global_options_file
-
File.join(File.expand_path("~"), ".rspec")
-
rescue ArgumentError
-
RSpec.warning "Unable to find ~/.rspec because the HOME environment variable is not set"
-
nil
-
end
-
end
-
end
-
end
-
1
module RSpec
-
1
module Core
-
# DSL defines methods to group examples, most notably `describe`,
-
# and exposes them as class methods of {RSpec}. They can also be
-
# exposed globally (on `main` and instances of `Module`) through
-
# the {Configuration} option `expose_dsl_globally`.
-
#
-
# By default the methods `describe`, `context` and `example_group`
-
# are exposed. These methods define a named context for one or
-
# more examples. The given block is evaluated in the context of
-
# a generated subclass of {RSpec::Core::ExampleGroup}.
-
#
-
# ## Examples:
-
#
-
# RSpec.describe "something" do
-
# context "when something is a certain way" do
-
# it "does something" do
-
# # example code goes here
-
# end
-
# end
-
# end
-
#
-
# @see ExampleGroup
-
# @see ExampleGroup.example_group
-
1
module DSL
-
# @private
-
1
def self.example_group_aliases
-
15
@example_group_aliases ||= []
-
end
-
-
# @private
-
1
def self.exposed_globally?
-
8
@exposed_globally ||= false
-
end
-
-
# @private
-
1
def self.expose_example_group_alias(name)
-
7
return if example_group_aliases.include?(name)
-
-
7
example_group_aliases << name
-
-
14
(class << RSpec; self; end).__send__(:define_method, name) do |*args, &example_group_block|
-
RSpec.world.register RSpec::Core::ExampleGroup.__send__(name, *args, &example_group_block)
-
end
-
-
7
expose_example_group_alias_globally(name) if exposed_globally?
-
end
-
-
1
class << self
-
# @private
-
1
attr_accessor :top_level
-
end
-
-
# Adds the describe method to Module and the top level binding.
-
# @api private
-
1
def self.expose_globally!
-
1
return if exposed_globally?
-
-
1
example_group_aliases.each do |method_name|
-
7
expose_example_group_alias_globally(method_name)
-
end
-
-
1
@exposed_globally = true
-
end
-
-
# Removes the describe method from Module and the top level binding.
-
# @api private
-
1
def self.remove_globally!
-
return unless exposed_globally?
-
-
example_group_aliases.each do |method_name|
-
change_global_dsl { undef_method method_name }
-
end
-
-
@exposed_globally = false
-
end
-
-
# @private
-
1
def self.expose_example_group_alias_globally(method_name)
-
7
change_global_dsl do
-
14
remove_method(method_name) if method_defined?(method_name)
-
14
define_method(method_name) { |*a, &b| ::RSpec.__send__(method_name, *a, &b) }
-
end
-
end
-
-
# @private
-
1
def self.change_global_dsl(&changes)
-
16
(class << top_level; self; end).class_exec(&changes)
-
8
Module.class_exec(&changes)
-
end
-
end
-
end
-
end
-
-
# Capture main without an eval.
-
1
::RSpec::Core::DSL.top_level = self
-
1
module RSpec
-
1
module Core
-
# Wrapper for an instance of a subclass of {ExampleGroup}. An instance of
-
# `RSpec::Core::Example` is returned by example definition methods
-
# such as {ExampleGroup.it it} and is yielded to the {ExampleGroup.it it},
-
# {Hooks#before before}, {Hooks#after after}, {Hooks#around around},
-
# {MemoizedHelpers::ClassMethods#let let} and
-
# {MemoizedHelpers::ClassMethods#subject subject} blocks.
-
#
-
# This allows us to provide rich metadata about each individual
-
# example without adding tons of methods directly to the ExampleGroup
-
# that users may inadvertantly redefine.
-
#
-
# Useful for configuring logging and/or taking some action based
-
# on the state of an example's metadata.
-
#
-
# @example
-
#
-
# RSpec.configure do |config|
-
# config.before do |example|
-
# log example.description
-
# end
-
#
-
# config.after do |example|
-
# log example.description
-
# end
-
#
-
# config.around do |example|
-
# log example.description
-
# example.run
-
# end
-
# end
-
#
-
# shared_examples "auditable" do
-
# it "does something" do
-
# log "#{example.full_description}: #{auditable.inspect}"
-
# auditable.should do_something
-
# end
-
# end
-
#
-
# @see ExampleGroup
-
# @note Example blocks are evaluated in the context of an instance
-
# of an `ExampleGroup`, not in the context of an instance of `Example`.
-
1
class Example
-
# @private
-
#
-
# Used to define methods that delegate to this example's metadata.
-
1
def self.delegate_to_metadata(key)
-
6
define_method(key) { @metadata[key] }
-
end
-
-
# @return [ExecutionResult] represents the result of running this example.
-
1
delegate_to_metadata :execution_result
-
# @return [String] the relative path to the file where this example was
-
# defined.
-
1
delegate_to_metadata :file_path
-
# @return [String] the full description (including the docstrings of
-
# all parent example groups).
-
1
delegate_to_metadata :full_description
-
# @return [String] the exact source location of this example in a form
-
# like `./path/to/spec.rb:17`
-
1
delegate_to_metadata :location
-
# @return [Boolean] flag that indicates that the example is not expected
-
# to pass. It will be run and will either have a pending result (if a
-
# failure occurs) or a failed result (if no failure occurs).
-
1
delegate_to_metadata :pending
-
# @return [Boolean] flag that will cause the example to not run.
-
# The {ExecutionResult} status will be `:pending`.
-
1
delegate_to_metadata :skip
-
-
# Returns the string submitted to `example` or its aliases (e.g.
-
# `specify`, `it`, etc). If no string is submitted (e.g.
-
# `it { is_expected.to do_something }`) it returns the message generated
-
# by the matcher if there is one, otherwise returns a message including
-
# the location of the example.
-
1
def description
-
description = if metadata[:description].to_s.empty?
-
location_description
-
else
-
metadata[:description]
-
end
-
-
RSpec.configuration.format_docstrings_block.call(description)
-
end
-
-
# Returns a description of the example that always includes the location.
-
1
def inspect_output
-
inspect_output = "\"#{description}\""
-
unless metadata[:description].to_s.empty?
-
inspect_output << " (#{location})"
-
end
-
inspect_output
-
end
-
-
# Returns the location-based argument that can be passed to the `rspec` command to rerun this example.
-
1
def location_rerun_argument
-
@location_rerun_argument ||= begin
-
loaded_spec_files = RSpec.configuration.loaded_spec_files
-
-
Metadata.ascending(metadata) do |meta|
-
return meta[:location] if loaded_spec_files.include?(meta[:absolute_file_path])
-
end
-
end
-
end
-
-
# Returns the location-based argument that can be passed to the `rspec` command to rerun this example.
-
#
-
# @deprecated Use {#location_rerun_argument} instead.
-
# @note If there are multiple examples identified by this location, they will use {#id}
-
# to rerun instead, but this method will still return the location (that's why it is deprecated!).
-
1
def rerun_argument
-
location_rerun_argument
-
end
-
-
# @return [String] the unique id of this example. Pass
-
# this at the command line to re-run this exact example.
-
1
def id
-
@id ||= Metadata.id_from(metadata)
-
end
-
-
# @private
-
1
def self.parse_id(id)
-
# http://rubular.com/r/OMZSAPcAfn
-
id.match(/\A(.*?)(?:\[([\d\s:,]+)\])?\z/).captures
-
end
-
-
# Duplicates the example and overrides metadata with the provided
-
# hash.
-
#
-
# @param metadata_overrides [Hash] the hash to override the example metadata
-
# @return [Example] a duplicate of the example with modified metadata
-
1
def duplicate_with(metadata_overrides={})
-
new_metadata = metadata.clone.merge(metadata_overrides)
-
-
RSpec::Core::Metadata::RESERVED_KEYS.each do |reserved_key|
-
new_metadata.delete reserved_key
-
end
-
-
# don't clone the example group because the new example
-
# must belong to the same example group (not a clone).
-
Example.new(example_group, description.clone,
-
new_metadata, new_metadata[:block])
-
end
-
-
# @attr_reader
-
#
-
# Returns the first exception raised in the context of running this
-
# example (nil if no exception is raised).
-
1
attr_reader :exception
-
-
# @attr_reader
-
#
-
# Returns the metadata object associated with this example.
-
1
attr_reader :metadata
-
-
# @attr_reader
-
# @private
-
#
-
# Returns the example_group_instance that provides the context for
-
# running this example.
-
1
attr_reader :example_group_instance
-
-
# @attr
-
# @private
-
1
attr_accessor :clock
-
-
# Creates a new instance of Example.
-
# @param example_group_class [Class] the subclass of ExampleGroup in which
-
# this Example is declared
-
# @param description [String] the String passed to the `it` method (or
-
# alias)
-
# @param user_metadata [Hash] additional args passed to `it` to be used as
-
# metadata
-
# @param example_block [Proc] the block of code that represents the
-
# example
-
# @api private
-
1
def initialize(example_group_class, description, user_metadata, example_block=nil)
-
@example_group_class = example_group_class
-
@example_block = example_block
-
-
@metadata = Metadata::ExampleHash.create(
-
@example_group_class.metadata, user_metadata,
-
example_group_class.method(:next_runnable_index_for),
-
description, example_block
-
)
-
-
# This should perhaps be done in `Metadata::ExampleHash.create`,
-
# but the logic there has no knowledge of `RSpec.world` and we
-
# want to keep it that way. It's easier to just assign it here.
-
@metadata[:last_run_status] = RSpec.configuration.last_run_statuses[id]
-
-
@example_group_instance = @exception = nil
-
@clock = RSpec::Core::Time
-
@reporter = RSpec::Core::NullReporter
-
end
-
-
# Provide a human-readable representation of this class
-
1
def inspect
-
"#<#{self.class.name} #{description.inspect}>"
-
end
-
1
alias to_s inspect
-
-
# @return [RSpec::Core::Reporter] the current reporter for the example
-
1
attr_reader :reporter
-
-
# Returns the example group class that provides the context for running
-
# this example.
-
1
def example_group
-
@example_group_class
-
end
-
-
1
alias_method :pending?, :pending
-
1
alias_method :skipped?, :skip
-
-
# @api private
-
# instance_execs the block passed to the constructor in the context of
-
# the instance of {ExampleGroup}.
-
# @param example_group_instance the instance of an ExampleGroup subclass
-
1
def run(example_group_instance, reporter)
-
@example_group_instance = example_group_instance
-
@reporter = reporter
-
hooks.register_global_singleton_context_hooks(self, RSpec.configuration.hooks)
-
RSpec.configuration.configure_example(self)
-
RSpec.current_example = self
-
-
start(reporter)
-
Pending.mark_pending!(self, pending) if pending?
-
-
begin
-
if skipped?
-
Pending.mark_pending! self, skip
-
elsif !RSpec.configuration.dry_run?
-
with_around_and_singleton_context_hooks do
-
begin
-
run_before_example
-
@example_group_instance.instance_exec(self, &@example_block)
-
-
if pending?
-
Pending.mark_fixed! self
-
-
raise Pending::PendingExampleFixedError,
-
'Expected example to fail since it is pending, but it passed.',
-
[location]
-
end
-
rescue Pending::SkipDeclaredInExample
-
# no-op, required metadata has already been set by the `skip`
-
# method.
-
rescue AllExceptionsExcludingDangerousOnesOnRubiesThatAllowIt => e
-
set_exception(e)
-
ensure
-
run_after_example
-
end
-
end
-
end
-
rescue Support::AllExceptionsExceptOnesWeMustNotRescue => e
-
set_exception(e)
-
ensure
-
@example_group_instance = nil # if you love something... let it go
-
end
-
-
finish(reporter)
-
ensure
-
execution_result.ensure_timing_set(clock)
-
RSpec.current_example = nil
-
end
-
-
1
if RSpec::Support::Ruby.jruby? || RUBY_VERSION.to_f < 1.9
-
# :nocov:
-
skipped
# For some reason, rescuing `Support::AllExceptionsExceptOnesWeMustNotRescue`
-
skipped
# in place of `Exception` above can cause the exit status to be the wrong
-
skipped
# thing. I have no idea why. See:
-
skipped
# https://github.com/rspec/rspec-core/pull/2063#discussion_r38284978
-
skipped
# @private
-
skipped
AllExceptionsExcludingDangerousOnesOnRubiesThatAllowIt = Exception
-
# :nocov:
-
else
-
# @private
-
1
AllExceptionsExcludingDangerousOnesOnRubiesThatAllowIt = Support::AllExceptionsExceptOnesWeMustNotRescue
-
end
-
-
# Wraps both a `Proc` and an {Example} for use in {Hooks#around
-
# around} hooks. In around hooks we need to yield this special
-
# kind of object (rather than the raw {Example}) because when
-
# there are multiple `around` hooks we have to wrap them recursively.
-
#
-
# @example
-
#
-
# RSpec.configure do |c|
-
# c.around do |ex| # Procsy which wraps the example
-
# if ex.metadata[:key] == :some_value && some_global_condition
-
# raise "some message"
-
# end
-
# ex.run # run delegates to ex.call.
-
# end
-
# end
-
#
-
# @note This class also exposes the instance methods of {Example},
-
# proxying them through to the wrapped {Example} instance.
-
1
class Procsy
-
# The {Example} instance.
-
1
attr_reader :example
-
-
1
Example.public_instance_methods(false).each do |name|
-
24
name_sym = name.to_sym
-
24
next if name_sym == :run || name_sym == :inspect || name_sym == :to_s
-
-
21
define_method(name) { |*a, &b| @example.__send__(name, *a, &b) }
-
end
-
-
1
Proc.public_instance_methods(false).each do |name|
-
16
name_sym = name.to_sym
-
16
next if name_sym == :call || name_sym == :inspect || name_sym == :to_s || name_sym == :to_proc
-
-
12
define_method(name) { |*a, &b| @proc.__send__(name, *a, &b) }
-
end
-
-
# Calls the proc and notes that the example has been executed.
-
1
def call(*args, &block)
-
@executed = true
-
@proc.call(*args, &block)
-
end
-
1
alias run call
-
-
# Provides a wrapped proc that will update our `executed?` state when
-
# executed.
-
1
def to_proc
-
method(:call).to_proc
-
end
-
-
1
def initialize(example, &block)
-
@example = example
-
@proc = block
-
@executed = false
-
end
-
-
# @private
-
1
def wrap(&block)
-
self.class.new(example, &block)
-
end
-
-
# Indicates whether or not the around hook has executed the example.
-
1
def executed?
-
@executed
-
end
-
-
# @private
-
1
def inspect
-
@example.inspect.gsub('Example', 'ExampleProcsy')
-
end
-
end
-
-
# @private
-
#
-
# The exception that will be displayed to the user -- either the failure of
-
# the example or the `pending_exception` if the example is pending.
-
1
def display_exception
-
@exception || execution_result.pending_exception
-
end
-
-
# @private
-
#
-
# Assigns the exception that will be displayed to the user -- either the failure of
-
# the example or the `pending_exception` if the example is pending.
-
1
def display_exception=(ex)
-
if pending? && !(Pending::PendingExampleFixedError === ex)
-
@exception = nil
-
execution_result.pending_fixed = false
-
execution_result.pending_exception = ex
-
else
-
@exception = ex
-
end
-
end
-
-
# rubocop:disable Style/AccessorMethodName
-
-
# @private
-
#
-
# Used internally to set an exception in an after hook, which
-
# captures the exception but doesn't raise it.
-
1
def set_exception(exception)
-
return self.display_exception = exception unless display_exception
-
-
unless RSpec::Core::MultipleExceptionError === display_exception
-
self.display_exception = RSpec::Core::MultipleExceptionError.new(display_exception)
-
end
-
-
display_exception.add exception
-
end
-
-
# @private
-
#
-
# Used to set the exception when `aggregate_failures` fails.
-
1
def set_aggregate_failures_exception(exception)
-
return set_exception(exception) unless display_exception
-
-
exception = RSpec::Core::MultipleExceptionError::InterfaceTag.for(exception)
-
exception.add display_exception
-
self.display_exception = exception
-
end
-
-
# rubocop:enable Style/AccessorMethodName
-
-
# @private
-
#
-
# Used internally to set an exception and fail without actually executing
-
# the example when an exception is raised in before(:context).
-
1
def fail_with_exception(reporter, exception)
-
start(reporter)
-
set_exception(exception)
-
finish(reporter)
-
end
-
-
# @private
-
#
-
# Used internally to skip without actually executing the example when
-
# skip is used in before(:context).
-
1
def skip_with_exception(reporter, exception)
-
start(reporter)
-
Pending.mark_skipped! self, exception.argument
-
finish(reporter)
-
end
-
-
# @private
-
1
def instance_exec(*args, &block)
-
@example_group_instance.instance_exec(*args, &block)
-
end
-
-
1
private
-
-
1
def hooks
-
example_group_instance.singleton_class.hooks
-
end
-
-
1
def with_around_example_hooks
-
hooks.run(:around, :example, self) { yield }
-
rescue Support::AllExceptionsExceptOnesWeMustNotRescue => e
-
set_exception(e)
-
end
-
-
1
def start(reporter)
-
reporter.example_started(self)
-
execution_result.started_at = clock.now
-
end
-
-
1
def finish(reporter)
-
pending_message = execution_result.pending_message
-
-
reporter.example_finished(self)
-
if @exception
-
record_finished :failed
-
execution_result.exception = @exception
-
reporter.example_failed self
-
false
-
elsif pending_message
-
record_finished :pending
-
execution_result.pending_message = pending_message
-
reporter.example_pending self
-
true
-
else
-
record_finished :passed
-
reporter.example_passed self
-
true
-
end
-
end
-
-
1
def record_finished(status)
-
execution_result.record_finished(status, clock.now)
-
end
-
-
1
def run_before_example
-
@example_group_instance.setup_mocks_for_rspec
-
hooks.run(:before, :example, self)
-
end
-
-
1
def with_around_and_singleton_context_hooks
-
singleton_context_hooks_host = example_group_instance.singleton_class
-
singleton_context_hooks_host.run_before_context_hooks(example_group_instance)
-
with_around_example_hooks { yield }
-
ensure
-
singleton_context_hooks_host.run_after_context_hooks(example_group_instance)
-
end
-
-
1
def run_after_example
-
assign_generated_description if defined?(::RSpec::Matchers)
-
hooks.run(:after, :example, self)
-
verify_mocks
-
ensure
-
@example_group_instance.teardown_mocks_for_rspec
-
end
-
-
1
def verify_mocks
-
@example_group_instance.verify_mocks_for_rspec if mocks_need_verification?
-
rescue Support::AllExceptionsExceptOnesWeMustNotRescue => e
-
set_exception(e)
-
end
-
-
1
def mocks_need_verification?
-
exception.nil? || execution_result.pending_fixed?
-
end
-
-
1
def assign_generated_description
-
if metadata[:description].empty? && (description = generate_description)
-
metadata[:description] = description
-
metadata[:full_description] << description
-
end
-
ensure
-
RSpec::Matchers.clear_generated_description
-
end
-
-
1
def generate_description
-
RSpec::Matchers.generated_description
-
rescue Support::AllExceptionsExceptOnesWeMustNotRescue => e
-
location_description + " (Got an error when generating description " \
-
"from matcher: #{e.class}: #{e.message} -- #{e.backtrace.first})"
-
end
-
-
1
def location_description
-
"example at #{location}"
-
end
-
-
# Represents the result of executing an example.
-
# Behaves like a hash for backwards compatibility.
-
1
class ExecutionResult
-
1
include HashImitatable
-
-
# @return [Symbol] `:passed`, `:failed` or `:pending`.
-
1
attr_accessor :status
-
-
# @return [Exception, nil] The failure, if there was one.
-
1
attr_accessor :exception
-
-
# @return [Time] When the example started.
-
1
attr_accessor :started_at
-
-
# @return [Time] When the example finished.
-
1
attr_accessor :finished_at
-
-
# @return [Float] How long the example took in seconds.
-
1
attr_accessor :run_time
-
-
# @return [String, nil] The reason the example was pending,
-
# or nil if the example was not pending.
-
1
attr_accessor :pending_message
-
-
# @return [Exception, nil] The exception triggered while
-
# executing the pending example. If no exception was triggered
-
# it would no longer get a status of `:pending` unless it was
-
# tagged with `:skip`.
-
1
attr_accessor :pending_exception
-
-
# @return [Boolean] For examples tagged with `:pending`,
-
# this indicates whether or not it now passes.
-
1
attr_accessor :pending_fixed
-
-
1
alias pending_fixed? pending_fixed
-
-
# @return [Boolean] Indicates if the example was completely skipped
-
# (typically done via `:skip` metadata or the `skip` method). Skipped examples
-
# will have a `:pending` result. A `:pending` result can also come from examples
-
# that were marked as `:pending`, which causes them to be run, and produces a
-
# `:failed` result if the example passes.
-
1
def example_skipped?
-
status == :pending && !pending_exception
-
end
-
-
# @api private
-
# Records the finished status of the example.
-
1
def record_finished(status, finished_at)
-
self.status = status
-
calculate_run_time(finished_at)
-
end
-
-
# @api private
-
# Populates finished_at and run_time if it has not yet been set
-
1
def ensure_timing_set(clock)
-
calculate_run_time(clock.now) unless finished_at
-
end
-
-
1
private
-
-
1
def calculate_run_time(finished_at)
-
self.finished_at = finished_at
-
self.run_time = (finished_at - started_at).to_f
-
end
-
-
# For backwards compatibility we present `status` as a string
-
# when presenting the legacy hash interface.
-
1
def hash_for_delegation
-
super.tap do |hash|
-
hash[:status] &&= status.to_s
-
end
-
end
-
-
1
def set_value(name, value)
-
value &&= value.to_sym if name == :status
-
super(name, value)
-
end
-
-
1
def get_value(name)
-
if name == :status
-
status.to_s if status
-
else
-
super
-
end
-
end
-
-
1
def issue_deprecation(_method_name, *_args)
-
RSpec.deprecate("Treating `metadata[:execution_result]` as a hash",
-
:replacement => "the attributes methods to access the data")
-
end
-
end
-
end
-
-
# @private
-
# Provides an execution context for before/after :suite hooks.
-
1
class SuiteHookContext < Example
-
1
def initialize
-
super(AnonymousExampleGroup, "", {})
-
@example_group_instance = AnonymousExampleGroup.new
-
end
-
-
# rubocop:disable Style/AccessorMethodName
-
-
# To ensure we don't silence errors.
-
1
def set_exception(exception)
-
raise exception
-
end
-
# rubocop:enable Style/AccessorMethodName
-
end
-
end
-
end
-
1
RSpec::Support.require_rspec_support 'recursive_const_methods'
-
-
1
module RSpec
-
1
module Core
-
# rubocop:disable Metrics/ClassLength
-
# ExampleGroup and {Example} are the main structural elements of
-
# rspec-core. Consider this example:
-
#
-
# describe Thing do
-
# it "does something" do
-
# end
-
# end
-
#
-
# The object returned by `describe Thing` is a subclass of ExampleGroup.
-
# The object returned by `it "does something"` is an instance of Example,
-
# which serves as a wrapper for an instance of the ExampleGroup in which it
-
# is declared.
-
#
-
# Example group bodies (e.g. `describe` or `context` blocks) are evaluated
-
# in the context of a new subclass of ExampleGroup. Individual examples are
-
# evaluated in the context of an instance of the specific ExampleGroup
-
# subclass to which they belong.
-
#
-
# Besides the class methods defined here, there are other interesting macros
-
# defined in {Hooks}, {MemoizedHelpers::ClassMethods} and
-
# {SharedExampleGroup}. There are additional instance methods available to
-
# your examples defined in {MemoizedHelpers} and {Pending}.
-
1
class ExampleGroup
-
1
extend Hooks
-
-
1
include MemoizedHelpers
-
1
extend MemoizedHelpers::ClassMethods
-
1
include Pending
-
1
extend SharedExampleGroup
-
-
# @private
-
1
def self.idempotently_define_singleton_method(name, &definition)
-
48
(class << self; self; end).module_exec do
-
24
remove_method(name) if method_defined?(name) && instance_method(name).owner == self
-
24
define_method(name, &definition)
-
end
-
end
-
-
# @!group Metadata
-
-
# The [Metadata](Metadata) object associated with this group.
-
# @see Metadata
-
1
def self.metadata
-
@metadata ||= nil
-
end
-
-
# Temporarily replace the provided metadata.
-
# Intended primarily to allow an example group's singleton class
-
# to return the metadata of the example that it exists for. This
-
# is necessary for shared example group inclusion to work properly
-
# with singleton example groups.
-
# @private
-
1
def self.with_replaced_metadata(meta)
-
orig_metadata = metadata
-
@metadata = meta
-
yield
-
ensure
-
@metadata = orig_metadata
-
end
-
-
# @private
-
# @return [Metadata] belonging to the parent of a nested {ExampleGroup}
-
1
def self.superclass_metadata
-
@superclass_metadata ||= superclass.respond_to?(:metadata) ? superclass.metadata : nil
-
end
-
-
# @private
-
1
def self.delegate_to_metadata(*names)
-
1
names.each do |name|
-
3
idempotently_define_singleton_method(name) { metadata.fetch(name) }
-
end
-
end
-
-
1
delegate_to_metadata :described_class, :file_path, :location
-
-
# @return [String] the current example group description
-
1
def self.description
-
description = metadata[:description]
-
RSpec.configuration.format_docstrings_block.call(description)
-
end
-
-
# Returns the class or module passed to the `describe` method (or alias).
-
# Returns nil if the subject is not a class or module.
-
# @example
-
# describe Thing do
-
# it "does something" do
-
# described_class == Thing
-
# end
-
# end
-
#
-
1
def described_class
-
self.class.described_class
-
end
-
-
# @!endgroup
-
-
# @!group Defining Examples
-
-
# @private
-
# @macro [attach] define_example_method
-
# @!scope class
-
# @overload $1
-
# @overload $1(&example_implementation)
-
# @param example_implementation [Block] The implementation of the example.
-
# @overload $1(doc_string, *metadata_keys, metadata={})
-
# @param doc_string [String] The example's doc string.
-
# @param metadata [Hash] Metadata for the example.
-
# @param metadata_keys [Array<Symbol>] Metadata tags for the example.
-
# Will be transformed into hash entries with `true` values.
-
# @overload $1(doc_string, *metadata_keys, metadata={}, &example_implementation)
-
# @param doc_string [String] The example's doc string.
-
# @param metadata [Hash] Metadata for the example.
-
# @param metadata_keys [Array<Symbol>] Metadata tags for the example.
-
# Will be transformed into hash entries with `true` values.
-
# @param example_implementation [Block] The implementation of the example.
-
# @yield [Example] the example object
-
# @example
-
# $1 do
-
# end
-
#
-
# $1 "does something" do
-
# end
-
#
-
# $1 "does something", :slow, :uses_js do
-
# end
-
#
-
# $1 "does something", :with => 'additional metadata' do
-
# end
-
#
-
# $1 "does something" do |ex|
-
# # ex is the Example object that contains metadata about the example
-
# end
-
1
def self.define_example_method(name, extra_options={})
-
12
idempotently_define_singleton_method(name) do |*all_args, &block|
-
desc, *args = *all_args
-
-
options = Metadata.build_hash_from(args)
-
options.update(:skip => RSpec::Core::Pending::NOT_YET_IMPLEMENTED) unless block
-
options.update(extra_options)
-
-
example = RSpec::Core::Example.new(self, desc, options, block)
-
examples << example
-
example
-
end
-
end
-
-
# Defines an example within a group.
-
1
define_example_method :example
-
# Defines an example within a group.
-
# This is the primary API to define a code example.
-
1
define_example_method :it
-
# Defines an example within a group.
-
# Useful for when your docstring does not read well off of `it`.
-
# @example
-
# RSpec.describe MyClass do
-
# specify "#do_something is deprecated" do
-
# # ...
-
# end
-
# end
-
1
define_example_method :specify
-
-
# Shortcut to define an example with `:focus => true`.
-
# @see example
-
1
define_example_method :focus, :focus => true
-
# Shortcut to define an example with `:focus => true`.
-
# @see example
-
1
define_example_method :fexample, :focus => true
-
# Shortcut to define an example with `:focus => true`.
-
# @see example
-
1
define_example_method :fit, :focus => true
-
# Shortcut to define an example with `:focus => true`.
-
# @see example
-
1
define_example_method :fspecify, :focus => true
-
# Shortcut to define an example with `:skip => 'Temporarily skipped with xexample'`.
-
# @see example
-
1
define_example_method :xexample, :skip => 'Temporarily skipped with xexample'
-
# Shortcut to define an example with `:skip => 'Temporarily skipped with xit'`.
-
# @see example
-
1
define_example_method :xit, :skip => 'Temporarily skipped with xit'
-
# Shortcut to define an example with `:skip => 'Temporarily skipped with xspecify'`.
-
# @see example
-
1
define_example_method :xspecify, :skip => 'Temporarily skipped with xspecify'
-
# Shortcut to define an example with `:skip => true`
-
# @see example
-
1
define_example_method :skip, :skip => true
-
# Shortcut to define an example with `:pending => true`
-
# @see example
-
1
define_example_method :pending, :pending => true
-
-
# @!endgroup
-
-
# @!group Defining Example Groups
-
-
# @private
-
# @macro [attach] define_example_group_method
-
# @!scope class
-
# @overload $1
-
# @overload $1(&example_group_definition)
-
# @param example_group_definition [Block] The definition of the example group.
-
# @overload $1(doc_string, *metadata_keys, metadata={}, &example_implementation)
-
# @param doc_string [String] The group's doc string.
-
# @param metadata [Hash] Metadata for the group.
-
# @param metadata_keys [Array<Symbol>] Metadata tags for the group.
-
# Will be transformed into hash entries with `true` values.
-
# @param example_group_definition [Block] The definition of the example group.
-
#
-
# Generates a subclass of this example group which inherits
-
# everything except the examples themselves.
-
#
-
# @example
-
#
-
# RSpec.describe "something" do # << This describe method is defined in
-
# # << RSpec::Core::DSL, included in the
-
# # << global namespace (optional)
-
# before do
-
# do_something_before
-
# end
-
#
-
# let(:thing) { Thing.new }
-
#
-
# $1 "attribute (of something)" do
-
# # examples in the group get the before hook
-
# # declared above, and can access `thing`
-
# end
-
# end
-
#
-
# @see DSL#describe
-
1
def self.define_example_group_method(name, metadata={})
-
7
idempotently_define_singleton_method(name) do |*args, &example_group_block|
-
thread_data = RSpec::Support.thread_local_data
-
top_level = self == ExampleGroup
-
-
if top_level
-
if thread_data[:in_example_group]
-
raise "Creating an isolated context from within a context is " \
-
"not allowed. Change `RSpec.#{name}` to `#{name}` or " \
-
"move this to a top-level scope."
-
end
-
-
thread_data[:in_example_group] = true
-
end
-
-
begin
-
-
description = args.shift
-
combined_metadata = metadata.dup
-
combined_metadata.merge!(args.pop) if args.last.is_a? Hash
-
args << combined_metadata
-
-
subclass(self, description, args, &example_group_block).tap do |child|
-
children << child
-
end
-
-
ensure
-
thread_data.delete(:in_example_group) if top_level
-
end
-
end
-
-
7
RSpec::Core::DSL.expose_example_group_alias(name)
-
end
-
-
1
define_example_group_method :example_group
-
-
# An alias of `example_group`. Generally used when grouping examples by a
-
# thing you are describing (e.g. an object, class or method).
-
# @see example_group
-
1
define_example_group_method :describe
-
-
# An alias of `example_group`. Generally used when grouping examples
-
# contextually (e.g. "with xyz", "when xyz" or "if xyz").
-
# @see example_group
-
1
define_example_group_method :context
-
-
# Shortcut to temporarily make an example group skipped.
-
# @see example_group
-
1
define_example_group_method :xdescribe, :skip => "Temporarily skipped with xdescribe"
-
-
# Shortcut to temporarily make an example group skipped.
-
# @see example_group
-
1
define_example_group_method :xcontext, :skip => "Temporarily skipped with xcontext"
-
-
# Shortcut to define an example group with `:focus => true`.
-
# @see example_group
-
1
define_example_group_method :fdescribe, :focus => true
-
-
# Shortcut to define an example group with `:focus => true`.
-
# @see example_group
-
1
define_example_group_method :fcontext, :focus => true
-
-
# @!endgroup
-
-
# @!group Including Shared Example Groups
-
-
# @private
-
# @macro [attach] define_nested_shared_group_method
-
# @!scope class
-
#
-
# @see SharedExampleGroup
-
1
def self.define_nested_shared_group_method(new_name, report_label="it should behave like")
-
2
idempotently_define_singleton_method(new_name) do |name, *args, &customization_block|
-
# Pass :caller so the :location metadata is set properly.
-
# Otherwise, it'll be set to the next line because that's
-
# the block's source_location.
-
group = example_group("#{report_label} #{name}", :caller => (the_caller = caller)) do
-
find_and_eval_shared("examples", name, the_caller.first, *args, &customization_block)
-
end
-
group.metadata[:shared_group_name] = name
-
group
-
end
-
end
-
-
# Generates a nested example group and includes the shared content
-
# mapped to `name` in the nested group.
-
1
define_nested_shared_group_method :it_behaves_like, "behaves like"
-
# Generates a nested example group and includes the shared content
-
# mapped to `name` in the nested group.
-
1
define_nested_shared_group_method :it_should_behave_like
-
-
# Includes shared content mapped to `name` directly in the group in which
-
# it is declared, as opposed to `it_behaves_like`, which creates a nested
-
# group. If given a block, that block is also eval'd in the current
-
# context.
-
#
-
# @see SharedExampleGroup
-
1
def self.include_context(name, *args, &block)
-
find_and_eval_shared("context", name, caller.first, *args, &block)
-
end
-
-
# Includes shared content mapped to `name` directly in the group in which
-
# it is declared, as opposed to `it_behaves_like`, which creates a nested
-
# group. If given a block, that block is also eval'd in the current
-
# context.
-
#
-
# @see SharedExampleGroup
-
1
def self.include_examples(name, *args, &block)
-
find_and_eval_shared("examples", name, caller.first, *args, &block)
-
end
-
-
# Clear memoized values when adding/removing examples
-
# @private
-
1
def self.reset_memoized
-
@descendant_filtered_examples = nil
-
@_descendants = nil
-
@parent_groups = nil
-
@declaration_locations = nil
-
end
-
-
# Adds an example to the example group
-
1
def self.add_example(example)
-
reset_memoized
-
examples << example
-
end
-
-
# Removes an example from the example group
-
1
def self.remove_example(example)
-
reset_memoized
-
examples.delete example
-
end
-
-
# @private
-
1
def self.find_and_eval_shared(label, name, inclusion_location, *args, &customization_block)
-
shared_block = RSpec.world.shared_example_group_registry.find(parent_groups, name)
-
-
unless shared_block
-
raise ArgumentError, "Could not find shared #{label} #{name.inspect}"
-
end
-
-
SharedExampleGroupInclusionStackFrame.with_frame(name, Metadata.relative_path(inclusion_location)) do
-
module_exec(*args, &shared_block)
-
module_exec(&customization_block) if customization_block
-
end
-
end
-
-
# @!endgroup
-
-
# @private
-
1
def self.subclass(parent, description, args, &example_group_block)
-
subclass = Class.new(parent)
-
subclass.set_it_up(description, *args, &example_group_block)
-
subclass.module_exec(&example_group_block) if example_group_block
-
-
# The LetDefinitions module must be included _after_ other modules
-
# to ensure that it takes precedence when there are name collisions.
-
# Thus, we delay including it until after the example group block
-
# has been eval'd.
-
MemoizedHelpers.define_helpers_on(subclass)
-
-
subclass
-
end
-
-
# @private
-
1
def self.set_it_up(description, *args, &example_group_block)
-
# Ruby 1.9 has a bug that can lead to infinite recursion and a
-
# SystemStackError if you include a module in a superclass after
-
# including it in a subclass: https://gist.github.com/845896
-
# To prevent this, we must include any modules in
-
# RSpec::Core::ExampleGroup before users create example groups and have
-
# a chance to include the same module in a subclass of
-
# RSpec::Core::ExampleGroup. So we need to configure example groups
-
# here.
-
ensure_example_groups_are_configured
-
-
user_metadata = Metadata.build_hash_from(args)
-
-
@metadata = Metadata::ExampleGroupHash.create(
-
superclass_metadata, user_metadata,
-
superclass.method(:next_runnable_index_for),
-
description, *args, &example_group_block
-
)
-
ExampleGroups.assign_const(self)
-
-
hooks.register_globals(self, RSpec.configuration.hooks)
-
RSpec.configuration.configure_group(self)
-
end
-
-
# @private
-
1
def self.examples
-
@examples ||= []
-
end
-
-
# @private
-
1
def self.filtered_examples
-
RSpec.world.filtered_examples[self]
-
end
-
-
# @private
-
1
def self.descendant_filtered_examples
-
@descendant_filtered_examples ||= filtered_examples +
-
FlatMap.flat_map(children, &:descendant_filtered_examples)
-
end
-
-
# @private
-
1
def self.children
-
@children ||= []
-
end
-
-
# @private
-
1
def self.next_runnable_index_for(file)
-
if self == ExampleGroup
-
RSpec.world.num_example_groups_defined_in(file)
-
else
-
children.count + examples.count
-
end + 1
-
end
-
-
# @private
-
1
def self.descendants
-
@_descendants ||= [self] + FlatMap.flat_map(children, &:descendants)
-
end
-
-
## @private
-
1
def self.parent_groups
-
@parent_groups ||= ancestors.select { |a| a < RSpec::Core::ExampleGroup }
-
end
-
-
# @private
-
1
def self.top_level?
-
superclass == ExampleGroup
-
end
-
-
# @private
-
1
def self.ensure_example_groups_are_configured
-
unless defined?(@@example_groups_configured)
-
RSpec.configuration.configure_mock_framework
-
RSpec.configuration.configure_expectation_framework
-
# rubocop:disable Style/ClassVars
-
@@example_groups_configured = true
-
# rubocop:enable Style/ClassVars
-
end
-
end
-
-
# @private
-
1
def self.before_context_ivars
-
@before_context_ivars ||= {}
-
end
-
-
# @private
-
1
def self.store_before_context_ivars(example_group_instance)
-
each_instance_variable_for_example(example_group_instance) do |ivar|
-
before_context_ivars[ivar] = example_group_instance.instance_variable_get(ivar)
-
end
-
end
-
-
# @private
-
1
def self.run_before_context_hooks(example_group_instance)
-
set_ivars(example_group_instance, superclass_before_context_ivars)
-
-
ContextHookMemoized::Before.isolate_for_context_hook(example_group_instance) do
-
hooks.run(:before, :context, example_group_instance)
-
end
-
ensure
-
store_before_context_ivars(example_group_instance)
-
end
-
-
1
if RUBY_VERSION.to_f >= 1.9
-
# @private
-
1
def self.superclass_before_context_ivars
-
superclass.before_context_ivars
-
end
-
else # 1.8.7
-
# :nocov:
-
skipped
# @private
-
skipped
def self.superclass_before_context_ivars
-
skipped
if superclass.respond_to?(:before_context_ivars)
-
skipped
superclass.before_context_ivars
-
skipped
else
-
skipped
# `self` must be the singleton class of an ExampleGroup instance.
-
skipped
# On 1.8.7, the superclass of a singleton class of an instance of A
-
skipped
# is A's singleton class. On 1.9+, it's A. On 1.8.7, the first ancestor
-
skipped
# is A, so we can mirror 1.8.7's behavior here. Note that we have to
-
skipped
# search for the first that responds to `before_context_ivars`
-
skipped
# in case a module has been included in the singleton class.
-
skipped
ancestors.find { |a| a.respond_to?(:before_context_ivars) }.before_context_ivars
-
skipped
end
-
skipped
end
-
# :nocov:
-
end
-
-
# @private
-
1
def self.run_after_context_hooks(example_group_instance)
-
set_ivars(example_group_instance, before_context_ivars)
-
-
ContextHookMemoized::After.isolate_for_context_hook(example_group_instance) do
-
hooks.run(:after, :context, example_group_instance)
-
end
-
ensure
-
before_context_ivars.clear
-
end
-
-
# Runs all the examples in this group.
-
1
def self.run(reporter=RSpec::Core::NullReporter)
-
return if RSpec.world.wants_to_quit
-
reporter.example_group_started(self)
-
-
should_run_context_hooks = descendant_filtered_examples.any?
-
begin
-
run_before_context_hooks(new('before(:context) hook')) if should_run_context_hooks
-
result_for_this_group = run_examples(reporter)
-
results_for_descendants = ordering_strategy.order(children).map { |child| child.run(reporter) }.all?
-
result_for_this_group && results_for_descendants
-
rescue Pending::SkipDeclaredInExample => ex
-
for_filtered_examples(reporter) { |example| example.skip_with_exception(reporter, ex) }
-
true
-
rescue Support::AllExceptionsExceptOnesWeMustNotRescue => ex
-
for_filtered_examples(reporter) { |example| example.fail_with_exception(reporter, ex) }
-
RSpec.world.wants_to_quit = true if reporter.fail_fast_limit_met?
-
false
-
ensure
-
run_after_context_hooks(new('after(:context) hook')) if should_run_context_hooks
-
reporter.example_group_finished(self)
-
end
-
end
-
-
# @private
-
1
def self.ordering_strategy
-
order = metadata.fetch(:order, :global)
-
registry = RSpec.configuration.ordering_registry
-
-
registry.fetch(order) do
-
warn <<-WARNING.gsub(/^ +\|/, '')
-
|WARNING: Ignoring unknown ordering specified using `:order => #{order.inspect}` metadata.
-
| Falling back to configured global ordering.
-
| Unrecognized ordering specified at: #{location}
-
WARNING
-
-
registry.fetch(:global)
-
end
-
end
-
-
# @private
-
1
def self.run_examples(reporter)
-
ordering_strategy.order(filtered_examples).map do |example|
-
next if RSpec.world.wants_to_quit
-
instance = new(example.inspect_output)
-
set_ivars(instance, before_context_ivars)
-
succeeded = example.run(instance, reporter)
-
if !succeeded && reporter.fail_fast_limit_met?
-
RSpec.world.wants_to_quit = true
-
end
-
succeeded
-
end.all?
-
end
-
-
# @private
-
1
def self.for_filtered_examples(reporter, &block)
-
filtered_examples.each(&block)
-
-
children.each do |child|
-
reporter.example_group_started(child)
-
child.for_filtered_examples(reporter, &block)
-
reporter.example_group_finished(child)
-
end
-
false
-
end
-
-
# @private
-
1
def self.declaration_locations
-
@declaration_locations ||= [Metadata.location_tuple_from(metadata)] +
-
examples.map { |e| Metadata.location_tuple_from(e.metadata) } +
-
FlatMap.flat_map(children, &:declaration_locations)
-
end
-
-
# @return [String] the unique id of this example group. Pass
-
# this at the command line to re-run this exact example group.
-
1
def self.id
-
Metadata.id_from(metadata)
-
end
-
-
# @private
-
1
def self.top_level_description
-
parent_groups.last.description
-
end
-
-
# @private
-
1
def self.set_ivars(instance, ivars)
-
ivars.each { |name, value| instance.instance_variable_set(name, value) }
-
end
-
-
1
if RUBY_VERSION.to_f < 1.9
-
# :nocov:
-
skipped
# @private
-
skipped
INSTANCE_VARIABLE_TO_IGNORE = '@__inspect_output'.freeze
-
# :nocov:
-
else
-
# @private
-
1
INSTANCE_VARIABLE_TO_IGNORE = :@__inspect_output
-
end
-
-
# @private
-
1
def self.each_instance_variable_for_example(group)
-
group.instance_variables.each do |ivar|
-
yield ivar unless ivar == INSTANCE_VARIABLE_TO_IGNORE
-
end
-
end
-
-
1
def initialize(inspect_output=nil)
-
@__inspect_output = inspect_output || '(no description provided)'
-
super() # no args get passed
-
end
-
-
# @private
-
1
def inspect
-
"#<#{self.class} #{@__inspect_output}>"
-
end
-
-
1
unless method_defined?(:singleton_class) # for 1.8.7
-
# :nocov:
-
skipped
# @private
-
skipped
def singleton_class
-
skipped
class << self; self; end
-
skipped
end
-
# :nocov:
-
end
-
-
# Raised when an RSpec API is called in the wrong scope, such as `before`
-
# being called from within an example rather than from within an example
-
# group block.
-
1
WrongScopeError = Class.new(NoMethodError)
-
-
1
def self.method_missing(name, *args)
-
if method_defined?(name)
-
raise WrongScopeError,
-
"`#{name}` is not available on an example group (e.g. a " \
-
"`describe` or `context` block). It is only available from " \
-
"within individual examples (e.g. `it` blocks) or from " \
-
"constructs that run in the scope of an example (e.g. " \
-
"`before`, `let`, etc)."
-
end
-
-
super
-
end
-
1
private_class_method :method_missing
-
-
1
private
-
-
1
def method_missing(name, *args)
-
if self.class.respond_to?(name)
-
raise WrongScopeError,
-
"`#{name}` is not available from within an example (e.g. an " \
-
"`it` block) or from constructs that run in the scope of an " \
-
"example (e.g. `before`, `let`, etc). It is only available " \
-
"on an example group (e.g. a `describe` or `context` block)."
-
end
-
-
super
-
end
-
end
-
# rubocop:enable Metrics/ClassLength
-
-
# @private
-
# Unnamed example group used by `SuiteHookContext`.
-
1
class AnonymousExampleGroup < ExampleGroup
-
1
def self.metadata
-
{}
-
end
-
end
-
-
# Contains information about the inclusion site of a shared example group.
-
1
class SharedExampleGroupInclusionStackFrame
-
# @return [String] the name of the shared example group
-
1
attr_reader :shared_group_name
-
# @return [String] the location where the shared example was included
-
1
attr_reader :inclusion_location
-
-
1
def initialize(shared_group_name, inclusion_location)
-
@shared_group_name = shared_group_name
-
@inclusion_location = inclusion_location
-
end
-
-
# @return [String] The {#inclusion_location}, formatted for display by a formatter.
-
1
def formatted_inclusion_location
-
@formatted_inclusion_location ||= begin
-
RSpec.configuration.backtrace_formatter.backtrace_line(
-
inclusion_location.sub(/(:\d+):in .+$/, '\1')
-
)
-
end
-
end
-
-
# @return [String] Description of this stack frame, in the form used by
-
# RSpec's built-in formatters.
-
1
def description
-
@description ||= "Shared Example Group: #{shared_group_name.inspect} " \
-
"called from #{formatted_inclusion_location}"
-
end
-
-
# @private
-
1
def self.current_backtrace
-
shared_example_group_inclusions.reverse
-
end
-
-
# @private
-
1
def self.with_frame(name, location)
-
current_stack = shared_example_group_inclusions
-
current_stack << new(name, location)
-
yield
-
ensure
-
current_stack.pop
-
end
-
-
# @private
-
1
def self.shared_example_group_inclusions
-
RSpec::Support.thread_local_data[:shared_example_group_inclusions] ||= []
-
end
-
end
-
end
-
-
# @private
-
#
-
# Namespace for the example group subclasses generated by top-level
-
# `describe`.
-
1
module ExampleGroups
-
1
extend Support::RecursiveConstMethods
-
-
1
def self.assign_const(group)
-
base_name = base_name_for(group)
-
const_scope = constant_scope_for(group)
-
name = disambiguate(base_name, const_scope)
-
-
const_scope.const_set(name, group)
-
end
-
-
1
def self.constant_scope_for(group)
-
const_scope = group.superclass
-
const_scope = self if const_scope == ::RSpec::Core::ExampleGroup
-
const_scope
-
end
-
-
1
def self.base_name_for(group)
-
return "Anonymous" if group.description.empty?
-
-
# Convert to CamelCase.
-
name = ' ' << group.description
-
name.gsub!(/[^0-9a-zA-Z]+([0-9a-zA-Z])/) do
-
match = ::Regexp.last_match[1]
-
match.upcase!
-
match
-
end
-
-
name.lstrip! # Remove leading whitespace
-
name.gsub!(/\W/, ''.freeze) # JRuby, RBX and others don't like non-ascii in const names
-
-
# Ruby requires first const letter to be A-Z. Use `Nested`
-
# as necessary to enforce that.
-
name.gsub!(/\A([^A-Z]|\z)/, 'Nested\1'.freeze)
-
-
name
-
end
-
-
1
if RUBY_VERSION == '1.9.2'
-
# :nocov:
-
skipped
class << self
-
skipped
alias _base_name_for base_name_for
-
skipped
def base_name_for(group)
-
skipped
_base_name_for(group) + '_'
-
skipped
end
-
skipped
end
-
skipped
private_class_method :_base_name_for
-
# :nocov:
-
end
-
-
1
def self.disambiguate(name, const_scope)
-
return name unless const_defined_on?(const_scope, name)
-
-
# Add a trailing number if needed to disambiguate from an existing
-
# constant.
-
name << "_2"
-
name.next! while const_defined_on?(const_scope, name)
-
name
-
end
-
end
-
end
-
1
module RSpec
-
1
module Core
-
# @private
-
1
class FilterManager
-
1
attr_reader :exclusions, :inclusions
-
-
1
def initialize
-
2
@exclusions, @inclusions = FilterRules.build
-
end
-
-
# @api private
-
#
-
# @param file_path [String]
-
# @param line_numbers [Array]
-
1
def add_location(file_path, line_numbers)
-
# locations is a hash of expanded paths to arrays of line
-
# numbers to match against. e.g.
-
# { "path/to/file.rb" => [37, 42] }
-
add_path_to_arrays_filter(:locations, File.expand_path(file_path), line_numbers)
-
end
-
-
1
def add_ids(rerun_path, scoped_ids)
-
# ids is a hash of relative paths to arrays of ids
-
# to match against. e.g.
-
# { "./path/to/file.rb" => ["1:1", "2:4"] }
-
rerun_path = Metadata.relative_path(File.expand_path rerun_path)
-
add_path_to_arrays_filter(:ids, rerun_path, scoped_ids)
-
end
-
-
1
def empty?
-
inclusions.empty? && exclusions.empty?
-
end
-
-
1
def prune(examples)
-
# Semantically, this is unnecessary (the filtering below will return the empty
-
# array unmodified), but for perf reasons it's worth exiting early here. Users
-
# commonly have top-level examples groups that do not have any direct examples
-
# and instead have nested groups with examples. In that kind of situation,
-
# `examples` will be empty.
-
return examples if examples.empty?
-
-
examples = prune_conditionally_filtered_examples(examples)
-
-
if inclusions.standalone?
-
examples.select { |e| inclusions.include_example?(e) }
-
else
-
locations, ids, non_scoped_inclusions = inclusions.split_file_scoped_rules
-
-
examples.select do |ex|
-
file_scoped_include?(ex.metadata, ids, locations) do
-
!exclusions.include_example?(ex) && non_scoped_inclusions.include_example?(ex)
-
end
-
end
-
end
-
end
-
-
1
def exclude(*args)
-
exclusions.add(args.last)
-
end
-
-
1
def exclude_only(*args)
-
exclusions.use_only(args.last)
-
end
-
-
1
def exclude_with_low_priority(*args)
-
exclusions.add_with_low_priority(args.last)
-
end
-
-
1
def include(*args)
-
inclusions.add(args.last)
-
end
-
-
1
def include_only(*args)
-
inclusions.use_only(args.last)
-
end
-
-
1
def include_with_low_priority(*args)
-
inclusions.add_with_low_priority(args.last)
-
end
-
-
1
private
-
-
1
def add_path_to_arrays_filter(filter_key, path, values)
-
filter = inclusions.delete(filter_key) || Hash.new { |h, k| h[k] = [] }
-
filter[path].concat(values)
-
inclusions.add(filter_key => filter)
-
end
-
-
1
def prune_conditionally_filtered_examples(examples)
-
examples.reject do |ex|
-
meta = ex.metadata
-
!meta.fetch(:if, true) || meta[:unless]
-
end
-
end
-
-
# When a user specifies a particular spec location, that takes priority
-
# over any exclusion filters (such as if the spec is tagged with `:slow`
-
# and there is a `:slow => true` exclusion filter), but only for specs
-
# defined in the same file as the location filters. Excluded specs in
-
# other files should still be excluded.
-
1
def file_scoped_include?(ex_metadata, ids, locations)
-
no_id_filters = ids[ex_metadata[:rerun_file_path]].empty?
-
no_location_filters = locations[
-
File.expand_path(ex_metadata[:rerun_file_path])
-
].empty?
-
-
return yield if no_location_filters && no_id_filters
-
-
MetadataFilter.filter_applies?(:ids, ids, ex_metadata) ||
-
MetadataFilter.filter_applies?(:locations, locations, ex_metadata)
-
end
-
end
-
-
# @private
-
1
class FilterRules
-
1
PROC_HEX_NUMBER = /0x[0-9a-f]+@/
-
1
PROJECT_DIR = File.expand_path('.')
-
-
1
attr_accessor :opposite
-
1
attr_reader :rules
-
-
1
def self.build
-
2
exclusions = ExclusionRules.new
-
2
inclusions = InclusionRules.new
-
2
exclusions.opposite = inclusions
-
2
inclusions.opposite = exclusions
-
2
[exclusions, inclusions]
-
end
-
-
1
def initialize(rules={})
-
4
@rules = rules
-
end
-
-
1
def add(updated)
-
@rules.merge!(updated).each_key { |k| opposite.delete(k) }
-
end
-
-
1
def add_with_low_priority(updated)
-
updated = updated.merge(@rules)
-
opposite.each_pair { |k, v| updated.delete(k) if updated[k] == v }
-
@rules.replace(updated)
-
end
-
-
1
def use_only(updated)
-
updated.each_key { |k| opposite.delete(k) }
-
@rules.replace(updated)
-
end
-
-
1
def clear
-
@rules.clear
-
end
-
-
1
def delete(key)
-
@rules.delete(key)
-
end
-
-
1
def fetch(*args, &block)
-
@rules.fetch(*args, &block)
-
end
-
-
1
def [](key)
-
@rules[key]
-
end
-
-
1
def empty?
-
rules.empty?
-
end
-
-
1
def each_pair(&block)
-
@rules.each_pair(&block)
-
end
-
-
1
def description
-
rules.inspect.gsub(PROC_HEX_NUMBER, '').gsub(PROJECT_DIR, '.').gsub(' (lambda)', '')
-
end
-
-
1
def include_example?(example)
-
MetadataFilter.apply?(:any?, @rules, example.metadata)
-
end
-
end
-
-
# @private
-
1
ExclusionRules = FilterRules
-
-
# @private
-
1
class InclusionRules < FilterRules
-
1
def add(*args)
-
apply_standalone_filter(*args) || super
-
end
-
-
1
def add_with_low_priority(*args)
-
apply_standalone_filter(*args) || super
-
end
-
-
1
def include_example?(example)
-
@rules.empty? || super
-
end
-
-
1
def standalone?
-
is_standalone_filter?(@rules)
-
end
-
-
1
def split_file_scoped_rules
-
rules_dup = @rules.dup
-
locations = rules_dup.delete(:locations) { Hash.new([]) }
-
ids = rules_dup.delete(:ids) { Hash.new([]) }
-
-
return locations, ids, self.class.new(rules_dup)
-
end
-
-
1
private
-
-
1
def apply_standalone_filter(updated)
-
return true if standalone?
-
return nil unless is_standalone_filter?(updated)
-
-
replace_filters(updated)
-
true
-
end
-
-
1
def replace_filters(new_rules)
-
@rules.replace(new_rules)
-
opposite.clear
-
end
-
-
1
def is_standalone_filter?(rules)
-
rules.key?(:full_description)
-
end
-
end
-
end
-
end
-
1
module RSpec
-
1
module Core
-
# @private
-
1
module FlatMap
-
1
if [].respond_to?(:flat_map)
-
1
def flat_map(array, &block)
-
1
array.flat_map(&block)
-
end
-
else # for 1.8.7
-
# :nocov:
-
skipped
def flat_map(array, &block)
-
skipped
array.map(&block).flatten(1)
-
skipped
end
-
# :nocov:
-
end
-
-
1
module_function :flat_map
-
end
-
end
-
end
-
1
RSpec::Support.require_rspec_support "directory_maker"
-
# ## Built-in Formatters
-
#
-
# * progress (default) - Prints dots for passing examples, `F` for failures, `*`
-
# for pending.
-
# * documentation - Prints the docstrings passed to `describe` and `it` methods
-
# (and their aliases).
-
# * html
-
# * json - Useful for archiving data for subsequent analysis.
-
#
-
# The progress formatter is the default, but you can choose any one or more of
-
# the other formatters by passing with the `--format` (or `-f` for short)
-
# command-line option, e.g.
-
#
-
# rspec --format documentation
-
#
-
# You can also send the output of multiple formatters to different streams, e.g.
-
#
-
# rspec --format documentation --format html --out results.html
-
#
-
# This example sends the output of the documentation formatter to `$stdout`, and
-
# the output of the html formatter to results.html.
-
#
-
# ## Custom Formatters
-
#
-
# You can tell RSpec to use a custom formatter by passing its path and name to
-
# the `rspec` commmand. For example, if you define MyCustomFormatter in
-
# path/to/my_custom_formatter.rb, you would type this command:
-
#
-
# rspec --require path/to/my_custom_formatter.rb --format MyCustomFormatter
-
#
-
# The reporter calls every formatter with this protocol:
-
#
-
# * To start
-
# * `start(StartNotification)`
-
# * Once per example group
-
# * `example_group_started(GroupNotification)`
-
# * Once per example
-
# * `example_started(ExampleNotification)`
-
# * One of these per example, depending on outcome
-
# * `example_passed(ExampleNotification)`
-
# * `example_failed(FailedExampleNotification)`
-
# * `example_pending(ExampleNotification)`
-
# * Optionally at any time
-
# * `message(MessageNotification)`
-
# * At the end of the suite
-
# * `stop(ExamplesNotification)`
-
# * `start_dump(NullNotification)`
-
# * `dump_pending(ExamplesNotification)`
-
# * `dump_failures(ExamplesNotification)`
-
# * `dump_summary(SummaryNotification)`
-
# * `seed(SeedNotification)`
-
# * `close(NullNotification)`
-
#
-
# Only the notifications to which you subscribe your formatter will be called
-
# on your formatter. To subscribe your formatter use:
-
# `RSpec::Core::Formatters#register` e.g.
-
#
-
# `RSpec::Core::Formatters.register FormatterClassName, :example_passed, :example_failed`
-
#
-
# We recommend you implement the methods yourself; for simplicity we provide the
-
# default formatter output via our notification objects but if you prefer you
-
# can subclass `RSpec::Core::Formatters::BaseTextFormatter` and override the
-
# methods you wish to enhance.
-
#
-
# @see RSpec::Core::Formatters::BaseTextFormatter
-
# @see RSpec::Core::Reporter
-
1
module RSpec::Core::Formatters
-
1
autoload :DocumentationFormatter, 'rspec/core/formatters/documentation_formatter'
-
1
autoload :HtmlFormatter, 'rspec/core/formatters/html_formatter'
-
1
autoload :FallbackMessageFormatter, 'rspec/core/formatters/fallback_message_formatter'
-
1
autoload :ProgressFormatter, 'rspec/core/formatters/progress_formatter'
-
1
autoload :ProfileFormatter, 'rspec/core/formatters/profile_formatter'
-
1
autoload :JsonFormatter, 'rspec/core/formatters/json_formatter'
-
1
autoload :BisectFormatter, 'rspec/core/formatters/bisect_formatter'
-
1
autoload :ExceptionPresenter, 'rspec/core/formatters/exception_presenter'
-
-
# Register the formatter class
-
# @param formatter_class [Class] formatter class to register
-
# @param notifications [Symbol, ...] one or more notifications to be
-
# registered to the specified formatter
-
#
-
# @see RSpec::Core::Formatters::BaseFormatter
-
1
def self.register(formatter_class, *notifications)
-
1
Loader.formatters[formatter_class] = notifications
-
end
-
-
# @api private
-
#
-
# `RSpec::Core::Formatters::Loader` is an internal class for
-
# managing formatters used by a particular configuration. It is
-
# not expected to be used directly, but only through the configuration
-
# interface.
-
1
class Loader
-
# @api private
-
#
-
# Internal formatters are stored here when loaded.
-
1
def self.formatters
-
1
@formatters ||= {}
-
end
-
-
# @api private
-
1
def initialize(reporter)
-
@formatters = []
-
@reporter = reporter
-
self.default_formatter = 'progress'
-
end
-
-
# @return [Array] the loaded formatters
-
1
attr_reader :formatters
-
-
# @return [Reporter] the reporter
-
1
attr_reader :reporter
-
-
# @return [String] the default formatter to setup, defaults to `progress`
-
1
attr_accessor :default_formatter
-
-
# @private
-
1
def setup_default(output_stream, deprecation_stream)
-
add default_formatter, output_stream if @formatters.empty?
-
-
unless @formatters.any? { |formatter| DeprecationFormatter === formatter }
-
add DeprecationFormatter, deprecation_stream, output_stream
-
end
-
-
unless existing_formatter_implements?(:message)
-
add FallbackMessageFormatter, output_stream
-
end
-
-
return unless RSpec.configuration.profile_examples?
-
-
@reporter.setup_profiler
-
-
return if existing_formatter_implements?(:dump_profile)
-
-
add RSpec::Core::Formatters::ProfileFormatter, output_stream
-
end
-
-
# @private
-
1
def add(formatter_to_use, *paths)
-
formatter_class = find_formatter(formatter_to_use)
-
-
args = paths.map { |p| p.respond_to?(:puts) ? p : file_at(p) }
-
-
if !Loader.formatters[formatter_class].nil?
-
formatter = formatter_class.new(*args)
-
register formatter, notifications_for(formatter_class)
-
elsif defined?(RSpec::LegacyFormatters)
-
formatter = RSpec::LegacyFormatters.load_formatter formatter_class, *args
-
register formatter, formatter.notifications
-
else
-
call_site = "Formatter added at: #{::RSpec::CallerFilter.first_non_rspec_line}"
-
-
RSpec.warn_deprecation <<-WARNING.gsub(/\s*\|/, ' ')
-
|The #{formatter_class} formatter uses the deprecated formatter
-
|interface not supported directly by RSpec 3.
-
|
-
|To continue to use this formatter you must install the
-
|`rspec-legacy_formatters` gem, which provides support
-
|for legacy formatters or upgrade the formatter to a
-
|compatible version.
-
|
-
|#{call_site}
-
WARNING
-
end
-
end
-
-
1
private
-
-
1
def find_formatter(formatter_to_use)
-
built_in_formatter(formatter_to_use) ||
-
custom_formatter(formatter_to_use) ||
-
(raise ArgumentError, "Formatter '#{formatter_to_use}' unknown - " \
-
"maybe you meant 'documentation' or 'progress'?.")
-
end
-
-
1
def register(formatter, notifications)
-
return if duplicate_formatter_exists?(formatter)
-
@reporter.register_listener formatter, *notifications
-
@formatters << formatter
-
formatter
-
end
-
-
1
def duplicate_formatter_exists?(new_formatter)
-
@formatters.any? do |formatter|
-
formatter.class == new_formatter.class && formatter.output == new_formatter.output
-
end
-
end
-
-
1
def existing_formatter_implements?(notification)
-
@reporter.registered_listeners(notification).any?
-
end
-
-
1
def built_in_formatter(key)
-
case key.to_s
-
when 'd', 'doc', 'documentation'
-
DocumentationFormatter
-
when 'h', 'html'
-
HtmlFormatter
-
when 'p', 'progress'
-
ProgressFormatter
-
when 'j', 'json'
-
JsonFormatter
-
when 'bisect'
-
BisectFormatter
-
end
-
end
-
-
1
def notifications_for(formatter_class)
-
formatter_class.ancestors.inject(::RSpec::Core::Set.new) do |notifications, klass|
-
notifications.merge Loader.formatters.fetch(klass) { ::RSpec::Core::Set.new }
-
end
-
end
-
-
1
def custom_formatter(formatter_ref)
-
if Class === formatter_ref
-
formatter_ref
-
elsif string_const?(formatter_ref)
-
begin
-
formatter_ref.gsub(/^::/, '').split('::').inject(Object) { |a, e| a.const_get e }
-
rescue NameError
-
require(path_for(formatter_ref)) ? retry : raise
-
end
-
end
-
end
-
-
1
def string_const?(str)
-
str.is_a?(String) && /\A[A-Z][a-zA-Z0-9_:]*\z/ =~ str
-
end
-
-
1
def path_for(const_ref)
-
underscore_with_fix_for_non_standard_rspec_naming(const_ref)
-
end
-
-
1
def underscore_with_fix_for_non_standard_rspec_naming(string)
-
underscore(string).sub(%r{(^|/)r_spec($|/)}, '\\1rspec\\2')
-
end
-
-
# activesupport/lib/active_support/inflector/methods.rb, line 48
-
1
def underscore(camel_cased_word)
-
word = camel_cased_word.to_s.dup
-
word.gsub!(/::/, '/')
-
word.gsub!(/([A-Z]+)([A-Z][a-z])/, '\1_\2')
-
word.gsub!(/([a-z\d])([A-Z])/, '\1_\2')
-
word.tr!("-", "_")
-
word.downcase!
-
word
-
end
-
-
1
def file_at(path)
-
RSpec::Support::DirectoryMaker.mkdir_p(File.dirname(path))
-
File.new(path, 'w')
-
end
-
end
-
end
-
1
RSpec::Support.require_rspec_core "formatters/helpers"
-
1
require 'stringio'
-
-
1
module RSpec
-
1
module Core
-
1
module Formatters
-
# RSpec's built-in formatters are all subclasses of
-
# RSpec::Core::Formatters::BaseTextFormatter.
-
#
-
# @see RSpec::Core::Formatters::BaseTextFormatter
-
# @see RSpec::Core::Reporter
-
# @see RSpec::Core::Formatters::Protocol
-
1
class BaseFormatter
-
# All formatters inheriting from this formatter will receive these
-
# notifications.
-
1
Formatters.register self, :start, :example_group_started, :close
-
1
attr_accessor :example_group
-
1
attr_reader :output
-
-
# @api public
-
# @param output [IO] the formatter output
-
# @see RSpec::Core::Formatters::Protocol#initialize
-
1
def initialize(output)
-
1
@output = output || StringIO.new
-
1
@example_group = nil
-
end
-
-
# @api public
-
#
-
# @param notification [StartNotification]
-
# @see RSpec::Core::Formatters::Protocol#start
-
1
def start(notification)
-
1
start_sync_output
-
1
@example_count = notification.count
-
end
-
-
# @api public
-
#
-
# @param notification [GroupNotification] containing example_group
-
# subclass of `RSpec::Core::ExampleGroup`
-
# @see RSpec::Core::Formatters::Protocol#example_group_started
-
1
def example_group_started(notification)
-
33
@example_group = notification.group
-
end
-
-
# @api public
-
#
-
# @param _notification [NullNotification] (Ignored)
-
# @see RSpec::Core::Formatters::Protocol#close
-
1
def close(_notification)
-
restore_sync_output
-
end
-
-
1
private
-
-
1
def start_sync_output
-
1
@old_sync, output.sync = output.sync, true if output_supports_sync
-
end
-
-
1
def restore_sync_output
-
output.sync = @old_sync if output_supports_sync && !output.closed?
-
end
-
-
1
def output_supports_sync
-
1
output.respond_to?(:sync=)
-
end
-
end
-
end
-
end
-
end
-
1
RSpec::Support.require_rspec_core "formatters/base_formatter"
-
1
RSpec::Support.require_rspec_core "formatters/console_codes"
-
-
1
module RSpec
-
1
module Core
-
1
module Formatters
-
# Base for all of RSpec's built-in formatters. See
-
# RSpec::Core::Formatters::BaseFormatter to learn more about all of the
-
# methods called by the reporter.
-
#
-
# @see RSpec::Core::Formatters::BaseFormatter
-
# @see RSpec::Core::Reporter
-
1
class BaseTextFormatter < BaseFormatter
-
1
Formatters.register self,
-
:message, :dump_summary, :dump_failures, :dump_pending, :seed
-
-
# @api public
-
#
-
# Used by the reporter to send messages to the output stream.
-
#
-
# @param notification [MessageNotification] containing message
-
1
def message(notification)
-
output.puts notification.message
-
end
-
-
# @api public
-
#
-
# Dumps detailed information about each example failure.
-
#
-
# @param notification [NullNotification]
-
1
def dump_failures(notification)
-
1
return if notification.failure_notifications.empty?
-
output.puts notification.fully_formatted_failed_examples
-
end
-
-
# @api public
-
#
-
# This method is invoked after the dumping of examples and failures.
-
# Each parameter is assigned to a corresponding attribute.
-
#
-
# @param summary [SummaryNotification] containing duration,
-
# example_count, failure_count and pending_count
-
1
def dump_summary(summary)
-
1
output.puts summary.fully_formatted
-
end
-
-
# @private
-
1
def dump_pending(notification)
-
1
return if notification.pending_examples.empty?
-
output.puts notification.fully_formatted_pending_examples
-
end
-
-
# @private
-
1
def seed(notification)
-
2
return unless notification.seed_used?
-
2
output.puts notification.fully_formatted
-
end
-
-
# @api public
-
#
-
# Invoked at the very end, `close` allows the formatter to clean
-
# up resources, e.g. open streams, etc.
-
#
-
# @param _notification [NullNotification] (Ignored)
-
1
def close(_notification)
-
1
return unless IO === output
-
1
return if output.closed?
-
-
1
output.puts
-
-
1
output.flush
-
1
output.close unless output == $stdout
-
end
-
end
-
end
-
end
-
end
-
1
module RSpec
-
1
module Core
-
1
module Formatters
-
# ConsoleCodes provides helpers for formatting console output
-
# with ANSI codes, e.g. color's and bold.
-
1
module ConsoleCodes
-
# @private
-
1
VT100_CODES =
-
{
-
:black => 30,
-
:red => 31,
-
:green => 32,
-
:yellow => 33,
-
:blue => 34,
-
:magenta => 35,
-
:cyan => 36,
-
:white => 37,
-
:bold => 1,
-
}
-
# @private
-
1
VT100_CODE_VALUES = VT100_CODES.invert
-
-
1
module_function
-
-
# @private
-
1
CONFIG_COLORS_TO_METHODS = Configuration.instance_methods.grep(/_color\z/).inject({}) do |hash, method|
-
6
hash[method.to_s.sub(/_color\z/, '').to_sym] = method
-
6
hash
-
end
-
-
# Fetches the correct code for the supplied symbol, or checks
-
# that a code is valid. Defaults to white (37).
-
#
-
# @param code_or_symbol [Symbol, Fixnum] Symbol or code to check
-
# @return [Fixnum] a console code
-
1
def console_code_for(code_or_symbol)
-
if (config_method = CONFIG_COLORS_TO_METHODS[code_or_symbol])
-
console_code_for RSpec.configuration.__send__(config_method)
-
elsif VT100_CODE_VALUES.key?(code_or_symbol)
-
code_or_symbol
-
else
-
VT100_CODES.fetch(code_or_symbol) do
-
console_code_for(:white)
-
end
-
end
-
end
-
-
# Wraps a piece of text in ANSI codes with the supplied code. Will
-
# only apply the control code if `RSpec.configuration.color_enabled?`
-
# returns true.
-
#
-
# @param text [String] the text to wrap
-
# @param code_or_symbol [Symbol, Fixnum] the desired control code
-
# @return [String] the wrapped text
-
1
def wrap(text, code_or_symbol)
-
22
if RSpec.configuration.color_enabled?
-
"\e[#{console_code_for(code_or_symbol)}m#{text}\e[0m"
-
else
-
22
text
-
end
-
end
-
end
-
end
-
end
-
end
-
1
RSpec::Support.require_rspec_core "formatters/helpers"
-
-
1
module RSpec
-
1
module Core
-
1
module Formatters
-
# @private
-
1
class DeprecationFormatter
-
1
Formatters.register self, :deprecation, :deprecation_summary
-
-
1
attr_reader :count, :deprecation_stream, :summary_stream
-
-
1
def initialize(deprecation_stream, summary_stream)
-
@deprecation_stream = deprecation_stream
-
@summary_stream = summary_stream
-
@seen_deprecations = Set.new
-
@count = 0
-
end
-
1
alias :output :deprecation_stream
-
-
1
def printer
-
@printer ||= case deprecation_stream
-
when File
-
ImmediatePrinter.new(FileStream.new(deprecation_stream),
-
summary_stream, self)
-
when RaiseErrorStream
-
ImmediatePrinter.new(deprecation_stream, summary_stream, self)
-
else
-
DelayedPrinter.new(deprecation_stream, summary_stream, self)
-
end
-
end
-
-
1
def deprecation(notification)
-
return if @seen_deprecations.include? notification
-
-
@count += 1
-
printer.print_deprecation_message notification
-
@seen_deprecations << notification
-
end
-
-
1
def deprecation_summary(_notification)
-
printer.deprecation_summary
-
end
-
-
1
def deprecation_message_for(data)
-
if data.message
-
SpecifiedDeprecationMessage.new(data)
-
else
-
GeneratedDeprecationMessage.new(data)
-
end
-
end
-
-
1
RAISE_ERROR_CONFIG_NOTICE = <<-EOS.gsub(/^\s+\|/, '')
-
|
-
|If you need more of the backtrace for any of these deprecations to
-
|identify where to make the necessary changes, you can configure
-
|`config.raise_errors_for_deprecations!`, and it will turn the
-
|deprecation warnings into errors, giving you the full backtrace.
-
EOS
-
-
1
DEPRECATION_STREAM_NOTICE = "Pass `--deprecation-out` or set " \
-
"`config.deprecation_stream` to a file for full output."
-
-
1
SpecifiedDeprecationMessage = Struct.new(:type) do
-
1
def initialize(data)
-
@message = data.message
-
super deprecation_type_for(data)
-
end
-
-
1
def to_s
-
output_formatted @message
-
end
-
-
1
def too_many_warnings_message
-
msg = "Too many similar deprecation messages reported, disregarding further reports. "
-
msg << DEPRECATION_STREAM_NOTICE
-
msg
-
end
-
-
1
private
-
-
1
def output_formatted(str)
-
return str unless str.lines.count > 1
-
separator = "#{'-' * 80}"
-
"#{separator}\n#{str.chomp}\n#{separator}"
-
end
-
-
1
def deprecation_type_for(data)
-
data.message.gsub(/(\w+\/)+\w+\.rb:\d+/, '')
-
end
-
end
-
-
1
GeneratedDeprecationMessage = Struct.new(:type) do
-
1
def initialize(data)
-
@data = data
-
super data.deprecated
-
end
-
-
1
def to_s
-
msg = "#{@data.deprecated} is deprecated."
-
msg << " Use #{@data.replacement} instead." if @data.replacement
-
msg << " Called from #{@data.call_site}." if @data.call_site
-
msg
-
end
-
-
1
def too_many_warnings_message
-
msg = "Too many uses of deprecated '#{type}'. "
-
msg << DEPRECATION_STREAM_NOTICE
-
msg
-
end
-
end
-
-
# @private
-
1
class ImmediatePrinter
-
1
attr_reader :deprecation_stream, :summary_stream, :deprecation_formatter
-
-
1
def initialize(deprecation_stream, summary_stream, deprecation_formatter)
-
@deprecation_stream = deprecation_stream
-
-
@summary_stream = summary_stream
-
@deprecation_formatter = deprecation_formatter
-
end
-
-
1
def print_deprecation_message(data)
-
deprecation_message = deprecation_formatter.deprecation_message_for(data)
-
deprecation_stream.puts deprecation_message.to_s
-
end
-
-
1
def deprecation_summary
-
return if deprecation_formatter.count.zero?
-
deprecation_stream.summarize(summary_stream, deprecation_formatter.count)
-
end
-
end
-
-
# @private
-
1
class DelayedPrinter
-
1
TOO_MANY_USES_LIMIT = 4
-
-
1
attr_reader :deprecation_stream, :summary_stream, :deprecation_formatter
-
-
1
def initialize(deprecation_stream, summary_stream, deprecation_formatter)
-
@deprecation_stream = deprecation_stream
-
@summary_stream = summary_stream
-
@deprecation_formatter = deprecation_formatter
-
@seen_deprecations = Hash.new { 0 }
-
@deprecation_messages = Hash.new { |h, k| h[k] = [] }
-
end
-
-
1
def print_deprecation_message(data)
-
deprecation_message = deprecation_formatter.deprecation_message_for(data)
-
@seen_deprecations[deprecation_message] += 1
-
-
stash_deprecation_message(deprecation_message)
-
end
-
-
1
def stash_deprecation_message(deprecation_message)
-
if @seen_deprecations[deprecation_message] < TOO_MANY_USES_LIMIT
-
@deprecation_messages[deprecation_message] << deprecation_message.to_s
-
elsif @seen_deprecations[deprecation_message] == TOO_MANY_USES_LIMIT
-
@deprecation_messages[deprecation_message] << deprecation_message.too_many_warnings_message
-
end
-
end
-
-
1
def deprecation_summary
-
return unless @deprecation_messages.any?
-
-
print_deferred_deprecation_warnings
-
deprecation_stream.puts RAISE_ERROR_CONFIG_NOTICE
-
-
summary_stream.puts "\n#{Helpers.pluralize(deprecation_formatter.count, 'deprecation warning')} total"
-
end
-
-
1
def print_deferred_deprecation_warnings
-
deprecation_stream.puts "\nDeprecation Warnings:\n\n"
-
@deprecation_messages.keys.sort_by(&:type).each do |deprecation|
-
messages = @deprecation_messages[deprecation]
-
messages.each { |msg| deprecation_stream.puts msg }
-
deprecation_stream.puts
-
end
-
end
-
end
-
-
# @private
-
# Not really a stream, but is usable in place of one.
-
1
class RaiseErrorStream
-
1
def puts(message)
-
raise DeprecationError, message
-
end
-
-
1
def summarize(summary_stream, deprecation_count)
-
summary_stream.puts "\n#{Helpers.pluralize(deprecation_count, 'deprecation')} found."
-
end
-
end
-
-
# @private
-
# Wraps a File object and provides file-specific operations.
-
1
class FileStream
-
1
def initialize(file)
-
@file = file
-
-
# In one of my test suites, I got lots of duplicate output in the
-
# deprecation file (e.g. 200 of the same deprecation, even though
-
# the `puts` below was only called 6 times). Setting `sync = true`
-
# fixes this (but we really have no idea why!).
-
@file.sync = true
-
end
-
-
1
def puts(*args)
-
@file.puts(*args)
-
end
-
-
1
def summarize(summary_stream, deprecation_count)
-
path = @file.respond_to?(:path) ? @file.path : @file.inspect
-
summary_stream.puts "\n#{Helpers.pluralize(deprecation_count, 'deprecation')} logged to #{path}"
-
puts RAISE_ERROR_CONFIG_NOTICE
-
end
-
end
-
end
-
end
-
-
# Deprecation Error.
-
1
DeprecationError = Class.new(StandardError)
-
end
-
end
-
# encoding: utf-8
-
1
RSpec::Support.require_rspec_core "formatters/snippet_extractor"
-
1
RSpec::Support.require_rspec_support "encoded_string"
-
-
1
module RSpec
-
1
module Core
-
1
module Formatters
-
# @private
-
1
class ExceptionPresenter
-
1
attr_reader :exception, :example, :description, :message_color,
-
:detail_formatter, :extra_detail_formatter, :backtrace_formatter
-
1
private :message_color, :detail_formatter, :extra_detail_formatter, :backtrace_formatter
-
-
1
def initialize(exception, example, options={})
-
@exception = exception
-
@example = example
-
@message_color = options.fetch(:message_color) { RSpec.configuration.failure_color }
-
@description = options.fetch(:description) { example.full_description }
-
@detail_formatter = options.fetch(:detail_formatter) { Proc.new {} }
-
@extra_detail_formatter = options.fetch(:extra_detail_formatter) { Proc.new {} }
-
@backtrace_formatter = options.fetch(:backtrace_formatter) { RSpec.configuration.backtrace_formatter }
-
@indentation = options.fetch(:indentation, 2)
-
@skip_shared_group_trace = options.fetch(:skip_shared_group_trace, false)
-
@failure_lines = options[:failure_lines]
-
end
-
-
1
def message_lines
-
add_shared_group_lines(failure_lines, Notifications::NullColorizer)
-
end
-
-
1
def colorized_message_lines(colorizer=::RSpec::Core::Formatters::ConsoleCodes)
-
add_shared_group_lines(failure_lines, colorizer).map do |line|
-
colorizer.wrap line, message_color
-
end
-
end
-
-
1
def formatted_backtrace(exception=@exception)
-
backtrace_formatter.format_backtrace(exception.backtrace, example.metadata) +
-
formatted_cause(exception)
-
end
-
-
1
if RSpec::Support::RubyFeatures.supports_exception_cause?
-
1
def formatted_cause(exception)
-
last_cause = final_exception(exception)
-
cause = []
-
-
if exception.cause
-
cause << '------------------'
-
cause << '--- Caused by: ---'
-
cause << "#{exception_class_name(last_cause)}:" unless exception_class_name(last_cause) =~ /RSpec/
-
-
encoded_string(last_cause.message.to_s).split("\n").each do |line|
-
cause << " #{line}"
-
end
-
-
cause << (" #{backtrace_formatter.format_backtrace(last_cause.backtrace, example.metadata).first}")
-
end
-
-
cause
-
end
-
else
-
# :nocov:
-
skipped
def formatted_cause(_)
-
skipped
[]
-
skipped
end
-
# :nocov:
-
end
-
-
1
def colorized_formatted_backtrace(colorizer=::RSpec::Core::Formatters::ConsoleCodes)
-
formatted_backtrace.map do |backtrace_info|
-
colorizer.wrap "# #{backtrace_info}", RSpec.configuration.detail_color
-
end
-
end
-
-
1
def fully_formatted(failure_number, colorizer=::RSpec::Core::Formatters::ConsoleCodes)
-
lines = fully_formatted_lines(failure_number, colorizer)
-
lines.join("\n") << "\n"
-
end
-
-
1
def fully_formatted_lines(failure_number, colorizer)
-
lines = [
-
description,
-
detail_formatter.call(example, colorizer),
-
formatted_message_and_backtrace(colorizer),
-
extra_detail_formatter.call(failure_number, colorizer),
-
].compact.flatten
-
-
lines = indent_lines(lines, failure_number)
-
lines.unshift("")
-
lines
-
end
-
-
1
private
-
-
1
def final_exception(exception, previous=[])
-
cause = exception.cause
-
if cause && !previous.include?(cause)
-
previous << cause
-
final_exception(cause, previous)
-
else
-
exception
-
end
-
end
-
-
1
if String.method_defined?(:encoding)
-
1
def encoding_of(string)
-
string.encoding
-
end
-
-
1
def encoded_string(string)
-
RSpec::Support::EncodedString.new(string, Encoding.default_external)
-
end
-
else # for 1.8.7
-
# :nocov:
-
skipped
def encoding_of(_string)
-
skipped
end
-
skipped
-
skipped
def encoded_string(string)
-
skipped
RSpec::Support::EncodedString.new(string)
-
skipped
end
-
# :nocov:
-
end
-
-
1
def indent_lines(lines, failure_number)
-
alignment_basis = "#{' ' * @indentation}#{failure_number}) "
-
indentation = ' ' * alignment_basis.length
-
-
lines.each_with_index.map do |line, index|
-
if index == 0
-
"#{alignment_basis}#{line}"
-
elsif line.empty?
-
line
-
else
-
"#{indentation}#{line}"
-
end
-
end
-
end
-
-
1
def exception_class_name(exception=@exception)
-
name = exception.class.name.to_s
-
name = "(anonymous error class)" if name == ''
-
name
-
end
-
-
1
def failure_lines
-
@failure_lines ||= [].tap do |lines|
-
lines.concat(failure_slash_error_lines)
-
-
sections = [failure_slash_error_lines, exception_lines]
-
if sections.any? { |section| section.size > 1 } && !exception_lines.first.empty?
-
lines << ''
-
end
-
-
lines.concat(exception_lines)
-
lines.concat(extra_failure_lines)
-
end
-
end
-
-
1
def failure_slash_error_lines
-
lines = read_failed_lines
-
if lines.count == 1
-
lines[0] = "Failure/Error: #{lines[0].strip}"
-
else
-
least_indentation = SnippetExtractor.least_indentation_from(lines)
-
lines = lines.map { |line| line.sub(/^#{least_indentation}/, ' ') }
-
lines.unshift('Failure/Error:')
-
end
-
lines
-
end
-
-
1
def exception_lines
-
lines = []
-
lines << "#{exception_class_name}:" unless exception_class_name =~ /RSpec/
-
encoded_string(exception.message.to_s).split("\n").each do |line|
-
lines << (line.empty? ? line : " #{line}")
-
end
-
lines
-
end
-
-
1
def extra_failure_lines
-
@extra_failure_lines ||= begin
-
lines = Array(example.metadata[:extra_failure_lines])
-
unless lines.empty?
-
lines.unshift('')
-
lines.push('')
-
end
-
lines
-
end
-
end
-
-
1
def add_shared_group_lines(lines, colorizer)
-
return lines if @skip_shared_group_trace
-
-
example.metadata[:shared_group_inclusion_backtrace].each do |frame|
-
lines << colorizer.wrap(frame.description, RSpec.configuration.default_color)
-
end
-
-
lines
-
end
-
-
1
def read_failed_lines
-
matching_line = find_failed_line
-
unless matching_line
-
return ["Unable to find matching line from backtrace"]
-
end
-
-
file_path, line_number = matching_line.match(/(.+?):(\d+)(|:\d+)/)[1..2]
-
max_line_count = RSpec.configuration.max_displayed_failure_line_count
-
lines = SnippetExtractor.extract_expression_lines_at(file_path, line_number.to_i, max_line_count)
-
RSpec.world.source_cache.syntax_highlighter.highlight(lines)
-
rescue SnippetExtractor::NoSuchFileError
-
["Unable to find #{file_path} to read failed line"]
-
rescue SnippetExtractor::NoSuchLineError
-
["Unable to find matching line in #{file_path}"]
-
rescue SecurityError
-
["Unable to read failed line"]
-
end
-
-
1
def find_failed_line
-
line_regex = RSpec.configuration.in_project_source_dir_regex
-
loaded_spec_files = RSpec.configuration.loaded_spec_files
-
-
exception_backtrace.find do |line|
-
next unless (line_path = line[/(.+?):(\d+)(|:\d+)/, 1])
-
path = File.expand_path(line_path)
-
loaded_spec_files.include?(path) || path =~ line_regex
-
end || exception_backtrace.first
-
end
-
-
1
def formatted_message_and_backtrace(colorizer)
-
lines = colorized_message_lines(colorizer) + colorized_formatted_backtrace(colorizer)
-
encoding = encoding_of("")
-
lines.map do |line|
-
RSpec::Support::EncodedString.new(line, encoding)
-
end
-
end
-
-
1
def exception_backtrace
-
exception.backtrace || []
-
end
-
-
# @private
-
# Configuring the `ExceptionPresenter` with the right set of options to handle
-
# pending vs failed vs skipped and aggregated (or not) failures is not simple.
-
# This class takes care of building an appropriate `ExceptionPresenter` for the
-
# provided example.
-
1
class Factory
-
1
def build
-
ExceptionPresenter.new(@exception, @example, options)
-
end
-
-
1
private
-
-
1
def initialize(example)
-
@example = example
-
@execution_result = example.execution_result
-
@exception = if @execution_result.status == :pending
-
@execution_result.pending_exception
-
else
-
@execution_result.exception
-
end
-
end
-
-
1
def options
-
with_multiple_error_options_as_needed(@exception, pending_options || {})
-
end
-
-
1
def pending_options
-
if @execution_result.pending_fixed?
-
{
-
:description => "#{@example.full_description} FIXED",
-
:message_color => RSpec.configuration.fixed_color,
-
:failure_lines => [
-
"Expected pending '#{@execution_result.pending_message}' to fail. No Error was raised."
-
]
-
}
-
elsif @execution_result.status == :pending
-
{
-
:message_color => RSpec.configuration.pending_color,
-
:detail_formatter => PENDING_DETAIL_FORMATTER
-
}
-
end
-
end
-
-
1
def with_multiple_error_options_as_needed(exception, options)
-
return options unless multiple_exceptions_error?(exception)
-
-
options = options.merge(
-
:failure_lines => [],
-
:extra_detail_formatter => sub_failure_list_formatter(exception, options[:message_color]),
-
:detail_formatter => multiple_exception_summarizer(exception,
-
options[:detail_formatter],
-
options[:message_color])
-
)
-
-
return options unless exception.aggregation_metadata[:hide_backtrace]
-
options[:backtrace_formatter] = EmptyBacktraceFormatter
-
options
-
end
-
-
1
def multiple_exceptions_error?(exception)
-
MultipleExceptionError::InterfaceTag === exception
-
end
-
-
1
def multiple_exception_summarizer(exception, prior_detail_formatter, color)
-
lambda do |example, colorizer|
-
summary = if exception.aggregation_metadata[:hide_backtrace]
-
# Since the backtrace is hidden, the subfailures will come
-
# immediately after this, and using `:` will read well.
-
"Got #{exception.exception_count_description}:"
-
else
-
# The backtrace comes after this, so using a `:` doesn't make sense
-
# since the failures may be many lines below.
-
"#{exception.summary}."
-
end
-
-
summary = colorizer.wrap(summary, color || RSpec.configuration.failure_color)
-
return summary unless prior_detail_formatter
-
[
-
prior_detail_formatter.call(example, colorizer),
-
summary
-
]
-
end
-
end
-
-
1
def sub_failure_list_formatter(exception, message_color)
-
common_backtrace_truncater = CommonBacktraceTruncater.new(exception)
-
-
lambda do |failure_number, colorizer|
-
FlatMap.flat_map(exception.all_exceptions.each_with_index) do |failure, index|
-
options = with_multiple_error_options_as_needed(
-
failure,
-
:description => nil,
-
:indentation => 0,
-
:message_color => message_color || RSpec.configuration.failure_color,
-
:skip_shared_group_trace => true
-
)
-
-
failure = common_backtrace_truncater.with_truncated_backtrace(failure)
-
presenter = ExceptionPresenter.new(failure, @example, options)
-
presenter.fully_formatted_lines("#{failure_number}.#{index + 1}", colorizer)
-
end
-
end
-
end
-
-
# @private
-
# Used to prevent a confusing backtrace from showing up from the `aggregate_failures`
-
# block declared for `:aggregate_failures` metadata.
-
1
module EmptyBacktraceFormatter
-
1
def self.format_backtrace(*)
-
[]
-
end
-
end
-
-
# @private
-
1
class CommonBacktraceTruncater
-
1
def initialize(parent)
-
@parent = parent
-
end
-
-
1
def with_truncated_backtrace(child)
-
child_bt = child.backtrace
-
parent_bt = @parent.backtrace
-
return child if child_bt.nil? || child_bt.empty? || parent_bt.nil?
-
-
index_before_first_common_frame = -1.downto(-child_bt.size).find do |index|
-
parent_bt[index] != child_bt[index]
-
end
-
-
return child if index_before_first_common_frame == -1
-
-
child = child.dup
-
child.set_backtrace(child_bt[0..index_before_first_common_frame])
-
child
-
end
-
end
-
end
-
-
# @private
-
1
PENDING_DETAIL_FORMATTER = Proc.new do |example, colorizer|
-
colorizer.wrap("# #{example.execution_result.pending_message}", :detail)
-
end
-
end
-
end
-
-
# Provides a single exception instance that provides access to
-
# multiple sub-exceptions. This is used in situations where a single
-
# individual spec has multiple exceptions, such as one in the `it` block
-
# and one in an `after` block.
-
1
class MultipleExceptionError < StandardError
-
# @private
-
# Used so there is a common module in the ancestor chain of this class
-
# and `RSpec::Expectations::MultipleExpectationsNotMetError`, which allows
-
# code to detect exceptions that are instances of either, without first
-
# checking to see if rspec-expectations is loaded.
-
1
module InterfaceTag
-
# Appends the provided exception to the list.
-
# @param exception [Exception] Exception to append to the list.
-
# @private
-
1
def add(exception)
-
# `PendingExampleFixedError` can be assigned to an example that initially has no
-
# failures, but when the `aggregate_failures` around hook completes, it notifies of
-
# a failure. If we do not ignore `PendingExampleFixedError` it would be surfaced to
-
# the user as part of a multiple exception error, which is undesirable. While it's
-
# pretty weird we handle this here, it's the best solution I've been able to come
-
# up with, and `PendingExampleFixedError` always represents the _lack_ of any exception
-
# so clearly when we are transitioning to a `MultipleExceptionError`, it makes sense to
-
# ignore it.
-
return if Pending::PendingExampleFixedError === exception
-
-
all_exceptions << exception
-
-
if exception.class.name =~ /RSpec/
-
failures << exception
-
else
-
other_errors << exception
-
end
-
end
-
-
# Provides a way to force `ex` to be something that satisfies the multiple
-
# exception error interface. If it already satisfies it, it will be returned;
-
# otherwise it will wrap it in a `MultipleExceptionError`.
-
# @private
-
1
def self.for(ex)
-
return ex if self === ex
-
MultipleExceptionError.new(ex)
-
end
-
end
-
-
1
include InterfaceTag
-
-
# @return [Array<Exception>] The list of failures.
-
1
attr_reader :failures
-
-
# @return [Array<Exception>] The list of other errors.
-
1
attr_reader :other_errors
-
-
# @return [Array<Exception>] The list of failures and other exceptions, combined.
-
1
attr_reader :all_exceptions
-
-
# @return [Hash] Metadata used by RSpec for formatting purposes.
-
1
attr_reader :aggregation_metadata
-
-
# @return [nil] Provided only for interface compatibility with
-
# `RSpec::Expectations::MultipleExpectationsNotMetError`.
-
1
attr_reader :aggregation_block_label
-
-
# @param exceptions [Array<Exception>] The initial list of exceptions.
-
1
def initialize(*exceptions)
-
super()
-
-
@failures = []
-
@other_errors = []
-
@all_exceptions = []
-
@aggregation_metadata = { :hide_backtrace => true }
-
@aggregation_block_label = nil
-
-
exceptions.each { |e| add e }
-
end
-
-
# @return [String] Combines all the exception messages into a single string.
-
# @note RSpec does not actually use this -- instead it formats each exception
-
# individually.
-
1
def message
-
all_exceptions.map(&:message).join("\n\n")
-
end
-
-
# @return [String] A summary of the failure, including the block label and a count of failures.
-
1
def summary
-
"Got #{exception_count_description}"
-
end
-
-
# return [String] A description of the failure/error counts.
-
1
def exception_count_description
-
failure_count = Formatters::Helpers.pluralize(failures.size, "failure")
-
return failure_count if other_errors.empty?
-
error_count = Formatters::Helpers.pluralize(other_errors.size, "other error")
-
"#{failure_count} and #{error_count}"
-
end
-
end
-
end
-
end
-
1
RSpec::Support.require_rspec_core "shell_escape"
-
-
1
module RSpec
-
1
module Core
-
1
module Formatters
-
# Formatters helpers.
-
1
module Helpers
-
# @private
-
1
SUB_SECOND_PRECISION = 5
-
-
# @private
-
1
DEFAULT_PRECISION = 2
-
-
# @api private
-
#
-
# Formats seconds into a human-readable string.
-
#
-
# @param duration [Float, Fixnum] in seconds
-
# @return [String] human-readable time
-
#
-
# @example
-
# format_duration(1) #=> "1 minute 1 second"
-
# format_duration(135.14) #=> "2 minutes 15.14 seconds"
-
1
def self.format_duration(duration)
-
precision = case
-
when duration < 1 then SUB_SECOND_PRECISION
-
when duration < 120 then DEFAULT_PRECISION
-
when duration < 300 then 1
-
else 0
-
end
-
-
if duration > 60
-
minutes = (duration.to_i / 60).to_i
-
seconds = duration - minutes * 60
-
-
"#{pluralize(minutes, 'minute')} #{pluralize(format_seconds(seconds, precision), 'second')}"
-
else
-
pluralize(format_seconds(duration, precision), 'second')
-
end
-
end
-
-
# @api private
-
#
-
# Formats seconds to have 5 digits of precision with trailing zeros
-
# removed if the number is less than 1 or with 2 digits of precision if
-
# the number is greater than zero.
-
#
-
# @param float [Float]
-
# @return [String] formatted float
-
#
-
# @example
-
# format_seconds(0.000006) #=> "0.00001"
-
# format_seconds(0.020000) #=> "0.02"
-
# format_seconds(1.00000000001) #=> "1"
-
#
-
# The precision used is set in {Helpers::SUB_SECOND_PRECISION} and
-
# {Helpers::DEFAULT_PRECISION}.
-
#
-
# @see #strip_trailing_zeroes
-
1
def self.format_seconds(float, precision=nil)
-
precision ||= (float < 1) ? SUB_SECOND_PRECISION : DEFAULT_PRECISION
-
formatted = "%.#{precision}f" % float
-
strip_trailing_zeroes(formatted)
-
end
-
-
# @api private
-
#
-
# Remove trailing zeros from a string.
-
#
-
# Only remove trailing zeros after a decimal place.
-
# see: http://rubular.com/r/ojtTydOgpn
-
#
-
# @param string [String] string with trailing zeros
-
# @return [String] string with trailing zeros removed
-
1
def self.strip_trailing_zeroes(string)
-
string.sub(/(?:(\..*[^0])0+|\.0+)$/, '\1')
-
end
-
1
private_class_method :strip_trailing_zeroes
-
-
# @api private
-
#
-
# Pluralize a word based on a count.
-
#
-
# @param count [Fixnum] number of objects
-
# @param string [String] word to be pluralized
-
# @return [String] pluralized word
-
1
def self.pluralize(count, string)
-
"#{count} #{string}#{'s' unless count.to_f == 1}"
-
end
-
-
# @api private
-
# Given a list of example ids, organizes them into a compact, ordered list.
-
1
def self.organize_ids(ids)
-
grouped = ids.inject(Hash.new { |h, k| h[k] = [] }) do |hash, id|
-
file, id = Example.parse_id(id)
-
hash[file] << id
-
hash
-
end
-
-
grouped.sort_by(&:first).map do |file, grouped_ids|
-
grouped_ids = grouped_ids.sort_by { |id| id.split(':').map(&:to_i) }
-
id = Metadata.id_from(:rerun_file_path => file, :scoped_id => grouped_ids.join(','))
-
ShellEscape.conditionally_quote(id)
-
end
-
end
-
end
-
end
-
end
-
end
-
1
RSpec::Support.require_rspec_core "formatters/base_text_formatter"
-
-
1
module RSpec
-
1
module Core
-
1
module Formatters
-
# @private
-
1
class ProgressFormatter < BaseTextFormatter
-
1
Formatters.register self, :example_passed, :example_pending, :example_failed, :start_dump
-
-
1
def example_passed(_notification)
-
21
output.print ConsoleCodes.wrap('.', :success)
-
end
-
-
1
def example_pending(_notification)
-
output.print ConsoleCodes.wrap('*', :pending)
-
end
-
-
1
def example_failed(_notification)
-
output.print ConsoleCodes.wrap('F', :failure)
-
end
-
-
1
def start_dump(_notification)
-
1
output.puts
-
end
-
end
-
end
-
end
-
end
-
1
RSpec::Support.require_rspec_core "source"
-
-
1
module RSpec
-
1
module Core
-
1
module Formatters
-
# @private
-
1
class SnippetExtractor
-
1
NoSuchFileError = Class.new(StandardError)
-
1
NoSuchLineError = Class.new(StandardError)
-
-
1
def self.extract_line_at(file_path, line_number)
-
source = source_from_file(file_path)
-
line = source.lines[line_number - 1]
-
raise NoSuchLineError unless line
-
line
-
end
-
-
1
def self.source_from_file(path)
-
raise NoSuchFileError unless File.exist?(path)
-
RSpec.world.source_cache.source_from_file(path)
-
end
-
-
1
if RSpec::Support::RubyFeatures.ripper_supported?
-
1
NoExpressionAtLineError = Class.new(StandardError)
-
-
1
attr_reader :source, :beginning_line_number, :max_line_count
-
-
1
def self.extract_expression_lines_at(file_path, beginning_line_number, max_line_count=nil)
-
if max_line_count == 1
-
[extract_line_at(file_path, beginning_line_number)]
-
else
-
source = source_from_file(file_path)
-
new(source, beginning_line_number, max_line_count).expression_lines
-
end
-
end
-
-
1
def initialize(source, beginning_line_number, max_line_count=nil)
-
@source = source
-
@beginning_line_number = beginning_line_number
-
@max_line_count = max_line_count
-
end
-
-
1
def expression_lines
-
line_range = line_range_of_expression
-
-
if max_line_count && line_range.count > max_line_count
-
line_range = (line_range.begin)..(line_range.begin + max_line_count - 1)
-
end
-
-
source.lines[(line_range.begin - 1)..(line_range.end - 1)]
-
rescue SyntaxError, NoExpressionAtLineError
-
[self.class.extract_line_at(source.path, beginning_line_number)]
-
end
-
-
1
private
-
-
1
def line_range_of_expression
-
@line_range_of_expression ||= begin
-
line_range = line_range_of_location_nodes_in_expression
-
initial_unclosed_tokens = unclosed_tokens_in_line_range(line_range)
-
unclosed_tokens = initial_unclosed_tokens
-
-
until (initial_unclosed_tokens & unclosed_tokens).empty?
-
line_range = (line_range.begin)..(line_range.end + 1)
-
unclosed_tokens = unclosed_tokens_in_line_range(line_range)
-
end
-
-
line_range
-
end
-
end
-
-
1
def unclosed_tokens_in_line_range(line_range)
-
tokens = FlatMap.flat_map(line_range) do |line_number|
-
source.tokens_by_line_number[line_number]
-
end
-
-
tokens.each_with_object([]) do |token, unclosed_tokens|
-
if token.opening?
-
unclosed_tokens << token
-
else
-
index = unclosed_tokens.rindex do |unclosed_token|
-
unclosed_token.closed_by?(token)
-
end
-
unclosed_tokens.delete_at(index) if index
-
end
-
end
-
end
-
-
1
def line_range_of_location_nodes_in_expression
-
line_numbers = expression_node.each_with_object(Set.new) do |node, set|
-
set << node.location.line if node.location
-
end
-
-
line_numbers.min..line_numbers.max
-
end
-
-
1
def expression_node
-
raise NoExpressionAtLineError if location_nodes_at_beginning_line.empty?
-
-
@expression_node ||= begin
-
common_ancestor_nodes = location_nodes_at_beginning_line.map do |node|
-
node.each_ancestor.to_a
-
end.reduce(:&)
-
-
common_ancestor_nodes.find { |node| expression_outmost_node?(node) }
-
end
-
end
-
-
1
def expression_outmost_node?(node)
-
return true unless node.parent
-
return false if node.type.to_s.start_with?('@')
-
![node, node.parent].all? do |n|
-
# See `Ripper::PARSER_EVENTS` for the complete list of sexp types.
-
type = n.type.to_s
-
type.end_with?('call') || type.start_with?('method_add_')
-
end
-
end
-
-
1
def location_nodes_at_beginning_line
-
source.nodes_by_line_number[beginning_line_number]
-
end
-
else
-
# :nocov:
-
skipped
def self.extract_expression_lines_at(file_path, beginning_line_number, *)
-
skipped
[extract_line_at(file_path, beginning_line_number)]
-
skipped
end
-
# :nocov:
-
end
-
-
1
def self.least_indentation_from(lines)
-
lines.map { |line| line[/^[ \t]*/] }.min
-
end
-
end
-
end
-
end
-
end
-
1
module RSpec
-
1
module Core
-
# Provides `before`, `after` and `around` hooks as a means of
-
# supporting common setup and teardown. This module is extended
-
# onto {ExampleGroup}, making the methods available from any `describe`
-
# or `context` block and included in {Configuration}, making them
-
# available off of the configuration object to define global setup
-
# or teardown logic.
-
1
module Hooks
-
# @api public
-
#
-
# @overload before(&block)
-
# @overload before(scope, &block)
-
# @param scope [Symbol] `:example`, `:context`, or `:suite`
-
# (defaults to `:example`)
-
# @overload before(scope, conditions, &block)
-
# @param scope [Symbol] `:example`, `:context`, or `:suite`
-
# (defaults to `:example`)
-
# @param conditions [Hash]
-
# constrains this hook to examples matching these conditions e.g.
-
# `before(:example, :ui => true) { ... }` will only run with examples
-
# or groups declared with `:ui => true`.
-
# @overload before(conditions, &block)
-
# @param conditions [Hash]
-
# constrains this hook to examples matching these conditions e.g.
-
# `before(:example, :ui => true) { ... }` will only run with examples
-
# or groups declared with `:ui => true`.
-
#
-
# @see #after
-
# @see #around
-
# @see ExampleGroup
-
# @see SharedContext
-
# @see SharedExampleGroup
-
# @see Configuration
-
#
-
# Declare a block of code to be run before each example (using `:example`)
-
# or once before any example (using `:context`). These are usually
-
# declared directly in the {ExampleGroup} to which they apply, but they
-
# can also be shared across multiple groups.
-
#
-
# You can also use `before(:suite)` to run a block of code before any
-
# example groups are run. This should be declared in {RSpec.configure}.
-
#
-
# Instance variables declared in `before(:example)` or `before(:context)`
-
# are accessible within each example.
-
#
-
# ### Order
-
#
-
# `before` hooks are stored in three scopes, which are run in order:
-
# `:suite`, `:context`, and `:example`. They can also be declared in
-
# several different places: `RSpec.configure`, a parent group, the current
-
# group. They are run in the following order:
-
#
-
# before(:suite) # Declared in RSpec.configure.
-
# before(:context) # Declared in RSpec.configure.
-
# before(:context) # Declared in a parent group.
-
# before(:context) # Declared in the current group.
-
# before(:example) # Declared in RSpec.configure.
-
# before(:example) # Declared in a parent group.
-
# before(:example) # Declared in the current group.
-
#
-
# If more than one `before` is declared within any one scope, they are run
-
# in the order in which they are declared.
-
#
-
# ### Conditions
-
#
-
# When you add a conditions hash to `before(:example)` or
-
# `before(:context)`, RSpec will only apply that hook to groups or
-
# examples that match the conditions. e.g.
-
#
-
# RSpec.configure do |config|
-
# config.before(:example, :authorized => true) do
-
# log_in_as :authorized_user
-
# end
-
# end
-
#
-
# describe Something, :authorized => true do
-
# # The before hook will run in before each example in this group.
-
# end
-
#
-
# describe SomethingElse do
-
# it "does something", :authorized => true do
-
# # The before hook will run before this example.
-
# end
-
#
-
# it "does something else" do
-
# # The hook will not run before this example.
-
# end
-
# end
-
#
-
# Note that filtered config `:context` hooks can still be applied
-
# to individual examples that have matching metadata. Just like
-
# Ruby's object model is that every object has a singleton class
-
# which has only a single instance, RSpec's model is that every
-
# example has a singleton example group containing just the one
-
# example.
-
#
-
# ### Warning: `before(:suite, :with => :conditions)`
-
#
-
# The conditions hash is used to match against specific examples. Since
-
# `before(:suite)` is not run in relation to any specific example or
-
# group, conditions passed along with `:suite` are effectively ignored.
-
#
-
# ### Exceptions
-
#
-
# When an exception is raised in a `before` block, RSpec skips any
-
# subsequent `before` blocks and the example, but runs all of the
-
# `after(:example)` and `after(:context)` hooks.
-
#
-
# ### Warning: implicit before blocks
-
#
-
# `before` hooks can also be declared in shared contexts which get
-
# included implicitly either by you or by extension libraries. Since
-
# RSpec runs these in the order in which they are declared within each
-
# scope, load order matters, and can lead to confusing results when one
-
# before block depends on state that is prepared in another before block
-
# that gets run later.
-
#
-
# ### Warning: `before(:context)`
-
#
-
# It is very tempting to use `before(:context)` to speed things up, but we
-
# recommend that you avoid this as there are a number of gotchas, as well
-
# as things that simply don't work.
-
#
-
# #### Context
-
#
-
# `before(:context)` is run in an example that is generated to provide
-
# group context for the block.
-
#
-
# #### Instance variables
-
#
-
# Instance variables declared in `before(:context)` are shared across all
-
# the examples in the group. This means that each example can change the
-
# state of a shared object, resulting in an ordering dependency that can
-
# make it difficult to reason about failures.
-
#
-
# #### Unsupported RSpec constructs
-
#
-
# RSpec has several constructs that reset state between each example
-
# automatically. These are not intended for use from within
-
# `before(:context)`:
-
#
-
# * `let` declarations
-
# * `subject` declarations
-
# * Any mocking, stubbing or test double declaration
-
#
-
# ### other frameworks
-
#
-
# Mock object frameworks and database transaction managers (like
-
# ActiveRecord) are typically designed around the idea of setting up
-
# before an example, running that one example, and then tearing down. This
-
# means that mocks and stubs can (sometimes) be declared in
-
# `before(:context)`, but get torn down before the first real example is
-
# ever run.
-
#
-
# You _can_ create database-backed model objects in a `before(:context)`
-
# in rspec-rails, but it will not be wrapped in a transaction for you, so
-
# you are on your own to clean up in an `after(:context)` block.
-
#
-
# @example before(:example) declared in an {ExampleGroup}
-
#
-
# describe Thing do
-
# before(:example) do
-
# @thing = Thing.new
-
# end
-
#
-
# it "does something" do
-
# # Here you can access @thing.
-
# end
-
# end
-
#
-
# @example before(:context) declared in an {ExampleGroup}
-
#
-
# describe Parser do
-
# before(:context) do
-
# File.open(file_to_parse, 'w') do |f|
-
# f.write <<-CONTENT
-
# stuff in the file
-
# CONTENT
-
# end
-
# end
-
#
-
# it "parses the file" do
-
# Parser.parse(file_to_parse)
-
# end
-
#
-
# after(:context) do
-
# File.delete(file_to_parse)
-
# end
-
# end
-
#
-
# @note The `:example` and `:context` scopes are also available as
-
# `:each` and `:all`, respectively. Use whichever you prefer.
-
# @note The `:scope` alias is only supported for hooks registered on
-
# `RSpec.configuration` since they exist independently of any
-
# example or example group.
-
1
def before(*args, &block)
-
hooks.register :append, :before, *args, &block
-
end
-
-
1
alias_method :append_before, :before
-
-
# Adds `block` to the front of the list of `before` blocks in the same
-
# scope (`:example`, `:context`, or `:suite`).
-
#
-
# See {#before} for scoping semantics.
-
1
def prepend_before(*args, &block)
-
hooks.register :prepend, :before, *args, &block
-
end
-
-
# @api public
-
# @overload after(&block)
-
# @overload after(scope, &block)
-
# @param scope [Symbol] `:example`, `:context`, or `:suite` (defaults to
-
# `:example`)
-
# @overload after(scope, conditions, &block)
-
# @param scope [Symbol] `:example`, `:context`, or `:suite` (defaults to
-
# `:example`)
-
# @param conditions [Hash]
-
# constrains this hook to examples matching these conditions e.g.
-
# `after(:example, :ui => true) { ... }` will only run with examples
-
# or groups declared with `:ui => true`.
-
# @overload after(conditions, &block)
-
# @param conditions [Hash]
-
# constrains this hook to examples matching these conditions e.g.
-
# `after(:example, :ui => true) { ... }` will only run with examples
-
# or groups declared with `:ui => true`.
-
#
-
# @see #before
-
# @see #around
-
# @see ExampleGroup
-
# @see SharedContext
-
# @see SharedExampleGroup
-
# @see Configuration
-
#
-
# Declare a block of code to be run after each example (using `:example`)
-
# or once after all examples n the context (using `:context`). See
-
# {#before} for more information about ordering.
-
#
-
# ### Exceptions
-
#
-
# `after` hooks are guaranteed to run even when there are exceptions in
-
# `before` hooks or examples. When an exception is raised in an after
-
# block, the exception is captured for later reporting, and subsequent
-
# `after` blocks are run.
-
#
-
# ### Order
-
#
-
# `after` hooks are stored in three scopes, which are run in order:
-
# `:example`, `:context`, and `:suite`. They can also be declared in
-
# several different places: `RSpec.configure`, a parent group, the current
-
# group. They are run in the following order:
-
#
-
# after(:example) # Declared in the current group.
-
# after(:example) # Declared in a parent group.
-
# after(:example) # Declared in RSpec.configure.
-
# after(:context) # Declared in the current group.
-
# after(:context) # Declared in a parent group.
-
# after(:context) # Declared in RSpec.configure.
-
# after(:suite) # Declared in RSpec.configure.
-
#
-
# This is the reverse of the order in which `before` hooks are run.
-
# Similarly, if more than one `after` is declared within any one scope,
-
# they are run in reverse order of that in which they are declared.
-
#
-
# @note The `:example` and `:context` scopes are also available as
-
# `:each` and `:all`, respectively. Use whichever you prefer.
-
# @note The `:scope` alias is only supported for hooks registered on
-
# `RSpec.configuration` since they exist independently of any
-
# example or example group.
-
1
def after(*args, &block)
-
hooks.register :prepend, :after, *args, &block
-
end
-
-
1
alias_method :prepend_after, :after
-
-
# Adds `block` to the back of the list of `after` blocks in the same
-
# scope (`:example`, `:context`, or `:suite`).
-
#
-
# See {#after} for scoping semantics.
-
1
def append_after(*args, &block)
-
hooks.register :append, :after, *args, &block
-
end
-
-
# @api public
-
# @overload around(&block)
-
# @overload around(scope, &block)
-
# @param scope [Symbol] `:example` (defaults to `:example`)
-
# present for syntax parity with `before` and `after`, but
-
# `:example`/`:each` is the only supported value.
-
# @overload around(scope, conditions, &block)
-
# @param scope [Symbol] `:example` (defaults to `:example`)
-
# present for syntax parity with `before` and `after`, but
-
# `:example`/`:each` is the only supported value.
-
# @param conditions [Hash] constrains this hook to examples matching
-
# these conditions e.g. `around(:example, :ui => true) { ... }` will
-
# only run with examples or groups declared with `:ui => true`.
-
# @overload around(conditions, &block)
-
# @param conditions [Hash] constrains this hook to examples matching
-
# these conditions e.g. `around(:example, :ui => true) { ... }` will
-
# only run with examples or groups declared with `:ui => true`.
-
#
-
# @yield [Example] the example to run
-
#
-
# @note the syntax of `around` is similar to that of `before` and `after`
-
# but the semantics are quite different. `before` and `after` hooks are
-
# run in the context of of the examples with which they are associated,
-
# whereas `around` hooks are actually responsible for running the
-
# examples. Consequently, `around` hooks do not have direct access to
-
# resources that are made available within the examples and their
-
# associated `before` and `after` hooks.
-
#
-
# @note `:example`/`:each` is the only supported scope.
-
#
-
# Declare a block of code, parts of which will be run before and parts
-
# after the example. It is your responsibility to run the example:
-
#
-
# around(:example) do |ex|
-
# # Do some stuff before.
-
# ex.run
-
# # Do some stuff after.
-
# end
-
#
-
# The yielded example aliases `run` with `call`, which lets you treat it
-
# like a `Proc`. This is especially handy when working with libaries
-
# that manage their own setup and teardown using a block or proc syntax,
-
# e.g.
-
#
-
# around(:example) {|ex| Database.transaction(&ex)}
-
# around(:example) {|ex| FakeFS(&ex)}
-
#
-
1
def around(*args, &block)
-
1
hooks.register :prepend, :around, *args, &block
-
end
-
-
# @private
-
# Holds the various registered hooks.
-
1
def hooks
-
@hooks ||= HookCollections.new(self, FilterableItemRepository::UpdateOptimized)
-
end
-
-
1
private
-
-
# @private
-
1
class Hook
-
1
attr_reader :block, :options
-
-
1
def initialize(block, options)
-
1
@block = block
-
1
@options = options
-
end
-
end
-
-
# @private
-
1
class BeforeHook < Hook
-
1
def run(example)
-
example.instance_exec(example, &block)
-
end
-
end
-
-
# @private
-
1
class AfterHook < Hook
-
1
def run(example)
-
example.instance_exec(example, &block)
-
rescue Support::AllExceptionsExceptOnesWeMustNotRescue => ex
-
example.set_exception(ex)
-
end
-
end
-
-
# @private
-
1
class AfterContextHook < Hook
-
1
def run(example)
-
example.instance_exec(example, &block)
-
rescue Support::AllExceptionsExceptOnesWeMustNotRescue => e
-
# TODO: Come up with a better solution for this.
-
RSpec.configuration.reporter.message <<-EOS
-
-
An error occurred in an `after(:context)` hook.
-
#{e.class}: #{e.message}
-
occurred at #{e.backtrace.first}
-
-
EOS
-
end
-
end
-
-
# @private
-
1
class AroundHook < Hook
-
1
def execute_with(example, procsy)
-
example.instance_exec(procsy, &block)
-
return if procsy.executed?
-
Pending.mark_skipped!(example,
-
"#{hook_description} did not execute the example")
-
end
-
-
1
if Proc.method_defined?(:source_location)
-
1
def hook_description
-
"around hook at #{Metadata.relative_path(block.source_location.join(':'))}"
-
end
-
else # for 1.8.7
-
# :nocov:
-
skipped
def hook_description
-
skipped
"around hook"
-
skipped
end
-
# :nocov:
-
end
-
end
-
-
# @private
-
#
-
# This provides the primary API used by other parts of rspec-core. By hiding all
-
# implementation details behind this facade, it's allowed us to heavily optimize
-
# this, so that, for example, hook collection objects are only instantiated when
-
# a hook is added. This allows us to avoid many object allocations for the common
-
# case of a group having no hooks.
-
#
-
# This is only possible because this interface provides a "tell, don't ask"-style
-
# API, so that callers _tell_ this class what to do with the hooks, rather than
-
# asking this class for a list of hooks, and then doing something with them.
-
1
class HookCollections
-
1
def initialize(owner, filterable_item_repo_class)
-
1
@owner = owner
-
1
@filterable_item_repo_class = filterable_item_repo_class
-
1
@before_example_hooks = nil
-
1
@after_example_hooks = nil
-
1
@before_context_hooks = nil
-
1
@after_context_hooks = nil
-
1
@around_example_hooks = nil
-
end
-
-
1
def register_globals(host, globals)
-
parent_groups = host.parent_groups
-
-
process(host, parent_groups, globals, :before, :example, &:options)
-
process(host, parent_groups, globals, :after, :example, &:options)
-
process(host, parent_groups, globals, :around, :example, &:options)
-
-
process(host, parent_groups, globals, :before, :context, &:options)
-
process(host, parent_groups, globals, :after, :context, &:options)
-
end
-
-
1
def register_global_singleton_context_hooks(example, globals)
-
parent_groups = example.example_group.parent_groups
-
-
process(example, parent_groups, globals, :before, :context) { {} }
-
process(example, parent_groups, globals, :after, :context) { {} }
-
end
-
-
1
def register(prepend_or_append, position, *args, &block)
-
1
scope, options = scope_and_options_from(*args)
-
-
1
if scope == :suite
-
# TODO: consider making this an error in RSpec 4. For SemVer reasons,
-
# we are only warning in RSpec 3.
-
RSpec.warn_with "WARNING: `#{position}(:suite)` hooks are only supported on " \
-
"the RSpec configuration object. This " \
-
"`#{position}(:suite)` hook, registered on an example " \
-
"group, will be ignored."
-
return
-
end
-
-
1
hook = HOOK_TYPES[position][scope].new(block, options)
-
1
ensure_hooks_initialized_for(position, scope).__send__(prepend_or_append, hook, options)
-
end
-
-
# @private
-
#
-
# Runs all of the blocks stored with the hook in the context of the
-
# example. If no example is provided, just calls the hook directly.
-
1
def run(position, scope, example_or_group)
-
return if RSpec.configuration.dry_run?
-
-
if scope == :context
-
run_owned_hooks_for(position, :context, example_or_group)
-
else
-
case position
-
when :before then run_example_hooks_for(example_or_group, :before, :reverse_each)
-
when :after then run_example_hooks_for(example_or_group, :after, :each)
-
when :around then run_around_example_hooks_for(example_or_group) { yield }
-
end
-
end
-
end
-
-
1
SCOPES = [:example, :context]
-
-
1
SCOPE_ALIASES = { :each => :example, :all => :context }
-
-
1
HOOK_TYPES = {
-
:before => Hash.new { BeforeHook },
-
:after => Hash.new { AfterHook },
-
1
:around => Hash.new { AroundHook }
-
}
-
-
1
HOOK_TYPES[:after][:context] = AfterContextHook
-
-
1
protected
-
-
1
EMPTY_HOOK_ARRAY = [].freeze
-
-
1
def matching_hooks_for(position, scope, example_or_group)
-
repository = hooks_for(position, scope) { return EMPTY_HOOK_ARRAY }
-
-
# It would be nice to not have to switch on type here, but
-
# we don't want to define `ExampleGroup#metadata` because then
-
# `metadata` from within an individual example would return the
-
# group's metadata but the user would probably expect it to be
-
# the example's metadata.
-
metadata = case example_or_group
-
when ExampleGroup then example_or_group.class.metadata
-
else example_or_group.metadata
-
end
-
-
repository.items_for(metadata)
-
end
-
-
1
def all_hooks_for(position, scope)
-
hooks_for(position, scope) { return EMPTY_HOOK_ARRAY }.items_and_filters.map(&:first)
-
end
-
-
1
def run_owned_hooks_for(position, scope, example_or_group)
-
matching_hooks_for(position, scope, example_or_group).each do |hook|
-
hook.run(example_or_group)
-
end
-
end
-
-
1
def processable_hooks_for(position, scope, host)
-
if scope == :example
-
all_hooks_for(position, scope)
-
else
-
matching_hooks_for(position, scope, host)
-
end
-
end
-
-
1
private
-
-
1
def hooks_for(position, scope)
-
if position == :before
-
scope == :example ? @before_example_hooks : @before_context_hooks
-
elsif position == :after
-
scope == :example ? @after_example_hooks : @after_context_hooks
-
else # around
-
@around_example_hooks
-
end || yield
-
end
-
-
1
def ensure_hooks_initialized_for(position, scope)
-
1
if position == :before
-
if scope == :example
-
@before_example_hooks ||= @filterable_item_repo_class.new(:all?)
-
else
-
@before_context_hooks ||= @filterable_item_repo_class.new(:all?)
-
end
-
1
elsif position == :after
-
if scope == :example
-
@after_example_hooks ||= @filterable_item_repo_class.new(:all?)
-
else
-
@after_context_hooks ||= @filterable_item_repo_class.new(:all?)
-
end
-
else # around
-
1
@around_example_hooks ||= @filterable_item_repo_class.new(:all?)
-
end
-
end
-
-
1
def process(host, parent_groups, globals, position, scope)
-
hooks_to_process = globals.processable_hooks_for(position, scope, host)
-
return if hooks_to_process.empty?
-
-
hooks_to_process -= FlatMap.flat_map(parent_groups) do |group|
-
group.hooks.all_hooks_for(position, scope)
-
end
-
return if hooks_to_process.empty?
-
-
repository = ensure_hooks_initialized_for(position, scope)
-
hooks_to_process.each { |hook| repository.append hook, (yield hook) }
-
end
-
-
1
def scope_and_options_from(*args)
-
1
return :suite if args.first == :suite
-
1
scope = extract_scope_from(args)
-
1
meta = Metadata.build_hash_from(args, :warn_about_example_group_filtering)
-
1
return scope, meta
-
end
-
-
1
def extract_scope_from(args)
-
1
if known_scope?(args.first)
-
1
normalized_scope_for(args.shift)
-
elsif args.any? { |a| a.is_a?(Symbol) }
-
error_message = "You must explicitly give a scope " \
-
"(#{SCOPES.join(", ")}) or scope alias " \
-
"(#{SCOPE_ALIASES.keys.join(", ")}) when using symbols as " \
-
"metadata for a hook."
-
raise ArgumentError.new error_message
-
else
-
:example
-
end
-
end
-
-
1
def known_scope?(scope)
-
1
SCOPES.include?(scope) || SCOPE_ALIASES.keys.include?(scope)
-
end
-
-
1
def normalized_scope_for(scope)
-
1
SCOPE_ALIASES[scope] || scope
-
end
-
-
1
def run_example_hooks_for(example, position, each_method)
-
owner_parent_groups.__send__(each_method) do |group|
-
group.hooks.run_owned_hooks_for(position, :example, example)
-
end
-
end
-
-
1
def run_around_example_hooks_for(example)
-
hooks = FlatMap.flat_map(owner_parent_groups) do |group|
-
group.hooks.matching_hooks_for(:around, :example, example)
-
end
-
-
return yield if hooks.empty? # exit early to avoid the extra allocation cost of `Example::Procsy`
-
-
initial_procsy = Example::Procsy.new(example) { yield }
-
hooks.inject(initial_procsy) do |procsy, around_hook|
-
procsy.wrap { around_hook.execute_with(example, procsy) }
-
end.call
-
end
-
-
1
if respond_to?(:singleton_class) && singleton_class.ancestors.include?(singleton_class)
-
1
def owner_parent_groups
-
@owner.parent_groups
-
end
-
else # Ruby < 2.1 (see https://bugs.ruby-lang.org/issues/8035)
-
# :nocov:
-
skipped
def owner_parent_groups
-
skipped
@owner_parent_groups ||= [@owner] + @owner.parent_groups
-
skipped
end
-
# :nocov:
-
end
-
end
-
end
-
end
-
end
-
1
RSpec::Support.require_rspec_support 'reentrant_mutex'
-
-
1
module RSpec
-
1
module Core
-
# This module is included in {ExampleGroup}, making the methods
-
# available to be called from within example blocks.
-
#
-
# @see ClassMethods
-
1
module MemoizedHelpers
-
# @note `subject` was contributed by Joe Ferris to support the one-liner
-
# syntax embraced by shoulda matchers:
-
#
-
# describe Widget do
-
# it { is_expected.to validate_presence_of(:name) }
-
# # or
-
# it { should validate_presence_of(:name) }
-
# end
-
#
-
# While the examples below demonstrate how to use `subject`
-
# explicitly in examples, we recommend that you define a method with
-
# an intention revealing name instead.
-
#
-
# @example
-
#
-
# # Explicit declaration of subject.
-
# describe Person do
-
# subject { Person.new(:birthdate => 19.years.ago) }
-
# it "should be eligible to vote" do
-
# subject.should be_eligible_to_vote
-
# # ^ ^ explicit reference to subject not recommended
-
# end
-
# end
-
#
-
# # Implicit subject => { Person.new }.
-
# describe Person do
-
# it "should be eligible to vote" do
-
# subject.should be_eligible_to_vote
-
# # ^ ^ explicit reference to subject not recommended
-
# end
-
# end
-
#
-
# # One-liner syntax - expectation is set on the subject.
-
# describe Person do
-
# it { is_expected.to be_eligible_to_vote }
-
# # or
-
# it { should be_eligible_to_vote }
-
# end
-
#
-
# @note Because `subject` is designed to create state that is reset
-
# between each example, and `before(:context)` is designed to setup
-
# state that is shared across _all_ examples in an example group,
-
# `subject` is _not_ intended to be used in a `before(:context)` hook.
-
#
-
# @see #should
-
# @see #should_not
-
# @see #is_expected
-
1
def subject
-
__memoized.fetch_or_store(:subject) do
-
described = described_class || self.class.metadata.fetch(:description_args).first
-
Class === described ? described.new : described
-
end
-
end
-
-
# When `should` is called with no explicit receiver, the call is
-
# delegated to the object returned by `subject`. Combined with an
-
# implicit subject this supports very concise expressions.
-
#
-
# @example
-
#
-
# describe Person do
-
# it { should be_eligible_to_vote }
-
# end
-
#
-
# @see #subject
-
# @see #is_expected
-
#
-
# @note This only works if you are using rspec-expectations.
-
# @note If you are using RSpec's newer expect-based syntax you may
-
# want to use `is_expected.to` instead of `should`.
-
1
def should(matcher=nil, message=nil)
-
RSpec::Expectations::PositiveExpectationHandler.handle_matcher(subject, matcher, message)
-
end
-
-
# Just like `should`, `should_not` delegates to the subject (implicit or
-
# explicit) of the example group.
-
#
-
# @example
-
#
-
# describe Person do
-
# it { should_not be_eligible_to_vote }
-
# end
-
#
-
# @see #subject
-
# @see #is_expected
-
#
-
# @note This only works if you are using rspec-expectations.
-
# @note If you are using RSpec's newer expect-based syntax you may
-
# want to use `is_expected.to_not` instead of `should_not`.
-
1
def should_not(matcher=nil, message=nil)
-
RSpec::Expectations::NegativeExpectationHandler.handle_matcher(subject, matcher, message)
-
end
-
-
# Wraps the `subject` in `expect` to make it the target of an expectation.
-
# Designed to read nicely for one-liners.
-
#
-
# @example
-
#
-
# describe [1, 2, 3] do
-
# it { is_expected.to be_an Array }
-
# it { is_expected.not_to include 4 }
-
# end
-
#
-
# @see #subject
-
# @see #should
-
# @see #should_not
-
#
-
# @note This only works if you are using rspec-expectations.
-
1
def is_expected
-
expect(subject)
-
end
-
-
# @private
-
# should just be placed in private section,
-
# but Ruby issues warnings on private attributes.
-
# and expanding it to the equivalent method upsets Rubocop,
-
# b/c it should obviously be a reader
-
1
attr_reader :__memoized
-
1
private :__memoized
-
-
1
private
-
-
# @private
-
1
def initialize(*)
-
__init_memoized
-
super
-
end
-
-
# @private
-
1
def __init_memoized
-
@__memoized = if RSpec.configuration.threadsafe?
-
ThreadsafeMemoized.new
-
else
-
NonThreadSafeMemoized.new
-
end
-
end
-
-
# @private
-
1
class ThreadsafeMemoized
-
1
def initialize
-
@memoized = {}
-
@mutex = Support::ReentrantMutex.new
-
end
-
-
1
def fetch_or_store(key)
-
@memoized.fetch(key) do # only first access pays for synchronization
-
@mutex.synchronize do
-
@memoized.fetch(key) { @memoized[key] = yield }
-
end
-
end
-
end
-
end
-
-
# @private
-
1
class NonThreadSafeMemoized
-
1
def initialize
-
@memoized = {}
-
end
-
-
1
def fetch_or_store(key)
-
@memoized.fetch(key) { @memoized[key] = yield }
-
end
-
end
-
-
# Used internally to customize the behavior of the
-
# memoized hash when used in a `before(:context)` hook.
-
#
-
# @private
-
1
class ContextHookMemoized
-
1
def self.isolate_for_context_hook(example_group_instance)
-
exploding_memoized = self
-
-
example_group_instance.instance_exec do
-
@__memoized = exploding_memoized
-
-
begin
-
yield
-
ensure
-
# This is doing a reset instead of just isolating for context hook.
-
# Really, this should set the old @__memoized back into place.
-
#
-
# Caller is the before and after context hooks
-
# which are both called from self.run
-
# I didn't look at why it made tests fail, maybe an object was getting reused in RSpec tests,
-
# if so, then that probably already works, and its the tests that are wrong.
-
__init_memoized
-
end
-
end
-
end
-
-
1
def self.fetch_or_store(key, &_block)
-
description = if key == :subject
-
"subject"
-
else
-
"let declaration `#{key}`"
-
end
-
-
raise <<-EOS
-
#{description} accessed in #{article} #{hook_expression} hook at:
-
#{CallerFilter.first_non_rspec_line}
-
-
`let` and `subject` declarations are not intended to be called
-
in #{article} #{hook_expression} hook, as they exist to define state that
-
is reset between each example, while #{hook_expression} exists to
-
#{hook_intention}.
-
EOS
-
end
-
-
# @private
-
1
class Before < self
-
1
def self.hook_expression
-
"`before(:context)`"
-
end
-
-
1
def self.article
-
"a"
-
end
-
-
1
def self.hook_intention
-
"define state that is shared across examples in an example group"
-
end
-
end
-
-
# @private
-
1
class After < self
-
1
def self.hook_expression
-
"`after(:context)`"
-
end
-
-
1
def self.article
-
"an"
-
end
-
-
1
def self.hook_intention
-
"cleanup state that is shared across examples in an example group"
-
end
-
end
-
end
-
-
# This module is extended onto {ExampleGroup}, making the methods
-
# available to be called from within example group blocks.
-
# You can think of them as being analagous to class macros.
-
1
module ClassMethods
-
# Generates a method whose return value is memoized after the first
-
# call. Useful for reducing duplication between examples that assign
-
# values to the same local variable.
-
#
-
# @note `let` _can_ enhance readability when used sparingly (1,2, or
-
# maybe 3 declarations) in any given example group, but that can
-
# quickly degrade with overuse. YMMV.
-
#
-
# @note `let` can be configured to be threadsafe or not.
-
# If it is threadsafe, it will take longer to access the value.
-
# If it is not threadsafe, it may behave in surprising ways in examples
-
# that spawn separate threads. Specify this on `RSpec.configure`
-
#
-
# @note Because `let` is designed to create state that is reset between
-
# each example, and `before(:context)` is designed to setup state that
-
# is shared across _all_ examples in an example group, `let` is _not_
-
# intended to be used in a `before(:context)` hook.
-
#
-
# @example
-
#
-
# describe Thing do
-
# let(:thing) { Thing.new }
-
#
-
# it "does something" do
-
# # First invocation, executes block, memoizes and returns result.
-
# thing.do_something
-
#
-
# # Second invocation, returns the memoized value.
-
# thing.should be_something
-
# end
-
# end
-
1
def let(name, &block)
-
# We have to pass the block directly to `define_method` to
-
# allow it to use method constructs like `super` and `return`.
-
raise "#let or #subject called without a block" if block.nil?
-
MemoizedHelpers.module_for(self).__send__(:define_method, name, &block)
-
-
# Apply the memoization. The method has been defined in an ancestor
-
# module so we can use `super` here to get the value.
-
if block.arity == 1
-
define_method(name) { __memoized.fetch_or_store(name) { super(RSpec.current_example, &nil) } }
-
else
-
define_method(name) { __memoized.fetch_or_store(name) { super(&nil) } }
-
end
-
end
-
-
# Just like `let`, except the block is invoked by an implicit `before`
-
# hook. This serves a dual purpose of setting up state and providing a
-
# memoized reference to that state.
-
#
-
# @example
-
#
-
# class Thing
-
# def self.count
-
# @count ||= 0
-
# end
-
#
-
# def self.count=(val)
-
# @count += val
-
# end
-
#
-
# def self.reset_count
-
# @count = 0
-
# end
-
#
-
# def initialize
-
# self.class.count += 1
-
# end
-
# end
-
#
-
# describe Thing do
-
# after(:example) { Thing.reset_count }
-
#
-
# context "using let" do
-
# let(:thing) { Thing.new }
-
#
-
# it "is not invoked implicitly" do
-
# Thing.count.should eq(0)
-
# end
-
#
-
# it "can be invoked explicitly" do
-
# thing
-
# Thing.count.should eq(1)
-
# end
-
# end
-
#
-
# context "using let!" do
-
# let!(:thing) { Thing.new }
-
#
-
# it "is invoked implicitly" do
-
# Thing.count.should eq(1)
-
# end
-
#
-
# it "returns memoized version on first invocation" do
-
# thing
-
# Thing.count.should eq(1)
-
# end
-
# end
-
# end
-
1
def let!(name, &block)
-
let(name, &block)
-
before { __send__(name) }
-
end
-
-
# Declares a `subject` for an example group which can then be wrapped
-
# with `expect` using `is_expected` to make it the target of an
-
# expectation in a concise, one-line example.
-
#
-
# Given a `name`, defines a method with that name which returns the
-
# `subject`. This lets you declare the subject once and access it
-
# implicitly in one-liners and explicitly using an intention revealing
-
# name.
-
#
-
# When given a `name`, calling `super` in the block is not supported.
-
#
-
# @note `subject` can be configured to be threadsafe or not.
-
# If it is threadsafe, it will take longer to access the value.
-
# If it is not threadsafe, it may behave in surprising ways in examples
-
# that spawn separate threads. Specify this on `RSpec.configure`
-
#
-
# @param name [String,Symbol] used to define an accessor with an
-
# intention revealing name
-
# @param block defines the value to be returned by `subject` in examples
-
#
-
# @example
-
#
-
# describe CheckingAccount, "with $50" do
-
# subject { CheckingAccount.new(Money.new(50, :USD)) }
-
# it { is_expected.to have_a_balance_of(Money.new(50, :USD)) }
-
# it { is_expected.not_to be_overdrawn }
-
# end
-
#
-
# describe CheckingAccount, "with a non-zero starting balance" do
-
# subject(:account) { CheckingAccount.new(Money.new(50, :USD)) }
-
# it { is_expected.not_to be_overdrawn }
-
# it "has a balance equal to the starting balance" do
-
# account.balance.should eq(Money.new(50, :USD))
-
# end
-
# end
-
#
-
# @see MemoizedHelpers#should
-
# @see MemoizedHelpers#should_not
-
# @see MemoizedHelpers#is_expected
-
1
def subject(name=nil, &block)
-
if name
-
let(name, &block)
-
alias_method :subject, name
-
-
self::NamedSubjectPreventSuper.__send__(:define_method, name) do
-
raise NotImplementedError, "`super` in named subjects is not supported"
-
end
-
else
-
let(:subject, &block)
-
end
-
end
-
-
# Just like `subject`, except the block is invoked by an implicit
-
# `before` hook. This serves a dual purpose of setting up state and
-
# providing a memoized reference to that state.
-
#
-
# @example
-
#
-
# class Thing
-
# def self.count
-
# @count ||= 0
-
# end
-
#
-
# def self.count=(val)
-
# @count += val
-
# end
-
#
-
# def self.reset_count
-
# @count = 0
-
# end
-
#
-
# def initialize
-
# self.class.count += 1
-
# end
-
# end
-
#
-
# describe Thing do
-
# after(:example) { Thing.reset_count }
-
#
-
# context "using subject" do
-
# subject { Thing.new }
-
#
-
# it "is not invoked implicitly" do
-
# Thing.count.should eq(0)
-
# end
-
#
-
# it "can be invoked explicitly" do
-
# subject
-
# Thing.count.should eq(1)
-
# end
-
# end
-
#
-
# context "using subject!" do
-
# subject!(:thing) { Thing.new }
-
#
-
# it "is invoked implicitly" do
-
# Thing.count.should eq(1)
-
# end
-
#
-
# it "returns memoized version on first invocation" do
-
# subject
-
# Thing.count.should eq(1)
-
# end
-
# end
-
# end
-
1
def subject!(name=nil, &block)
-
subject(name, &block)
-
before { subject }
-
end
-
end
-
-
# @private
-
#
-
# Gets the LetDefinitions module. The module is mixed into
-
# the example group and is used to hold all let definitions.
-
# This is done so that the block passed to `let` can be
-
# forwarded directly on to `define_method`, so that all method
-
# constructs (including `super` and `return`) can be used in
-
# a `let` block.
-
#
-
# The memoization is provided by a method definition on the
-
# example group that supers to the LetDefinitions definition
-
# in order to get the value to memoize.
-
1
def self.module_for(example_group)
-
get_constant_or_yield(example_group, :LetDefinitions) do
-
mod = Module.new do
-
include Module.new {
-
example_group.const_set(:NamedSubjectPreventSuper, self)
-
}
-
end
-
-
example_group.const_set(:LetDefinitions, mod)
-
mod
-
end
-
end
-
-
# @private
-
1
def self.define_helpers_on(example_group)
-
example_group.__send__(:include, module_for(example_group))
-
end
-
-
1
if Module.method(:const_defined?).arity == 1 # for 1.8
-
# @private
-
#
-
# Gets the named constant or yields.
-
# On 1.8, const_defined? / const_get do not take into
-
# account the inheritance hierarchy.
-
# :nocov:
-
skipped
def self.get_constant_or_yield(example_group, name)
-
skipped
if example_group.const_defined?(name)
-
skipped
example_group.const_get(name)
-
skipped
else
-
skipped
yield
-
skipped
end
-
skipped
end
-
# :nocov:
-
else
-
# @private
-
#
-
# Gets the named constant or yields.
-
# On 1.9, const_defined? / const_get take into account the
-
# the inheritance by default, and accept an argument to
-
# disable this behavior. It's important that we don't
-
# consider inheritance here; each example group level that
-
# uses a `let` should get its own `LetDefinitions` module.
-
1
def self.get_constant_or_yield(example_group, name)
-
if example_group.const_defined?(name, (check_ancestors = false))
-
example_group.const_get(name, check_ancestors)
-
else
-
yield
-
end
-
end
-
end
-
end
-
end
-
end
-
1
module RSpec
-
1
module Core
-
# Each ExampleGroup class and Example instance owns an instance of
-
# Metadata, which is Hash extended to support lazy evaluation of values
-
# associated with keys that may or may not be used by any example or group.
-
#
-
# In addition to metadata that is used internally, this also stores
-
# user-supplied metadata, e.g.
-
#
-
# describe Something, :type => :ui do
-
# it "does something", :slow => true do
-
# # ...
-
# end
-
# end
-
#
-
# `:type => :ui` is stored in the Metadata owned by the example group, and
-
# `:slow => true` is stored in the Metadata owned by the example. These can
-
# then be used to select which examples are run using the `--tag` option on
-
# the command line, or several methods on `Configuration` used to filter a
-
# run (e.g. `filter_run_including`, `filter_run_excluding`, etc).
-
#
-
# @see Example#metadata
-
# @see ExampleGroup.metadata
-
# @see FilterManager
-
# @see Configuration#filter_run_including
-
# @see Configuration#filter_run_excluding
-
1
module Metadata
-
# Matches strings either at the beginning of the input or prefixed with a
-
# whitespace, containing the current path, either postfixed with the
-
# separator, or at the end of the string. Match groups are the character
-
# before and the character after the string if any.
-
#
-
# http://rubular.com/r/fT0gmX6VJX
-
# http://rubular.com/r/duOrD4i3wb
-
# http://rubular.com/r/sbAMHFrOx1
-
1
def self.relative_path_regex
-
@relative_path_regex ||= /(\A|\s)#{File.expand_path('.')}(#{File::SEPARATOR}|\s|\Z)/
-
end
-
-
# @api private
-
#
-
# @param line [String] current code line
-
# @return [String] relative path to line
-
1
def self.relative_path(line)
-
line = line.sub(relative_path_regex, "\\1.\\2".freeze)
-
line = line.sub(/\A([^:]+:\d+)$/, '\\1'.freeze)
-
return nil if line == '-e:1'.freeze
-
line
-
rescue SecurityError
-
# :nocov:
-
skipped
nil
-
# :nocov:
-
end
-
-
# @private
-
# Iteratively walks up from the given metadata through all
-
# example group ancestors, yielding each metadata hash along the way.
-
1
def self.ascending(metadata)
-
yield metadata
-
return unless (group_metadata = metadata.fetch(:example_group) { metadata[:parent_example_group] })
-
-
loop do
-
yield group_metadata
-
break unless (group_metadata = group_metadata[:parent_example_group])
-
end
-
end
-
-
# @private
-
# Returns an enumerator that iteratively walks up the given metadata through all
-
# example group ancestors, yielding each metadata hash along the way.
-
1
def self.ascend(metadata)
-
enum_for(:ascending, metadata)
-
end
-
-
# @private
-
# Used internally to build a hash from an args array.
-
# Symbols are converted into hash keys with a value of `true`.
-
# This is done to support simple tagging using a symbol, rather
-
# than needing to do `:symbol => true`.
-
1
def self.build_hash_from(args, warn_about_example_group_filtering=false)
-
2
hash = args.last.is_a?(Hash) ? args.pop : {}
-
-
2
hash[args.pop] = true while args.last.is_a?(Symbol)
-
-
2
if warn_about_example_group_filtering && hash.key?(:example_group)
-
RSpec.deprecate("Filtering by an `:example_group` subhash",
-
:replacement => "the subhash to filter directly")
-
end
-
-
2
hash
-
end
-
-
# @private
-
1
def self.deep_hash_dup(object)
-
return object.dup if Array === object
-
return object unless Hash === object
-
-
object.inject(object.dup) do |duplicate, (key, value)|
-
duplicate[key] = deep_hash_dup(value)
-
duplicate
-
end
-
end
-
-
# @private
-
1
def self.id_from(metadata)
-
"#{metadata[:rerun_file_path]}[#{metadata[:scoped_id]}]"
-
end
-
-
# @private
-
1
def self.location_tuple_from(metadata)
-
[metadata[:absolute_file_path], metadata[:line_number]]
-
end
-
-
# @private
-
# Used internally to populate metadata hashes with computed keys
-
# managed by RSpec.
-
1
class HashPopulator
-
1
attr_reader :metadata, :user_metadata, :description_args, :block
-
-
1
def initialize(metadata, user_metadata, index_provider, description_args, block)
-
@metadata = metadata
-
@user_metadata = user_metadata
-
@index_provider = index_provider
-
@description_args = description_args
-
@block = block
-
end
-
-
1
def populate
-
ensure_valid_user_keys
-
-
metadata[:execution_result] = Example::ExecutionResult.new
-
metadata[:block] = block
-
metadata[:description_args] = description_args
-
metadata[:description] = build_description_from(*metadata[:description_args])
-
metadata[:full_description] = full_description
-
metadata[:described_class] = described_class
-
-
populate_location_attributes
-
metadata.update(user_metadata)
-
RSpec.configuration.apply_derived_metadata_to(metadata)
-
end
-
-
1
private
-
-
1
def populate_location_attributes
-
backtrace = user_metadata.delete(:caller)
-
-
file_path, line_number = if backtrace
-
file_path_and_line_number_from(backtrace)
-
elsif block.respond_to?(:source_location)
-
block.source_location
-
else
-
file_path_and_line_number_from(caller)
-
end
-
-
relative_file_path = Metadata.relative_path(file_path)
-
absolute_file_path = File.expand_path(relative_file_path)
-
metadata[:file_path] = relative_file_path
-
metadata[:line_number] = line_number.to_i
-
metadata[:location] = "#{relative_file_path}:#{line_number}"
-
metadata[:absolute_file_path] = absolute_file_path
-
metadata[:rerun_file_path] ||= relative_file_path
-
metadata[:scoped_id] = build_scoped_id_for(absolute_file_path)
-
end
-
-
1
def file_path_and_line_number_from(backtrace)
-
first_caller_from_outside_rspec = backtrace.find { |l| l !~ CallerFilter::LIB_REGEX }
-
first_caller_from_outside_rspec ||= backtrace.first
-
/(.+?):(\d+)(?:|:\d+)/.match(first_caller_from_outside_rspec).captures
-
end
-
-
1
def description_separator(parent_part, child_part)
-
if parent_part.is_a?(Module) && child_part =~ /^(#|::|\.)/
-
''.freeze
-
else
-
' '.freeze
-
end
-
end
-
-
1
def build_description_from(parent_description=nil, my_description=nil)
-
return parent_description.to_s unless my_description
-
separator = description_separator(parent_description, my_description)
-
(parent_description.to_s + separator) << my_description.to_s
-
end
-
-
1
def build_scoped_id_for(file_path)
-
index = @index_provider.call(file_path).to_s
-
parent_scoped_id = metadata.fetch(:scoped_id) { return index }
-
"#{parent_scoped_id}:#{index}"
-
end
-
-
1
def ensure_valid_user_keys
-
RESERVED_KEYS.each do |key|
-
next unless user_metadata.key?(key)
-
raise <<-EOM.gsub(/^\s+\|/, '')
-
|#{"*" * 50}
-
|:#{key} is not allowed
-
|
-
|RSpec reserves some hash keys for its own internal use,
-
|including :#{key}, which is used on:
-
|
-
| #{CallerFilter.first_non_rspec_line}.
-
|
-
|Here are all of RSpec's reserved hash keys:
-
|
-
| #{RESERVED_KEYS.join("\n ")}
-
|#{"*" * 50}
-
EOM
-
end
-
end
-
end
-
-
# @private
-
1
class ExampleHash < HashPopulator
-
1
def self.create(group_metadata, user_metadata, index_provider, description, block)
-
example_metadata = group_metadata.dup
-
group_metadata = Hash.new(&ExampleGroupHash.backwards_compatibility_default_proc do |hash|
-
hash[:parent_example_group]
-
end)
-
group_metadata.update(example_metadata)
-
-
example_metadata[:example_group] = group_metadata
-
example_metadata[:shared_group_inclusion_backtrace] = SharedExampleGroupInclusionStackFrame.current_backtrace
-
example_metadata.delete(:parent_example_group)
-
-
description_args = description.nil? ? [] : [description]
-
hash = new(example_metadata, user_metadata, index_provider, description_args, block)
-
hash.populate
-
hash.metadata
-
end
-
-
1
private
-
-
1
def described_class
-
metadata[:example_group][:described_class]
-
end
-
-
1
def full_description
-
build_description_from(
-
metadata[:example_group][:full_description],
-
metadata[:description]
-
)
-
end
-
end
-
-
# @private
-
1
class ExampleGroupHash < HashPopulator
-
1
def self.create(parent_group_metadata, user_metadata, example_group_index, *args, &block)
-
group_metadata = hash_with_backwards_compatibility_default_proc
-
-
if parent_group_metadata
-
group_metadata.update(parent_group_metadata)
-
group_metadata[:parent_example_group] = parent_group_metadata
-
end
-
-
hash = new(group_metadata, user_metadata, example_group_index, args, block)
-
hash.populate
-
hash.metadata
-
end
-
-
1
def self.hash_with_backwards_compatibility_default_proc
-
Hash.new(&backwards_compatibility_default_proc { |hash| hash })
-
end
-
-
1
def self.backwards_compatibility_default_proc(&example_group_selector)
-
Proc.new do |hash, key|
-
case key
-
when :example_group
-
# We commonly get here when rspec-core is applying a previously
-
# configured filter rule, such as when a gem configures:
-
#
-
# RSpec.configure do |c|
-
# c.include MyGemHelpers, :example_group => { :file_path => /spec\/my_gem_specs/ }
-
# end
-
#
-
# It's confusing for a user to get a deprecation at this point in
-
# the code, so instead we issue a deprecation from the config APIs
-
# that take a metadata hash, and MetadataFilter sets this thread
-
# local to silence the warning here since it would be so
-
# confusing.
-
unless RSpec::Support.thread_local_data[:silence_metadata_example_group_deprecations]
-
RSpec.deprecate("The `:example_group` key in an example group's metadata hash",
-
:replacement => "the example group's hash directly for the " \
-
"computed keys and `:parent_example_group` to access the parent " \
-
"example group metadata")
-
end
-
-
group_hash = example_group_selector.call(hash)
-
LegacyExampleGroupHash.new(group_hash) if group_hash
-
when :example_group_block
-
RSpec.deprecate("`metadata[:example_group_block]`",
-
:replacement => "`metadata[:block]`")
-
hash[:block]
-
when :describes
-
RSpec.deprecate("`metadata[:describes]`",
-
:replacement => "`metadata[:described_class]`")
-
hash[:described_class]
-
end
-
end
-
end
-
-
1
private
-
-
1
def described_class
-
candidate = metadata[:description_args].first
-
return candidate unless NilClass === candidate || String === candidate
-
parent_group = metadata[:parent_example_group]
-
parent_group && parent_group[:described_class]
-
end
-
-
1
def full_description
-
description = metadata[:description]
-
parent_example_group = metadata[:parent_example_group]
-
return description unless parent_example_group
-
-
parent_description = parent_example_group[:full_description]
-
separator = description_separator(parent_example_group[:description_args].last,
-
metadata[:description_args].first)
-
-
parent_description + separator + description
-
end
-
end
-
-
# @private
-
1
RESERVED_KEYS = [
-
:description,
-
:description_args,
-
:described_class,
-
:example_group,
-
:parent_example_group,
-
:execution_result,
-
:last_run_status,
-
:file_path,
-
:absolute_file_path,
-
:rerun_file_path,
-
:full_description,
-
:line_number,
-
:location,
-
:scoped_id,
-
:block,
-
:shared_group_inclusion_backtrace
-
]
-
end
-
-
# Mixin that makes the including class imitate a hash for backwards
-
# compatibility. The including class should use `attr_accessor` to
-
# declare attributes.
-
# @private
-
1
module HashImitatable
-
1
def self.included(klass)
-
2
klass.extend ClassMethods
-
end
-
-
1
def to_h
-
hash = extra_hash_attributes.dup
-
-
self.class.hash_attribute_names.each do |name|
-
hash[name] = __send__(name)
-
end
-
-
hash
-
end
-
-
1
(Hash.public_instance_methods - Object.public_instance_methods).each do |method_name|
-
138
next if [:[], :[]=, :to_h].include?(method_name.to_sym)
-
-
135
define_method(method_name) do |*args, &block|
-
issue_deprecation(method_name, *args)
-
-
hash = hash_for_delegation
-
self.class.hash_attribute_names.each do |name|
-
hash.delete(name) unless instance_variable_defined?(:"@#{name}")
-
end
-
-
hash.__send__(method_name, *args, &block).tap do
-
# apply mutations back to the object
-
hash.each do |name, value|
-
if directly_supports_attribute?(name)
-
set_value(name, value)
-
else
-
extra_hash_attributes[name] = value
-
end
-
end
-
end
-
end
-
end
-
-
1
def [](key)
-
issue_deprecation(:[], key)
-
-
if directly_supports_attribute?(key)
-
get_value(key)
-
else
-
extra_hash_attributes[key]
-
end
-
end
-
-
1
def []=(key, value)
-
issue_deprecation(:[]=, key, value)
-
-
if directly_supports_attribute?(key)
-
set_value(key, value)
-
else
-
extra_hash_attributes[key] = value
-
end
-
end
-
-
1
private
-
-
1
def extra_hash_attributes
-
@extra_hash_attributes ||= {}
-
end
-
-
1
def directly_supports_attribute?(name)
-
self.class.hash_attribute_names.include?(name)
-
end
-
-
1
def get_value(name)
-
__send__(name)
-
end
-
-
1
def set_value(name, value)
-
__send__(:"#{name}=", value)
-
end
-
-
1
def hash_for_delegation
-
to_h
-
end
-
-
1
def issue_deprecation(_method_name, *_args)
-
# no-op by default: subclasses can override
-
end
-
-
# @private
-
1
module ClassMethods
-
1
def hash_attribute_names
-
8
@hash_attribute_names ||= []
-
end
-
-
1
def attr_accessor(*names)
-
8
hash_attribute_names.concat(names)
-
8
super
-
end
-
end
-
end
-
-
# @private
-
# Together with the example group metadata hash default block,
-
# provides backwards compatibility for the old `:example_group`
-
# key. In RSpec 2.x, the computed keys of a group's metadata
-
# were exposed from a nested subhash keyed by `[:example_group]`, and
-
# then the parent group's metadata was exposed by sub-subhash
-
# keyed by `[:example_group][:example_group]`.
-
#
-
# In RSpec 3, we reorganized this to that the computed keys are
-
# exposed directly of the group metadata hash (no nesting), and
-
# `:parent_example_group` returns the parent group's metadata.
-
#
-
# Maintaining backwards compatibility was difficult: we wanted
-
# `:example_group` to return an object that:
-
#
-
# * Exposes the top-level metadata keys that used to be nested
-
# under `:example_group`.
-
# * Supports mutation (rspec-rails, for example, assigns
-
# `metadata[:example_group][:described_class]` when you use
-
# anonymous controller specs) such that changes are written
-
# back to the top-level metadata hash.
-
# * Exposes the parent group metadata as
-
# `[:example_group][:example_group]`.
-
1
class LegacyExampleGroupHash
-
1
include HashImitatable
-
-
1
def initialize(metadata)
-
@metadata = metadata
-
parent_group_metadata = metadata.fetch(:parent_example_group) { {} }[:example_group]
-
self[:example_group] = parent_group_metadata if parent_group_metadata
-
end
-
-
1
def to_h
-
super.merge(@metadata)
-
end
-
-
1
private
-
-
1
def directly_supports_attribute?(name)
-
name != :example_group
-
end
-
-
1
def get_value(name)
-
@metadata[name]
-
end
-
-
1
def set_value(name, value)
-
@metadata[name] = value
-
end
-
end
-
end
-
end
-
1
module RSpec
-
1
module Core
-
# Contains metadata filtering logic. This has been extracted from
-
# the metadata classes because it operates ON a metadata hash but
-
# does not manage any of the state in the hash. We're moving towards
-
# having metadata be a raw hash (not a custom subclass), so externalizing
-
# this filtering logic helps us move in that direction.
-
1
module MetadataFilter
-
1
class << self
-
# @private
-
1
def apply?(predicate, filters, metadata)
-
filters.__send__(predicate) { |k, v| filter_applies?(k, v, metadata) }
-
end
-
-
# @private
-
1
def filter_applies?(key, value, metadata)
-
silence_metadata_example_group_deprecations do
-
return location_filter_applies?(value, metadata) if key == :locations
-
return id_filter_applies?(value, metadata) if key == :ids
-
return filters_apply?(key, value, metadata) if Hash === value
-
-
return false unless metadata.key?(key)
-
return true if TrueClass === value && !!metadata[key]
-
return filter_applies_to_any_value?(key, value, metadata) if Array === metadata[key] && !(Proc === value)
-
-
case value
-
when Regexp
-
metadata[key] =~ value
-
when Proc
-
proc_filter_applies?(key, value, metadata)
-
else
-
metadata[key].to_s == value.to_s
-
end
-
end
-
end
-
-
1
private
-
-
1
def filter_applies_to_any_value?(key, value, metadata)
-
metadata[key].any? { |v| filter_applies?(key, v, key => value) }
-
end
-
-
1
def id_filter_applies?(rerun_paths_to_scoped_ids, metadata)
-
scoped_ids = rerun_paths_to_scoped_ids.fetch(metadata[:rerun_file_path]) { return false }
-
-
Metadata.ascend(metadata).any? do |meta|
-
scoped_ids.include?(meta[:scoped_id])
-
end
-
end
-
-
1
def location_filter_applies?(locations, metadata)
-
Metadata.ascend(metadata).any? do |meta|
-
file_path = meta[:absolute_file_path]
-
line_num = meta[:line_number]
-
-
locations[file_path].any? do |filter_line_num|
-
line_num == RSpec.world.preceding_declaration_line(file_path, filter_line_num)
-
end
-
end
-
end
-
-
1
def proc_filter_applies?(key, proc, metadata)
-
case proc.arity
-
when 0 then proc.call
-
when 2 then proc.call(metadata[key], metadata)
-
else proc.call(metadata[key])
-
end
-
end
-
-
1
def filters_apply?(key, value, metadata)
-
subhash = metadata[key]
-
return false unless Hash === subhash || HashImitatable === subhash
-
value.all? { |k, v| filter_applies?(k, v, subhash) }
-
end
-
-
1
def silence_metadata_example_group_deprecations
-
RSpec::Support.thread_local_data[:silence_metadata_example_group_deprecations] = true
-
yield
-
ensure
-
RSpec::Support.thread_local_data.delete(:silence_metadata_example_group_deprecations)
-
end
-
end
-
end
-
-
# Tracks a collection of filterable items (e.g. modules, hooks, etc)
-
# and provides an optimized API to get the applicable items for the
-
# metadata of an example or example group.
-
#
-
# There are two implementations, optimized for different uses.
-
# @private
-
1
module FilterableItemRepository
-
# This implementation is simple, and is optimized for frequent
-
# updates but rare queries. `append` and `prepend` do no extra
-
# processing, and no internal memoization is done, since this
-
# is not optimized for queries.
-
#
-
# This is ideal for use by a example or example group, which may
-
# be updated multiple times with globally configured hooks, etc,
-
# but will not be queried frequently by other examples or examle
-
# groups.
-
# @private
-
1
class UpdateOptimized
-
1
attr_reader :items_and_filters
-
-
1
def initialize(applies_predicate)
-
5
@applies_predicate = applies_predicate
-
5
@items_and_filters = []
-
end
-
-
1
def append(item, metadata)
-
1
@items_and_filters << [item, metadata]
-
end
-
-
1
def prepend(item, metadata)
-
1
@items_and_filters.unshift [item, metadata]
-
end
-
-
1
def items_for(request_meta)
-
@items_and_filters.each_with_object([]) do |(item, item_meta), to_return|
-
to_return << item if item_meta.empty? ||
-
MetadataFilter.apply?(@applies_predicate, item_meta, request_meta)
-
end
-
end
-
-
1
unless [].respond_to?(:each_with_object) # For 1.8.7
-
# :nocov:
-
skipped
undef items_for
-
skipped
def items_for(request_meta)
-
skipped
@items_and_filters.inject([]) do |to_return, (item, item_meta)|
-
skipped
to_return << item if item_meta.empty? ||
-
skipped
MetadataFilter.apply?(@applies_predicate, item_meta, request_meta)
-
skipped
to_return
-
skipped
end
-
skipped
end
-
# :nocov:
-
end
-
end
-
-
# This implementation is much more complex, and is optimized for
-
# rare (or hopefully no) updates once the queries start. Updates
-
# incur a cost as it has to clear the memoization and keep track
-
# of applicable keys. Queries will be O(N) the first time an item
-
# is provided with a given set of applicable metadata; subsequent
-
# queries with items with the same set of applicable metadata will
-
# be O(1) due to internal memoization.
-
#
-
# This is ideal for use by config, where filterable items (e.g. hooks)
-
# are typically added at the start of the process (e.g. in `spec_helper`)
-
# and then repeatedly queried as example groups and examples are defined.
-
# @private
-
1
class QueryOptimized < UpdateOptimized
-
1
alias find_items_for items_for
-
1
private :find_items_for
-
-
1
def initialize(applies_predicate)
-
5
super
-
5
@applicable_keys = Set.new
-
5
@proc_keys = Set.new
-
5
@memoized_lookups = Hash.new do |hash, applicable_metadata|
-
hash[applicable_metadata] = find_items_for(applicable_metadata)
-
end
-
end
-
-
1
def append(item, metadata)
-
1
super
-
1
handle_mutation(metadata)
-
end
-
-
1
def prepend(item, metadata)
-
1
super
-
1
handle_mutation(metadata)
-
end
-
-
1
def items_for(metadata)
-
# The filtering of `metadata` to `applicable_metadata` is the key thing
-
# that makes the memoization actually useful in practice, since each
-
# example and example group have different metadata (e.g. location and
-
# description). By filtering to the metadata keys our items care about,
-
# we can ignore extra metadata keys that differ for each example/group.
-
# For example, given `config.include DBHelpers, :db`, example groups
-
# can be split into these two sets: those that are tagged with `:db` and those
-
# that are not. For each set, this method for the first group in the set is
-
# still an `O(N)` calculation, but all subsequent groups in the set will be
-
# constant time lookups when they call this method.
-
applicable_metadata = applicable_metadata_from(metadata)
-
-
if applicable_metadata.any? { |k, _| @proc_keys.include?(k) }
-
# It's unsafe to memoize lookups involving procs (since they can
-
# be non-deterministic), so we skip the memoization in this case.
-
find_items_for(applicable_metadata)
-
else
-
@memoized_lookups[applicable_metadata]
-
end
-
end
-
-
1
private
-
-
1
def handle_mutation(metadata)
-
2
@applicable_keys.merge(metadata.keys)
-
2
@proc_keys.merge(proc_keys_from metadata)
-
2
@memoized_lookups.clear
-
end
-
-
1
def applicable_metadata_from(metadata)
-
@applicable_keys.inject({}) do |hash, key|
-
hash[key] = metadata[key] if metadata.key?(key)
-
hash
-
end
-
end
-
-
1
def proc_keys_from(metadata)
-
2
metadata.each_with_object([]) do |(key, value), to_return|
-
1
to_return << key if Proc === value
-
end
-
end
-
-
1
unless [].respond_to?(:each_with_object) # For 1.8.7
-
# :nocov:
-
skipped
undef proc_keys_from
-
skipped
def proc_keys_from(metadata)
-
skipped
metadata.inject([]) do |to_return, (key, value)|
-
skipped
to_return << key if Proc === value
-
skipped
to_return
-
skipped
end
-
skipped
end
-
# :nocov:
-
end
-
end
-
end
-
end
-
end
-
1
require 'rspec/mocks'
-
-
1
module RSpec
-
1
module Core
-
1
module MockingAdapters
-
# @private
-
1
module RSpec
-
1
include ::RSpec::Mocks::ExampleMethods
-
-
1
def self.framework_name
-
1
:rspec
-
end
-
-
1
def self.configuration
-
::RSpec::Mocks.configuration
-
end
-
-
1
def setup_mocks_for_rspec
-
21
::RSpec::Mocks.setup
-
end
-
-
1
def verify_mocks_for_rspec
-
21
::RSpec::Mocks.verify
-
end
-
-
1
def teardown_mocks_for_rspec
-
21
::RSpec::Mocks.teardown
-
end
-
end
-
end
-
end
-
end
-
1
RSpec::Support.require_rspec_core "formatters/exception_presenter"
-
1
RSpec::Support.require_rspec_core "formatters/helpers"
-
1
RSpec::Support.require_rspec_core "shell_escape"
-
-
1
module RSpec::Core
-
# Notifications are value objects passed to formatters to provide them
-
# with information about a particular event of interest.
-
1
module Notifications
-
# @private
-
1
module NullColorizer
-
1
module_function
-
-
1
def wrap(line, _code_or_symbol)
-
line
-
end
-
end
-
-
# The `StartNotification` represents a notification sent by the reporter
-
# when the suite is started. It contains the expected amount of examples
-
# to be executed, and the load time of RSpec.
-
#
-
# @attr count [Fixnum] the number counted
-
# @attr load_time [Float] the number of seconds taken to boot RSpec
-
# and load the spec files
-
1
StartNotification = Struct.new(:count, :load_time)
-
-
# The `ExampleNotification` represents notifications sent by the reporter
-
# which contain information about the current (or soon to be) example.
-
# It is used by formatters to access information about that example.
-
#
-
# @example
-
# def example_started(notification)
-
# puts "Hey I started #{notification.example.description}"
-
# end
-
#
-
# @attr example [RSpec::Core::Example] the current example
-
1
ExampleNotification = Struct.new(:example)
-
1
class ExampleNotification
-
# @private
-
1
def self.for(example)
-
execution_result = example.execution_result
-
-
return SkippedExampleNotification.new(example) if execution_result.example_skipped?
-
return new(example) unless execution_result.status == :pending || execution_result.status == :failed
-
-
klass = if execution_result.pending_fixed?
-
PendingExampleFixedNotification
-
elsif execution_result.status == :pending
-
PendingExampleFailedAsExpectedNotification
-
else
-
FailedExampleNotification
-
end
-
-
exception_presenter = Formatters::ExceptionPresenter::Factory.new(example).build
-
klass.new(example, exception_presenter)
-
end
-
-
1
private_class_method :new
-
end
-
-
# The `ExamplesNotification` represents notifications sent by the reporter
-
# which contain information about the suites examples.
-
#
-
# @example
-
# def stop(notification)
-
# puts "Hey I ran #{notification.examples.size}"
-
# end
-
#
-
1
class ExamplesNotification
-
1
def initialize(reporter)
-
@reporter = reporter
-
end
-
-
# @return [Array<RSpec::Core::Example>] list of examples
-
1
def examples
-
@reporter.examples
-
end
-
-
# @return [Array<RSpec::Core::Example>] list of failed examples
-
1
def failed_examples
-
@reporter.failed_examples
-
end
-
-
# @return [Array<RSpec::Core::Example>] list of pending examples
-
1
def pending_examples
-
@reporter.pending_examples
-
end
-
-
# @return [Array<RSpec::Core::Notifications::ExampleNotification>]
-
# returns examples as notifications
-
1
def notifications
-
@notifications ||= format_examples(examples)
-
end
-
-
# @return [Array<RSpec::Core::Notifications::FailedExampleNotification>]
-
# returns failed examples as notifications
-
1
def failure_notifications
-
@failed_notifications ||= format_examples(failed_examples)
-
end
-
-
# @return [Array<RSpec::Core::Notifications::SkippedExampleNotification,
-
# RSpec::Core::Notifications::PendingExampleFailedAsExpectedNotification>]
-
# returns pending examples as notifications
-
1
def pending_notifications
-
@pending_notifications ||= format_examples(pending_examples)
-
end
-
-
# @return [String] The list of failed examples, fully formatted in the way
-
# that RSpec's built-in formatters emit.
-
1
def fully_formatted_failed_examples(colorizer=::RSpec::Core::Formatters::ConsoleCodes)
-
formatted = "\nFailures:\n"
-
-
failure_notifications.each_with_index do |failure, index|
-
formatted << failure.fully_formatted(index.next, colorizer)
-
end
-
-
formatted
-
end
-
-
# @return [String] The list of pending examples, fully formatted in the
-
# way that RSpec's built-in formatters emit.
-
1
def fully_formatted_pending_examples(colorizer=::RSpec::Core::Formatters::ConsoleCodes)
-
formatted = "\nPending: (Failures listed here are expected and do not affect your suite's status)\n"
-
-
pending_notifications.each_with_index do |notification, index|
-
formatted << notification.fully_formatted(index.next, colorizer)
-
end
-
-
formatted
-
end
-
-
1
private
-
-
1
def format_examples(examples)
-
examples.map do |example|
-
ExampleNotification.for(example)
-
end
-
end
-
end
-
-
# The `FailedExampleNotification` extends `ExampleNotification` with
-
# things useful for examples that have failure info -- typically a
-
# failed or pending spec.
-
#
-
# @example
-
# def example_failed(notification)
-
# puts "Hey I failed :("
-
# puts "Here's my stack trace"
-
# puts notification.exception.backtrace.join("\n")
-
# end
-
#
-
# @attr [RSpec::Core::Example] example the current example
-
# @see ExampleNotification
-
1
class FailedExampleNotification < ExampleNotification
-
1
public_class_method :new
-
-
# @return [Exception] The example failure
-
1
def exception
-
@exception_presenter.exception
-
end
-
-
# @return [String] The example description
-
1
def description
-
@exception_presenter.description
-
end
-
-
# Returns the message generated for this failure line by line.
-
#
-
# @return [Array<String>] The example failure message
-
1
def message_lines
-
@exception_presenter.message_lines
-
end
-
-
# Returns the message generated for this failure colorized line by line.
-
#
-
# @param colorizer [#wrap] An object to colorize the message_lines by
-
# @return [Array<String>] The example failure message colorized
-
1
def colorized_message_lines(colorizer=::RSpec::Core::Formatters::ConsoleCodes)
-
@exception_presenter.colorized_message_lines(colorizer)
-
end
-
-
# Returns the failures formatted backtrace.
-
#
-
# @return [Array<String>] the examples backtrace lines
-
1
def formatted_backtrace
-
@exception_presenter.formatted_backtrace
-
end
-
-
# Returns the failures colorized formatted backtrace.
-
#
-
# @param colorizer [#wrap] An object to colorize the message_lines by
-
# @return [Array<String>] the examples colorized backtrace lines
-
1
def colorized_formatted_backtrace(colorizer=::RSpec::Core::Formatters::ConsoleCodes)
-
@exception_presenter.colorized_formatted_backtrace(colorizer)
-
end
-
-
# @return [String] The failure information fully formatted in the way that
-
# RSpec's built-in formatters emit.
-
1
def fully_formatted(failure_number, colorizer=::RSpec::Core::Formatters::ConsoleCodes)
-
@exception_presenter.fully_formatted(failure_number, colorizer)
-
end
-
-
1
private
-
-
1
def initialize(example, exception_presenter=Formatters::ExceptionPresenter.new(example.execution_result.exception, example))
-
@exception_presenter = exception_presenter
-
super(example)
-
end
-
end
-
-
# @deprecated Use {FailedExampleNotification} instead.
-
1
class PendingExampleFixedNotification < FailedExampleNotification; end
-
-
# @deprecated Use {FailedExampleNotification} instead.
-
1
class PendingExampleFailedAsExpectedNotification < FailedExampleNotification; end
-
-
# The `SkippedExampleNotification` extends `ExampleNotification` with
-
# things useful for specs that are skipped.
-
#
-
# @attr [RSpec::Core::Example] example the current example
-
# @see ExampleNotification
-
1
class SkippedExampleNotification < ExampleNotification
-
1
public_class_method :new
-
-
# @return [String] The pending detail fully formatted in the way that
-
# RSpec's built-in formatters emit.
-
1
def fully_formatted(pending_number, colorizer=::RSpec::Core::Formatters::ConsoleCodes)
-
formatted_caller = RSpec.configuration.backtrace_formatter.backtrace_line(example.location)
-
colorizer.wrap("\n #{pending_number}) #{example.full_description}", :pending) << "\n " <<
-
Formatters::ExceptionPresenter::PENDING_DETAIL_FORMATTER.call(example, colorizer) <<
-
"\n" << colorizer.wrap(" # #{formatted_caller}\n", :detail)
-
end
-
end
-
-
# The `GroupNotification` represents notifications sent by the reporter
-
# which contain information about the currently running (or soon to be)
-
# example group. It is used by formatters to access information about that
-
# group.
-
#
-
# @example
-
# def example_group_started(notification)
-
# puts "Hey I started #{notification.group.description}"
-
# end
-
# @attr group [RSpec::Core::ExampleGroup] the current group
-
1
GroupNotification = Struct.new(:group)
-
-
# The `MessageNotification` encapsulates generic messages that the reporter
-
# sends to formatters.
-
#
-
# @attr message [String] the message
-
1
MessageNotification = Struct.new(:message)
-
-
# The `SeedNotification` holds the seed used to randomize examples and
-
# whether that seed has been used or not.
-
#
-
# @attr seed [Fixnum] the seed used to randomize ordering
-
# @attr used [Boolean] whether the seed has been used or not
-
1
SeedNotification = Struct.new(:seed, :used)
-
1
class SeedNotification
-
# @api
-
# @return [Boolean] has the seed been used?
-
1
def seed_used?
-
!!used
-
end
-
1
private :used
-
-
# @return [String] The seed information fully formatted in the way that
-
# RSpec's built-in formatters emit.
-
1
def fully_formatted
-
"\nRandomized with seed #{seed}\n"
-
end
-
end
-
-
# The `SummaryNotification` holds information about the results of running
-
# a test suite. It is used by formatters to provide information at the end
-
# of the test run.
-
#
-
# @attr duration [Float] the time taken (in seconds) to run the suite
-
# @attr examples [Array<RSpec::Core::Example>] the examples run
-
# @attr failed_examples [Array<RSpec::Core::Example>] the failed examples
-
# @attr pending_examples [Array<RSpec::Core::Example>] the pending examples
-
# @attr load_time [Float] the number of seconds taken to boot RSpec
-
# and load the spec files
-
1
SummaryNotification = Struct.new(:duration, :examples, :failed_examples,
-
:pending_examples, :load_time)
-
1
class SummaryNotification
-
# @api
-
# @return [Fixnum] the number of examples run
-
1
def example_count
-
@example_count ||= examples.size
-
end
-
-
# @api
-
# @return [Fixnum] the number of failed examples
-
1
def failure_count
-
@failure_count ||= failed_examples.size
-
end
-
-
# @api
-
# @return [Fixnum] the number of pending examples
-
1
def pending_count
-
@pending_count ||= pending_examples.size
-
end
-
-
# @api
-
# @return [String] A line summarising the result totals of the spec run.
-
1
def totals_line
-
summary = Formatters::Helpers.pluralize(example_count, "example")
-
summary << ", " << Formatters::Helpers.pluralize(failure_count, "failure")
-
summary << ", #{pending_count} pending" if pending_count > 0
-
summary
-
end
-
-
# @api public
-
#
-
# Wraps the results line with colors based on the configured
-
# colors for failure, pending, and success. Defaults to red,
-
# yellow, green accordingly.
-
#
-
# @param colorizer [#wrap] An object which supports wrapping text with
-
# specific colors.
-
# @return [String] A colorized results line.
-
1
def colorized_totals_line(colorizer=::RSpec::Core::Formatters::ConsoleCodes)
-
if failure_count > 0
-
colorizer.wrap(totals_line, RSpec.configuration.failure_color)
-
elsif pending_count > 0
-
colorizer.wrap(totals_line, RSpec.configuration.pending_color)
-
else
-
colorizer.wrap(totals_line, RSpec.configuration.success_color)
-
end
-
end
-
-
# @api public
-
#
-
# Formats failures into a rerunable command format.
-
#
-
# @param colorizer [#wrap] An object which supports wrapping text with
-
# specific colors.
-
# @return [String] A colorized summary line.
-
1
def colorized_rerun_commands(colorizer=::RSpec::Core::Formatters::ConsoleCodes)
-
"\nFailed examples:\n\n" +
-
failed_examples.map do |example|
-
colorizer.wrap("rspec #{rerun_argument_for(example)}", RSpec.configuration.failure_color) + " " +
-
colorizer.wrap("# #{example.full_description}", RSpec.configuration.detail_color)
-
end.join("\n")
-
end
-
-
# @return [String] a formatted version of the time it took to run the
-
# suite
-
1
def formatted_duration
-
Formatters::Helpers.format_duration(duration)
-
end
-
-
# @return [String] a formatted version of the time it took to boot RSpec
-
# and load the spec files
-
1
def formatted_load_time
-
Formatters::Helpers.format_duration(load_time)
-
end
-
-
# @return [String] The summary information fully formatted in the way that
-
# RSpec's built-in formatters emit.
-
1
def fully_formatted(colorizer=::RSpec::Core::Formatters::ConsoleCodes)
-
formatted = "\nFinished in #{formatted_duration} " \
-
"(files took #{formatted_load_time} to load)\n" \
-
"#{colorized_totals_line(colorizer)}\n"
-
-
unless failed_examples.empty?
-
formatted << colorized_rerun_commands(colorizer) << "\n"
-
end
-
-
formatted
-
end
-
-
1
private
-
-
1
include RSpec::Core::ShellEscape
-
-
1
def rerun_argument_for(example)
-
location = example.location_rerun_argument
-
return location unless duplicate_rerun_locations.include?(location)
-
conditionally_quote(example.id)
-
end
-
-
1
def duplicate_rerun_locations
-
@duplicate_rerun_locations ||= begin
-
locations = RSpec.world.all_examples.map(&:location_rerun_argument)
-
-
Set.new.tap do |s|
-
locations.group_by { |l| l }.each do |l, ls|
-
s << l if ls.count > 1
-
end
-
end
-
end
-
end
-
end
-
-
# The `ProfileNotification` holds information about the results of running a
-
# test suite when profiling is enabled. It is used by formatters to provide
-
# information at the end of the test run for profiling information.
-
#
-
# @attr duration [Float] the time taken (in seconds) to run the suite
-
# @attr examples [Array<RSpec::Core::Example>] the examples run
-
# @attr number_of_examples [Fixnum] the number of examples to profile
-
# @attr example_groups [Array<RSpec::Core::Profiler>] example groups run
-
1
class ProfileNotification
-
1
def initialize(duration, examples, number_of_examples, example_groups)
-
@duration = duration
-
@examples = examples
-
@number_of_examples = number_of_examples
-
@example_groups = example_groups
-
end
-
1
attr_reader :duration, :examples, :number_of_examples
-
-
# @return [Array<RSpec::Core::Example>] the slowest examples
-
1
def slowest_examples
-
@slowest_examples ||=
-
examples.sort_by do |example|
-
-example.execution_result.run_time
-
end.first(number_of_examples)
-
end
-
-
# @return [Float] the time taken (in seconds) to run the slowest examples
-
1
def slow_duration
-
@slow_duration ||=
-
slowest_examples.inject(0.0) do |i, e|
-
i + e.execution_result.run_time
-
end
-
end
-
-
# @return [String] the percentage of total time taken
-
1
def percentage
-
@percentage ||=
-
begin
-
time_taken = slow_duration / duration
-
'%.1f' % ((time_taken.nan? ? 0.0 : time_taken) * 100)
-
end
-
end
-
-
# @return [Array<RSpec::Core::Example>] the slowest example groups
-
1
def slowest_groups
-
@slowest_groups ||= calculate_slowest_groups
-
end
-
-
1
private
-
-
1
def calculate_slowest_groups
-
# stop if we've only one example group
-
return {} if @example_groups.keys.length <= 1
-
-
@example_groups.each_value do |hash|
-
hash[:average] = hash[:total_time].to_f / hash[:count]
-
end
-
-
groups = @example_groups.sort_by { |_, hash| -hash[:average] }.first(number_of_examples)
-
groups.map { |group, data| [group.location, data] }
-
end
-
end
-
-
# The `DeprecationNotification` is issued by the reporter when a deprecated
-
# part of RSpec is encountered. It represents information about the
-
# deprecated call site.
-
#
-
# @attr message [String] A custom message about the deprecation
-
# @attr deprecated [String] A custom message about the deprecation (alias of
-
# message)
-
# @attr replacement [String] An optional replacement for the deprecation
-
# @attr call_site [String] An optional call site from which the deprecation
-
# was issued
-
1
DeprecationNotification = Struct.new(:deprecated, :message, :replacement, :call_site)
-
1
class DeprecationNotification
-
1
private_class_method :new
-
-
# @api
-
# Convenience way to initialize the notification
-
1
def self.from_hash(data)
-
new data[:deprecated], data[:message], data[:replacement], data[:call_site]
-
end
-
end
-
-
# `NullNotification` represents a placeholder value for notifications that
-
# currently require no information, but we may wish to extend in future.
-
1
class NullNotification
-
end
-
-
# `CustomNotification` is used when sending custom events to formatters /
-
# other registered listeners, it creates attributes based on supplied hash
-
# of options.
-
1
class CustomNotification < Struct
-
# @param options [Hash] A hash of method / value pairs to create on this notification
-
# @return [CustomNotification]
-
#
-
# Build a custom notification based on the supplied option key / values.
-
1
def self.for(options={})
-
return NullNotification if options.keys.empty?
-
new(*options.keys).new(*options.values)
-
end
-
end
-
end
-
end
-
# http://www.ruby-doc.org/stdlib/libdoc/optparse/rdoc/classes/OptionParser.html
-
1
require 'optparse'
-
-
1
module RSpec::Core
-
# @private
-
1
class Parser
-
1
def self.parse(args, source=nil)
-
new(args).parse(source)
-
end
-
-
1
attr_reader :original_args
-
-
1
def initialize(original_args)
-
@original_args = original_args
-
end
-
-
1
def parse(source=nil)
-
return { :files_or_directories_to_run => [] } if original_args.empty?
-
args = original_args.dup
-
-
options = args.delete('--tty') ? { :tty => true } : {}
-
begin
-
parser(options).parse!(args)
-
rescue OptionParser::InvalidOption => e
-
failure = e.message
-
failure << " (defined in #{source})" if source
-
abort "#{failure}\n\nPlease use --help for a listing of valid options"
-
end
-
-
options[:files_or_directories_to_run] = args
-
options
-
end
-
-
1
private
-
-
# rubocop:disable MethodLength
-
# rubocop:disable Metrics/AbcSize
-
# rubocop:disable CyclomaticComplexity
-
1
def parser(options)
-
OptionParser.new do |parser|
-
parser.banner = "Usage: rspec [options] [files or directories]\n\n"
-
-
parser.on('-I PATH', 'Specify PATH to add to $LOAD_PATH (may be used more than once).') do |dirs|
-
options[:libs] ||= []
-
options[:libs].concat(dirs.split(File::PATH_SEPARATOR))
-
end
-
-
parser.on('-r', '--require PATH', 'Require a file.') do |path|
-
options[:requires] ||= []
-
options[:requires] << path
-
end
-
-
parser.on('-O', '--options PATH', 'Specify the path to a custom options file.') do |path|
-
options[:custom_options_file] = path
-
end
-
-
parser.on('--order TYPE[:SEED]', 'Run examples by the specified order type.',
-
' [defined] examples and groups are run in the order they are defined',
-
' [rand] randomize the order of groups and examples',
-
' [random] alias for rand',
-
' [random:SEED] e.g. --order random:123') do |o|
-
options[:order] = o
-
end
-
-
parser.on('--seed SEED', Integer, 'Equivalent of --order rand:SEED.') do |seed|
-
options[:order] = "rand:#{seed}"
-
end
-
-
parser.on('--bisect[=verbose]', 'Repeatedly runs the suite in order to isolate the failures to the ',
-
' smallest reproducible case.') do |argument|
-
bisect_and_exit(argument)
-
end
-
-
parser.on('--[no-]fail-fast[=COUNT]', 'Abort the run after a certain number of failures (1 by default).') do |argument|
-
if argument == true
-
value = 1
-
elsif argument == false || argument == 0
-
value = false
-
else
-
begin
-
value = Integer(argument)
-
rescue ArgumentError
-
RSpec.warning "Expected an integer value for `--fail-fast`, got: #{argument.inspect}", :call_site => nil
-
end
-
end
-
set_fail_fast(options, value)
-
end
-
-
parser.on('--failure-exit-code CODE', Integer,
-
'Override the exit code used when there are failing specs.') do |code|
-
options[:failure_exit_code] = code
-
end
-
-
parser.on('--dry-run', 'Print the formatter output of your suite without',
-
' running any examples or hooks') do |_o|
-
options[:dry_run] = true
-
end
-
-
parser.on('-X', '--[no-]drb', 'Run examples via DRb.') do |o|
-
options[:drb] = o
-
end
-
-
parser.on('--drb-port PORT', 'Port to connect to the DRb server.') do |o|
-
options[:drb_port] = o.to_i
-
end
-
-
parser.on('--init', 'Initialize your project with RSpec.') do |_cmd|
-
initialize_project_and_exit
-
end
-
-
parser.separator("\n **** Output ****\n\n")
-
-
parser.on('-f', '--format FORMATTER', 'Choose a formatter.',
-
' [p]rogress (default - dots)',
-
' [d]ocumentation (group and example names)',
-
' [h]tml',
-
' [j]son',
-
' custom formatter class name') do |o|
-
options[:formatters] ||= []
-
options[:formatters] << [o]
-
end
-
-
parser.on('-o', '--out FILE',
-
'Write output to a file instead of $stdout. This option applies',
-
' to the previously specified --format, or the default format',
-
' if no format is specified.'
-
) do |o|
-
options[:formatters] ||= [['progress']]
-
options[:formatters].last << o
-
end
-
-
parser.on('--deprecation-out FILE', 'Write deprecation warnings to a file instead of $stderr.') do |file|
-
options[:deprecation_stream] = file
-
end
-
-
parser.on('-b', '--backtrace', 'Enable full backtrace.') do |_o|
-
options[:full_backtrace] = true
-
end
-
-
parser.on('-c', '--[no-]color', '--[no-]colour', 'Enable color in the output.') do |o|
-
options[:color] = o
-
end
-
-
parser.on('-p', '--[no-]profile [COUNT]',
-
'Enable profiling of examples and list the slowest examples (default: 10).') do |argument|
-
options[:profile_examples] = if argument.nil?
-
true
-
elsif argument == false
-
false
-
else
-
begin
-
Integer(argument)
-
rescue ArgumentError
-
RSpec.warning "Non integer specified as profile count, seperate " \
-
"your path from options with -- e.g. " \
-
"`rspec --profile -- #{argument}`",
-
:call_site => nil
-
true
-
end
-
end
-
end
-
-
parser.on('-w', '--warnings', 'Enable ruby warnings') do
-
$VERBOSE = true
-
end
-
-
parser.separator <<-FILTERING
-
-
**** Filtering/tags ****
-
-
In addition to the following options for selecting specific files, groups, or
-
examples, you can select individual examples by appending the line number(s) to
-
the filename:
-
-
rspec path/to/a_spec.rb:37:87
-
-
You can also pass example ids enclosed in square brackets:
-
-
rspec path/to/a_spec.rb[1:5,1:6] # run the 5th and 6th examples/groups defined in the 1st group
-
-
FILTERING
-
-
parser.on('--only-failures', "Filter to just the examples that failed the last time they ran.") do
-
configure_only_failures(options)
-
end
-
-
parser.on("--next-failure", "Apply `--only-failures` and abort after one failure.",
-
" (Equivalent to `--only-failures --fail-fast --order defined`)") do
-
configure_only_failures(options)
-
set_fail_fast(options, 1)
-
options[:order] ||= 'defined'
-
end
-
-
parser.on('-P', '--pattern PATTERN', 'Load files matching pattern (default: "spec/**/*_spec.rb").') do |o|
-
if options[:pattern]
-
options[:pattern] += ',' + o
-
else
-
options[:pattern] = o
-
end
-
end
-
-
parser.on('--exclude-pattern PATTERN',
-
'Load files except those matching pattern. Opposite effect of --pattern.') do |o|
-
options[:exclude_pattern] = o
-
end
-
-
parser.on('-e', '--example STRING', "Run examples whose full nested names include STRING (may be",
-
" used more than once)") do |o|
-
(options[:full_description] ||= []) << Regexp.compile(Regexp.escape(o))
-
end
-
-
parser.on('-t', '--tag TAG[:VALUE]',
-
'Run examples with the specified tag, or exclude examples',
-
'by adding ~ before the tag.',
-
' - e.g. ~slow',
-
' - TAG is always converted to a symbol') do |tag|
-
filter_type = tag =~ /^~/ ? :exclusion_filter : :inclusion_filter
-
-
name, value = tag.gsub(/^(~@|~|@)/, '').split(':', 2)
-
name = name.to_sym
-
-
parsed_value = case value
-
when nil then true # The default value for tags is true
-
when 'true' then true
-
when 'false' then false
-
when 'nil' then nil
-
when /^:/ then value[1..-1].to_sym
-
when /^\d+$/ then Integer(value)
-
when /^\d+.\d+$/ then Float(value)
-
else
-
value
-
end
-
-
add_tag_filter(options, filter_type, name, parsed_value)
-
end
-
-
parser.on('--default-path PATH', 'Set the default path where RSpec looks for examples (can',
-
' be a path to a file or a directory).') do |path|
-
options[:default_path] = path
-
end
-
-
parser.separator("\n **** Utility ****\n\n")
-
-
parser.on('-v', '--version', 'Display the version.') do
-
print_version_and_exit
-
end
-
-
# These options would otherwise be confusing to users, so we forcibly
-
# prevent them from executing.
-
#
-
# * --I is too similar to -I.
-
# * -d was a shorthand for --debugger, which is removed, but now would
-
# trigger --default-path.
-
invalid_options = %w[-d --I]
-
-
parser.on_tail('-h', '--help', "You're looking at it.") do
-
print_help_and_exit(parser, invalid_options)
-
end
-
-
# This prevents usage of the invalid_options.
-
invalid_options.each do |option|
-
parser.on(option) do
-
raise OptionParser::InvalidOption.new
-
end
-
end
-
end
-
end
-
# rubocop:enable Metrics/AbcSize
-
# rubocop:enable MethodLength
-
# rubocop:enable CyclomaticComplexity
-
-
1
def add_tag_filter(options, filter_type, tag_name, value=true)
-
(options[filter_type] ||= {})[tag_name] = value
-
end
-
-
1
def set_fail_fast(options, value)
-
options[:fail_fast] = value
-
end
-
-
1
def configure_only_failures(options)
-
options[:only_failures] = true
-
add_tag_filter(options, :inclusion_filter, :last_run_status, 'failed')
-
end
-
-
1
def initialize_project_and_exit
-
RSpec::Support.require_rspec_core "project_initializer"
-
ProjectInitializer.new.run
-
exit
-
end
-
-
1
def bisect_and_exit(argument)
-
RSpec::Support.require_rspec_core "bisect/coordinator"
-
-
success = Bisect::Coordinator.bisect_with(
-
original_args,
-
RSpec.configuration,
-
bisect_formatter_for(argument)
-
)
-
-
exit(success ? 0 : 1)
-
end
-
-
1
def bisect_formatter_for(argument)
-
return Formatters::BisectDebugFormatter if argument == "verbose"
-
Formatters::BisectProgressFormatter
-
end
-
-
1
def print_version_and_exit
-
puts RSpec::Core::Version::STRING
-
exit
-
end
-
-
1
def print_help_and_exit(parser, invalid_options)
-
# Removing the blank invalid options from the output.
-
puts parser.to_s.gsub(/^\s+(#{invalid_options.join('|')})\s*$\n/, '')
-
exit
-
end
-
end
-
end
-
1
module RSpec
-
1
module Core
-
# @private
-
1
module Ordering
-
# @private
-
# The default global ordering (defined order).
-
1
class Identity
-
1
def order(items)
-
items
-
end
-
end
-
-
# @private
-
# Orders items randomly.
-
1
class Random
-
1
def initialize(configuration)
-
1
@configuration = configuration
-
1
@used = false
-
end
-
-
1
def used?
-
@used
-
end
-
-
1
def order(items)
-
@used = true
-
-
seed = @configuration.seed.to_s
-
items.sort_by { |item| jenkins_hash_digest(seed + item.id) }
-
end
-
-
1
private
-
-
# http://en.wikipedia.org/wiki/Jenkins_hash_function
-
# Jenkins provides a good distribution and is simpler than MD5.
-
# It's a bit slower than MD5 (primarily because `Digest::MD5` is
-
# implemented in C) but has the advantage of not requiring us
-
# to load another part of stdlib, which we try to minimize.
-
1
def jenkins_hash_digest(string)
-
hash = 0
-
-
string.each_byte do |byte|
-
hash += byte
-
hash &= MAX_32_BIT
-
hash += ((hash << 10) & MAX_32_BIT)
-
hash &= MAX_32_BIT
-
hash ^= hash >> 6
-
end
-
-
hash += ((hash << 3) & MAX_32_BIT)
-
hash &= MAX_32_BIT
-
hash ^= hash >> 11
-
hash += ((hash << 15) & MAX_32_BIT)
-
hash &= MAX_32_BIT
-
hash
-
end
-
-
1
MAX_32_BIT = 4_294_967_295
-
end
-
-
# @private
-
# Orders items based on a custom block.
-
1
class Custom
-
1
def initialize(callable)
-
@callable = callable
-
end
-
-
1
def order(list)
-
@callable.call(list)
-
end
-
end
-
-
# @private
-
# Stores the different ordering strategies.
-
1
class Registry
-
1
def initialize(configuration)
-
1
@configuration = configuration
-
1
@strategies = {}
-
-
1
register(:random, Random.new(configuration))
-
-
1
identity = Identity.new
-
1
register(:defined, identity)
-
-
# The default global ordering is --defined.
-
1
register(:global, identity)
-
end
-
-
1
def fetch(name, &fallback)
-
@strategies.fetch(name, &fallback)
-
end
-
-
1
def register(sym, strategy)
-
3
@strategies[sym] = strategy
-
end
-
-
1
def used_random_seed?
-
@strategies[:random].used?
-
end
-
end
-
-
# @private
-
# Manages ordering configuration.
-
#
-
# @note This is not intended to be used externally. Use
-
# the APIs provided by `RSpec::Core::Configuration` instead.
-
1
class ConfigurationManager
-
1
attr_reader :seed, :ordering_registry
-
-
1
def initialize
-
1
@ordering_registry = Registry.new(self)
-
1
@seed = rand(0xFFFF)
-
1
@seed_forced = false
-
1
@order_forced = false
-
end
-
-
1
def seed_used?
-
ordering_registry.used_random_seed?
-
end
-
-
1
def seed=(seed)
-
return if @seed_forced
-
register_ordering(:global, ordering_registry.fetch(:random))
-
@seed = seed.to_i
-
end
-
-
1
def order=(type)
-
order, seed = type.to_s.split(':')
-
@seed = seed.to_i if seed
-
-
ordering_name = if order.include?('rand')
-
:random
-
elsif order == 'defined'
-
:defined
-
end
-
-
register_ordering(:global, ordering_registry.fetch(ordering_name)) if ordering_name
-
end
-
-
1
def force(hash)
-
if hash.key?(:seed)
-
self.seed = hash[:seed]
-
@seed_forced = true
-
@order_forced = true
-
elsif hash.key?(:order)
-
self.order = hash[:order]
-
@order_forced = true
-
end
-
end
-
-
1
def register_ordering(name, strategy=Custom.new(Proc.new { |l| yield l }))
-
return if @order_forced && name == :global
-
ordering_registry.register(name, strategy)
-
end
-
end
-
end
-
end
-
end
-
1
module RSpec
-
1
module Core
-
# Provides methods to mark examples as pending. These methods are available
-
# to be called from within any example or hook.
-
1
module Pending
-
# Raised in the middle of an example to indicate that it should be marked
-
# as skipped.
-
1
class SkipDeclaredInExample < StandardError
-
1
attr_reader :argument
-
-
1
def initialize(argument)
-
@argument = argument
-
end
-
end
-
-
# If Test::Unit is loaded, we'll use its error as baseclass, so that
-
# Test::Unit will report unmet RSpec expectations as failures rather than
-
# errors.
-
1
begin
-
1
class PendingExampleFixedError < Test::Unit::AssertionFailedError; end
-
rescue
-
1
class PendingExampleFixedError < StandardError; end
-
end
-
-
# @private
-
1
NO_REASON_GIVEN = 'No reason given'
-
-
# @private
-
1
NOT_YET_IMPLEMENTED = 'Not yet implemented'
-
-
# @overload pending()
-
# @overload pending(message)
-
#
-
# Marks an example as pending. The rest of the example will still be
-
# executed, and if it passes the example will fail to indicate that the
-
# pending can be removed.
-
#
-
# @param message [String] optional message to add to the summary report.
-
#
-
# @example
-
# describe "an example" do
-
# # reported as "Pending: no reason given"
-
# it "is pending with no message" do
-
# pending
-
# raise "broken"
-
# end
-
#
-
# # reported as "Pending: something else getting finished"
-
# it "is pending with a custom message" do
-
# pending("something else getting finished")
-
# raise "broken"
-
# end
-
# end
-
#
-
# @note `before(:example)` hooks are eval'd when you use the `pending`
-
# method within an example. If you want to declare an example `pending`
-
# and bypass the `before` hooks as well, you can pass `:pending => true`
-
# to the `it` method:
-
#
-
# it "does something", :pending => true do
-
# # ...
-
# end
-
#
-
# or pass `:pending => "something else getting finished"` to add a
-
# message to the summary report:
-
#
-
# it "does something", :pending => "something else getting finished" do
-
# # ...
-
# end
-
1
def pending(message=nil)
-
current_example = RSpec.current_example
-
-
if block_given?
-
raise ArgumentError, <<-EOS.gsub(/^\s+\|/, '')
-
|The semantics of `RSpec::Core::Pending#pending` have changed in
-
|RSpec 3. In RSpec 2.x, it caused the example to be skipped. In
-
|RSpec 3, the rest of the example is still run but is expected to
-
|fail, and will be marked as a failure (rather than as pending) if
-
|the example passes.
-
|
-
|Passing a block within an example is now deprecated. Marking the
-
|example as pending provides the same behavior in RSpec 3 which was
-
|provided only by the block in RSpec 2.x.
-
|
-
|Move the code in the block provided to `pending` into the rest of
-
|the example body.
-
|
-
|Called from #{CallerFilter.first_non_rspec_line}.
-
|
-
EOS
-
elsif current_example
-
Pending.mark_pending! current_example, message
-
else
-
raise "`pending` may not be used outside of examples, such as in " \
-
"before(:context). Maybe you want `skip`?"
-
end
-
end
-
-
# @overload skip()
-
# @overload skip(message)
-
#
-
# Marks an example as pending and skips execution.
-
#
-
# @param message [String] optional message to add to the summary report.
-
#
-
# @example
-
# describe "an example" do
-
# # reported as "Pending: no reason given"
-
# it "is skipped with no message" do
-
# skip
-
# end
-
#
-
# # reported as "Pending: something else getting finished"
-
# it "is skipped with a custom message" do
-
# skip "something else getting finished"
-
# end
-
# end
-
1
def skip(message=nil)
-
current_example = RSpec.current_example
-
-
Pending.mark_skipped!(current_example, message) if current_example
-
-
raise SkipDeclaredInExample.new(message)
-
end
-
-
# @private
-
#
-
# Mark example as skipped.
-
#
-
# @param example [RSpec::Core::Example] the example to mark as skipped
-
# @param message_or_bool [Boolean, String] the message to use, or true
-
1
def self.mark_skipped!(example, message_or_bool)
-
Pending.mark_pending! example, message_or_bool
-
example.metadata[:skip] = true
-
end
-
-
# @private
-
#
-
# Mark example as pending.
-
#
-
# @param example [RSpec::Core::Example] the example to mark as pending
-
# @param message_or_bool [Boolean, String] the message to use, or true
-
1
def self.mark_pending!(example, message_or_bool)
-
message = if !message_or_bool || !(String === message_or_bool)
-
NO_REASON_GIVEN
-
else
-
message_or_bool
-
end
-
-
example.metadata[:pending] = true
-
example.execution_result.pending_message = message
-
example.execution_result.pending_fixed = false
-
end
-
-
# @private
-
#
-
# Mark example as fixed.
-
#
-
# @param example [RSpec::Core::Example] the example to mark as fixed
-
1
def self.mark_fixed!(example)
-
example.execution_result.pending_fixed = true
-
end
-
end
-
end
-
end
-
1
module RSpec::Core
-
# A reporter will send notifications to listeners, usually formatters for the
-
# spec suite run.
-
1
class Reporter
-
# @private
-
1
RSPEC_NOTIFICATIONS = Set.new(
-
[
-
:close, :deprecation, :deprecation_summary, :dump_failures, :dump_pending,
-
:dump_profile, :dump_summary, :example_failed, :example_group_finished,
-
:example_group_started, :example_passed, :example_pending, :example_started,
-
:message, :seed, :start, :start_dump, :stop, :example_finished
-
])
-
-
1
def initialize(configuration)
-
@configuration = configuration
-
@listeners = Hash.new { |h, k| h[k] = Set.new }
-
@examples = []
-
@failed_examples = []
-
@pending_examples = []
-
@duration = @start = @load_time = nil
-
end
-
-
# @private
-
1
attr_reader :examples, :failed_examples, :pending_examples
-
-
# @private
-
1
def reset
-
@examples = []
-
@failed_examples = []
-
@pending_examples = []
-
@profiler = Profiler.new if defined?(@profiler)
-
end
-
-
# @private
-
1
def setup_profiler
-
@profiler = Profiler.new
-
register_listener @profiler, *Profiler::NOTIFICATIONS
-
end
-
-
# Registers a listener to a list of notifications. The reporter will send
-
# notification of events to all registered listeners.
-
#
-
# @param listener [Object] An obect that wishes to be notified of reporter
-
# events
-
# @param notifications [Array] Array of symbols represents the events a
-
# listener wishes to subscribe too
-
1
def register_listener(listener, *notifications)
-
notifications.each do |notification|
-
@listeners[notification.to_sym] << listener
-
end
-
true
-
end
-
-
# @private
-
1
def registered_listeners(notification)
-
@listeners[notification].to_a
-
end
-
-
# @overload report(count, &block)
-
# @overload report(count, &block)
-
# @param expected_example_count [Integer] the number of examples being run
-
# @yield [Block] block yields itself for further reporting.
-
#
-
# Initializes the report run and yields itself for further reporting. The
-
# block is required, so that the reporter can manage cleaning up after the
-
# run.
-
#
-
# @example
-
#
-
# reporter.report(group.examples.size) do |r|
-
# example_groups.map {|g| g.run(r) }
-
# end
-
#
-
1
def report(expected_example_count)
-
start(expected_example_count)
-
begin
-
yield self
-
ensure
-
finish
-
end
-
end
-
-
# @private
-
1
def start(expected_example_count, time=RSpec::Core::Time.now)
-
@start = time
-
@load_time = (@start - @configuration.start_time).to_f
-
notify :seed, Notifications::SeedNotification.new(@configuration.seed, seed_used?)
-
notify :start, Notifications::StartNotification.new(expected_example_count, @load_time)
-
end
-
-
# @param message [#to_s] A message object to send to formatters
-
#
-
# Send a custom message to supporting formatters.
-
1
def message(message)
-
notify :message, Notifications::MessageNotification.new(message)
-
end
-
-
# @param event [Symbol] Name of the custom event to trigger on formatters
-
# @param options [Hash] Hash of arguments to provide via `CustomNotification`
-
#
-
# Publish a custom event to supporting registered formatters.
-
# @see RSpec::Core::Notifications::CustomNotification
-
1
def publish(event, options={})
-
if RSPEC_NOTIFICATIONS.include? event
-
raise "RSpec::Core::Reporter#publish is intended for sending custom " \
-
"events not internal RSpec ones, please rename your custom event."
-
end
-
notify event, Notifications::CustomNotification.for(options)
-
end
-
-
# @private
-
1
def example_group_started(group)
-
notify :example_group_started, Notifications::GroupNotification.new(group) unless group.descendant_filtered_examples.empty?
-
end
-
-
# @private
-
1
def example_group_finished(group)
-
notify :example_group_finished, Notifications::GroupNotification.new(group) unless group.descendant_filtered_examples.empty?
-
end
-
-
# @private
-
1
def example_started(example)
-
@examples << example
-
notify :example_started, Notifications::ExampleNotification.for(example)
-
end
-
-
# @private
-
1
def example_finished(example)
-
notify :example_finished, Notifications::ExampleNotification.for(example)
-
end
-
-
# @private
-
1
def example_passed(example)
-
notify :example_passed, Notifications::ExampleNotification.for(example)
-
end
-
-
# @private
-
1
def example_failed(example)
-
@failed_examples << example
-
notify :example_failed, Notifications::ExampleNotification.for(example)
-
end
-
-
# @private
-
1
def example_pending(example)
-
@pending_examples << example
-
notify :example_pending, Notifications::ExampleNotification.for(example)
-
end
-
-
# @private
-
1
def deprecation(hash)
-
notify :deprecation, Notifications::DeprecationNotification.from_hash(hash)
-
end
-
-
# @private
-
1
def finish
-
close_after do
-
stop
-
notify :start_dump, Notifications::NullNotification
-
notify :dump_pending, Notifications::ExamplesNotification.new(self)
-
notify :dump_failures, Notifications::ExamplesNotification.new(self)
-
notify :deprecation_summary, Notifications::NullNotification
-
unless mute_profile_output?
-
notify :dump_profile, Notifications::ProfileNotification.new(@duration, @examples,
-
@configuration.profile_examples,
-
@profiler.example_groups)
-
end
-
notify :dump_summary, Notifications::SummaryNotification.new(@duration, @examples, @failed_examples,
-
@pending_examples, @load_time)
-
notify :seed, Notifications::SeedNotification.new(@configuration.seed, seed_used?)
-
end
-
end
-
-
# @private
-
1
def close_after
-
yield
-
ensure
-
close
-
end
-
-
# @private
-
1
def stop
-
@duration = (RSpec::Core::Time.now - @start).to_f if @start
-
notify :stop, Notifications::ExamplesNotification.new(self)
-
end
-
-
# @private
-
1
def notify(event, notification)
-
registered_listeners(event).each do |formatter|
-
formatter.__send__(event, notification)
-
end
-
end
-
-
# @private
-
1
def abort_with(msg, exit_status)
-
message(msg)
-
close
-
exit!(exit_status)
-
end
-
-
# @private
-
1
def fail_fast_limit_met?
-
return false unless (fail_fast = @configuration.fail_fast)
-
-
if fail_fast == true
-
@failed_examples.any?
-
else
-
fail_fast <= @failed_examples.size
-
end
-
end
-
-
1
private
-
-
1
def close
-
notify :close, Notifications::NullNotification
-
end
-
-
1
def mute_profile_output?
-
# Don't print out profiled info if there are failures and `--fail-fast` is
-
# used, it just clutters the output.
-
!@configuration.profile_examples? || fail_fast_limit_met?
-
end
-
-
1
def seed_used?
-
@configuration.seed && @configuration.seed_used?
-
end
-
end
-
-
# @private
-
# # Used in place of a {Reporter} for situations where we don't want reporting output.
-
1
class NullReporter
-
1
def self.method_missing(*)
-
# ignore
-
end
-
1
private_class_method :method_missing
-
end
-
end
-
# This is borrowed (slightly modified) from Scott Taylor's
-
# project_path project:
-
# http://github.com/smtlaissezfaire/project_path
-
1
module RSpec
-
1
module Core
-
# @private
-
1
module RubyProject
-
1
def add_to_load_path(*dirs)
-
dirs.each { |dir| add_dir_to_load_path(File.join(root, dir)) }
-
end
-
-
1
def add_dir_to_load_path(dir)
-
$LOAD_PATH.unshift(dir) unless $LOAD_PATH.include?(dir)
-
end
-
-
1
def root
-
@project_root ||= determine_root
-
end
-
-
1
def determine_root
-
find_first_parent_containing('spec') || '.'
-
end
-
-
1
def find_first_parent_containing(dir)
-
ascend_until { |path| File.exist?(File.join(path, dir)) }
-
end
-
-
1
def ascend_until
-
fs = File::SEPARATOR
-
escaped_slash = "\\#{fs}"
-
special = "_RSPEC_ESCAPED_SLASH_"
-
project_path = File.expand_path(".")
-
parts = project_path.gsub(escaped_slash, special).squeeze(fs).split(fs).map do |x|
-
x.gsub(special, escaped_slash)
-
end
-
-
until parts.empty?
-
path = parts.join(fs)
-
path = fs if path == ""
-
return path if yield(path)
-
parts.pop
-
end
-
end
-
-
1
module_function :add_to_load_path
-
1
module_function :add_dir_to_load_path
-
1
module_function :root
-
1
module_function :determine_root
-
1
module_function :find_first_parent_containing
-
1
module_function :ascend_until
-
end
-
end
-
end
-
1
module RSpec
-
1
module Core
-
# Provides the main entry point to run a suite of RSpec examples.
-
1
class Runner
-
# @attr_reader
-
# @private
-
1
attr_reader :options, :configuration, :world
-
-
# Register an `at_exit` hook that runs the suite when the process exits.
-
#
-
# @note This is not generally needed. The `rspec` command takes care
-
# of running examples for you without involving an `at_exit`
-
# hook. This is only needed if you are running specs using
-
# the `ruby` command, and even then, the normal way to invoke
-
# this is by requiring `rspec/autorun`.
-
1
def self.autorun
-
if autorun_disabled?
-
RSpec.deprecate("Requiring `rspec/autorun` when running RSpec via the `rspec` command")
-
return
-
elsif installed_at_exit? || running_in_drb?
-
return
-
end
-
-
at_exit { perform_at_exit }
-
@installed_at_exit = true
-
end
-
-
# @private
-
1
def self.perform_at_exit
-
# Don't bother running any specs and just let the program terminate
-
# if we got here due to an unrescued exception (anything other than
-
# SystemExit, which is raised when somebody calls Kernel#exit).
-
return unless $!.nil? || $!.is_a?(SystemExit)
-
-
# We got here because either the end of the program was reached or
-
# somebody called Kernel#exit. Run the specs and then override any
-
# existing exit status with RSpec's exit status if any specs failed.
-
invoke
-
end
-
-
# Runs the suite of specs and exits the process with an appropriate exit
-
# code.
-
1
def self.invoke
-
disable_autorun!
-
status = run(ARGV, $stderr, $stdout).to_i
-
exit(status) if status != 0
-
end
-
-
# Run a suite of RSpec examples. Does not exit.
-
#
-
# This is used internally by RSpec to run a suite, but is available
-
# for use by any other automation tool.
-
#
-
# If you want to run this multiple times in the same process, and you
-
# want files like `spec_helper.rb` to be reloaded, be sure to load `load`
-
# instead of `require`.
-
#
-
# @param args [Array] command-line-supported arguments
-
# @param err [IO] error stream
-
# @param out [IO] output stream
-
# @return [Fixnum] exit status code. 0 if all specs passed,
-
# or the configured failure exit code (1 by default) if specs
-
# failed.
-
1
def self.run(args, err=$stderr, out=$stdout)
-
trap_interrupt
-
options = ConfigurationOptions.new(args)
-
-
if options.options[:drb]
-
require 'rspec/core/drb'
-
begin
-
DRbRunner.new(options).run(err, out)
-
return
-
rescue DRb::DRbConnError
-
err.puts "No DRb server is running. Running in local process instead ..."
-
end
-
end
-
-
new(options).run(err, out)
-
end
-
-
1
def initialize(options, configuration=RSpec.configuration, world=RSpec.world)
-
@options = options
-
@configuration = configuration
-
@world = world
-
end
-
-
# Configures and runs a spec suite.
-
#
-
# @param err [IO] error stream
-
# @param out [IO] output stream
-
1
def run(err, out)
-
setup(err, out)
-
run_specs(@world.ordered_example_groups).tap do
-
persist_example_statuses
-
end
-
end
-
-
# Wires together the various configuration objects and state holders.
-
#
-
# @param err [IO] error stream
-
# @param out [IO] output stream
-
1
def setup(err, out)
-
@configuration.error_stream = err
-
@configuration.output_stream = out if @configuration.output_stream == $stdout
-
@options.configure(@configuration)
-
@configuration.load_spec_files
-
@world.announce_filters
-
end
-
-
# Runs the provided example groups.
-
#
-
# @param example_groups [Array<RSpec::Core::ExampleGroup>] groups to run
-
# @return [Fixnum] exit status code. 0 if all specs passed,
-
# or the configured failure exit code (1 by default) if specs
-
# failed.
-
1
def run_specs(example_groups)
-
@configuration.reporter.report(@world.example_count(example_groups)) do |reporter|
-
@configuration.with_suite_hooks do
-
example_groups.map { |g| g.run(reporter) }.all? ? 0 : @configuration.failure_exit_code
-
end
-
end
-
end
-
-
1
private
-
-
1
def persist_example_statuses
-
return unless (path = @configuration.example_status_persistence_file_path)
-
-
ExampleStatusPersister.persist(@world.all_examples, path)
-
rescue SystemCallError => e
-
RSpec.warning "Could not write example statuses to #{path} (configured as " \
-
"`config.example_status_persistence_file_path`) due to a " \
-
"system error: #{e.inspect}. Please check that the config " \
-
"option is set to an accessible, valid file path", :call_site => nil
-
end
-
-
# @private
-
1
def self.disable_autorun!
-
@autorun_disabled = true
-
end
-
-
# @private
-
1
def self.autorun_disabled?
-
@autorun_disabled ||= false
-
end
-
-
# @private
-
1
def self.installed_at_exit?
-
@installed_at_exit ||= false
-
end
-
-
# @private
-
# rubocop:disable Lint/EnsureReturn
-
1
def self.running_in_drb?
-
if defined?(DRb) && DRb.current_server
-
require 'socket'
-
require 'uri'
-
local_ipv4 = IPSocket.getaddress(Socket.gethostname)
-
local_drb = ["127.0.0.1", "localhost", local_ipv4].any? { |addr| addr == URI(DRb.current_server.uri).host }
-
end
-
rescue DRb::DRbServerNotFound
-
ensure
-
return local_drb || false
-
end
-
# rubocop:enable Lint/EnsureReturn
-
-
# @private
-
1
def self.trap_interrupt
-
trap('INT') { handle_interrupt }
-
end
-
-
# @private
-
1
def self.handle_interrupt
-
if RSpec.world.wants_to_quit
-
exit!(1)
-
else
-
RSpec.world.wants_to_quit = true
-
STDERR.puts "\nRSpec is shutting down and will print the summary report... Interrupt again to force quit."
-
end
-
end
-
end
-
end
-
end
-
1
module RSpec
-
1
module Core
-
# @private
-
#
-
# We use this to replace `::Set` so we can have the advantage of
-
# constant time key lookups for unique arrays but without the
-
# potential to pollute a developers environment with an extra
-
# piece of the stdlib. This helps to prevent false positive
-
# builds.
-
#
-
1
class Set
-
1
include Enumerable
-
-
1
def initialize(array=[])
-
14
@values = {}
-
14
merge(array)
-
end
-
-
1
def empty?
-
@values.empty?
-
end
-
-
1
def <<(key)
-
@values[key] = true
-
self
-
end
-
-
1
def delete(key)
-
@values.delete(key)
-
end
-
-
1
def each(&block)
-
@values.keys.each(&block)
-
self
-
end
-
-
1
def include?(key)
-
@values.key?(key)
-
end
-
-
1
def merge(values)
-
18
values.each do |key|
-
29
@values[key] = true
-
end
-
18
self
-
end
-
end
-
end
-
end
-
1
module RSpec
-
1
module Core
-
# Represents some functionality that is shared with multiple example groups.
-
# The functionality is defined by the provided block, which is lazily
-
# eval'd when the `SharedExampleGroupModule` instance is included in an example
-
# group.
-
1
class SharedExampleGroupModule < Module
-
1
def initialize(description, definition)
-
@description = description
-
@definition = definition
-
end
-
-
# Provides a human-readable representation of this module.
-
1
def inspect
-
"#<#{self.class.name} #{@description.inspect}>"
-
end
-
1
alias to_s inspect
-
-
# Ruby callback for when a module is included in another module is class.
-
# Our definition evaluates the shared group block in the context of the
-
# including example group.
-
1
def included(klass)
-
inclusion_line = klass.metadata[:location]
-
SharedExampleGroupInclusionStackFrame.with_frame(@description, inclusion_line) do
-
klass.class_exec(&@definition)
-
end
-
end
-
end
-
-
# Shared example groups let you define common context and/or common
-
# examples that you wish to use in multiple example groups.
-
#
-
# When defined, the shared group block is stored for later evaluation.
-
# It can later be included in an example group either explicitly
-
# (using `include_examples`, `include_context` or `it_behaves_like`)
-
# or implicitly (via matching metadata).
-
#
-
# Named shared example groups are scoped based on where they are
-
# defined. Shared groups defined in an example group are available
-
# for inclusion in that example group or any child example groups,
-
# but not in any parent or sibling example groups. Shared example
-
# groups defined at the top level can be included from any example group.
-
1
module SharedExampleGroup
-
# @overload shared_examples(name, &block)
-
# @param name [String, Symbol, Module] identifer to use when looking up
-
# this shared group
-
# @param block The block to be eval'd
-
# @overload shared_examples(name, metadata, &block)
-
# @param name [String, Symbol, Module] identifer to use when looking up
-
# this shared group
-
# @param metadata [Array<Symbol>, Hash] metadata to attach to this
-
# group; any example group or example with matching metadata will
-
# automatically include this shared example group.
-
# @param block The block to be eval'd
-
# @overload shared_examples(metadata, &block)
-
# @param metadata [Array<Symbol>, Hash] metadata to attach to this
-
# group; any example group or example with matching metadata will
-
# automatically include this shared example group.
-
# @param block The block to be eval'd
-
#
-
# Stores the block for later use. The block will be evaluated
-
# in the context of an example group via `include_examples`,
-
# `include_context`, or `it_behaves_like`.
-
#
-
# @example
-
# shared_examples "auditable" do
-
# it "stores an audit record on save!" do
-
# expect { auditable.save! }.to change(Audit, :count).by(1)
-
# end
-
# end
-
#
-
# describe Account do
-
# it_behaves_like "auditable" do
-
# let(:auditable) { Account.new }
-
# end
-
# end
-
#
-
# @see ExampleGroup.it_behaves_like
-
# @see ExampleGroup.include_examples
-
# @see ExampleGroup.include_context
-
1
def shared_examples(name, *args, &block)
-
top_level = self == ExampleGroup
-
if top_level && RSpec::Support.thread_local_data[:in_example_group]
-
raise "Creating isolated shared examples from within a context is " \
-
"not allowed. Remove `RSpec.` prefix or move this to a " \
-
"top-level scope."
-
end
-
-
RSpec.world.shared_example_group_registry.add(self, name, *args, &block)
-
end
-
1
alias shared_context shared_examples
-
1
alias shared_examples_for shared_examples
-
-
# @api private
-
#
-
# Shared examples top level DSL.
-
1
module TopLevelDSL
-
# @private
-
# rubocop:disable Lint/NestedMethodDefinition
-
1
def self.definitions
-
2
proc do
-
3
def shared_examples(name, *args, &block)
-
RSpec.world.shared_example_group_registry.add(:main, name, *args, &block)
-
end
-
3
alias shared_context shared_examples
-
3
alias shared_examples_for shared_examples
-
end
-
end
-
# rubocop:enable Lint/NestedMethodDefinition
-
-
# @private
-
1
def self.exposed_globally?
-
1
@exposed_globally ||= false
-
end
-
-
# @api private
-
#
-
# Adds the top level DSL methods to Module and the top level binding.
-
1
def self.expose_globally!
-
1
return if exposed_globally?
-
1
Core::DSL.change_global_dsl(&definitions)
-
1
@exposed_globally = true
-
end
-
-
# @api private
-
#
-
# Removes the top level DSL methods to Module and the top level binding.
-
1
def self.remove_globally!
-
return unless exposed_globally?
-
-
Core::DSL.change_global_dsl do
-
undef shared_examples
-
undef shared_context
-
undef shared_examples_for
-
end
-
-
@exposed_globally = false
-
end
-
end
-
-
# @private
-
1
class Registry
-
1
def add(context, name, *metadata_args, &block)
-
ensure_block_has_source_location(block) { CallerFilter.first_non_rspec_line }
-
-
if valid_name?(name)
-
warn_if_key_taken context, name, block
-
shared_example_groups[context][name] = block
-
else
-
metadata_args.unshift name
-
end
-
-
return if metadata_args.empty?
-
RSpec.configuration.include SharedExampleGroupModule.new(name, block), *metadata_args
-
end
-
-
1
def find(lookup_contexts, name)
-
lookup_contexts.each do |context|
-
found = shared_example_groups[context][name]
-
return found if found
-
end
-
-
shared_example_groups[:main][name]
-
end
-
-
1
private
-
-
1
def shared_example_groups
-
@shared_example_groups ||= Hash.new { |hash, context| hash[context] = {} }
-
end
-
-
1
def valid_name?(candidate)
-
case candidate
-
when String, Symbol, Module then true
-
else false
-
end
-
end
-
-
1
def warn_if_key_taken(context, key, new_block)
-
existing_block = shared_example_groups[context][key]
-
-
return unless existing_block
-
-
RSpec.warn_with <<-WARNING.gsub(/^ +\|/, ''), :call_site => nil
-
|WARNING: Shared example group '#{key}' has been previously defined at:
-
| #{formatted_location existing_block}
-
|...and you are now defining it at:
-
| #{formatted_location new_block}
-
|The new definition will overwrite the original one.
-
WARNING
-
end
-
-
1
def formatted_location(block)
-
block.source_location.join ":"
-
end
-
-
1
if Proc.method_defined?(:source_location)
-
1
def ensure_block_has_source_location(_block); end
-
else # for 1.8.7
-
# :nocov:
-
skipped
def ensure_block_has_source_location(block)
-
skipped
source_location = yield.split(':')
-
skipped
block.extend Module.new { define_method(:source_location) { source_location } }
-
skipped
end
-
# :nocov:
-
end
-
end
-
end
-
end
-
-
1
instance_exec(&Core::SharedExampleGroup::TopLevelDSL.definitions)
-
end
-
1
module RSpec
-
1
module Core
-
# @private
-
# Deals with the fact that `shellwords` only works on POSIX systems.
-
1
module ShellEscape
-
1
module_function
-
-
1
def quote(argument)
-
"'#{argument.gsub("'", "\\\\'")}'"
-
end
-
-
1
if RSpec::Support::OS.windows?
-
# :nocov:
-
skipped
alias escape quote
-
# :nocov:
-
else
-
1
require 'shellwords'
-
-
1
def escape(shell_command)
-
shell_command.shellescape
-
end
-
end
-
-
# Known shells that require quoting: zsh, csh, tcsh.
-
#
-
# Feel free to add other shells to this list that are known to
-
# allow `rspec ./some_spec.rb[1:1]` syntax without quoting the id.
-
#
-
# @private
-
1
SHELLS_ALLOWING_UNQUOTED_IDS = %w[ bash ksh fish ]
-
-
1
def conditionally_quote(id)
-
return id if shell_allows_unquoted_ids?
-
quote(id)
-
end
-
-
1
def shell_allows_unquoted_ids?
-
# Note: ENV['SHELL'] isn't necessarily the shell the user is currently running.
-
# According to http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap08.html:
-
# "This variable shall represent a pathname of the user's preferred command language interpreter."
-
#
-
# It's the best we can easily do, though. We err on the side of safety (quoting
-
# the id when not actually needed) so it's not a big deal if the user is actually
-
# using a different shell.
-
SHELLS_ALLOWING_UNQUOTED_IDS.include?(ENV['SHELL'].to_s.split('/').last)
-
end
-
end
-
end
-
end
-
1
RSpec::Support.require_rspec_core 'source/node'
-
1
RSpec::Support.require_rspec_core 'source/syntax_highlighter'
-
1
RSpec::Support.require_rspec_core 'source/token'
-
-
1
module RSpec
-
1
module Core
-
# @private
-
# Represents a Ruby source file and provides access to AST and tokens.
-
1
class Source
-
1
attr_reader :source, :path
-
-
1
def self.from_file(path)
-
source = File.read(path)
-
new(source, path)
-
end
-
-
1
def initialize(source_string, path=nil)
-
@source = source_string
-
@path = path ? File.expand_path(path) : '(string)'
-
end
-
-
1
def lines
-
@lines ||= source.split("\n")
-
end
-
-
1
def ast
-
@ast ||= begin
-
require 'ripper'
-
sexp = Ripper.sexp(source)
-
raise SyntaxError unless sexp
-
Node.new(sexp)
-
end
-
end
-
-
1
def tokens
-
@tokens ||= begin
-
require 'ripper'
-
tokens = Ripper.lex(source)
-
Token.tokens_from_ripper_tokens(tokens)
-
end
-
end
-
-
1
def nodes_by_line_number
-
@nodes_by_line_number ||= begin
-
nodes_by_line_number = ast.select(&:location).group_by { |node| node.location.line }
-
Hash.new { |hash, key| hash[key] = [] }.merge(nodes_by_line_number)
-
end
-
end
-
-
1
def tokens_by_line_number
-
@tokens_by_line_number ||= begin
-
nodes_by_line_number = tokens.group_by { |token| token.location.line }
-
Hash.new { |hash, key| hash[key] = [] }.merge(nodes_by_line_number)
-
end
-
end
-
-
1
def inspect
-
"#<#{self.class} #{path}>"
-
end
-
-
# @private
-
1
class Cache
-
1
attr_reader :syntax_highlighter
-
-
1
def initialize(configuration)
-
@sources_by_path = {}
-
@syntax_highlighter = SyntaxHighlighter.new(configuration)
-
end
-
-
1
def source_from_file(path)
-
@sources_by_path[path] ||= Source.from_file(path)
-
end
-
end
-
end
-
end
-
end
-
1
module RSpec
-
1
module Core
-
1
class Source
-
# @private
-
# Represents a source location of node or token.
-
1
Location = Struct.new(:line, :column) do
-
1
def self.location?(array)
-
array.is_a?(Array) && array.size == 2 && array.all? { |e| e.is_a?(Integer) }
-
end
-
end
-
end
-
end
-
end
-
1
RSpec::Support.require_rspec_core "source/location"
-
-
1
module RSpec
-
1
module Core
-
1
class Source
-
# @private
-
# A wrapper for Ripper AST node which is generated with `Ripper.sexp`.
-
1
class Node
-
1
include Enumerable
-
-
1
attr_reader :sexp, :parent
-
-
1
def self.sexp?(array)
-
array.is_a?(Array) && array.first.is_a?(Symbol)
-
end
-
-
1
def initialize(ripper_sexp, parent=nil)
-
@sexp = ripper_sexp.freeze
-
@parent = parent
-
end
-
-
1
def type
-
sexp[0]
-
end
-
-
1
def args
-
@args ||= raw_args.map do |raw_arg|
-
if Node.sexp?(raw_arg)
-
Node.new(raw_arg, self)
-
elsif Location.location?(raw_arg)
-
Location.new(*raw_arg)
-
elsif raw_arg.is_a?(Array)
-
GroupNode.new(raw_arg, self)
-
else
-
raw_arg
-
end
-
end.freeze
-
end
-
-
1
def children
-
@children ||= args.select { |arg| arg.is_a?(Node) }.freeze
-
end
-
-
1
def location
-
@location ||= args.find { |arg| arg.is_a?(Location) }
-
end
-
-
1
def each(&block)
-
return to_enum(__method__) unless block_given?
-
-
yield self
-
-
children.each do |child|
-
child.each(&block)
-
end
-
end
-
-
1
def each_ancestor
-
return to_enum(__method__) unless block_given?
-
-
current_node = self
-
-
while (current_node = current_node.parent)
-
yield current_node
-
end
-
end
-
-
1
def inspect
-
"#<#{self.class} #{type}>"
-
end
-
-
1
private
-
-
1
def raw_args
-
sexp[1..-1] || []
-
end
-
end
-
-
# @private
-
1
class GroupNode < Node
-
1
def type
-
:group
-
end
-
-
1
private
-
-
1
def raw_args
-
sexp
-
end
-
end
-
end
-
end
-
end
-
1
module RSpec
-
1
module Core
-
1
class Source
-
# @private
-
# Provides terminal syntax highlighting of code snippets
-
# when coderay is available.
-
1
class SyntaxHighlighter
-
1
def initialize(configuration)
-
@configuration = configuration
-
end
-
-
1
def highlight(lines)
-
implementation.highlight_syntax(lines)
-
end
-
-
1
private
-
-
1
if RSpec::Support::OS.windows?
-
# :nocov:
-
skipped
def implementation
-
skipped
WindowsImplementation
-
skipped
end
-
# :nocov:
-
else
-
1
def implementation
-
return color_enabled_implementation if @configuration.color_enabled?
-
NoSyntaxHighlightingImplementation
-
end
-
end
-
-
1
def color_enabled_implementation
-
@color_enabled_implementation ||= begin
-
require 'coderay'
-
CodeRayImplementation
-
rescue LoadError
-
NoSyntaxHighlightingImplementation
-
end
-
end
-
-
# @private
-
1
module CodeRayImplementation
-
1
RESET_CODE = "\e[0m"
-
-
1
def self.highlight_syntax(lines)
-
highlighted = begin
-
CodeRay.encode(lines.join("\n"), :ruby, :terminal)
-
rescue Support::AllExceptionsExceptOnesWeMustNotRescue
-
return lines
-
end
-
-
highlighted.split("\n").map do |line|
-
line.sub(/\S/) { |char| char.insert(0, RESET_CODE) }
-
end
-
end
-
end
-
-
# @private
-
1
module NoSyntaxHighlightingImplementation
-
1
def self.highlight_syntax(lines)
-
lines
-
end
-
end
-
-
# @private
-
# Not sure why, but our code above (and/or coderay itself) does not work
-
# on Windows, so we disable the feature on Windows.
-
1
WindowsImplementation = NoSyntaxHighlightingImplementation
-
end
-
end
-
end
-
end
-
1
RSpec::Support.require_rspec_core "source/location"
-
-
1
module RSpec
-
1
module Core
-
1
class Source
-
# @private
-
# A wrapper for Ripper token which is generated with `Ripper.lex`.
-
1
class Token
-
1
CLOSING_TYPES_BY_OPENING_TYPE = {
-
:on_lbracket => :on_rbracket,
-
:on_lparen => :on_rparen,
-
:on_lbrace => :on_rbrace,
-
:on_heredoc_beg => :on_heredoc_end
-
}.freeze
-
-
1
CLOSING_KEYWORDS_BY_OPENING_KEYWORD = {
-
'do' => 'end'
-
}.freeze
-
-
1
attr_reader :token
-
-
1
def self.tokens_from_ripper_tokens(ripper_tokens)
-
ripper_tokens.map { |ripper_token| new(ripper_token) }.freeze
-
end
-
-
1
def initialize(ripper_token)
-
@token = ripper_token.freeze
-
end
-
-
1
def location
-
@location ||= Location.new(*token[0])
-
end
-
-
1
def type
-
token[1]
-
end
-
-
1
def string
-
token[2]
-
end
-
-
1
def ==(other)
-
token == other.token
-
end
-
-
1
alias_method :eql?, :==
-
-
1
def inspect
-
"#<#{self.class} #{type} #{string.inspect}>"
-
end
-
-
1
def keyword?
-
type == :on_kw
-
end
-
-
1
def opening?
-
opening_delimiter? || opening_keyword?
-
end
-
-
1
def closed_by?(other)
-
closed_by_delimiter?(other) || closed_by_keyword?(other)
-
end
-
-
1
private
-
-
1
def opening_delimiter?
-
CLOSING_TYPES_BY_OPENING_TYPE.key?(type)
-
end
-
-
1
def opening_keyword?
-
return false unless keyword?
-
CLOSING_KEYWORDS_BY_OPENING_KEYWORD.key?(string)
-
end
-
-
1
def closed_by_delimiter?(other)
-
other.type == CLOSING_TYPES_BY_OPENING_TYPE[type]
-
end
-
-
1
def closed_by_keyword?(other)
-
return false unless other.keyword?
-
other.string == CLOSING_KEYWORDS_BY_OPENING_KEYWORD[string]
-
end
-
end
-
end
-
end
-
end
-
1
module RSpec
-
1
module Core
-
# Version information for RSpec Core.
-
1
module Version
-
# Current version of RSpec Core, in semantic versioning format.
-
1
STRING = '3.4.4'
-
end
-
end
-
end
-
1
require "rspec/support/warnings"
-
-
1
module RSpec
-
1
module Core
-
# @private
-
1
module Warnings
-
# @private
-
#
-
# Used internally to print deprecation warnings.
-
1
def deprecate(deprecated, data={})
-
RSpec.configuration.reporter.deprecation(
-
{
-
:deprecated => deprecated,
-
:call_site => CallerFilter.first_non_rspec_line
-
}.merge(data)
-
)
-
end
-
-
# @private
-
#
-
# Used internally to print deprecation warnings.
-
1
def warn_deprecation(message, opts={})
-
RSpec.configuration.reporter.deprecation opts.merge(:message => message)
-
end
-
-
# @private
-
1
def warn_with(message, options={})
-
if options[:use_spec_location_as_call_site]
-
message += "." unless message.end_with?(".")
-
-
if RSpec.current_example
-
message += " Warning generated from spec at `#{RSpec.current_example.location}`."
-
end
-
end
-
-
super(message, options)
-
end
-
end
-
end
-
end
-
1
module RSpec
-
1
module Core
-
# @api private
-
#
-
# Internal container for global non-configuration data.
-
1
class World
-
# @private
-
1
attr_reader :example_groups, :filtered_examples
-
-
# Used internally to determine what to do when a SIGINT is received.
-
1
attr_accessor :wants_to_quit
-
-
1
def initialize(configuration=RSpec.configuration)
-
1
@configuration = configuration
-
1
@example_groups = []
-
1
@example_group_counts_by_spec_file = Hash.new(0)
-
1
@filtered_examples = Hash.new do |hash, group|
-
hash[group] = filter_manager.prune(group.examples)
-
end
-
end
-
-
# @api private
-
#
-
# Apply ordering strategy from configuration to example groups.
-
1
def ordered_example_groups
-
ordering_strategy = @configuration.ordering_registry.fetch(:global)
-
ordering_strategy.order(@example_groups)
-
end
-
-
# @api private
-
#
-
# Reset world to 'scratch' before running suite.
-
1
def reset
-
example_groups.clear
-
@shared_example_group_registry = nil
-
end
-
-
# @private
-
1
def filter_manager
-
@configuration.filter_manager
-
end
-
-
# @private
-
1
def registered_example_group_files
-
@example_group_counts_by_spec_file.keys
-
end
-
-
# @api private
-
#
-
# Register an example group.
-
1
def register(example_group)
-
@configuration.on_example_group_definition_callbacks.each { |block| block.call(example_group) }
-
example_groups << example_group
-
@example_group_counts_by_spec_file[example_group.metadata[:absolute_file_path]] += 1
-
example_group
-
end
-
-
# @private
-
1
def num_example_groups_defined_in(file)
-
@example_group_counts_by_spec_file[file]
-
end
-
-
# @private
-
1
def shared_example_group_registry
-
@shared_example_group_registry ||= SharedExampleGroup::Registry.new
-
end
-
-
# @private
-
1
def inclusion_filter
-
@configuration.inclusion_filter
-
end
-
-
# @private
-
1
def exclusion_filter
-
@configuration.exclusion_filter
-
end
-
-
# @api private
-
#
-
# Get count of examples to be run.
-
1
def example_count(groups=example_groups)
-
FlatMap.flat_map(groups) { |g| g.descendants }.
-
inject(0) { |a, e| a + e.filtered_examples.size }
-
end
-
-
# @private
-
1
def all_example_groups
-
1
FlatMap.flat_map(example_groups) { |g| g.descendants }
-
end
-
-
# @private
-
1
def all_examples
-
FlatMap.flat_map(all_example_groups) { |g| g.examples }
-
end
-
-
# @api private
-
#
-
# Find line number of previous declaration.
-
1
def preceding_declaration_line(absolute_file_name, filter_line)
-
line_numbers = descending_declaration_line_numbers_by_file.fetch(absolute_file_name) do
-
return nil
-
end
-
-
line_numbers.find { |num| num <= filter_line }
-
end
-
-
# @private
-
1
def reporter
-
@configuration.reporter
-
end
-
-
# @private
-
1
def source_cache
-
@source_cache ||= begin
-
RSpec::Support.require_rspec_core "source"
-
Source::Cache.new(@configuration)
-
end
-
end
-
-
# @api private
-
#
-
# Notify reporter of filters.
-
1
def announce_filters
-
fail_if_config_and_cli_options_invalid
-
filter_announcements = []
-
-
announce_inclusion_filter filter_announcements
-
announce_exclusion_filter filter_announcements
-
-
unless filter_manager.empty?
-
if filter_announcements.length == 1
-
report_filter_message("Run options: #{filter_announcements[0]}")
-
else
-
report_filter_message("Run options:\n #{filter_announcements.join("\n ")}")
-
end
-
end
-
-
if @configuration.run_all_when_everything_filtered? && example_count.zero? && !@configuration.only_failures?
-
report_filter_message("#{everything_filtered_message}; ignoring #{inclusion_filter.description}")
-
filtered_examples.clear
-
inclusion_filter.clear
-
end
-
-
return unless example_count.zero?
-
-
example_groups.clear
-
if filter_manager.empty?
-
report_filter_message("No examples found.")
-
elsif exclusion_filter.empty? || inclusion_filter.empty?
-
report_filter_message(everything_filtered_message)
-
end
-
end
-
-
# @private
-
1
def report_filter_message(message)
-
reporter.message(message) unless @configuration.silence_filter_announcements?
-
end
-
-
# @private
-
1
def everything_filtered_message
-
"\nAll examples were filtered out"
-
end
-
-
# @api private
-
#
-
# Add inclusion filters to announcement message.
-
1
def announce_inclusion_filter(announcements)
-
return if inclusion_filter.empty?
-
-
announcements << "include #{inclusion_filter.description}"
-
end
-
-
# @api private
-
#
-
# Add exclusion filters to announcement message.
-
1
def announce_exclusion_filter(announcements)
-
return if exclusion_filter.empty?
-
-
announcements << "exclude #{exclusion_filter.description}"
-
end
-
-
1
private
-
-
1
def descending_declaration_line_numbers_by_file
-
@descending_declaration_line_numbers_by_file ||= begin
-
declaration_locations = FlatMap.flat_map(example_groups, &:declaration_locations)
-
hash_of_arrays = Hash.new { |h, k| h[k] = [] }
-
-
# TODO: change `inject` to `each_with_object` when we drop 1.8.7 support.
-
line_nums_by_file = declaration_locations.inject(hash_of_arrays) do |hash, (file_name, line_number)|
-
hash[file_name] << line_number
-
hash
-
end
-
-
line_nums_by_file.each_value do |list|
-
list.sort!
-
list.reverse!
-
end
-
end
-
end
-
-
1
def fail_if_config_and_cli_options_invalid
-
return unless @configuration.only_failures_but_not_configured?
-
-
reporter.abort_with(
-
"\nTo use `--only-failures`, you must first set " \
-
"`config.example_status_persistence_file_path`.",
-
1 # exit code
-
)
-
end
-
end
-
end
-
end
-
2
require 'rspec/support'
-
2
RSpec::Support.require_rspec_support "caller_filter"
-
2
RSpec::Support.require_rspec_support "warnings"
-
2
RSpec::Support.require_rspec_support "object_formatter"
-
-
2
require 'rspec/matchers'
-
-
14
RSpec::Support.define_optimized_require_for_rspec(:expectations) { |f| require_relative(f) }
-
-
%w[
-
expectation_target
-
configuration
-
fail_with
-
handler
-
version
-
12
].each { |file| RSpec::Support.require_rspec_expectations(file) }
-
-
2
module RSpec
-
# RSpec::Expectations provides a simple, readable API to express
-
# the expected outcomes in a code example. To express an expected
-
# outcome, wrap an object or block in `expect`, call `to` or `to_not`
-
# (aliased as `not_to`) and pass it a matcher object:
-
#
-
# expect(order.total).to eq(Money.new(5.55, :USD))
-
# expect(list).to include(user)
-
# expect(message).not_to match(/foo/)
-
# expect { do_something }.to raise_error
-
#
-
# The last form (the block form) is needed to match against ruby constructs
-
# that are not objects, but can only be observed when executing a block
-
# of code. This includes raising errors, throwing symbols, yielding,
-
# and changing values.
-
#
-
# When `expect(...).to` is invoked with a matcher, it turns around
-
# and calls `matcher.matches?(<object wrapped by expect>)`. For example,
-
# in the expression:
-
#
-
# expect(order.total).to eq(Money.new(5.55, :USD))
-
#
-
# ...`eq(Money.new(5.55, :USD))` returns a matcher object, and it results
-
# in the equivalent of `eq.matches?(order.total)`. If `matches?` returns
-
# `true`, the expectation is met and execution continues. If `false`, then
-
# the spec fails with the message returned by `eq.failure_message`.
-
#
-
# Given the expression:
-
#
-
# expect(order.entries).not_to include(entry)
-
#
-
# ...the `not_to` method (also available as `to_not`) invokes the equivalent of
-
# `include.matches?(order.entries)`, but it interprets `false` as success, and
-
# `true` as a failure, using the message generated by
-
# `include.failure_message_when_negated`.
-
#
-
# rspec-expectations ships with a standard set of useful matchers, and writing
-
# your own matchers is quite simple.
-
#
-
# See [RSpec::Matchers](../RSpec/Matchers) for more information about the
-
# built-in matchers that ship with rspec-expectations, and how to write your
-
# own custom matchers.
-
2
module Expectations
-
# Exception raised when an expectation fails.
-
#
-
# @note We subclass Exception so that in a stub implementation if
-
# the user sets an expectation, it can't be caught in their
-
# code by a bare `rescue`.
-
# @api public
-
2
class ExpectationNotMetError < Exception
-
end
-
-
# Exception raised from `aggregate_failures` when multiple expectations fail.
-
#
-
# @note The constant is defined here but the extensive logic of this class
-
# is lazily defined when `FailureAggregator` is autoloaded, since we do
-
# not need to waste time defining that functionality unless
-
# `aggregate_failures` is used.
-
2
class MultipleExpectationsNotMetError < ExpectationNotMetError
-
end
-
-
2
autoload :FailureAggregator, "rspec/expectations/failure_aggregator"
-
end
-
end
-
2
module RSpec
-
2
module Expectations
-
# Wraps the target of an expectation.
-
#
-
# @example
-
# expect(something) # => ExpectationTarget wrapping something
-
# expect { do_something } # => ExpectationTarget wrapping the block
-
#
-
# # used with `to`
-
# expect(actual).to eq(3)
-
#
-
# # with `not_to`
-
# expect(actual).not_to eq(3)
-
#
-
# @note `ExpectationTarget` is not intended to be instantiated
-
# directly by users. Use `expect` instead.
-
2
class ExpectationTarget
-
# @private
-
# Used as a sentinel value to be able to tell when the user
-
# did not pass an argument. We can't use `nil` for that because
-
# `nil` is a valid value to pass.
-
2
UndefinedValue = Module.new
-
-
# @api private
-
2
def initialize(value)
-
11
@target = value
-
end
-
-
# @private
-
2
def self.for(value, block)
-
11
if UndefinedValue.equal?(value)
-
unless block
-
raise ArgumentError, "You must pass either an argument or a block to `expect`."
-
end
-
BlockExpectationTarget.new(block)
-
11
elsif block
-
raise ArgumentError, "You cannot pass both an argument and a block to `expect`."
-
else
-
11
new(value)
-
end
-
end
-
-
# Runs the given expectation, passing if `matcher` returns true.
-
# @example
-
# expect(value).to eq(5)
-
# expect { perform }.to raise_error
-
# @param [Matcher]
-
# matcher
-
# @param [String or Proc] message optional message to display when the expectation fails
-
# @return [Boolean] true if the expectation succeeds (else raises)
-
# @see RSpec::Matchers
-
2
def to(matcher=nil, message=nil, &block)
-
11
prevent_operator_matchers(:to) unless matcher
-
11
RSpec::Expectations::PositiveExpectationHandler.handle_matcher(@target, matcher, message, &block)
-
end
-
-
# Runs the given expectation, passing if `matcher` returns false.
-
# @example
-
# expect(value).not_to eq(5)
-
# @param [Matcher]
-
# matcher
-
# @param [String or Proc] message optional message to display when the expectation fails
-
# @return [Boolean] false if the negative expectation succeeds (else raises)
-
# @see RSpec::Matchers
-
2
def not_to(matcher=nil, message=nil, &block)
-
prevent_operator_matchers(:not_to) unless matcher
-
RSpec::Expectations::NegativeExpectationHandler.handle_matcher(@target, matcher, message, &block)
-
end
-
2
alias to_not not_to
-
-
2
private
-
-
2
def prevent_operator_matchers(verb)
-
raise ArgumentError, "The expect syntax does not support operator matchers, " \
-
"so you must pass a matcher to `##{verb}`."
-
end
-
end
-
-
# @private
-
# Validates the provided matcher to ensure it supports block
-
# expectations, in order to avoid user confusion when they
-
# use a block thinking the expectation will be on the return
-
# value of the block rather than the block itself.
-
2
class BlockExpectationTarget < ExpectationTarget
-
2
def to(matcher, message=nil, &block)
-
enforce_block_expectation(matcher)
-
super
-
end
-
-
2
def not_to(matcher, message=nil, &block)
-
enforce_block_expectation(matcher)
-
super
-
end
-
2
alias to_not not_to
-
-
2
private
-
-
2
def enforce_block_expectation(matcher)
-
return if supports_block_expectations?(matcher)
-
-
raise ExpectationNotMetError, "You must pass an argument rather than a block to use the provided " \
-
"matcher (#{RSpec::Support::ObjectFormatter.format(matcher)}), or the matcher must implement " \
-
"`supports_block_expectations?`."
-
end
-
-
2
def supports_block_expectations?(matcher)
-
matcher.supports_block_expectations?
-
rescue NoMethodError
-
false
-
end
-
end
-
end
-
end
-
2
module RSpec
-
2
module Expectations
-
2
class << self
-
# @private
-
2
def differ
-
RSpec::Support::Differ.new(
-
:object_preparer => lambda { |object| RSpec::Matchers::Composable.surface_descriptions_in(object) },
-
:color => RSpec::Matchers.configuration.color?
-
)
-
end
-
-
# Raises an RSpec::Expectations::ExpectationNotMetError with message.
-
# @param [String] message
-
# @param [Object] expected
-
# @param [Object] actual
-
#
-
# Adds a diff to the failure message when `expected` and `actual` are
-
# both present.
-
2
def fail_with(message, expected=nil, actual=nil)
-
unless message
-
raise ArgumentError, "Failure message is nil. Does your matcher define the " \
-
"appropriate failure_message[_when_negated] method to return a string?"
-
end
-
-
message = ::RSpec::Matchers::ExpectedsForMultipleDiffs.from(expected).message_with_diff(message, differ, actual)
-
-
RSpec::Support.notify_failure(RSpec::Expectations::ExpectationNotMetError.new message)
-
end
-
end
-
end
-
end
-
2
module RSpec
-
2
module Expectations
-
# @private
-
2
module ExpectationHelper
-
2
def self.check_message(msg)
-
11
unless msg.nil? || msg.respond_to?(:to_str) || msg.respond_to?(:call)
-
::Kernel.warn [
-
"WARNING: ignoring the provided expectation message argument (",
-
msg.inspect,
-
") since it is not a string or a proc."
-
].join
-
end
-
end
-
-
# Returns an RSpec-3+ compatible matcher, wrapping a legacy one
-
# in an adapter if necessary.
-
#
-
# @private
-
2
def self.modern_matcher_from(matcher)
-
LegacyMatcherAdapter::RSpec2.wrap(matcher) ||
-
11
LegacyMatcherAdapter::RSpec1.wrap(matcher) || matcher
-
end
-
-
2
def self.with_matcher(handler, matcher, message)
-
11
check_message(message)
-
11
matcher = modern_matcher_from(matcher)
-
11
yield matcher
-
ensure
-
11
::RSpec::Matchers.last_expectation_handler = handler
-
11
::RSpec::Matchers.last_matcher = matcher
-
end
-
-
2
def self.handle_failure(matcher, message, failure_message_method)
-
message = message.call if message.respond_to?(:call)
-
message ||= matcher.__send__(failure_message_method)
-
-
if matcher.respond_to?(:diffable?) && matcher.diffable?
-
::RSpec::Expectations.fail_with message, matcher.expected, matcher.actual
-
else
-
::RSpec::Expectations.fail_with message
-
end
-
end
-
end
-
-
# @private
-
2
class PositiveExpectationHandler
-
2
def self.handle_matcher(actual, initial_matcher, message=nil, &block)
-
11
ExpectationHelper.with_matcher(self, initial_matcher, message) do |matcher|
-
11
return ::RSpec::Matchers::BuiltIn::PositiveOperatorMatcher.new(actual) unless initial_matcher
-
11
matcher.matches?(actual, &block) || ExpectationHelper.handle_failure(matcher, message, :failure_message)
-
end
-
end
-
-
2
def self.verb
-
"should"
-
end
-
-
2
def self.should_method
-
:should
-
end
-
-
2
def self.opposite_should_method
-
:should_not
-
end
-
end
-
-
# @private
-
2
class NegativeExpectationHandler
-
2
def self.handle_matcher(actual, initial_matcher, message=nil, &block)
-
ExpectationHelper.with_matcher(self, initial_matcher, message) do |matcher|
-
return ::RSpec::Matchers::BuiltIn::NegativeOperatorMatcher.new(actual) unless initial_matcher
-
!(does_not_match?(matcher, actual, &block) || ExpectationHelper.handle_failure(matcher, message, :failure_message_when_negated))
-
end
-
end
-
-
2
def self.does_not_match?(matcher, actual, &block)
-
if matcher.respond_to?(:does_not_match?)
-
matcher.does_not_match?(actual, &block)
-
else
-
!matcher.matches?(actual, &block)
-
end
-
end
-
-
2
def self.verb
-
"should not"
-
end
-
-
2
def self.should_method
-
:should_not
-
end
-
-
2
def self.opposite_should_method
-
:should
-
end
-
end
-
-
# Wraps a matcher written against one of the legacy protocols in
-
# order to present the current protocol.
-
#
-
# @private
-
2
class LegacyMatcherAdapter < Matchers::MatcherDelegator
-
2
def initialize(matcher)
-
super
-
::RSpec.warn_deprecation(<<-EOS.gsub(/^\s+\|/, ''), :type => "legacy_matcher")
-
|#{matcher.class.name || matcher.inspect} implements a legacy RSpec matcher
-
|protocol. For the current protocol you should expose the failure messages
-
|via the `failure_message` and `failure_message_when_negated` methods.
-
|(Used from #{CallerFilter.first_non_rspec_line})
-
EOS
-
end
-
-
2
def self.wrap(matcher)
-
22
new(matcher) if interface_matches?(matcher)
-
end
-
-
# Starting in RSpec 1.2 (and continuing through all 2.x releases),
-
# the failure message protocol was:
-
# * `failure_message_for_should`
-
# * `failure_message_for_should_not`
-
# @private
-
2
class RSpec2 < self
-
2
def failure_message
-
base_matcher.failure_message_for_should
-
end
-
-
2
def failure_message_when_negated
-
base_matcher.failure_message_for_should_not
-
end
-
-
2
def self.interface_matches?(matcher)
-
(
-
!matcher.respond_to?(:failure_message) &&
-
11
matcher.respond_to?(:failure_message_for_should)
-
) || (
-
!matcher.respond_to?(:failure_message_when_negated) &&
-
11
matcher.respond_to?(:failure_message_for_should_not)
-
11
)
-
end
-
end
-
-
# Before RSpec 1.2, the failure message protocol was:
-
# * `failure_message`
-
# * `negative_failure_message`
-
# @private
-
2
class RSpec1 < self
-
2
def failure_message
-
base_matcher.failure_message
-
end
-
-
2
def failure_message_when_negated
-
base_matcher.negative_failure_message
-
end
-
-
# Note: `failure_message` is part of the RSpec 3 protocol
-
# (paired with `failure_message_when_negated`), so we don't check
-
# for `failure_message` here.
-
2
def self.interface_matches?(matcher)
-
!matcher.respond_to?(:failure_message_when_negated) &&
-
11
matcher.respond_to?(:negative_failure_message)
-
end
-
end
-
end
-
-
# RSpec 3.0 was released with the class name misspelled. For SemVer compatibility,
-
# we will provide this misspelled alias until 4.0.
-
# @deprecated Use LegacyMatcherAdapter instead.
-
# @private
-
2
LegacyMacherAdapter = LegacyMatcherAdapter
-
end
-
end
-
2
module RSpec
-
2
module Expectations
-
# @api private
-
# Provides methods for enabling and disabling the available
-
# syntaxes provided by rspec-expectations.
-
2
module Syntax
-
2
module_function
-
-
# @api private
-
# Determines where we add `should` and `should_not`.
-
2
def default_should_host
-
6
@default_should_host ||= ::Object.ancestors.last
-
end
-
-
# @api private
-
# Instructs rspec-expectations to warn on first usage of `should` or `should_not`.
-
# Enabled by default. This is largely here to facilitate testing.
-
2
def warn_about_should!
-
2
@warn_about_should = true
-
end
-
-
# @api private
-
# Generates a deprecation warning for the given method if no warning
-
# has already been issued.
-
2
def warn_about_should_unless_configured(method_name)
-
return unless @warn_about_should
-
-
RSpec.deprecate(
-
"Using `#{method_name}` from rspec-expectations' old `:should` syntax without explicitly enabling the syntax",
-
:replacement => "the new `:expect` syntax or explicitly enable `:should` with `config.expect_with(:rspec) { |c| c.syntax = :should }`"
-
)
-
-
@warn_about_should = false
-
end
-
-
# @api private
-
# Enables the `should` syntax.
-
2
def enable_should(syntax_host=default_should_host)
-
3
@warn_about_should = false if syntax_host == default_should_host
-
3
return if should_enabled?(syntax_host)
-
-
2
syntax_host.module_exec do
-
2
def should(matcher=nil, message=nil, &block)
-
::RSpec::Expectations::Syntax.warn_about_should_unless_configured(__method__)
-
::RSpec::Expectations::PositiveExpectationHandler.handle_matcher(self, matcher, message, &block)
-
end
-
-
2
def should_not(matcher=nil, message=nil, &block)
-
::RSpec::Expectations::Syntax.warn_about_should_unless_configured(__method__)
-
::RSpec::Expectations::NegativeExpectationHandler.handle_matcher(self, matcher, message, &block)
-
end
-
end
-
end
-
-
# @api private
-
# Disables the `should` syntax.
-
2
def disable_should(syntax_host=default_should_host)
-
return unless should_enabled?(syntax_host)
-
-
syntax_host.module_exec do
-
undef should
-
undef should_not
-
end
-
end
-
-
# @api private
-
# Enables the `expect` syntax.
-
2
def enable_expect(syntax_host=::RSpec::Matchers)
-
2
return if expect_enabled?(syntax_host)
-
-
2
syntax_host.module_exec do
-
2
def expect(value=::RSpec::Expectations::ExpectationTarget::UndefinedValue, &block)
-
11
::RSpec::Expectations::ExpectationTarget.for(value, block)
-
end
-
end
-
end
-
-
# @api private
-
# Disables the `expect` syntax.
-
2
def disable_expect(syntax_host=::RSpec::Matchers)
-
return unless expect_enabled?(syntax_host)
-
-
syntax_host.module_exec do
-
undef expect
-
end
-
end
-
-
# @api private
-
# Indicates whether or not the `should` syntax is enabled.
-
2
def should_enabled?(syntax_host=default_should_host)
-
4
syntax_host.method_defined?(:should)
-
end
-
-
# @api private
-
# Indicates whether or not the `expect` syntax is enabled.
-
2
def expect_enabled?(syntax_host=::RSpec::Matchers)
-
3
syntax_host.method_defined?(:expect)
-
end
-
end
-
end
-
end
-
-
2
if defined?(BasicObject)
-
# The legacy `:should` syntax adds the following methods directly to
-
# `BasicObject` so that they are available off of any object. Note, however,
-
# that this syntax does not always play nice with delegate/proxy objects.
-
# We recommend you use the non-monkeypatching `:expect` syntax instead.
-
2
class BasicObject
-
# @method should
-
# Passes if `matcher` returns true. Available on every `Object`.
-
# @example
-
# actual.should eq expected
-
# actual.should match /expression/
-
# @param [Matcher]
-
# matcher
-
# @param [String] message optional message to display when the expectation fails
-
# @return [Boolean] true if the expectation succeeds (else raises)
-
# @note This is only available when you have enabled the `:should` syntax.
-
# @see RSpec::Matchers
-
-
# @method should_not
-
# Passes if `matcher` returns false. Available on every `Object`.
-
# @example
-
# actual.should_not eq expected
-
# @param [Matcher]
-
# matcher
-
# @param [String] message optional message to display when the expectation fails
-
# @return [Boolean] false if the negative expectation succeeds (else raises)
-
# @note This is only available when you have enabled the `:should` syntax.
-
# @see RSpec::Matchers
-
end
-
end
-
2
module RSpec
-
2
module Expectations
-
# @private
-
2
module Version
-
2
STRING = '3.4.0'
-
end
-
end
-
end
-
2
require 'rspec/support'
-
2
RSpec::Support.require_rspec_support 'matcher_definition'
-
20
RSpec::Support.define_optimized_require_for_rspec(:matchers) { |f| require_relative(f) }
-
-
%w[
-
english_phrasing
-
composable
-
built_in
-
generated_descriptions
-
dsl
-
matcher_delegator
-
aliased_matcher
-
expecteds_for_multiple_diffs
-
18
].each { |file| RSpec::Support.require_rspec_matchers(file) }
-
-
# RSpec's top level namespace. All of rspec-expectations is contained
-
# in the `RSpec::Expectations` and `RSpec::Matchers` namespaces.
-
2
module RSpec
-
# RSpec::Matchers provides a number of useful matchers we use to define
-
# expectations. Any object that implements the [matcher protocol](Matchers/MatcherProtocol)
-
# can be used as a matcher.
-
#
-
# ## Predicates
-
#
-
# In addition to matchers that are defined explicitly, RSpec will create
-
# custom matchers on the fly for any arbitrary predicate, giving your specs a
-
# much more natural language feel.
-
#
-
# A Ruby predicate is a method that ends with a "?" and returns true or false.
-
# Common examples are `empty?`, `nil?`, and `instance_of?`.
-
#
-
# All you need to do is write `expect(..).to be_` followed by the predicate
-
# without the question mark, and RSpec will figure it out from there.
-
# For example:
-
#
-
# expect([]).to be_empty # => [].empty?() | passes
-
# expect([]).not_to be_empty # => [].empty?() | fails
-
#
-
# In addtion to prefixing the predicate matchers with "be_", you can also use "be_a_"
-
# and "be_an_", making your specs read much more naturally:
-
#
-
# expect("a string").to be_an_instance_of(String) # =>"a string".instance_of?(String) # passes
-
#
-
# expect(3).to be_a_kind_of(Fixnum) # => 3.kind_of?(Numeric) | passes
-
# expect(3).to be_a_kind_of(Numeric) # => 3.kind_of?(Numeric) | passes
-
# expect(3).to be_an_instance_of(Fixnum) # => 3.instance_of?(Fixnum) | passes
-
# expect(3).not_to be_an_instance_of(Numeric) # => 3.instance_of?(Numeric) | fails
-
#
-
# RSpec will also create custom matchers for predicates like `has_key?`. To
-
# use this feature, just state that the object should have_key(:key) and RSpec will
-
# call has_key?(:key) on the target. For example:
-
#
-
# expect(:a => "A").to have_key(:a)
-
# expect(:a => "A").to have_key(:b) # fails
-
#
-
# You can use this feature to invoke any predicate that begins with "has_", whether it is
-
# part of the Ruby libraries (like `Hash#has_key?`) or a method you wrote on your own class.
-
#
-
# Note that RSpec does not provide composable aliases for these dynamic predicate
-
# matchers. You can easily define your own aliases, though:
-
#
-
# RSpec::Matchers.alias_matcher :a_user_who_is_an_admin, :be_an_admin
-
# expect(user_list).to include(a_user_who_is_an_admin)
-
#
-
# ## Custom Matchers
-
#
-
# When you find that none of the stock matchers provide a natural feeling
-
# expectation, you can very easily write your own using RSpec's matcher DSL
-
# or writing one from scratch.
-
#
-
# ### Matcher DSL
-
#
-
# Imagine that you are writing a game in which players can be in various
-
# zones on a virtual board. To specify that bob should be in zone 4, you
-
# could say:
-
#
-
# expect(bob.current_zone).to eql(Zone.new("4"))
-
#
-
# But you might find it more expressive to say:
-
#
-
# expect(bob).to be_in_zone("4")
-
#
-
# and/or
-
#
-
# expect(bob).not_to be_in_zone("3")
-
#
-
# You can create such a matcher like so:
-
#
-
# RSpec::Matchers.define :be_in_zone do |zone|
-
# match do |player|
-
# player.in_zone?(zone)
-
# end
-
# end
-
#
-
# This will generate a <tt>be_in_zone</tt> method that returns a matcher
-
# with logical default messages for failures. You can override the failure
-
# messages and the generated description as follows:
-
#
-
# RSpec::Matchers.define :be_in_zone do |zone|
-
# match do |player|
-
# player.in_zone?(zone)
-
# end
-
#
-
# failure_message do |player|
-
# # generate and return the appropriate string.
-
# end
-
#
-
# failure_message_when_negated do |player|
-
# # generate and return the appropriate string.
-
# end
-
#
-
# description do
-
# # generate and return the appropriate string.
-
# end
-
# end
-
#
-
# Each of the message-generation methods has access to the block arguments
-
# passed to the <tt>create</tt> method (in this case, <tt>zone</tt>). The
-
# failure message methods (<tt>failure_message</tt> and
-
# <tt>failure_message_when_negated</tt>) are passed the actual value (the
-
# receiver of <tt>expect(..)</tt> or <tt>expect(..).not_to</tt>).
-
#
-
# ### Custom Matcher from scratch
-
#
-
# You could also write a custom matcher from scratch, as follows:
-
#
-
# class BeInZone
-
# def initialize(expected)
-
# @expected = expected
-
# end
-
#
-
# def matches?(target)
-
# @target = target
-
# @target.current_zone.eql?(Zone.new(@expected))
-
# end
-
#
-
# def failure_message
-
# "expected #{@target.inspect} to be in Zone #{@expected}"
-
# end
-
#
-
# def failure_message_when_negated
-
# "expected #{@target.inspect} not to be in Zone #{@expected}"
-
# end
-
# end
-
#
-
# ... and a method like this:
-
#
-
# def be_in_zone(expected)
-
# BeInZone.new(expected)
-
# end
-
#
-
# And then expose the method to your specs. This is normally done
-
# by including the method and the class in a module, which is then
-
# included in your spec:
-
#
-
# module CustomGameMatchers
-
# class BeInZone
-
# # ...
-
# end
-
#
-
# def be_in_zone(expected)
-
# # ...
-
# end
-
# end
-
#
-
# describe "Player behaviour" do
-
# include CustomGameMatchers
-
# # ...
-
# end
-
#
-
# or you can include in globally in a spec_helper.rb file <tt>require</tt>d
-
# from your spec file(s):
-
#
-
# RSpec::configure do |config|
-
# config.include(CustomGameMatchers)
-
# end
-
#
-
# ### Making custom matchers composable
-
#
-
# RSpec's built-in matchers are designed to be composed, in expressions like:
-
#
-
# expect(["barn", 2.45]).to contain_exactly(
-
# a_value_within(0.1).of(2.5),
-
# a_string_starting_with("bar")
-
# )
-
#
-
# Custom matchers can easily participate in composed matcher expressions like these.
-
# Include {RSpec::Matchers::Composable} in your custom matcher to make it support
-
# being composed (matchers defined using the DSL have this included automatically).
-
# Within your matcher's `matches?` method (or the `match` block, if using the DSL),
-
# use `values_match?(expected, actual)` rather than `expected == actual`.
-
# Under the covers, `values_match?` is able to match arbitrary
-
# nested data structures containing a mix of both matchers and non-matcher objects.
-
# It uses `===` and `==` to perform the matching, considering the values to
-
# match if either returns `true`. The `Composable` mixin also provides some helper
-
# methods for surfacing the matcher descriptions within your matcher's description
-
# or failure messages.
-
#
-
# RSpec's built-in matchers each have a number of aliases that rephrase the matcher
-
# from a verb phrase (such as `be_within`) to a noun phrase (such as `a_value_within`),
-
# which reads better when the matcher is passed as an argument in a composed matcher
-
# expressions, and also uses the noun-phrase wording in the matcher's `description`,
-
# for readable failure messages. You can alias your custom matchers in similar fashion
-
# using {RSpec::Matchers.alias_matcher}.
-
2
module Matchers
-
# @method expect
-
# Supports `expect(actual).to matcher` syntax by wrapping `actual` in an
-
# `ExpectationTarget`.
-
# @example
-
# expect(actual).to eq(expected)
-
# expect(actual).not_to eq(expected)
-
# @return [ExpectationTarget]
-
# @see ExpectationTarget#to
-
# @see ExpectationTarget#not_to
-
-
# Defines a matcher alias. The returned matcher's `description` will be overriden
-
# to reflect the phrasing of the new name, which will be used in failure messages
-
# when passed as an argument to another matcher in a composed matcher expression.
-
#
-
# @param new_name [Symbol] the new name for the matcher
-
# @param old_name [Symbol] the original name for the matcher
-
# @param options [Hash] options for the aliased matcher
-
# @option options [Class] :klass the ruby class to use as the decorator. (Not normally used).
-
# @yield [String] optional block that, when given, is used to define the overriden
-
# logic. The yielded arg is the original description or failure message. If no
-
# block is provided, a default override is used based on the old and new names.
-
#
-
# @example
-
# RSpec::Matchers.alias_matcher :a_list_that_sums_to, :sum_to
-
# sum_to(3).description # => "sum to 3"
-
# a_list_that_sums_to(3).description # => "a list that sums to 3"
-
#
-
# @example
-
# RSpec::Matchers.alias_matcher :a_list_sorted_by, :be_sorted_by do |description|
-
# description.sub("be sorted by", "a list sorted by")
-
# end
-
#
-
# be_sorted_by(:age).description # => "be sorted by age"
-
# a_list_sorted_by(:age).description # => "a list sorted by age"
-
#
-
# @!macro [attach] alias_matcher
-
# @!parse
-
# alias $1 $2
-
2
def self.alias_matcher(new_name, old_name, options={}, &description_override)
-
description_override ||= lambda do |old_desc|
-
old_desc.gsub(EnglishPhrasing.split_words(old_name), EnglishPhrasing.split_words(new_name))
-
115
end
-
227
klass = options.fetch(:klass) { AliasedMatcher }
-
-
115
define_method(new_name) do |*args, &block|
-
matcher = __send__(old_name, *args, &block)
-
klass.new(matcher, description_override)
-
end
-
end
-
-
# Defines a negated matcher. The returned matcher's `description` and `failure_message`
-
# will be overriden to reflect the phrasing of the new name, and the match logic will
-
# be based on the original matcher but negated.
-
#
-
# @param negated_name [Symbol] the name for the negated matcher
-
# @param base_name [Symbol] the name of the original matcher that will be negated
-
# @yield [String] optional block that, when given, is used to define the overriden
-
# logic. The yielded arg is the original description or failure message. If no
-
# block is provided, a default override is used based on the old and new names.
-
#
-
# @example
-
# RSpec::Matchers.define_negated_matcher :exclude, :include
-
# include(1, 2).description # => "include 1 and 2"
-
# exclude(1, 2).description # => "exclude 1 and 2"
-
#
-
# @note While the most obvious negated form may be to add a `not_` prefix,
-
# the failure messages you get with that form can be confusing (e.g.
-
# "expected [actual] to not [verb], but did not"). We've found it works
-
# best to find a more positive name for the negated form, such as
-
# `avoid_changing` rather than `not_change`.
-
2
def self.define_negated_matcher(negated_name, base_name, &description_override)
-
1
alias_matcher(negated_name, base_name, :klass => AliasedNegatedMatcher, &description_override)
-
end
-
-
# Allows multiple expectations in the provided block to fail, and then
-
# aggregates them into a single exception, rather than aborting on the
-
# first expectation failure like normal. This allows you to see all
-
# failures from an entire set of expectations without splitting each
-
# off into its own example (which may slow things down if the example
-
# setup is expensive).
-
#
-
# @param label [String] label for this aggregation block, which will be
-
# included in the aggregated exception message.
-
# @param metadata [Hash] additional metadata about this failure aggregation
-
# block. If multiple expectations fail, it will be exposed from the
-
# {Expectations::MultipleExpectationsNotMetError} exception. Mostly
-
# intended for internal RSpec use but you can use it as well.
-
# @yield Block containing as many expectation as you want. The block is
-
# simply yielded to, so you can trust that anything that works outside
-
# the block should work within it.
-
# @raise [Expectations::MultipleExpectationsNotMetError] raised when
-
# multiple expectations fail.
-
# @raise [Expectations::ExpectationNotMetError] raised when a single
-
# expectation fails.
-
# @raise [Exception] other sorts of exceptions will be raised as normal.
-
#
-
# @example
-
# aggregate_failures("verifying response") do
-
# expect(response.status).to eq(200)
-
# expect(response.headers).to include("Content-Type" => "text/plain")
-
# expect(response.body).to include("Success")
-
# end
-
#
-
# @note The implementation of this feature uses a thread-local variable,
-
# which means that if you have an expectation failure in another thread,
-
# it'll abort like normal.
-
2
def aggregate_failures(label=nil, metadata={}, &block)
-
Expectations::FailureAggregator.new(label, metadata).aggregate(&block)
-
end
-
-
# Passes if actual is truthy (anything but false or nil)
-
2
def be_truthy
-
BuiltIn::BeTruthy.new
-
end
-
2
alias_matcher :a_truthy_value, :be_truthy
-
-
# Passes if actual is falsey (false or nil)
-
2
def be_falsey
-
BuiltIn::BeFalsey.new
-
end
-
2
alias_matcher :be_falsy, :be_falsey
-
2
alias_matcher :a_falsey_value, :be_falsey
-
2
alias_matcher :a_falsy_value, :be_falsey
-
-
# Passes if actual is nil
-
2
def be_nil
-
BuiltIn::BeNil.new
-
end
-
2
alias_matcher :a_nil_value, :be_nil
-
-
# @example
-
# expect(actual).to be_truthy
-
# expect(actual).to be_falsey
-
# expect(actual).to be_nil
-
# expect(actual).to be_[arbitrary_predicate](*args)
-
# expect(actual).not_to be_nil
-
# expect(actual).not_to be_[arbitrary_predicate](*args)
-
#
-
# Given true, false, or nil, will pass if actual value is true, false or
-
# nil (respectively). Given no args means the caller should satisfy an if
-
# condition (to be or not to be).
-
#
-
# Predicates are any Ruby method that ends in a "?" and returns true or
-
# false. Given be_ followed by arbitrary_predicate (without the "?"),
-
# RSpec will match convert that into a query against the target object.
-
#
-
# The arbitrary_predicate feature will handle any predicate prefixed with
-
# "be_an_" (e.g. be_an_instance_of), "be_a_" (e.g. be_a_kind_of) or "be_"
-
# (e.g. be_empty), letting you choose the prefix that best suits the
-
# predicate.
-
2
def be(*args)
-
args.empty? ? Matchers::BuiltIn::Be.new : equal(*args)
-
end
-
2
alias_matcher :a_value, :be, :klass => AliasedMatcherWithOperatorSupport
-
-
# passes if target.kind_of?(klass)
-
2
def be_a(klass)
-
be_a_kind_of(klass)
-
end
-
2
alias_method :be_an, :be_a
-
-
# Passes if actual.instance_of?(expected)
-
#
-
# @example
-
# expect(5).to be_an_instance_of(Fixnum)
-
# expect(5).not_to be_an_instance_of(Numeric)
-
# expect(5).not_to be_an_instance_of(Float)
-
2
def be_an_instance_of(expected)
-
BuiltIn::BeAnInstanceOf.new(expected)
-
end
-
2
alias_method :be_instance_of, :be_an_instance_of
-
2
alias_matcher :an_instance_of, :be_an_instance_of
-
-
# Passes if actual.kind_of?(expected)
-
#
-
# @example
-
# expect(5).to be_a_kind_of(Fixnum)
-
# expect(5).to be_a_kind_of(Numeric)
-
# expect(5).not_to be_a_kind_of(Float)
-
2
def be_a_kind_of(expected)
-
BuiltIn::BeAKindOf.new(expected)
-
end
-
2
alias_method :be_kind_of, :be_a_kind_of
-
2
alias_matcher :a_kind_of, :be_a_kind_of
-
-
# Passes if actual.between?(min, max). Works with any Comparable object,
-
# including String, Symbol, Time, or Numeric (Fixnum, Bignum, Integer,
-
# Float, Complex, and Rational).
-
#
-
# By default, `be_between` is inclusive (i.e. passes when given either the max or min value),
-
# but you can make it `exclusive` by chaining that off the matcher.
-
#
-
# @example
-
# expect(5).to be_between(1, 10)
-
# expect(11).not_to be_between(1, 10)
-
# expect(10).not_to be_between(1, 10).exclusive
-
2
def be_between(min, max)
-
BuiltIn::BeBetween.new(min, max)
-
end
-
2
alias_matcher :a_value_between, :be_between
-
-
# Passes if actual == expected +/- delta
-
#
-
# @example
-
# expect(result).to be_within(0.5).of(3.0)
-
# expect(result).not_to be_within(0.5).of(3.0)
-
2
def be_within(delta)
-
BuiltIn::BeWithin.new(delta)
-
end
-
2
alias_matcher :a_value_within, :be_within
-
2
alias_matcher :within, :be_within
-
-
# Applied to a proc, specifies that its execution will cause some value to
-
# change.
-
#
-
# @param [Object] receiver
-
# @param [Symbol] message the message to send the receiver
-
#
-
# You can either pass <tt>receiver</tt> and <tt>message</tt>, or a block,
-
# but not both.
-
#
-
# When passing a block, it must use the `{ ... }` format, not
-
# do/end, as `{ ... }` binds to the `change` method, whereas do/end
-
# would errantly bind to the `expect(..).to` or `expect(...).not_to` method.
-
#
-
# You can chain any of the following off of the end to specify details
-
# about the change:
-
#
-
# * `from`
-
# * `to`
-
#
-
# or any one of:
-
#
-
# * `by`
-
# * `by_at_least`
-
# * `by_at_most`
-
#
-
# @example
-
# expect {
-
# team.add_player(player)
-
# }.to change(roster, :count)
-
#
-
# expect {
-
# team.add_player(player)
-
# }.to change(roster, :count).by(1)
-
#
-
# expect {
-
# team.add_player(player)
-
# }.to change(roster, :count).by_at_least(1)
-
#
-
# expect {
-
# team.add_player(player)
-
# }.to change(roster, :count).by_at_most(1)
-
#
-
# string = "string"
-
# expect {
-
# string.reverse!
-
# }.to change { string }.from("string").to("gnirts")
-
#
-
# string = "string"
-
# expect {
-
# string
-
# }.not_to change { string }.from("string")
-
#
-
# expect {
-
# person.happy_birthday
-
# }.to change(person, :birthday).from(32).to(33)
-
#
-
# expect {
-
# employee.develop_great_new_social_networking_app
-
# }.to change(employee, :title).from("Mail Clerk").to("CEO")
-
#
-
# expect {
-
# doctor.leave_office
-
# }.to change(doctor, :sign).from(/is in/).to(/is out/)
-
#
-
# user = User.new(:type => "admin")
-
# expect {
-
# user.symbolize_type
-
# }.to change(user, :type).from(String).to(Symbol)
-
#
-
# == Notes
-
#
-
# Evaluates `receiver.message` or `block` before and after it
-
# evaluates the block passed to `expect`.
-
#
-
# `expect( ... ).not_to change` supports the form that specifies `from`
-
# (which specifies what you expect the starting, unchanged value to be)
-
# but does not support forms with subsequent calls to `by`, `by_at_least`,
-
# `by_at_most` or `to`.
-
2
def change(receiver=nil, message=nil, &block)
-
BuiltIn::Change.new(receiver, message, &block)
-
end
-
2
alias_matcher :a_block_changing, :change
-
2
alias_matcher :changing, :change
-
-
# Passes if actual contains all of the expected regardless of order.
-
# This works for collections. Pass in multiple args and it will only
-
# pass if all args are found in collection.
-
#
-
# @note This is also available using the `=~` operator with `should`,
-
# but `=~` is not supported with `expect`.
-
#
-
# @example
-
# expect([1, 2, 3]).to contain_exactly(1, 2, 3)
-
# expect([1, 2, 3]).to contain_exactly(1, 3, 2)
-
#
-
# @see #match_array
-
2
def contain_exactly(*items)
-
BuiltIn::ContainExactly.new(items)
-
end
-
2
alias_matcher :a_collection_containing_exactly, :contain_exactly
-
2
alias_matcher :containing_exactly, :contain_exactly
-
-
# Passes if actual covers expected. This works for
-
# Ranges. You can also pass in multiple args
-
# and it will only pass if all args are found in Range.
-
#
-
# @example
-
# expect(1..10).to cover(5)
-
# expect(1..10).to cover(4, 6)
-
# expect(1..10).to cover(4, 6, 11) # fails
-
# expect(1..10).not_to cover(11)
-
# expect(1..10).not_to cover(5) # fails
-
#
-
# ### Warning:: Ruby >= 1.9 only
-
2
def cover(*values)
-
BuiltIn::Cover.new(*values)
-
end
-
2
alias_matcher :a_range_covering, :cover
-
2
alias_matcher :covering, :cover
-
-
# Matches if the actual value ends with the expected value(s). In the case
-
# of a string, matches against the last `expected.length` characters of the
-
# actual string. In the case of an array, matches against the last
-
# `expected.length` elements of the actual array.
-
#
-
# @example
-
# expect("this string").to end_with "string"
-
# expect([0, 1, 2, 3, 4]).to end_with 4
-
# expect([0, 2, 3, 4, 4]).to end_with 3, 4
-
2
def end_with(*expected)
-
BuiltIn::EndWith.new(*expected)
-
end
-
2
alias_matcher :a_collection_ending_with, :end_with
-
2
alias_matcher :a_string_ending_with, :end_with
-
2
alias_matcher :ending_with, :end_with
-
-
# Passes if <tt>actual == expected</tt>.
-
#
-
# See http://www.ruby-doc.org/core/classes/Object.html#M001057 for more
-
# information about equality in Ruby.
-
#
-
# @example
-
# expect(5).to eq(5)
-
# expect(5).not_to eq(3)
-
2
def eq(expected)
-
BuiltIn::Eq.new(expected)
-
end
-
2
alias_matcher :an_object_eq_to, :eq
-
2
alias_matcher :eq_to, :eq
-
-
# Passes if `actual.eql?(expected)`
-
#
-
# See http://www.ruby-doc.org/core/classes/Object.html#M001057 for more
-
# information about equality in Ruby.
-
#
-
# @example
-
# expect(5).to eql(5)
-
# expect(5).not_to eql(3)
-
2
def eql(expected)
-
BuiltIn::Eql.new(expected)
-
end
-
2
alias_matcher :an_object_eql_to, :eql
-
2
alias_matcher :eql_to, :eql
-
-
# Passes if <tt>actual.equal?(expected)</tt> (object identity).
-
#
-
# See http://www.ruby-doc.org/core/classes/Object.html#M001057 for more
-
# information about equality in Ruby.
-
#
-
# @example
-
# expect(5).to equal(5) # Fixnums are equal
-
# expect("5").not_to equal("5") # Strings that look the same are not the same object
-
2
def equal(expected)
-
BuiltIn::Equal.new(expected)
-
end
-
2
alias_matcher :an_object_equal_to, :equal
-
2
alias_matcher :equal_to, :equal
-
-
# Passes if `actual.exist?` or `actual.exists?`
-
#
-
# @example
-
# expect(File).to exist("path/to/file")
-
2
def exist(*args)
-
BuiltIn::Exist.new(*args)
-
end
-
2
alias_matcher :an_object_existing, :exist
-
2
alias_matcher :existing, :exist
-
-
# Passes if actual's attribute values match the expected attributes hash.
-
# This works no matter how you define your attribute readers.
-
#
-
# @example
-
# Person = Struct.new(:name, :age)
-
# person = Person.new("Bob", 32)
-
#
-
# expect(person).to have_attributes(:name => "Bob", :age => 32)
-
# expect(person).to have_attributes(:name => a_string_starting_with("B"), :age => (a_value > 30) )
-
#
-
# @note It will fail if actual doesn't respond to any of the expected attributes.
-
#
-
# @example
-
# expect(person).to have_attributes(:color => "red")
-
2
def have_attributes(expected)
-
BuiltIn::HaveAttributes.new(expected)
-
end
-
2
alias_matcher :an_object_having_attributes, :have_attributes
-
-
# Passes if actual includes expected. This works for
-
# collections and Strings. You can also pass in multiple args
-
# and it will only pass if all args are found in collection.
-
#
-
# @example
-
# expect([1,2,3]).to include(3)
-
# expect([1,2,3]).to include(2,3)
-
# expect([1,2,3]).to include(2,3,4) # fails
-
# expect([1,2,3]).not_to include(4)
-
# expect("spread").to include("read")
-
# expect("spread").not_to include("red")
-
# expect(:a => 1, :b => 2).to include(:a)
-
# expect(:a => 1, :b => 2).to include(:a, :b)
-
# expect(:a => 1, :b => 2).to include(:a => 1)
-
# expect(:a => 1, :b => 2).to include(:b => 2, :a => 1)
-
# expect(:a => 1, :b => 2).to include(:c) # fails
-
# expect(:a => 1, :b => 2).not_to include(:a => 2)
-
2
def include(*expected)
-
BuiltIn::Include.new(*expected)
-
end
-
2
alias_matcher :a_collection_including, :include
-
2
alias_matcher :a_string_including, :include
-
2
alias_matcher :a_hash_including, :include
-
2
alias_matcher :including, :include
-
-
# Passes if the provided matcher passes when checked against all
-
# elements of the collection.
-
#
-
# @example
-
# expect([1, 3, 5]).to all be_odd
-
# expect([1, 3, 6]).to all be_odd # fails
-
#
-
# @note The negative form `not_to all` is not supported. Instead
-
# use `not_to include` or pass a negative form of a matcher
-
# as the argument (e.g. `all exclude(:foo)`).
-
#
-
# @note You can also use this with compound matchers as well.
-
#
-
# @example
-
# expect([1, 3, 5]).to all( be_odd.and be_an(Integer) )
-
2
def all(expected)
-
BuiltIn::All.new(expected)
-
end
-
-
# Given a `Regexp` or `String`, passes if `actual.match(pattern)`
-
# Given an arbitrary nested data structure (e.g. arrays and hashes),
-
# matches if `expected === actual` || `actual == expected` for each
-
# pair of elements.
-
#
-
# @example
-
# expect(email).to match(/^([^\s]+)((?:[-a-z0-9]+\.)+[a-z]{2,})$/i)
-
# expect(email).to match("@example.com")
-
#
-
# @example
-
# hash = {
-
# :a => {
-
# :b => ["foo", 5],
-
# :c => { :d => 2.05 }
-
# }
-
# }
-
#
-
# expect(hash).to match(
-
# :a => {
-
# :b => a_collection_containing_exactly(
-
# a_string_starting_with("f"),
-
# an_instance_of(Fixnum)
-
# ),
-
# :c => { :d => (a_value < 3) }
-
# }
-
# )
-
#
-
# @note The `match_regex` alias is deprecated and is not recommended for use.
-
# It was added in 2.12.1 to facilitate its use from within custom
-
# matchers (due to how the custom matcher DSL was evaluated in 2.x,
-
# `match` could not be used there), but is no longer needed in 3.x.
-
2
def match(expected)
-
BuiltIn::Match.new(expected)
-
end
-
2
alias_matcher :match_regex, :match
-
2
alias_matcher :an_object_matching, :match
-
2
alias_matcher :a_string_matching, :match
-
2
alias_matcher :matching, :match
-
-
# An alternate form of `contain_exactly` that accepts
-
# the expected contents as a single array arg rather
-
# that splatted out as individual items.
-
#
-
# @example
-
# expect(results).to contain_exactly(1, 2)
-
# # is identical to:
-
# expect(results).to match_array([1, 2])
-
#
-
# @see #contain_exactly
-
2
def match_array(items)
-
contain_exactly(*items)
-
end
-
-
# With no arg, passes if the block outputs `to_stdout` or `to_stderr`.
-
# With a string, passes if the block outputs that specific string `to_stdout` or `to_stderr`.
-
# With a regexp or matcher, passes if the block outputs a string `to_stdout` or `to_stderr` that matches.
-
#
-
# To capture output from any spawned subprocess as well, use `to_stdout_from_any_process` or
-
# `to_stderr_from_any_process`. Output from any process that inherits the main process's corresponding
-
# standard stream will be captured.
-
#
-
# @example
-
# expect { print 'foo' }.to output.to_stdout
-
# expect { print 'foo' }.to output('foo').to_stdout
-
# expect { print 'foo' }.to output(/foo/).to_stdout
-
#
-
# expect { do_something }.to_not output.to_stdout
-
#
-
# expect { warn('foo') }.to output.to_stderr
-
# expect { warn('foo') }.to output('foo').to_stderr
-
# expect { warn('foo') }.to output(/foo/).to_stderr
-
#
-
# expect { do_something }.to_not output.to_stderr
-
#
-
# expect { system('echo foo') }.to output("foo\n").to_stdout_from_any_process
-
# expect { system('echo foo', out: :err) }.to output("foo\n").to_stderr_from_any_process
-
#
-
# @note `to_stdout` and `to_stderr` work by temporarily replacing `$stdout` or `$stderr`,
-
# so they're not able to intercept stream output that explicitly uses `STDOUT`/`STDERR`
-
# or that uses a reference to `$stdout`/`$stderr` that was stored before the
-
# matcher was used.
-
# @note `to_stdout_from_any_process` and `to_stderr_from_any_process` use Tempfiles, and
-
# are thus significantly (~30x) slower than `to_stdout` and `to_stderr`.
-
2
def output(expected=nil)
-
BuiltIn::Output.new(expected)
-
end
-
2
alias_matcher :a_block_outputting, :output
-
-
# With no args, matches if any error is raised.
-
# With a named error, matches only if that specific error is raised.
-
# With a named error and messsage specified as a String, matches only if both match.
-
# With a named error and messsage specified as a Regexp, matches only if both match.
-
# Pass an optional block to perform extra verifications on the exception matched
-
#
-
# @example
-
# expect { do_something_risky }.to raise_error
-
# expect { do_something_risky }.to raise_error(PoorRiskDecisionError)
-
# expect { do_something_risky }.to raise_error(PoorRiskDecisionError) { |error| expect(error.data).to eq 42 }
-
# expect { do_something_risky }.to raise_error(PoorRiskDecisionError, "that was too risky")
-
# expect { do_something_risky }.to raise_error(PoorRiskDecisionError, /oo ri/)
-
#
-
# expect { do_something_risky }.not_to raise_error
-
2
def raise_error(error=nil, message=nil, &block)
-
BuiltIn::RaiseError.new(error, message, &block)
-
end
-
2
alias_method :raise_exception, :raise_error
-
-
2
alias_matcher :a_block_raising, :raise_error do |desc|
-
desc.sub("raise", "a block raising")
-
end
-
-
2
alias_matcher :raising, :raise_error do |desc|
-
desc.sub("raise", "raising")
-
end
-
-
# Matches if the target object responds to all of the names
-
# provided. Names can be Strings or Symbols.
-
#
-
# @example
-
# expect("string").to respond_to(:length)
-
#
-
2
def respond_to(*names)
-
BuiltIn::RespondTo.new(*names)
-
end
-
2
alias_matcher :an_object_responding_to, :respond_to
-
2
alias_matcher :responding_to, :respond_to
-
-
# Passes if the submitted block returns true. Yields target to the
-
# block.
-
#
-
# Generally speaking, this should be thought of as a last resort when
-
# you can't find any other way to specify the behaviour you wish to
-
# specify.
-
#
-
# If you do find yourself in such a situation, you could always write
-
# a custom matcher, which would likely make your specs more expressive.
-
#
-
# @param description [String] optional description to be used for this matcher.
-
#
-
# @example
-
# expect(5).to satisfy { |n| n > 3 }
-
# expect(5).to satisfy("be greater than 3") { |n| n > 3 }
-
2
def satisfy(description="satisfy block", &block)
-
BuiltIn::Satisfy.new(description, &block)
-
end
-
2
alias_matcher :an_object_satisfying, :satisfy
-
2
alias_matcher :satisfying, :satisfy
-
-
# Matches if the actual value starts with the expected value(s). In the
-
# case of a string, matches against the first `expected.length` characters
-
# of the actual string. In the case of an array, matches against the first
-
# `expected.length` elements of the actual array.
-
#
-
# @example
-
# expect("this string").to start_with "this s"
-
# expect([0, 1, 2, 3, 4]).to start_with 0
-
# expect([0, 2, 3, 4, 4]).to start_with 0, 1
-
2
def start_with(*expected)
-
BuiltIn::StartWith.new(*expected)
-
end
-
2
alias_matcher :a_collection_starting_with, :start_with
-
2
alias_matcher :a_string_starting_with, :start_with
-
2
alias_matcher :starting_with, :start_with
-
-
# Given no argument, matches if a proc throws any Symbol.
-
#
-
# Given a Symbol, matches if the given proc throws the specified Symbol.
-
#
-
# Given a Symbol and an arg, matches if the given proc throws the
-
# specified Symbol with the specified arg.
-
#
-
# @example
-
# expect { do_something_risky }.to throw_symbol
-
# expect { do_something_risky }.to throw_symbol(:that_was_risky)
-
# expect { do_something_risky }.to throw_symbol(:that_was_risky, 'culprit')
-
#
-
# expect { do_something_risky }.not_to throw_symbol
-
# expect { do_something_risky }.not_to throw_symbol(:that_was_risky)
-
# expect { do_something_risky }.not_to throw_symbol(:that_was_risky, 'culprit')
-
2
def throw_symbol(expected_symbol=nil, expected_arg=nil)
-
BuiltIn::ThrowSymbol.new(expected_symbol, expected_arg)
-
end
-
-
2
alias_matcher :a_block_throwing, :throw_symbol do |desc|
-
desc.sub("throw", "a block throwing")
-
end
-
-
2
alias_matcher :throwing, :throw_symbol do |desc|
-
desc.sub("throw", "throwing")
-
end
-
-
# Passes if the method called in the expect block yields, regardless
-
# of whether or not arguments are yielded.
-
#
-
# @example
-
# expect { |b| 5.tap(&b) }.to yield_control
-
# expect { |b| "a".to_sym(&b) }.not_to yield_control
-
#
-
# @note Your expect block must accept a parameter and pass it on to
-
# the method-under-test as a block.
-
2
def yield_control
-
BuiltIn::YieldControl.new
-
end
-
2
alias_matcher :a_block_yielding_control, :yield_control
-
2
alias_matcher :yielding_control, :yield_control
-
-
# Passes if the method called in the expect block yields with
-
# no arguments. Fails if it does not yield, or yields with arguments.
-
#
-
# @example
-
# expect { |b| User.transaction(&b) }.to yield_with_no_args
-
# expect { |b| 5.tap(&b) }.not_to yield_with_no_args # because it yields with `5`
-
# expect { |b| "a".to_sym(&b) }.not_to yield_with_no_args # because it does not yield
-
#
-
# @note Your expect block must accept a parameter and pass it on to
-
# the method-under-test as a block.
-
# @note This matcher is not designed for use with methods that yield
-
# multiple times.
-
2
def yield_with_no_args
-
BuiltIn::YieldWithNoArgs.new
-
end
-
2
alias_matcher :a_block_yielding_with_no_args, :yield_with_no_args
-
2
alias_matcher :yielding_with_no_args, :yield_with_no_args
-
-
# Given no arguments, matches if the method called in the expect
-
# block yields with arguments (regardless of what they are or how
-
# many there are).
-
#
-
# Given arguments, matches if the method called in the expect block
-
# yields with arguments that match the given arguments.
-
#
-
# Argument matching is done using `===` (the case match operator)
-
# and `==`. If the expected and actual arguments match with either
-
# operator, the matcher will pass.
-
#
-
# @example
-
# expect { |b| 5.tap(&b) }.to yield_with_args # because #tap yields an arg
-
# expect { |b| 5.tap(&b) }.to yield_with_args(5) # because 5 == 5
-
# expect { |b| 5.tap(&b) }.to yield_with_args(Fixnum) # because Fixnum === 5
-
# expect { |b| File.open("f.txt", &b) }.to yield_with_args(/txt/) # because /txt/ === "f.txt"
-
#
-
# expect { |b| User.transaction(&b) }.not_to yield_with_args # because it yields no args
-
# expect { |b| 5.tap(&b) }.not_to yield_with_args(1, 2, 3)
-
#
-
# @note Your expect block must accept a parameter and pass it on to
-
# the method-under-test as a block.
-
# @note This matcher is not designed for use with methods that yield
-
# multiple times.
-
2
def yield_with_args(*args)
-
BuiltIn::YieldWithArgs.new(*args)
-
end
-
2
alias_matcher :a_block_yielding_with_args, :yield_with_args
-
2
alias_matcher :yielding_with_args, :yield_with_args
-
-
# Designed for use with methods that repeatedly yield (such as
-
# iterators). Passes if the method called in the expect block yields
-
# multiple times with arguments matching those given.
-
#
-
# Argument matching is done using `===` (the case match operator)
-
# and `==`. If the expected and actual arguments match with either
-
# operator, the matcher will pass.
-
#
-
# @example
-
# expect { |b| [1, 2, 3].each(&b) }.to yield_successive_args(1, 2, 3)
-
# expect { |b| { :a => 1, :b => 2 }.each(&b) }.to yield_successive_args([:a, 1], [:b, 2])
-
# expect { |b| [1, 2, 3].each(&b) }.not_to yield_successive_args(1, 2)
-
#
-
# @note Your expect block must accept a parameter and pass it on to
-
# the method-under-test as a block.
-
2
def yield_successive_args(*args)
-
BuiltIn::YieldSuccessiveArgs.new(*args)
-
end
-
2
alias_matcher :a_block_yielding_successive_args, :yield_successive_args
-
2
alias_matcher :yielding_successive_args, :yield_successive_args
-
-
# Delegates to {RSpec::Expectations.configuration}.
-
# This is here because rspec-core's `expect_with` option
-
# looks for a `configuration` method on the mixin
-
# (`RSpec::Matchers`) to yield to a block.
-
# @return [RSpec::Expectations::Configuration] the configuration object
-
2
def self.configuration
-
2
Expectations.configuration
-
end
-
-
2
private
-
-
2
BE_PREDICATE_REGEX = /^(be_(?:an?_)?)(.*)/
-
2
HAS_REGEX = /^(?:have_)(.*)/
-
2
DYNAMIC_MATCHER_REGEX = Regexp.union(BE_PREDICATE_REGEX, HAS_REGEX)
-
-
2
def method_missing(method, *args, &block)
-
17
case method.to_s
-
when BE_PREDICATE_REGEX
-
11
BuiltIn::BePredicate.new(method, *args, &block)
-
when HAS_REGEX
-
BuiltIn::Has.new(method, *args, &block)
-
else
-
6
super
-
end
-
end
-
-
2
if RUBY_VERSION.to_f >= 1.9
-
2
def respond_to_missing?(method, *)
-
method =~ DYNAMIC_MATCHER_REGEX || super
-
end
-
else # for 1.8.7
-
# :nocov:
-
skipped
def respond_to?(method, *)
-
skipped
method = method.to_s
-
skipped
method =~ DYNAMIC_MATCHER_REGEX || super
-
skipped
end
-
skipped
public :respond_to?
-
# :nocov:
-
end
-
-
# @api private
-
2
def self.is_a_matcher?(obj)
-
return true if ::RSpec::Matchers::BuiltIn::BaseMatcher === obj
-
begin
-
return false if obj.respond_to?(:i_respond_to_everything_so_im_not_really_a_matcher)
-
rescue NoMethodError
-
# Some objects, like BasicObject, don't implemented standard
-
# reflection methods.
-
return false
-
end
-
return false unless obj.respond_to?(:matches?)
-
-
obj.respond_to?(:failure_message) ||
-
obj.respond_to?(:failure_message_for_should) # support legacy matchers
-
end
-
-
2
::RSpec::Support.register_matcher_definition do |obj|
-
is_a_matcher?(obj)
-
end
-
-
# @api private
-
2
def self.is_a_describable_matcher?(obj)
-
is_a_matcher?(obj) && obj.respond_to?(:description)
-
end
-
-
2
if RSpec::Support::Ruby.mri? && RUBY_VERSION[0, 3] == '1.9'
-
# @api private
-
# Note that `included` doesn't work for this because it is triggered
-
# _after_ `RSpec::Matchers` is an ancestor of the inclusion host, rather
-
# than _before_, like `append_features`. It's important we check this before
-
# in order to find the cases where it was already previously included.
-
def self.append_features(mod)
-
return super if mod < self # `mod < self` indicates a re-inclusion.
-
-
subclasses = ObjectSpace.each_object(Class).select { |c| c < mod && c < self }
-
return super unless subclasses.any?
-
-
subclasses.reject! { |s| subclasses.any? { |s2| s < s2 } } # Filter to the root ancestor.
-
subclasses = subclasses.map { |s| "`#{s}`" }.join(", ")
-
-
RSpec.warning "`#{self}` has been included in a superclass (`#{mod}`) " \
-
"after previously being included in subclasses (#{subclasses}), " \
-
"which can trigger infinite recursion from `super` due to an MRI 1.9 bug " \
-
"(https://redmine.ruby-lang.org/issues/3351). To work around this, " \
-
"either upgrade to MRI 2.0+, include a dup of the module (e.g. " \
-
"`include #{self}.dup`), or find a way to include `#{self}` in `#{mod}` " \
-
"before it is included in subclasses (#{subclasses}). See " \
-
"https://github.com/rspec/rspec-expectations/issues/814 for more info"
-
-
super
-
end
-
end
-
end
-
end
-
2
module RSpec
-
2
module Matchers
-
# Decorator that wraps a matcher and overrides `description`
-
# using the provided block in order to support an alias
-
# of a matcher. This is intended for use when composing
-
# matchers, so that you can use an expression like
-
# `include( a_value_within(0.1).of(3) )` rather than
-
# `include( be_within(0.1).of(3) )`, and have the corresponding
-
# description read naturally.
-
#
-
# @api private
-
2
class AliasedMatcher < MatcherDelegator
-
2
def initialize(base_matcher, description_block)
-
@description_block = description_block
-
super(base_matcher)
-
end
-
-
# Forward messages on to the wrapped matcher.
-
# Since many matchers provide a fluent interface
-
# (e.g. `a_value_within(0.1).of(3)`), we need to wrap
-
# the returned value if it responds to `description`,
-
# so that our override can be applied when it is eventually
-
# used.
-
2
def method_missing(*)
-
return_val = super
-
return return_val unless RSpec::Matchers.is_a_matcher?(return_val)
-
self.class.new(return_val, @description_block)
-
end
-
-
# Provides the description of the aliased matcher. Aliased matchers
-
# are designed to behave identically to the original matcher except
-
# for the description and failure messages. The description is different
-
# to reflect the aliased name.
-
#
-
# @api private
-
2
def description
-
@description_block.call(super)
-
end
-
-
# Provides the failure_message of the aliased matcher. Aliased matchers
-
# are designed to behave identically to the original matcher except
-
# for the description and failure messages. The failure_message is different
-
# to reflect the aliased name.
-
#
-
# @api private
-
2
def failure_message
-
@description_block.call(super)
-
end
-
-
# Provides the failure_message_when_negated of the aliased matcher. Aliased matchers
-
# are designed to behave identically to the original matcher except
-
# for the description and failure messages. The failure_message_when_negated is different
-
# to reflect the aliased name.
-
#
-
# @api private
-
2
def failure_message_when_negated
-
@description_block.call(super)
-
end
-
end
-
-
# Decorator used for matchers that have special implementations of
-
# operators like `==` and `===`.
-
# @private
-
2
class AliasedMatcherWithOperatorSupport < AliasedMatcher
-
# We undef these so that they get delegated via `method_missing`.
-
2
undef ==
-
2
undef ===
-
end
-
-
# @private
-
2
class AliasedNegatedMatcher < AliasedMatcher
-
2
def matches?(*args, &block)
-
if @base_matcher.respond_to?(:does_not_match?)
-
@base_matcher.does_not_match?(*args, &block)
-
else
-
!super
-
end
-
end
-
-
2
def does_not_match?(*args, &block)
-
@base_matcher.matches?(*args, &block)
-
end
-
-
2
def failure_message
-
optimal_failure_message(__method__, :failure_message_when_negated)
-
end
-
-
2
def failure_message_when_negated
-
optimal_failure_message(__method__, :failure_message)
-
end
-
-
2
private
-
-
2
DefaultFailureMessages = BuiltIn::BaseMatcher::DefaultFailureMessages
-
-
# For a matcher that uses the default failure messages, we prefer to
-
# use the override provided by the `description_block`, because it
-
# includes the phrasing that the user has expressed a preference for
-
# by going through the effort of defining a negated matcher.
-
#
-
# However, if the override didn't actually change anything, then we
-
# should return the opposite failure message instead -- the overriden
-
# message is going to be confusing if we return it as-is, as it represents
-
# the non-negated failure message for a negated match (or vice versa).
-
2
def optimal_failure_message(same, inverted)
-
if DefaultFailureMessages.has_default_failure_messages?(@base_matcher)
-
base_message = @base_matcher.__send__(same)
-
overriden = @description_block.call(base_message)
-
return overriden if overriden != base_message
-
end
-
-
@base_matcher.__send__(inverted)
-
end
-
end
-
end
-
end
-
2
RSpec::Support.require_rspec_matchers "built_in/base_matcher"
-
-
2
module RSpec
-
2
module Matchers
-
# Container module for all built-in matchers. The matcher classes are here
-
# (rather than directly under `RSpec::Matchers`) in order to prevent name
-
# collisions, since `RSpec::Matchers` gets included into the user's namespace.
-
#
-
# Autoloading is used to delay when the matcher classes get loaded, allowing
-
# rspec-matchers to boot faster, and avoiding loading matchers the user is
-
# not using.
-
2
module BuiltIn
-
2
autoload :BeAKindOf, 'rspec/matchers/built_in/be_kind_of'
-
2
autoload :BeAnInstanceOf, 'rspec/matchers/built_in/be_instance_of'
-
2
autoload :BeBetween, 'rspec/matchers/built_in/be_between'
-
2
autoload :Be, 'rspec/matchers/built_in/be'
-
2
autoload :BeComparedTo, 'rspec/matchers/built_in/be'
-
2
autoload :BeFalsey, 'rspec/matchers/built_in/be'
-
2
autoload :BeNil, 'rspec/matchers/built_in/be'
-
2
autoload :BePredicate, 'rspec/matchers/built_in/be'
-
2
autoload :BeTruthy, 'rspec/matchers/built_in/be'
-
2
autoload :BeWithin, 'rspec/matchers/built_in/be_within'
-
2
autoload :Change, 'rspec/matchers/built_in/change'
-
2
autoload :Compound, 'rspec/matchers/built_in/compound'
-
2
autoload :ContainExactly, 'rspec/matchers/built_in/contain_exactly'
-
2
autoload :Cover, 'rspec/matchers/built_in/cover'
-
2
autoload :EndWith, 'rspec/matchers/built_in/start_or_end_with'
-
2
autoload :Eq, 'rspec/matchers/built_in/eq'
-
2
autoload :Eql, 'rspec/matchers/built_in/eql'
-
2
autoload :Equal, 'rspec/matchers/built_in/equal'
-
2
autoload :Exist, 'rspec/matchers/built_in/exist'
-
2
autoload :Has, 'rspec/matchers/built_in/has'
-
2
autoload :HaveAttributes, 'rspec/matchers/built_in/have_attributes'
-
2
autoload :Include, 'rspec/matchers/built_in/include'
-
2
autoload :All, 'rspec/matchers/built_in/all'
-
2
autoload :Match, 'rspec/matchers/built_in/match'
-
2
autoload :NegativeOperatorMatcher, 'rspec/matchers/built_in/operators'
-
2
autoload :OperatorMatcher, 'rspec/matchers/built_in/operators'
-
2
autoload :Output, 'rspec/matchers/built_in/output'
-
2
autoload :PositiveOperatorMatcher, 'rspec/matchers/built_in/operators'
-
2
autoload :RaiseError, 'rspec/matchers/built_in/raise_error'
-
2
autoload :RespondTo, 'rspec/matchers/built_in/respond_to'
-
2
autoload :Satisfy, 'rspec/matchers/built_in/satisfy'
-
2
autoload :StartWith, 'rspec/matchers/built_in/start_or_end_with'
-
2
autoload :ThrowSymbol, 'rspec/matchers/built_in/throw_symbol'
-
2
autoload :YieldControl, 'rspec/matchers/built_in/yield'
-
2
autoload :YieldSuccessiveArgs, 'rspec/matchers/built_in/yield'
-
2
autoload :YieldWithArgs, 'rspec/matchers/built_in/yield'
-
2
autoload :YieldWithNoArgs, 'rspec/matchers/built_in/yield'
-
end
-
end
-
end
-
2
module RSpec
-
2
module Matchers
-
2
module BuiltIn
-
# @api private
-
#
-
# Used _internally_ as a base class for matchers that ship with
-
# rspec-expectations and rspec-rails.
-
#
-
# ### Warning:
-
#
-
# This class is for internal use, and subject to change without notice.
-
# We strongly recommend that you do not base your custom matchers on this
-
# class. If/when this changes, we will announce it and remove this warning.
-
2
class BaseMatcher
-
2
include RSpec::Matchers::Composable
-
-
# @api private
-
# Used to detect when no arg is passed to `initialize`.
-
# `nil` cannot be used because it's a valid value to pass.
-
2
UNDEFINED = Object.new.freeze
-
-
# @private
-
2
attr_reader :actual, :expected, :rescued_exception
-
-
2
def initialize(expected=UNDEFINED)
-
@expected = expected unless UNDEFINED.equal?(expected)
-
end
-
-
# @api private
-
# Indicates if the match is successful. Delegates to `match`, which
-
# should be defined on a subclass. Takes care of consistently
-
# initializing the `actual` attribute.
-
2
def matches?(actual)
-
@actual = actual
-
match(expected, actual)
-
end
-
-
# @api private
-
# Used to wrap a block of code that will indicate failure by
-
# raising one of the named exceptions.
-
#
-
# This is used by rspec-rails for some of its matchers that
-
# wrap rails' assertions.
-
2
def match_unless_raises(*exceptions)
-
exceptions.unshift Exception if exceptions.empty?
-
begin
-
yield
-
true
-
rescue *exceptions => @rescued_exception
-
false
-
end
-
end
-
-
# @api private
-
# Generates a description using {EnglishPhrasing}.
-
# @return [String]
-
2
def description
-
desc = EnglishPhrasing.split_words(self.class.matcher_name)
-
desc << EnglishPhrasing.list(@expected) if defined?(@expected)
-
desc
-
end
-
-
# @api private
-
# Matchers are not diffable by default. Override this to make your
-
# subclass diffable.
-
2
def diffable?
-
false
-
end
-
-
# @api private
-
# Most matchers are value matchers (i.e. meant to work with `expect(value)`)
-
# rather than block matchers (i.e. meant to work with `expect { }`), so
-
# this defaults to false. Block matchers must override this to return true.
-
2
def supports_block_expectations?
-
false
-
end
-
-
# @api private
-
2
def expects_call_stack_jump?
-
false
-
end
-
-
# @private
-
2
def expected_formatted
-
RSpec::Support::ObjectFormatter.format(@expected)
-
end
-
-
# @private
-
2
def actual_formatted
-
RSpec::Support::ObjectFormatter.format(@actual)
-
end
-
-
# @private
-
2
def self.matcher_name
-
@matcher_name ||= underscore(name.split('::').last)
-
end
-
-
# @private
-
# Borrowed from ActiveSupport.
-
2
def self.underscore(camel_cased_word)
-
word = camel_cased_word.to_s.dup
-
word.gsub!(/([A-Z]+)([A-Z][a-z])/, '\1_\2')
-
word.gsub!(/([a-z\d])([A-Z])/, '\1_\2')
-
word.tr!('-', '_')
-
word.downcase!
-
word
-
end
-
2
private_class_method :underscore
-
-
2
private
-
-
2
def assert_ivars(*expected_ivars)
-
return unless (expected_ivars - present_ivars).any?
-
ivar_list = EnglishPhrasing.list(expected_ivars)
-
raise "#{self.class.name} needs to supply#{ivar_list}"
-
end
-
-
2
if RUBY_VERSION.to_f < 1.9
-
# :nocov:
-
skipped
def present_ivars
-
skipped
instance_variables.map(&:to_sym)
-
skipped
end
-
# :nocov:
-
else
-
2
alias present_ivars instance_variables
-
end
-
-
# @private
-
2
module HashFormatting
-
# `{ :a => 5, :b => 2 }.inspect` produces:
-
#
-
# {:a=>5, :b=>2}
-
#
-
# ...but it looks much better as:
-
#
-
# {:a => 5, :b => 2}
-
#
-
# This is idempotent and safe to run on a string multiple times.
-
2
def improve_hash_formatting(inspect_string)
-
inspect_string.gsub(/(\S)=>(\S)/, '\1 => \2')
-
end
-
2
module_function :improve_hash_formatting
-
end
-
-
2
include HashFormatting
-
-
# @api private
-
# Provides default implementations of failure messages, based on the `description`.
-
2
module DefaultFailureMessages
-
# @api private
-
# Provides a good generic failure message. Based on `description`.
-
# When subclassing, if you are not satisfied with this failure message
-
# you often only need to override `description`.
-
# @return [String]
-
2
def failure_message
-
"expected #{description_of @actual} to #{description}"
-
end
-
-
# @api private
-
# Provides a good generic negative failure message. Based on `description`.
-
# When subclassing, if you are not satisfied with this failure message
-
# you often only need to override `description`.
-
# @return [String]
-
2
def failure_message_when_negated
-
"expected #{description_of @actual} not to #{description}"
-
end
-
-
# @private
-
2
def self.has_default_failure_messages?(matcher)
-
matcher.method(:failure_message).owner == self &&
-
matcher.method(:failure_message_when_negated).owner == self
-
rescue NameError
-
false
-
end
-
end
-
-
2
include DefaultFailureMessages
-
end
-
end
-
end
-
end
-
1
module RSpec
-
1
module Matchers
-
1
module BuiltIn
-
# @api private
-
# Provides the implementation for `be_truthy`.
-
# Not intended to be instantiated directly.
-
1
class BeTruthy < BaseMatcher
-
# @api private
-
# @return [String]
-
1
def failure_message
-
"expected: truthy value\n got: #{actual_formatted}"
-
end
-
-
# @api private
-
# @return [String]
-
1
def failure_message_when_negated
-
"expected: falsey value\n got: #{actual_formatted}"
-
end
-
-
1
private
-
-
1
def match(_, actual)
-
!!actual
-
end
-
end
-
-
# @api private
-
# Provides the implementation for `be_falsey`.
-
# Not intended to be instantiated directly.
-
1
class BeFalsey < BaseMatcher
-
# @api private
-
# @return [String]
-
1
def failure_message
-
"expected: falsey value\n got: #{actual_formatted}"
-
end
-
-
# @api private
-
# @return [String]
-
1
def failure_message_when_negated
-
"expected: truthy value\n got: #{actual_formatted}"
-
end
-
-
1
private
-
-
1
def match(_, actual)
-
!actual
-
end
-
end
-
-
# @api private
-
# Provides the implementation for `be_nil`.
-
# Not intended to be instantiated directly.
-
1
class BeNil < BaseMatcher
-
# @api private
-
# @return [String]
-
1
def failure_message
-
"expected: nil\n got: #{actual_formatted}"
-
end
-
-
# @api private
-
# @return [String]
-
1
def failure_message_when_negated
-
"expected: not nil\n got: nil"
-
end
-
-
1
private
-
-
1
def match(_, actual)
-
actual.nil?
-
end
-
end
-
-
# @private
-
1
module BeHelpers
-
1
private
-
-
1
def args_to_s
-
@args.empty? ? "" : parenthesize(inspected_args.join(', '))
-
end
-
-
1
def parenthesize(string)
-
"(#{string})"
-
end
-
-
1
def inspected_args
-
@args.map { |a| RSpec::Support::ObjectFormatter.format(a) }
-
end
-
-
1
def expected_to_sentence
-
EnglishPhrasing.split_words(@expected)
-
end
-
-
1
def args_to_sentence
-
EnglishPhrasing.list(@args)
-
end
-
end
-
-
# @api private
-
# Provides the implementation for `be`.
-
# Not intended to be instantiated directly.
-
1
class Be < BaseMatcher
-
1
include BeHelpers
-
-
1
def initialize(*args)
-
@args = args
-
end
-
-
# @api private
-
# @return [String]
-
1
def failure_message
-
"expected #{actual_formatted} to evaluate to true"
-
end
-
-
# @api private
-
# @return [String]
-
1
def failure_message_when_negated
-
"expected #{actual_formatted} to evaluate to false"
-
end
-
-
1
[:==, :<, :<=, :>=, :>, :===, :=~].each do |operator|
-
7
define_method operator do |operand|
-
BeComparedTo.new(operand, operator)
-
end
-
end
-
-
1
private
-
-
1
def match(_, actual)
-
!!actual
-
end
-
end
-
-
# @api private
-
# Provides the implementation of `be <operator> value`.
-
# Not intended to be instantiated directly.
-
1
class BeComparedTo < BaseMatcher
-
1
include BeHelpers
-
-
1
def initialize(operand, operator)
-
@expected, @operator = operand, operator
-
@args = []
-
end
-
-
1
def matches?(actual)
-
@actual = actual
-
@actual.__send__ @operator, @expected
-
rescue ArgumentError
-
false
-
end
-
-
# @api private
-
# @return [String]
-
1
def failure_message
-
"expected: #{@operator} #{expected_formatted}\n got: #{@operator.to_s.gsub(/./, ' ')} #{actual_formatted}"
-
end
-
-
# @api private
-
# @return [String]
-
1
def failure_message_when_negated
-
message = "`expect(#{actual_formatted}).not_to be #{@operator} #{expected_formatted}`"
-
if [:<, :>, :<=, :>=].include?(@operator)
-
message + " not only FAILED, it is a bit confusing."
-
else
-
message
-
end
-
end
-
-
# @api private
-
# @return [String]
-
1
def description
-
"be #{@operator} #{expected_to_sentence}#{args_to_sentence}"
-
end
-
end
-
-
# @api private
-
# Provides the implementation of `be_<predicate>`.
-
# Not intended to be instantiated directly.
-
1
class BePredicate < BaseMatcher
-
1
include BeHelpers
-
-
1
def initialize(*args, &block)
-
11
@expected = parse_expected(args.shift)
-
11
@args = args
-
11
@block = block
-
end
-
-
1
def matches?(actual, &block)
-
11
@actual = actual
-
11
@block ||= block
-
11
predicate_accessible? && predicate_matches?
-
end
-
-
1
def does_not_match?(actual, &block)
-
@actual = actual
-
@block ||= block
-
predicate_accessible? && !predicate_matches?
-
end
-
-
# @api private
-
# @return [String]
-
1
def failure_message
-
failure_message_expecting(true)
-
end
-
-
# @api private
-
# @return [String]
-
1
def failure_message_when_negated
-
failure_message_expecting(false)
-
end
-
-
# @api private
-
# @return [String]
-
1
def description
-
"#{prefix_to_sentence}#{expected_to_sentence}#{args_to_sentence}"
-
end
-
-
1
private
-
-
1
def predicate_accessible?
-
11
actual.respond_to?(predicate) || actual.respond_to?(present_tense_predicate)
-
end
-
-
# support 1.8.7, evaluate once at load time for performance
-
1
if String === methods.first
-
# :nocov:
-
skipped
def private_predicate?
-
skipped
@actual.private_methods.include? predicate.to_s
-
skipped
end
-
# :nocov:
-
else
-
1
def private_predicate?
-
@actual.private_methods.include? predicate
-
end
-
end
-
-
1
def predicate_matches?
-
11
method_name = actual.respond_to?(predicate) ? predicate : present_tense_predicate
-
11
@predicate_matches = actual.__send__(method_name, *@args, &@block)
-
end
-
-
1
def predicate
-
33
:"#{@expected}?"
-
end
-
-
1
def present_tense_predicate
-
:"#{@expected}s?"
-
end
-
-
1
def parse_expected(expected)
-
11
@prefix, expected = prefix_and_expected(expected)
-
11
expected
-
end
-
-
1
def prefix_and_expected(symbol)
-
11
Matchers::BE_PREDICATE_REGEX.match(symbol.to_s).captures.compact
-
end
-
-
1
def prefix_to_sentence
-
EnglishPhrasing.split_words(@prefix)
-
end
-
-
1
def failure_message_expecting(value)
-
validity_message ||
-
"expected `#{actual_formatted}.#{predicate}#{args_to_s}` to return #{value}, got #{description_of @predicate_matches}"
-
end
-
-
1
def validity_message
-
return nil if predicate_accessible?
-
-
msg = "expected #{actual_formatted} to respond to `#{predicate}`"
-
-
if private_predicate?
-
msg << " but `#{predicate}` is a private method"
-
elsif predicate == :true?
-
msg << " or perhaps you meant `be true` or `be_truthy`"
-
elsif predicate == :false?
-
msg << " or perhaps you meant `be false` or `be_falsey`"
-
end
-
-
msg
-
end
-
end
-
end
-
end
-
end
-
1
module RSpec
-
1
module Matchers
-
1
module BuiltIn
-
# @api private
-
# Provides the implementation for `contain_exactly` and `match_array`.
-
# Not intended to be instantiated directly.
-
1
class ContainExactly < BaseMatcher
-
# @api private
-
# @return [String]
-
1
def failure_message
-
if Array === actual
-
generate_failure_message
-
else
-
"expected a collection that can be converted to an array with " \
-
"`#to_ary` or `#to_a`, but got #{actual_formatted}"
-
end
-
end
-
-
# @api private
-
# @return [String]
-
1
def failure_message_when_negated
-
list = EnglishPhrasing.list(surface_descriptions_in(expected))
-
"expected #{actual_formatted} not to contain exactly#{list}"
-
end
-
-
# @api private
-
# @return [String]
-
1
def description
-
list = EnglishPhrasing.list(surface_descriptions_in(expected))
-
"contain exactly#{list}"
-
end
-
-
1
private
-
-
1
def generate_failure_message
-
message = expected_collection_line
-
message += actual_collection_line
-
message += missing_elements_line unless missing_items.empty?
-
message += extra_elements_line unless extra_items.empty?
-
message
-
end
-
-
1
def expected_collection_line
-
message_line('expected collection contained', expected, true)
-
end
-
-
1
def actual_collection_line
-
message_line('actual collection contained', actual)
-
end
-
-
1
def missing_elements_line
-
message_line('the missing elements were', missing_items, true)
-
end
-
-
1
def extra_elements_line
-
message_line('the extra elements were', extra_items)
-
end
-
-
1
def describe_collection(collection, surface_descriptions=false)
-
if surface_descriptions
-
"#{description_of(safe_sort(surface_descriptions_in collection))}\n"
-
else
-
"#{description_of(safe_sort(collection))}\n"
-
end
-
end
-
-
1
def message_line(prefix, collection, surface_descriptions=false)
-
"%-32s%s" % [prefix + ':',
-
describe_collection(collection, surface_descriptions)]
-
end
-
-
1
def match(_expected, _actual)
-
return false unless convert_actual_to_an_array
-
match_when_sorted? || (extra_items.empty? && missing_items.empty?)
-
end
-
-
# This cannot always work (e.g. when dealing with unsortable items,
-
# or matchers as expected items), but it's practically free compared to
-
# the slowness of the full matching algorithm, and in common cases this
-
# works, so it's worth a try.
-
1
def match_when_sorted?
-
values_match?(safe_sort(expected), safe_sort(actual))
-
end
-
-
1
def convert_actual_to_an_array
-
if actual.respond_to?(:to_ary)
-
@actual = actual.to_ary
-
elsif should_enumerate?(actual) && actual.respond_to?(:to_a)
-
@actual = actual.to_a
-
else
-
return false
-
end
-
end
-
-
1
def safe_sort(array)
-
array.sort
-
rescue Support::AllExceptionsExceptOnesWeMustNotRescue
-
array
-
end
-
-
1
def missing_items
-
@missing_items ||= best_solution.unmatched_expected_indexes.map do |index|
-
expected[index]
-
end
-
end
-
-
1
def extra_items
-
@extra_items ||= best_solution.unmatched_actual_indexes.map do |index|
-
actual[index]
-
end
-
end
-
-
1
def best_solution
-
@best_solution ||= pairings_maximizer.find_best_solution
-
end
-
-
1
def pairings_maximizer
-
@pairings_maximizer ||= begin
-
expected_matches = Hash[Array.new(expected.size) { |i| [i, []] }]
-
actual_matches = Hash[Array.new(actual.size) { |i| [i, []] }]
-
-
expected.each_with_index do |e, ei|
-
actual.each_with_index do |a, ai|
-
next unless values_match?(e, a)
-
-
expected_matches[ei] << ai
-
actual_matches[ai] << ei
-
end
-
end
-
-
PairingsMaximizer.new(expected_matches, actual_matches)
-
end
-
end
-
-
# Once we started supporting composing matchers, the algorithm for this matcher got
-
# much more complicated. Consider this expression:
-
#
-
# expect(["fool", "food"]).to contain_exactly(/foo/, /fool/)
-
#
-
# This should pass (because we can pair /fool/ with "fool" and /foo/ with "food"), but
-
# the original algorithm used by this matcher would pair the first elements it could
-
# (/foo/ with "fool"), which would leave /fool/ and "food" unmatched. When we have
-
# an expected element which is a matcher that matches a superset of actual items
-
# compared to another expected element matcher, we need to consider every possible pairing.
-
#
-
# This class is designed to maximize the number of actual/expected pairings -- or,
-
# conversely, to minimize the number of unpaired items. It's essentially a brute
-
# force solution, but with a few heuristics applied to reduce the size of the
-
# problem space:
-
#
-
# * Any items which match none of the items in the other list are immediately
-
# placed into the `unmatched_expected_indexes` or `unmatched_actual_indexes` array.
-
# The extra items and missing items in the matcher failure message are derived
-
# from these arrays.
-
# * Any items which reciprocally match only each other are paired up and not
-
# considered further.
-
#
-
# What's left is only the items which match multiple items from the other list
-
# (or vice versa). From here, it performs a brute-force depth-first search,
-
# looking for a solution which pairs all elements in both lists, or, barring that,
-
# that produces the fewest unmatched items.
-
#
-
# @private
-
1
class PairingsMaximizer
-
1
Solution = Struct.new(:unmatched_expected_indexes, :unmatched_actual_indexes,
-
:indeterminate_expected_indexes, :indeterminate_actual_indexes) do
-
1
def worse_than?(other)
-
unmatched_item_count > other.unmatched_item_count
-
end
-
-
1
def candidate?
-
indeterminate_expected_indexes.empty? &&
-
indeterminate_actual_indexes.empty?
-
end
-
-
1
def ideal?
-
candidate? && (
-
unmatched_expected_indexes.empty? ||
-
unmatched_actual_indexes.empty?
-
)
-
end
-
-
1
def unmatched_item_count
-
unmatched_expected_indexes.count + unmatched_actual_indexes.count
-
end
-
-
1
def +(derived_candidate_solution)
-
self.class.new(
-
unmatched_expected_indexes + derived_candidate_solution.unmatched_expected_indexes,
-
unmatched_actual_indexes + derived_candidate_solution.unmatched_actual_indexes,
-
# Ignore the indeterminate indexes: by the time we get here,
-
# we've dealt with all indeterminates.
-
[], []
-
)
-
end
-
end
-
-
1
attr_reader :expected_to_actual_matched_indexes, :actual_to_expected_matched_indexes, :solution
-
-
1
def initialize(expected_to_actual_matched_indexes, actual_to_expected_matched_indexes)
-
@expected_to_actual_matched_indexes = expected_to_actual_matched_indexes
-
@actual_to_expected_matched_indexes = actual_to_expected_matched_indexes
-
-
unmatched_expected_indexes, indeterminate_expected_indexes =
-
categorize_indexes(expected_to_actual_matched_indexes, actual_to_expected_matched_indexes)
-
-
unmatched_actual_indexes, indeterminate_actual_indexes =
-
categorize_indexes(actual_to_expected_matched_indexes, expected_to_actual_matched_indexes)
-
-
@solution = Solution.new(unmatched_expected_indexes, unmatched_actual_indexes,
-
indeterminate_expected_indexes, indeterminate_actual_indexes)
-
end
-
-
1
def find_best_solution
-
return solution if solution.candidate?
-
best_solution_so_far = NullSolution
-
-
expected_index = solution.indeterminate_expected_indexes.first
-
actuals = expected_to_actual_matched_indexes[expected_index]
-
-
actuals.each do |actual_index|
-
solution = best_solution_for_pairing(expected_index, actual_index)
-
return solution if solution.ideal?
-
best_solution_so_far = solution if best_solution_so_far.worse_than?(solution)
-
end
-
-
best_solution_so_far
-
end
-
-
1
private
-
-
# @private
-
# Starting solution that is worse than any other real solution.
-
1
NullSolution = Class.new do
-
1
def self.worse_than?(_other)
-
true
-
end
-
end
-
-
1
def categorize_indexes(indexes_to_categorize, other_indexes)
-
unmatched = []
-
indeterminate = []
-
-
indexes_to_categorize.each_pair do |index, matches|
-
if matches.empty?
-
unmatched << index
-
elsif !reciprocal_single_match?(matches, index, other_indexes)
-
indeterminate << index
-
end
-
end
-
-
return unmatched, indeterminate
-
end
-
-
1
def reciprocal_single_match?(matches, index, other_list)
-
return false unless matches.one?
-
other_list[matches.first] == [index]
-
end
-
-
1
def best_solution_for_pairing(expected_index, actual_index)
-
modified_expecteds = apply_pairing_to(
-
solution.indeterminate_expected_indexes,
-
expected_to_actual_matched_indexes, actual_index)
-
-
modified_expecteds.delete(expected_index)
-
-
modified_actuals = apply_pairing_to(
-
solution.indeterminate_actual_indexes,
-
actual_to_expected_matched_indexes, expected_index)
-
-
modified_actuals.delete(actual_index)
-
-
solution + self.class.new(modified_expecteds, modified_actuals).find_best_solution
-
end
-
-
1
def apply_pairing_to(indeterminates, original_matches, other_list_index)
-
indeterminates.inject({}) do |accum, index|
-
accum[index] = original_matches[index] - [other_list_index]
-
accum
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
1
require 'rspec/support'
-
-
1
module RSpec
-
1
module Matchers
-
1
module BuiltIn
-
# @api private
-
# Provides the implementation for operator matchers.
-
# Not intended to be instantiated directly.
-
# Only available for use with `should`.
-
1
class OperatorMatcher
-
1
class << self
-
# @private
-
1
def registry
-
4
@registry ||= {}
-
end
-
-
# @private
-
1
def register(klass, operator, matcher)
-
2
registry[klass] ||= {}
-
2
registry[klass][operator] = matcher
-
end
-
-
# @private
-
1
def unregister(klass, operator)
-
registry[klass] && registry[klass].delete(operator)
-
end
-
-
# @private
-
1
def get(klass, operator)
-
klass.ancestors.each do |ancestor|
-
matcher = registry[ancestor] && registry[ancestor][operator]
-
return matcher if matcher
-
end
-
-
nil
-
end
-
end
-
-
1
register Enumerable, '=~', BuiltIn::ContainExactly
-
-
1
def initialize(actual)
-
@actual = actual
-
end
-
-
# @private
-
1
def self.use_custom_matcher_or_delegate(operator)
-
7
define_method(operator) do |expected|
-
if !has_non_generic_implementation_of?(operator) && (matcher = OperatorMatcher.get(@actual.class, operator))
-
@actual.__send__(::RSpec::Matchers.last_expectation_handler.should_method, matcher.new(expected))
-
else
-
eval_match(@actual, operator, expected)
-
end
-
end
-
-
7
negative_operator = operator.sub(/^=/, '!')
-
7
if negative_operator != operator && respond_to?(negative_operator)
-
2
define_method(negative_operator) do |_expected|
-
opposite_should = ::RSpec::Matchers.last_expectation_handler.opposite_should_method
-
raise "RSpec does not support `#{::RSpec::Matchers.last_expectation_handler.should_method} #{negative_operator} expected`. " \
-
"Use `#{opposite_should} #{operator} expected` instead."
-
end
-
end
-
end
-
-
1
['==', '===', '=~', '>', '>=', '<', '<='].each do |operator|
-
7
use_custom_matcher_or_delegate operator
-
end
-
-
# @private
-
1
def fail_with_message(message)
-
RSpec::Expectations.fail_with(message, @expected, @actual)
-
end
-
-
# @api private
-
# @return [String]
-
1
def description
-
"#{@operator} #{RSpec::Support::ObjectFormatter.format(@expected)}"
-
end
-
-
1
private
-
-
1
def has_non_generic_implementation_of?(op)
-
Support.method_handle_for(@actual, op).owner != ::Kernel
-
rescue NameError
-
false
-
end
-
-
1
def eval_match(actual, operator, expected)
-
::RSpec::Matchers.last_matcher = self
-
@operator, @expected = operator, expected
-
__delegate_operator(actual, operator, expected)
-
end
-
end
-
-
# @private
-
# Handles operator matcher for `should`.
-
1
class PositiveOperatorMatcher < OperatorMatcher
-
1
def __delegate_operator(actual, operator, expected)
-
if actual.__send__(operator, expected)
-
true
-
else
-
expected_formatted = RSpec::Support::ObjectFormatter.format(expected)
-
actual_formatted = RSpec::Support::ObjectFormatter.format(actual)
-
-
if ['==', '===', '=~'].include?(operator)
-
fail_with_message("expected: #{expected_formatted}\n got: #{actual_formatted} (using #{operator})")
-
else
-
fail_with_message("expected: #{operator} #{expected_formatted}\n got: #{operator.gsub(/./, ' ')} #{actual_formatted}")
-
end
-
end
-
end
-
end
-
-
# @private
-
# Handles operator matcher for `should_not`.
-
1
class NegativeOperatorMatcher < OperatorMatcher
-
1
def __delegate_operator(actual, operator, expected)
-
return false unless actual.__send__(operator, expected)
-
-
expected_formatted = RSpec::Support::ObjectFormatter.format(expected)
-
actual_formatted = RSpec::Support::ObjectFormatter.format(actual)
-
-
fail_with_message("expected not: #{operator} #{expected_formatted}\n got: #{operator.gsub(/./, ' ')} #{actual_formatted}")
-
end
-
end
-
end
-
end
-
end
-
2
RSpec::Support.require_rspec_support "fuzzy_matcher"
-
-
2
module RSpec
-
2
module Matchers
-
# Mixin designed to support the composable matcher features
-
# of RSpec 3+. Mix it into your custom matcher classes to
-
# allow them to be used in a composable fashion.
-
#
-
# @api public
-
2
module Composable
-
# Creates a compound `and` expectation. The matcher will
-
# only pass if both sub-matchers pass.
-
# This can be chained together to form an arbitrarily long
-
# chain of matchers.
-
#
-
# @example
-
# expect(alphabet).to start_with("a").and end_with("z")
-
# expect(alphabet).to start_with("a") & end_with("z")
-
#
-
# @note The negative form (`expect(...).not_to matcher.and other`)
-
# is not supported at this time.
-
2
def and(matcher)
-
BuiltIn::Compound::And.new self, matcher
-
end
-
2
alias & and
-
-
# Creates a compound `or` expectation. The matcher will
-
# pass if either sub-matcher passes.
-
# This can be chained together to form an arbitrarily long
-
# chain of matchers.
-
#
-
# @example
-
# expect(stoplight.color).to eq("red").or eq("green").or eq("yellow")
-
# expect(stoplight.color).to eq("red") | eq("green") | eq("yellow")
-
#
-
# @note The negative form (`expect(...).not_to matcher.or other`)
-
# is not supported at this time.
-
2
def or(matcher)
-
BuiltIn::Compound::Or.new self, matcher
-
end
-
2
alias | or
-
-
# Delegates to `#matches?`. Allows matchers to be used in composable
-
# fashion and also supports using matchers in case statements.
-
2
def ===(value)
-
matches?(value)
-
end
-
-
2
private
-
-
# This provides a generic way to fuzzy-match an expected value against
-
# an actual value. It understands nested data structures (e.g. hashes
-
# and arrays) and is able to match against a matcher being used as
-
# the expected value or within the expected value at any level of
-
# nesting.
-
#
-
# Within a custom matcher you are encouraged to use this whenever your
-
# matcher needs to match two values, unless it needs more precise semantics.
-
# For example, the `eq` matcher _does not_ use this as it is meant to
-
# use `==` (and only `==`) for matching.
-
#
-
# @param expected [Object] what is expected
-
# @param actual [Object] the actual value
-
#
-
# @!visibility public
-
2
def values_match?(expected, actual)
-
expected = with_matchers_cloned(expected)
-
Support::FuzzyMatcher.values_match?(expected, actual)
-
end
-
-
# Returns the description of the given object in a way that is
-
# aware of composed matchers. If the object is a matcher with
-
# a `description` method, returns the description; otherwise
-
# returns `object.inspect`.
-
#
-
# You are encouraged to use this in your custom matcher's
-
# `description`, `failure_message` or
-
# `failure_message_when_negated` implementation if you are
-
# supporting matcher arguments.
-
#
-
# @!visibility public
-
2
def description_of(object)
-
RSpec::Support::ObjectFormatter.format(object)
-
end
-
-
# Transforms the given data structue (typically a hash or array)
-
# into a new data structure that, when `#inspect` is called on it,
-
# will provide descriptions of any contained matchers rather than
-
# the normal `#inspect` output.
-
#
-
# You are encouraged to use this in your custom matcher's
-
# `description`, `failure_message` or
-
# `failure_message_when_negated` implementation if you are
-
# supporting any arguments which may be a data structure
-
# containing matchers.
-
#
-
# @!visibility public
-
2
def surface_descriptions_in(item)
-
if Matchers.is_a_describable_matcher?(item)
-
DescribableItem.new(item)
-
elsif Hash === item
-
Hash[surface_descriptions_in(item.to_a)]
-
elsif Struct === item || unreadable_io?(item)
-
RSpec::Support::ObjectFormatter.format(item)
-
elsif should_enumerate?(item)
-
item.map { |subitem| surface_descriptions_in(subitem) }
-
else
-
item
-
end
-
end
-
-
# @private
-
# Historically, a single matcher instance was only checked
-
# against a single value. Given that the matcher was only
-
# used once, it's been common to memoize some intermediate
-
# calculation that is derived from the `actual` value in
-
# order to reuse that intermediate result in the failure
-
# message.
-
#
-
# This can cause a problem when using such a matcher as an
-
# argument to another matcher in a composed matcher expression,
-
# since the matcher instance may be checked against multiple
-
# values and produce invalid results due to the memoization.
-
#
-
# To deal with this, we clone any matchers in `expected` via
-
# this method when using `values_match?`, so that any memoization
-
# does not "leak" between checks.
-
2
def with_matchers_cloned(object)
-
if Matchers.is_a_matcher?(object)
-
object.clone
-
elsif Hash === object
-
Hash[with_matchers_cloned(object.to_a)]
-
elsif Struct === object || unreadable_io?(object)
-
object
-
elsif should_enumerate?(object)
-
object.map { |subobject| with_matchers_cloned(subobject) }
-
else
-
object
-
end
-
end
-
-
2
if String.ancestors.include?(Enumerable) # 1.8.7
-
# :nocov:
-
skipped
# Strings are not enumerable on 1.9, and on 1.8 they are an infinitely
-
skipped
# nested enumerable: since ruby lacks a character class, it yields
-
skipped
# 1-character strings, which are themselves enumerable, composed of a
-
skipped
# a single 1-character string, which is an enumerable, etc.
-
skipped
#
-
skipped
# @api private
-
skipped
def should_enumerate?(item)
-
skipped
return false if String === item
-
skipped
Enumerable === item && !(Range === item) && item.none? { |subitem| subitem.equal?(item) }
-
skipped
end
-
# :nocov:
-
else
-
# @api private
-
2
def should_enumerate?(item)
-
Enumerable === item && !(Range === item) && item.none? { |subitem| subitem.equal?(item) }
-
end
-
end
-
-
# @api private
-
2
def unreadable_io?(object)
-
return false unless IO === object
-
object.each {} # STDOUT is enumerable but raises an error
-
false
-
rescue IOError
-
true
-
end
-
2
module_function :surface_descriptions_in, :should_enumerate?, :unreadable_io?
-
-
# Wraps an item in order to surface its `description` via `inspect`.
-
# @api private
-
2
DescribableItem = Struct.new(:item) do
-
2
def inspect
-
"(#{item.description})"
-
end
-
-
2
def pretty_print(pp)
-
pp.text "(#{item.description})"
-
end
-
end
-
end
-
end
-
end
-
2
module RSpec
-
2
module Matchers
-
# Defines the custom matcher DSL.
-
2
module DSL
-
# Defines a custom matcher.
-
# @see RSpec::Matchers
-
2
def define(name, &declarations)
-
warn_about_block_args(name, declarations)
-
define_method name do |*expected, &block_arg|
-
RSpec::Matchers::DSL::Matcher.new(name, declarations, self, *expected, &block_arg)
-
end
-
end
-
2
alias_method :matcher, :define
-
-
2
private
-
-
2
if Proc.method_defined?(:parameters)
-
2
def warn_about_block_args(name, declarations)
-
declarations.parameters.each do |type, arg_name|
-
next unless type == :block
-
RSpec.warning("Your `#{name}` custom matcher receives a block argument (`#{arg_name}`), " \
-
"but due to limitations in ruby, RSpec cannot provide the block. Instead, " \
-
"use the `block_arg` method to access the block")
-
end
-
end
-
else
-
# :nocov:
-
skipped
def warn_about_block_args(*)
-
skipped
# There's no way to detect block params on 1.8 since the method reflection APIs don't expose it
-
skipped
end
-
# :nocov:
-
end
-
-
4
RSpec.configure { |c| c.extend self } if RSpec.respond_to?(:configure)
-
-
# Contains the methods that are available from within the
-
# `RSpec::Matchers.define` DSL for creating custom matchers.
-
2
module Macros
-
# Stores the block that is used to determine whether this matcher passes
-
# or fails. The block should return a boolean value. When the matcher is
-
# passed to `expect(...).to` and the block returns `true`, then the expectation
-
# passes. Similarly, when the matcher is passed to `expect(...).not_to` and the
-
# block returns `false`, then the expectation passes.
-
#
-
# @example
-
#
-
# RSpec::Matchers.define :be_even do
-
# match do |actual|
-
# actual.even?
-
# end
-
# end
-
#
-
# expect(4).to be_even # passes
-
# expect(3).not_to be_even # passes
-
# expect(3).to be_even # fails
-
# expect(4).not_to be_even # fails
-
#
-
# @yield [Object] actual the actual value (i.e. the value wrapped by `expect`)
-
2
def match(&match_block)
-
define_user_override(:matches?, match_block) do |actual|
-
begin
-
@actual = actual
-
RSpec::Support.with_failure_notifier(RAISE_NOTIFIER) do
-
super(*actual_arg_for(match_block))
-
end
-
rescue RSpec::Expectations::ExpectationNotMetError
-
false
-
end
-
end
-
end
-
-
# @private
-
2
RAISE_NOTIFIER = Proc.new { |err, _opts| raise err }
-
-
# Use this to define the block for a negative expectation (`expect(...).not_to`)
-
# when the positive and negative forms require different handling. This
-
# is rarely necessary, but can be helpful, for example, when specifying
-
# asynchronous processes that require different timeouts.
-
#
-
# @yield [Object] actual the actual value (i.e. the value wrapped by `expect`)
-
2
def match_when_negated(&match_block)
-
define_user_override(:does_not_match?, match_block) do |actual|
-
@actual = actual
-
super(*actual_arg_for(match_block))
-
end
-
end
-
-
# Use this instead of `match` when the block will raise an exception
-
# rather than returning false to indicate a failure.
-
#
-
# @example
-
#
-
# RSpec::Matchers.define :accept_as_valid do |candidate_address|
-
# match_unless_raises ValidationException do |validator|
-
# validator.validate(candidate_address)
-
# end
-
# end
-
#
-
# expect(email_validator).to accept_as_valid("person@company.com")
-
#
-
# @yield [Object] actual the actual object (i.e. the value wrapped by `expect`)
-
2
def match_unless_raises(expected_exception=Exception, &match_block)
-
define_user_override(:matches?, match_block) do |actual|
-
@actual = actual
-
begin
-
super(*actual_arg_for(match_block))
-
rescue expected_exception => @rescued_exception
-
false
-
else
-
true
-
end
-
end
-
end
-
-
# Customizes the failure messsage to use when this matcher is
-
# asked to positively match. Only use this when the message
-
# generated by default doesn't suit your needs.
-
#
-
# @example
-
#
-
# RSpec::Matchers.define :have_strength do |expected|
-
# match { your_match_logic }
-
#
-
# failure_message do |actual|
-
# "Expected strength of #{expected}, but had #{actual.strength}"
-
# end
-
# end
-
#
-
# @yield [Object] actual the actual object (i.e. the value wrapped by `expect`)
-
2
def failure_message(&definition)
-
define_user_override(__method__, definition)
-
end
-
-
# Customize the failure messsage to use when this matcher is asked
-
# to negatively match. Only use this when the message generated by
-
# default doesn't suit your needs.
-
#
-
# @example
-
#
-
# RSpec::Matchers.define :have_strength do |expected|
-
# match { your_match_logic }
-
#
-
# failure_message_when_negated do |actual|
-
# "Expected not to have strength of #{expected}, but did"
-
# end
-
# end
-
#
-
# @yield [Object] actual the actual object (i.e. the value wrapped by `expect`)
-
2
def failure_message_when_negated(&definition)
-
define_user_override(__method__, definition)
-
end
-
-
# Customize the description to use for one-liners. Only use this when
-
# the description generated by default doesn't suit your needs.
-
#
-
# @example
-
#
-
# RSpec::Matchers.define :qualify_for do |expected|
-
# match { your_match_logic }
-
#
-
# description do
-
# "qualify for #{expected}"
-
# end
-
# end
-
#
-
# @yield [Object] actual the actual object (i.e. the value wrapped by `expect`)
-
2
def description(&definition)
-
define_user_override(__method__, definition)
-
end
-
-
# Tells the matcher to diff the actual and expected values in the failure
-
# message.
-
2
def diffable
-
define_method(:diffable?) { true }
-
end
-
-
# Declares that the matcher can be used in a block expectation.
-
# Users will not be able to use your matcher in a block
-
# expectation without declaring this.
-
# (e.g. `expect { do_something }.to matcher`).
-
2
def supports_block_expectations
-
define_method(:supports_block_expectations?) { true }
-
end
-
-
# Convenience for defining methods on this matcher to create a fluent
-
# interface. The trick about fluent interfaces is that each method must
-
# return self in order to chain methods together. `chain` handles that
-
# for you. If the method is invoked and the
-
# `include_chain_clauses_in_custom_matcher_descriptions` config option
-
# hash been enabled, the chained method name and args will be added to the
-
# default description and failure message.
-
#
-
# In the common case where you just want the chained method to store some
-
# value(s) for later use (e.g. in `match`), you can provide one or more
-
# attribute names instead of a block; the chained method will store its
-
# arguments in instance variables with those names, and the values will
-
# be exposed via getters.
-
#
-
# @example
-
#
-
# RSpec::Matchers.define :have_errors_on do |key|
-
# chain :with do |message|
-
# @message = message
-
# end
-
#
-
# match do |actual|
-
# actual.errors[key] == @message
-
# end
-
# end
-
#
-
# expect(minor).to have_errors_on(:age).with("Not old enough to participate")
-
2
def chain(method_name, *attr_names, &definition)
-
unless block_given? ^ attr_names.any?
-
raise ArgumentError, "You must pass either a block or some attribute names (but not both) to `chain`."
-
end
-
-
definition = assign_attributes(attr_names) if attr_names.any?
-
-
define_user_override(method_name, definition) do |*args, &block|
-
super(*args, &block)
-
@chained_method_clauses.push([method_name, args])
-
self
-
end
-
end
-
-
2
def assign_attributes(attr_names)
-
attr_reader(*attr_names)
-
private(*attr_names)
-
-
lambda do |*attr_values|
-
attr_names.zip(attr_values) do |attr_name, attr_value|
-
instance_variable_set(:"@#{attr_name}", attr_value)
-
end
-
end
-
end
-
-
# assign_attributes isn't defined in the private section below because
-
# that makes MRI 1.9.2 emit a warning about private attributes.
-
2
private :assign_attributes
-
-
2
private
-
-
# Does the following:
-
#
-
# - Defines the named method using a user-provided block
-
# in @user_method_defs, which is included as an ancestor
-
# in the singleton class in which we eval the `define` block.
-
# - Defines an overriden definition for the same method
-
# usign the provided `our_def` block.
-
# - Provides a default `our_def` block for the common case
-
# of needing to call the user's definition with `@actual`
-
# as an arg, but only if their block's arity can handle it.
-
#
-
# This compiles the user block into an actual method, allowing
-
# them to use normal method constructs like `return`
-
# (e.g. for a early guard statement), while allowing us to define
-
# an override that can provide the wrapped handling
-
# (e.g. assigning `@actual`, rescueing errors, etc) and
-
# can `super` to the user's definition.
-
2
def define_user_override(method_name, user_def, &our_def)
-
@user_method_defs.__send__(:define_method, method_name, &user_def)
-
our_def ||= lambda { super(*actual_arg_for(user_def)) }
-
define_method(method_name, &our_def)
-
end
-
-
# Defines deprecated macro methods from RSpec 2 for backwards compatibility.
-
# @deprecated Use the methods from {Macros} instead.
-
2
module Deprecated
-
# @deprecated Use {Macros#match} instead.
-
2
def match_for_should(&definition)
-
RSpec.deprecate("`match_for_should`", :replacement => "`match`")
-
match(&definition)
-
end
-
-
# @deprecated Use {Macros#match_when_negated} instead.
-
2
def match_for_should_not(&definition)
-
RSpec.deprecate("`match_for_should_not`", :replacement => "`match_when_negated`")
-
match_when_negated(&definition)
-
end
-
-
# @deprecated Use {Macros#failure_message} instead.
-
2
def failure_message_for_should(&definition)
-
RSpec.deprecate("`failure_message_for_should`", :replacement => "`failure_message`")
-
failure_message(&definition)
-
end
-
-
# @deprecated Use {Macros#failure_message_when_negated} instead.
-
2
def failure_message_for_should_not(&definition)
-
RSpec.deprecate("`failure_message_for_should_not`", :replacement => "`failure_message_when_negated`")
-
failure_message_when_negated(&definition)
-
end
-
end
-
end
-
-
# Defines default implementations of the matcher
-
# protocol methods for custom matchers. You can
-
# override any of these using the {RSpec::Matchers::DSL::Macros Macros} methods
-
# from within an `RSpec::Matchers.define` block.
-
2
module DefaultImplementations
-
2
include BuiltIn::BaseMatcher::DefaultFailureMessages
-
-
# @api private
-
# Used internally by objects returns by `should` and `should_not`.
-
2
def diffable?
-
false
-
end
-
-
# The default description.
-
2
def description
-
english_name = EnglishPhrasing.split_words(name)
-
expected_list = EnglishPhrasing.list(expected)
-
"#{english_name}#{expected_list}#{chained_method_clause_sentences}"
-
end
-
-
# Matchers do not support block expectations by default. You
-
# must opt-in.
-
2
def supports_block_expectations?
-
false
-
end
-
-
# Most matchers do not expect call stack jumps.
-
2
def expects_call_stack_jump?
-
false
-
end
-
-
2
private
-
-
2
def chained_method_clause_sentences
-
return '' unless Expectations.configuration.include_chain_clauses_in_custom_matcher_descriptions?
-
-
@chained_method_clauses.map do |(method_name, method_args)|
-
english_name = EnglishPhrasing.split_words(method_name)
-
arg_list = EnglishPhrasing.list(method_args)
-
" #{english_name}#{arg_list}"
-
end.join
-
end
-
end
-
-
# The class used for custom matchers. The block passed to
-
# `RSpec::Matchers.define` will be evaluated in the context
-
# of the singleton class of an instance, and will have the
-
# {RSpec::Matchers::DSL::Macros Macros} methods available.
-
2
class Matcher
-
# Provides default implementations for the matcher protocol methods.
-
2
include DefaultImplementations
-
-
# Allows expectation expressions to be used in the match block.
-
2
include RSpec::Matchers
-
-
# Supports the matcher composability features of RSpec 3+.
-
2
include Composable
-
-
# Makes the macro methods available to an `RSpec::Matchers.define` block.
-
2
extend Macros
-
2
extend Macros::Deprecated
-
-
# Exposes the value being matched against -- generally the object
-
# object wrapped by `expect`.
-
2
attr_reader :actual
-
-
# Exposes the exception raised during the matching by `match_unless_raises`.
-
# Could be useful to extract details for a failure message.
-
2
attr_reader :rescued_exception
-
-
# The block parameter used in the expectation
-
2
attr_reader :block_arg
-
-
# The name of the matcher.
-
2
attr_reader :name
-
-
# @api private
-
2
def initialize(name, declarations, matcher_execution_context, *expected, &block_arg)
-
@name = name
-
@actual = nil
-
@expected_as_array = expected
-
@matcher_execution_context = matcher_execution_context
-
@chained_method_clauses = []
-
@block_arg = block_arg
-
-
class << self
-
# See `Macros#define_user_override` above, for an explanation.
-
include(@user_method_defs = Module.new)
-
self
-
end.class_exec(*expected, &declarations)
-
end
-
-
# Provides the expected value. This will return an array if
-
# multiple arguments were passed to the matcher; otherwise it
-
# will return a single value.
-
# @see #expected_as_array
-
2
def expected
-
if expected_as_array.size == 1
-
expected_as_array[0]
-
else
-
expected_as_array
-
end
-
end
-
-
# Returns the expected value as an an array. This exists primarily
-
# to aid in upgrading from RSpec 2.x, since in RSpec 2, `expected`
-
# always returned an array.
-
# @see #expected
-
2
attr_reader :expected_as_array
-
-
# Adds the name (rather than a cryptic hex number)
-
# so we can identify an instance of
-
# the matcher in error messages (e.g. for `NoMethodError`)
-
2
def inspect
-
"#<#{self.class.name} #{name}>"
-
end
-
-
2
if RUBY_VERSION.to_f >= 1.9
-
# Indicates that this matcher responds to messages
-
# from the `@matcher_execution_context` as well.
-
# Also, supports getting a method object for such methods.
-
2
def respond_to_missing?(method, include_private=false)
-
super || @matcher_execution_context.respond_to?(method, include_private)
-
end
-
else # for 1.8.7
-
# :nocov:
-
skipped
# Indicates that this matcher responds to messages
-
skipped
# from the `@matcher_execution_context` as well.
-
skipped
def respond_to?(method, include_private=false)
-
skipped
super || @matcher_execution_context.respond_to?(method, include_private)
-
skipped
end
-
# :nocov:
-
end
-
-
2
private
-
-
2
def actual_arg_for(block)
-
block.arity.zero? ? [] : [@actual]
-
end
-
-
# Takes care of forwarding unhandled messages to the
-
# `@matcher_execution_context` (typically the current
-
# running `RSpec::Core::Example`). This is needed by
-
# rspec-rails so that it can define matchers that wrap
-
# Rails' test helper methods, but it's also a useful
-
# feature in its own right.
-
2
def method_missing(method, *args, &block)
-
if @matcher_execution_context.respond_to?(method)
-
@matcher_execution_context.__send__ method, *args, &block
-
else
-
super(method, *args, &block)
-
end
-
end
-
end
-
end
-
end
-
end
-
-
2
RSpec::Matchers.extend RSpec::Matchers::DSL
-
2
module RSpec
-
2
module Matchers
-
# Facilitates converting ruby objects to English phrases.
-
2
module EnglishPhrasing
-
# Converts a symbol into an English expression.
-
#
-
# split_words(:banana_creme_pie) #=> "banana creme pie"
-
#
-
2
def self.split_words(sym)
-
sym.to_s.gsub(/_/, ' ')
-
end
-
-
# @note The returned string has a leading space except
-
# when given an empty list.
-
#
-
# Converts an object (often a collection of objects)
-
# into an English list.
-
#
-
# list(['banana', 'kiwi', 'mango'])
-
# #=> " \"banana\", \"kiwi\", and \"mango\""
-
#
-
# Given an empty collection, returns the empty string.
-
#
-
# list([]) #=> ""
-
#
-
2
def self.list(obj)
-
return " #{RSpec::Support::ObjectFormatter.format(obj)}" if !obj || Struct === obj
-
items = Array(obj).map { |w| RSpec::Support::ObjectFormatter.format(w) }
-
case items.length
-
when 0
-
""
-
when 1
-
" #{items[0]}"
-
when 2
-
" #{items[0]} and #{items[1]}"
-
else
-
" #{items[0...-1].join(', ')}, and #{items[-1]}"
-
end
-
end
-
end
-
end
-
end
-
2
module RSpec
-
2
module Matchers
-
# @api private
-
# Handles list of expected values when there is a need to render
-
# multiple diffs. Also can handle one value.
-
2
class ExpectedsForMultipleDiffs
-
# @private
-
# Default diff label when there is only one matcher in diff
-
# output
-
2
DEFAULT_DIFF_LABEL = "Diff:".freeze
-
-
# @private
-
# Maximum readable matcher description length
-
2
DESCRIPTION_MAX_LENGTH = 65
-
-
2
def initialize(expected_list)
-
@expected_list = expected_list
-
end
-
-
# @api private
-
# Wraps provided expected value in instance of
-
# ExpectedForMultipleDiffs. If provided value is already an
-
# ExpectedForMultipleDiffs then it just returns it.
-
# @param [Any] expected value to be wrapped
-
# @return [RSpec::Matchers::ExpectedsForMultipleDiffs]
-
2
def self.from(expected)
-
return expected if self === expected
-
new([[expected, DEFAULT_DIFF_LABEL]])
-
end
-
-
# @api private
-
# Wraps provided matcher list in instance of
-
# ExpectedForMultipleDiffs.
-
# @param [Array<Any>] matchers list of matchers to wrap
-
# @return [RSpec::Matchers::ExpectedsForMultipleDiffs]
-
2
def self.for_many_matchers(matchers)
-
new(matchers.map { |m| [m.expected, diff_label_for(m)] })
-
end
-
-
# @api private
-
# Returns message with diff(s) appended for provided differ
-
# factory and actual value if there are any
-
# @param [String] message original failure message
-
# @param [Proc] differ
-
# @param [Any] actual value
-
# @return [String]
-
2
def message_with_diff(message, differ, actual)
-
diff = diffs(differ, actual)
-
message = "#{message}\n#{diff}" unless diff.empty?
-
message
-
end
-
-
2
private
-
-
2
def self.diff_label_for(matcher)
-
"Diff for (#{truncated(RSpec::Support::ObjectFormatter.format(matcher))}):"
-
end
-
-
2
def self.truncated(description)
-
return description if description.length <= DESCRIPTION_MAX_LENGTH
-
description[0...DESCRIPTION_MAX_LENGTH - 3] << "..."
-
end
-
-
2
def diffs(differ, actual)
-
@expected_list.map do |(expected, diff_label)|
-
diff = differ.diff(actual, expected)
-
next if diff.strip.empty?
-
"#{diff_label}#{diff}"
-
end.compact.join("\n")
-
end
-
end
-
end
-
end
-
2
module RSpec
-
2
module Matchers
-
2
class << self
-
# @private
-
2
attr_accessor :last_matcher, :last_expectation_handler
-
end
-
-
# @api private
-
# Used by rspec-core to clear the state used to generate
-
# descriptions after an example.
-
2
def self.clear_generated_description
-
21
self.last_matcher = nil
-
21
self.last_expectation_handler = nil
-
end
-
-
# @api private
-
# Generates an an example description based on the last expectation.
-
# Used by rspec-core's one-liner syntax.
-
2
def self.generated_description
-
return nil if last_expectation_handler.nil?
-
"#{last_expectation_handler.verb} #{last_description}"
-
end
-
-
2
private
-
-
2
def self.last_description
-
last_matcher.respond_to?(:description) ? last_matcher.description : <<-MESSAGE
-
When you call a matcher in an example without a String, like this:
-
-
specify { expect(object).to matcher }
-
-
or this:
-
-
it { is_expected.to matcher }
-
-
RSpec expects the matcher to have a #description method. You should either
-
add a String to the example this matcher is being used in, or give it a
-
description method. Then you won't have to suffer this lengthy warning again.
-
MESSAGE
-
end
-
end
-
end
-
2
module RSpec
-
2
module Matchers
-
# Provides the necessary plumbing to wrap a matcher with a decorator.
-
# @private
-
2
class MatcherDelegator
-
2
include Composable
-
2
attr_reader :base_matcher
-
-
2
def initialize(base_matcher)
-
@base_matcher = base_matcher
-
end
-
-
2
def method_missing(*args, &block)
-
base_matcher.__send__(*args, &block)
-
end
-
-
2
if ::RUBY_VERSION.to_f > 1.8
-
2
def respond_to_missing?(name, include_all=false)
-
super || base_matcher.respond_to?(name, include_all)
-
end
-
else
-
# :nocov:
-
skipped
def respond_to?(name, include_all=false)
-
skipped
super || base_matcher.respond_to?(name, include_all)
-
skipped
end
-
# :nocov:
-
end
-
-
2
def initialize_copy(other)
-
@base_matcher = @base_matcher.clone
-
super
-
end
-
end
-
end
-
end
-
1
require 'rspec/support'
-
1
RSpec::Support.require_rspec_support 'caller_filter'
-
1
RSpec::Support.require_rspec_support 'warnings'
-
1
RSpec::Support.require_rspec_support 'ruby_features'
-
-
22
RSpec::Support.define_optimized_require_for_rspec(:mocks) { |f| require_relative f }
-
-
%w[
-
instance_method_stasher
-
method_double
-
argument_matchers
-
example_methods
-
proxy
-
test_double
-
argument_list_matcher
-
message_expectation
-
order_group
-
error_generator
-
space
-
mutate_const
-
targets
-
syntax
-
configuration
-
verifying_double
-
version
-
18
].each { |name| RSpec::Support.require_rspec_mocks name }
-
-
# Share the top-level RSpec namespace, because we are a core supported
-
# extension.
-
1
module RSpec
-
# Contains top-level utility methods. While this contains a few
-
# public methods, these are not generally meant to be called from
-
# a test or example. They exist primarily for integration with
-
# test frameworks (such as rspec-core).
-
1
module Mocks
-
# Performs per-test/example setup. This should be called before
-
# an test or example begins.
-
1
def self.setup
-
21
@space_stack << (@space = space.new_scope)
-
end
-
-
# Verifies any message expectations that were set during the
-
# test or example. This should be called at the end of an example.
-
1
def self.verify
-
21
space.verify_all
-
end
-
-
# Cleans up all test double state (including any methods that were
-
# redefined on partial doubles). This _must_ be called after
-
# each example, even if an error was raised during the example.
-
1
def self.teardown
-
21
space.reset_all
-
21
@space_stack.pop
-
21
@space = @space_stack.last || @root_space
-
end
-
-
# Adds an allowance (stub) on `subject`
-
#
-
# @param subject the subject to which the message will be added
-
# @param message a symbol, representing the message that will be
-
# added.
-
# @param opts a hash of options, :expected_from is used to set the
-
# original call site
-
# @yield an optional implementation for the allowance
-
#
-
# @example Defines the implementation of `foo` on `bar`, using the passed block
-
# x = 0
-
# RSpec::Mocks.allow_message(bar, :foo) { x += 1 }
-
1
def self.allow_message(subject, message, opts={}, &block)
-
space.proxy_for(subject).add_stub(message, opts, &block)
-
end
-
-
# Sets a message expectation on `subject`.
-
# @param subject the subject on which the message will be expected
-
# @param message a symbol, representing the message that will be
-
# expected.
-
# @param opts a hash of options, :expected_from is used to set the
-
# original call site
-
# @yield an optional implementation for the expectation
-
#
-
# @example Expect the message `foo` to receive `bar`, then call it
-
# RSpec::Mocks.expect_message(bar, :foo)
-
# bar.foo
-
1
def self.expect_message(subject, message, opts={}, &block)
-
space.proxy_for(subject).add_message_expectation(message, opts, &block)
-
end
-
-
# Call the passed block and verify mocks after it has executed. This allows
-
# mock usage in arbitrary places, such as a `before(:all)` hook.
-
1
def self.with_temporary_scope
-
setup
-
-
begin
-
yield
-
verify
-
ensure
-
teardown
-
end
-
end
-
-
1
class << self
-
# @private
-
1
attr_reader :space
-
end
-
1
@space_stack = []
-
1
@root_space = @space = RSpec::Mocks::RootSpace.new
-
-
# @private
-
1
IGNORED_BACKTRACE_LINE = 'this backtrace line is ignored'
-
-
# To speed up boot time a bit, delay loading optional or rarely
-
# used features until their first use.
-
1
autoload :AnyInstance, "rspec/mocks/any_instance"
-
1
autoload :ExpectChain, "rspec/mocks/message_chain"
-
1
autoload :StubChain, "rspec/mocks/message_chain"
-
1
autoload :MarshalExtension, "rspec/mocks/marshal_extension"
-
-
# Namespace for mock-related matchers.
-
1
module Matchers
-
1
autoload :HaveReceived, "rspec/mocks/matchers/have_received"
-
1
autoload :Receive, "rspec/mocks/matchers/receive"
-
1
autoload :ReceiveMessageChain, "rspec/mocks/matchers/receive_message_chain"
-
1
autoload :ReceiveMessages, "rspec/mocks/matchers/receive_messages"
-
end
-
end
-
end
-
# We intentionally do not use the `RSpec::Support.require...` methods
-
# here so that this file can be loaded individually, as documented
-
# below.
-
1
require 'rspec/mocks/argument_matchers'
-
1
require 'rspec/support/fuzzy_matcher'
-
-
1
module RSpec
-
1
module Mocks
-
# Wrapper for matching arguments against a list of expected values. Used by
-
# the `with` method on a `MessageExpectation`:
-
#
-
# expect(object).to receive(:message).with(:a, 'b', 3)
-
# object.message(:a, 'b', 3)
-
#
-
# Values passed to `with` can be literal values or argument matchers that
-
# match against the real objects .e.g.
-
#
-
# expect(object).to receive(:message).with(hash_including(:a => 'b'))
-
#
-
# Can also be used directly to match the contents of any `Array`. This
-
# enables 3rd party mocking libs to take advantage of rspec's argument
-
# matching without using the rest of rspec-mocks.
-
#
-
# require 'rspec/mocks/argument_list_matcher'
-
# include RSpec::Mocks::ArgumentMatchers
-
#
-
# arg_list_matcher = RSpec::Mocks::ArgumentListMatcher.new(123, hash_including(:a => 'b'))
-
# arg_list_matcher.args_match?(123, :a => 'b')
-
#
-
# This class is immutable.
-
#
-
# @see ArgumentMatchers
-
1
class ArgumentListMatcher
-
# @private
-
1
attr_reader :expected_args
-
-
# @api public
-
# @param [Array] expected_args a list of expected literals and/or argument matchers
-
#
-
# Initializes an `ArgumentListMatcher` with a collection of literal
-
# values and/or argument matchers.
-
#
-
# @see ArgumentMatchers
-
# @see #args_match?
-
1
def initialize(*expected_args)
-
1
@expected_args = expected_args
-
1
ensure_expected_args_valid!
-
end
-
-
# @api public
-
# @param [Array] args
-
#
-
# Matches each element in the `expected_args` against the element in the same
-
# position of the arguments passed to `new`.
-
#
-
# @see #initialize
-
1
def args_match?(*args)
-
Support::FuzzyMatcher.values_match?(resolve_expected_args_based_on(args), args)
-
end
-
-
# @private
-
# Resolves abstract arg placeholders like `no_args` and `any_args` into
-
# a more concrete arg list based on the provided `actual_args`.
-
1
def resolve_expected_args_based_on(actual_args)
-
return [] if [ArgumentMatchers::NoArgsMatcher::INSTANCE] == expected_args
-
-
any_args_index = expected_args.index { |a| ArgumentMatchers::AnyArgsMatcher::INSTANCE == a }
-
return expected_args unless any_args_index
-
-
replace_any_args_with_splat_of_anything(any_args_index, actual_args.count)
-
end
-
-
1
private
-
-
1
def replace_any_args_with_splat_of_anything(before_count, actual_args_count)
-
any_args_count = actual_args_count - expected_args.count + 1
-
after_count = expected_args.count - before_count - 1
-
-
any_args = 1.upto(any_args_count).map { ArgumentMatchers::AnyArgMatcher::INSTANCE }
-
expected_args.first(before_count) + any_args + expected_args.last(after_count)
-
end
-
-
1
def ensure_expected_args_valid!
-
2
if expected_args.count { |a| ArgumentMatchers::AnyArgsMatcher::INSTANCE == a } > 1
-
raise ArgumentError, "`any_args` can only be passed to " \
-
"`with` once but you have passed it multiple times."
-
1
elsif expected_args.count > 1 && expected_args.any? { |a| ArgumentMatchers::NoArgsMatcher::INSTANCE == a }
-
raise ArgumentError, "`no_args` can only be passed as a " \
-
"singleton argument to `with` (i.e. `with(no_args)`), " \
-
"but you have passed additional arguments."
-
end
-
end
-
-
# Value that will match all argument lists.
-
#
-
# @private
-
1
MATCH_ALL = new(ArgumentMatchers::AnyArgsMatcher::INSTANCE)
-
end
-
end
-
end
-
# This cannot take advantage of our relative requires, since this file is a
-
# dependency of `rspec/mocks/argument_list_matcher.rb`. See comment there for
-
# details.
-
1
require 'rspec/support/matcher_definition'
-
-
1
module RSpec
-
1
module Mocks
-
# ArgumentMatchers are placeholders that you can include in message
-
# expectations to match arguments against a broader check than simple
-
# equality.
-
#
-
# With the exception of `any_args` and `no_args`, they all match against
-
# the arg in same position in the argument list.
-
#
-
# @see ArgumentListMatcher
-
1
module ArgumentMatchers
-
# Acts like an arg splat, matching any number of args at any point in an arg list.
-
#
-
# @example
-
# expect(object).to receive(:message).with(1, 2, any_args)
-
#
-
# # matches any of these:
-
# object.message(1, 2)
-
# object.message(1, 2, 3)
-
# object.message(1, 2, 3, 4)
-
1
def any_args
-
AnyArgsMatcher::INSTANCE
-
end
-
-
# Matches any argument at all.
-
#
-
# @example
-
# expect(object).to receive(:message).with(anything)
-
1
def anything
-
AnyArgMatcher::INSTANCE
-
end
-
-
# Matches no arguments.
-
#
-
# @example
-
# expect(object).to receive(:message).with(no_args)
-
1
def no_args
-
NoArgsMatcher::INSTANCE
-
end
-
-
# Matches if the actual argument responds to the specified messages.
-
#
-
# @example
-
# expect(object).to receive(:message).with(duck_type(:hello))
-
# expect(object).to receive(:message).with(duck_type(:hello, :goodbye))
-
1
def duck_type(*args)
-
DuckTypeMatcher.new(*args)
-
end
-
-
# Matches a boolean value.
-
#
-
# @example
-
# expect(object).to receive(:message).with(boolean())
-
1
def boolean
-
BooleanMatcher::INSTANCE
-
end
-
-
# Matches a hash that includes the specified key(s) or key/value pairs.
-
# Ignores any additional keys.
-
#
-
# @example
-
# expect(object).to receive(:message).with(hash_including(:key => val))
-
# expect(object).to receive(:message).with(hash_including(:key))
-
# expect(object).to receive(:message).with(hash_including(:key, :key2 => val2))
-
1
def hash_including(*args)
-
HashIncludingMatcher.new(ArgumentMatchers.anythingize_lonely_keys(*args))
-
end
-
-
# Matches an array that includes the specified items at least once.
-
# Ignores duplicates and additional values
-
#
-
# @example
-
# expect(object).to receive(:message).with(array_including(1,2,3))
-
# expect(object).to receive(:message).with(array_including([1,2,3]))
-
1
def array_including(*args)
-
actually_an_array = Array === args.first && args.count == 1 ? args.first : args
-
ArrayIncludingMatcher.new(actually_an_array)
-
end
-
-
# Matches a hash that doesn't include the specified key(s) or key/value.
-
#
-
# @example
-
# expect(object).to receive(:message).with(hash_excluding(:key => val))
-
# expect(object).to receive(:message).with(hash_excluding(:key))
-
# expect(object).to receive(:message).with(hash_excluding(:key, :key2 => :val2))
-
1
def hash_excluding(*args)
-
HashExcludingMatcher.new(ArgumentMatchers.anythingize_lonely_keys(*args))
-
end
-
-
1
alias_method :hash_not_including, :hash_excluding
-
-
# Matches if `arg.instance_of?(klass)`
-
#
-
# @example
-
# expect(object).to receive(:message).with(instance_of(Thing))
-
1
def instance_of(klass)
-
InstanceOf.new(klass)
-
end
-
-
1
alias_method :an_instance_of, :instance_of
-
-
# Matches if `arg.kind_of?(klass)`
-
#
-
# @example
-
# expect(object).to receive(:message).with(kind_of(Thing))
-
1
def kind_of(klass)
-
KindOf.new(klass)
-
end
-
-
1
alias_method :a_kind_of, :kind_of
-
-
# @private
-
1
def self.anythingize_lonely_keys(*args)
-
hash = args.last.class == Hash ? args.delete_at(-1) : {}
-
args.each { | arg | hash[arg] = AnyArgMatcher::INSTANCE }
-
hash
-
end
-
-
# Intended to be subclassed by stateless, immutable argument matchers.
-
# Provides a `<klass name>::INSTANCE` constant for accessing a global
-
# singleton instance of the matcher. There is no need to construct
-
# multiple instance since there is no state. It also facilities the
-
# special case logic we need for some of these matchers, by making it
-
# easy to do comparisons like: `[klass::INSTANCE] == args` rather than
-
# `args.count == 1 && klass === args.first`.
-
#
-
# @private
-
1
class SingletonMatcher
-
1
private_class_method :new
-
-
1
def self.inherited(subklass)
-
4
subklass.const_set(:INSTANCE, subklass.send(:new))
-
end
-
end
-
-
# @private
-
1
class AnyArgsMatcher < SingletonMatcher
-
1
def description
-
"*(any args)"
-
end
-
end
-
-
# @private
-
1
class AnyArgMatcher < SingletonMatcher
-
1
def ===(_other)
-
true
-
end
-
-
1
def description
-
"anything"
-
end
-
end
-
-
# @private
-
1
class NoArgsMatcher < SingletonMatcher
-
1
def description
-
"no args"
-
end
-
end
-
-
# @private
-
1
class BooleanMatcher < SingletonMatcher
-
1
def ===(value)
-
true == value || false == value
-
end
-
-
1
def description
-
"boolean"
-
end
-
end
-
-
# @private
-
1
class BaseHashMatcher
-
1
def initialize(expected)
-
@expected = expected
-
end
-
-
1
def ===(predicate, actual)
-
@expected.__send__(predicate) do |k, v|
-
actual.key?(k) && Support::FuzzyMatcher.values_match?(v, actual[k])
-
end
-
rescue NoMethodError
-
false
-
end
-
-
1
def description(name)
-
"#{name}(#{formatted_expected_hash.inspect.sub(/^\{/, "").sub(/\}$/, "")})"
-
end
-
-
1
private
-
-
1
def formatted_expected_hash
-
Hash[
-
@expected.map do |k, v|
-
k = RSpec::Support.rspec_description_for_object(k)
-
v = RSpec::Support.rspec_description_for_object(v)
-
-
[k, v]
-
end
-
]
-
end
-
end
-
-
# @private
-
1
class HashIncludingMatcher < BaseHashMatcher
-
1
def ===(actual)
-
super(:all?, actual)
-
end
-
-
1
def description
-
super("hash_including")
-
end
-
end
-
-
# @private
-
1
class HashExcludingMatcher < BaseHashMatcher
-
1
def ===(actual)
-
super(:none?, actual)
-
end
-
-
1
def description
-
super("hash_not_including")
-
end
-
end
-
-
# @private
-
1
class ArrayIncludingMatcher
-
1
def initialize(expected)
-
@expected = expected
-
end
-
-
1
def ===(actual)
-
actual = actual.uniq
-
@expected.uniq.all? do |expected_element|
-
actual.any? do |actual_element|
-
RSpec::Support::FuzzyMatcher.values_match?(expected_element, actual_element)
-
end
-
end
-
end
-
-
1
def description
-
"array_including(#{formatted_expected_values})"
-
end
-
-
1
private
-
-
1
def formatted_expected_values
-
@expected.map do |x|
-
RSpec::Support.rspec_description_for_object(x)
-
end.join(", ")
-
end
-
end
-
-
# @private
-
1
class DuckTypeMatcher
-
1
def initialize(*methods_to_respond_to)
-
@methods_to_respond_to = methods_to_respond_to
-
end
-
-
1
def ===(value)
-
@methods_to_respond_to.all? { |message| value.respond_to?(message) }
-
end
-
-
1
def description
-
"duck_type(#{@methods_to_respond_to.map(&:inspect).join(', ')})"
-
end
-
end
-
-
# @private
-
1
class InstanceOf
-
1
def initialize(klass)
-
@klass = klass
-
end
-
-
1
def ===(actual)
-
actual.instance_of?(@klass)
-
end
-
-
1
def description
-
"an_instance_of(#{@klass.name})"
-
end
-
end
-
-
# @private
-
1
class KindOf
-
1
def initialize(klass)
-
@klass = klass
-
end
-
-
1
def ===(actual)
-
actual.kind_of?(@klass)
-
end
-
-
1
def description
-
"kind of #{@klass.name}"
-
end
-
end
-
-
1
matcher_namespace = name + '::'
-
1
::RSpec::Support.register_matcher_definition do |object|
-
# This is the best we have for now. We should tag all of our matchers
-
# with a module or something so we can test for it directly.
-
#
-
# (Note Module#parent in ActiveSupport is defined in a similar way.)
-
begin
-
object.class.name.include?(matcher_namespace)
-
rescue NoMethodError
-
# Some objects, like BasicObject, don't implemented standard
-
# reflection methods.
-
false
-
end
-
end
-
end
-
end
-
end
-
1
module RSpec
-
1
module Mocks
-
# Provides configuration options for rspec-mocks.
-
1
class Configuration
-
1
def initialize
-
1
@allow_message_expectations_on_nil = nil
-
1
@yield_receiver_to_any_instance_implementation_blocks = true
-
1
@verify_doubled_constant_names = false
-
1
@transfer_nested_constants = false
-
1
@verify_partial_doubles = false
-
end
-
-
# Sets whether RSpec will warn, ignore, or fail a test when
-
# expectations are set on nil.
-
# By default, when this flag is not set, warning messages are issued when
-
# expectations are set on nil. This is to prevent false-positives and to
-
# catch potential bugs early on.
-
# When set to `true`, warning messages are suppressed.
-
# When set to `false`, it will raise an error.
-
#
-
# @example
-
# RSpec.configure do |config|
-
# config.mock_with :rspec do |mocks|
-
# mocks.allow_message_expectations_on_nil = false
-
# end
-
# end
-
1
attr_accessor :allow_message_expectations_on_nil
-
-
1
def yield_receiver_to_any_instance_implementation_blocks?
-
@yield_receiver_to_any_instance_implementation_blocks
-
end
-
-
# Sets whether or not RSpec will yield the receiving instance of a
-
# message to blocks that are used for any_instance stub implementations.
-
# When set, the first yielded argument will be the receiving instance.
-
# Defaults to `true`.
-
#
-
# @example
-
# RSpec.configure do |rspec|
-
# rspec.mock_with :rspec do |mocks|
-
# mocks.yield_receiver_to_any_instance_implementation_blocks = false
-
# end
-
# end
-
1
attr_writer :yield_receiver_to_any_instance_implementation_blocks
-
-
# Adds `stub` and `should_receive` to the given
-
# modules or classes. This is usually only necessary
-
# if you application uses some proxy classes that
-
# "strip themselves down" to a bare minimum set of
-
# methods and remove `stub` and `should_receive` in
-
# the process.
-
#
-
# @example
-
# RSpec.configure do |rspec|
-
# rspec.mock_with :rspec do |mocks|
-
# mocks.add_stub_and_should_receive_to Delegator
-
# end
-
# end
-
#
-
1
def add_stub_and_should_receive_to(*modules)
-
modules.each do |mod|
-
Syntax.enable_should(mod)
-
end
-
end
-
-
# Provides the ability to set either `expect`,
-
# `should` or both syntaxes. RSpec uses `expect`
-
# syntax by default. This is needed if you want to
-
# explicitly enable `should` syntax and/or explicitly
-
# disable `expect` syntax.
-
#
-
# @example
-
# RSpec.configure do |rspec|
-
# rspec.mock_with :rspec do |mocks|
-
# mocks.syntax = [:expect, :should]
-
# end
-
# end
-
#
-
1
def syntax=(*values)
-
1
syntaxes = values.flatten
-
1
if syntaxes.include?(:expect)
-
1
Syntax.enable_expect
-
else
-
Syntax.disable_expect
-
end
-
-
1
if syntaxes.include?(:should)
-
1
Syntax.enable_should
-
else
-
Syntax.disable_should
-
end
-
end
-
-
# Returns an array with a list of syntaxes
-
# that are enabled.
-
#
-
# @example
-
# unless RSpec::Mocks.configuration.syntax.include?(:expect)
-
# raise "this RSpec extension gem requires the rspec-mocks `:expect` syntax"
-
# end
-
#
-
1
def syntax
-
syntaxes = []
-
syntaxes << :should if Syntax.should_enabled?
-
syntaxes << :expect if Syntax.expect_enabled?
-
syntaxes
-
end
-
-
1
def verify_doubled_constant_names?
-
!!@verify_doubled_constant_names
-
end
-
-
# When this is set to true, an error will be raised when
-
# `instance_double` or `class_double` is given the name of an undefined
-
# constant. You probably only want to set this when running your entire
-
# test suite, with all production code loaded. Setting this for an
-
# isolated unit test will prevent you from being able to isolate it!
-
1
attr_writer :verify_doubled_constant_names
-
-
# Provides a way to perform customisations when verifying doubles.
-
#
-
# @example
-
# RSpec::Mocks.configuration.before_verifying_doubles do |ref|
-
# ref.some_method!
-
# end
-
1
def before_verifying_doubles(&block)
-
1
verifying_double_callbacks << block
-
end
-
1
alias :when_declaring_verifying_double :before_verifying_doubles
-
-
# @api private
-
# Returns an array of blocks to call when verifying doubles
-
1
def verifying_double_callbacks
-
1
@verifying_double_callbacks ||= []
-
end
-
-
1
def transfer_nested_constants?
-
!!@transfer_nested_constants
-
end
-
-
# Sets the default for the `transfer_nested_constants` option when
-
# stubbing constants.
-
1
attr_writer :transfer_nested_constants
-
-
# When set to true, partial mocks will be verified the same as object
-
# doubles. Any stubs will have their arguments checked against the original
-
# method, and methods that do not exist cannot be stubbed.
-
1
def verify_partial_doubles=(val)
-
@verify_partial_doubles = !!val
-
end
-
-
1
def verify_partial_doubles?
-
@verify_partial_doubles
-
end
-
-
1
if ::RSpec.respond_to?(:configuration)
-
1
def color?
-
::RSpec.configuration.color_enabled?
-
end
-
else
-
# Indicates whether or not diffs should be colored.
-
# Delegates to rspec-core's color option if rspec-core
-
# is loaded; otherwise you can set it here.
-
attr_writer :color
-
-
# Indicates whether or not diffs should be colored.
-
# Delegates to rspec-core's color option if rspec-core
-
# is loaded; otherwise you can set it here.
-
def color?
-
@color
-
end
-
end
-
-
# Monkey-patch `Marshal.dump` to enable dumping of mocked or stubbed
-
# objects. By default this will not work since RSpec mocks works by
-
# adding singleton methods that cannot be serialized. This patch removes
-
# these singleton methods before serialization. Setting to falsey removes
-
# the patch.
-
#
-
# This method is idempotent.
-
1
def patch_marshal_to_support_partial_doubles=(val)
-
if val
-
RSpec::Mocks::MarshalExtension.patch!
-
else
-
RSpec::Mocks::MarshalExtension.unpatch!
-
end
-
end
-
-
# @api private
-
# Resets the configured syntax to the default.
-
1
def reset_syntaxes_to_default
-
1
self.syntax = [:should, :expect]
-
1
RSpec::Mocks::Syntax.warn_about_should!
-
end
-
end
-
-
# Mocks specific configuration, as distinct from `RSpec.configuration`
-
# which is core RSpec configuration.
-
1
def self.configuration
-
2
@configuration ||= Configuration.new
-
end
-
-
1
configuration.reset_syntaxes_to_default
-
end
-
end
-
1
RSpec::Support.require_rspec_support "object_formatter"
-
-
1
module RSpec
-
1
module Mocks
-
# Raised when a message expectation is not satisfied.
-
1
MockExpectationError = Class.new(Exception)
-
-
# Raised when a test double is used after it has been torn
-
# down (typically at the end of an rspec-core example).
-
1
ExpiredTestDoubleError = Class.new(MockExpectationError)
-
-
# Raised when doubles or partial doubles are used outside of the per-test lifecycle.
-
1
OutsideOfExampleError = Class.new(StandardError)
-
-
# Raised when an expectation customization method (e.g. `with`,
-
# `and_return`) is called on a message expectation which has already been
-
# invoked.
-
1
MockExpectationAlreadyInvokedError = Class.new(Exception)
-
-
# Raised for situations that RSpec cannot support due to mutations made
-
# externally on arguments that RSpec is holding onto to use for later
-
# comparisons.
-
#
-
# @deprecated We no longer raise this error but the constant remains until
-
# RSpec 4 for SemVer reasons.
-
1
CannotSupportArgMutationsError = Class.new(StandardError)
-
-
# @private
-
1
UnsupportedMatcherError = Class.new(StandardError)
-
# @private
-
1
NegationUnsupportedError = Class.new(StandardError)
-
# @private
-
1
VerifyingDoubleNotDefinedError = Class.new(StandardError)
-
-
# @private
-
1
class ErrorGenerator
-
1
attr_writer :opts
-
-
1
def initialize(target=nil)
-
@target = target
-
end
-
-
# @private
-
1
def opts
-
@opts ||= {}
-
end
-
-
# @private
-
1
def raise_unexpected_message_error(message, args)
-
__raise "#{intro} received unexpected message :#{message} with #{format_args(args)}"
-
end
-
-
# @private
-
1
def raise_unexpected_message_args_error(expectation, args_for_multiple_calls, source_id=nil)
-
__raise error_message(expectation, args_for_multiple_calls), nil, source_id
-
end
-
-
# @private
-
1
def raise_missing_default_stub_error(expectation, args_for_multiple_calls)
-
message = error_message(expectation, args_for_multiple_calls)
-
message << "\n Please stub a default value first if message might be received with other args as well. \n"
-
-
__raise message
-
end
-
-
# @private
-
1
def raise_similar_message_args_error(expectation, args_for_multiple_calls, backtrace_line=nil)
-
__raise error_message(expectation, args_for_multiple_calls), backtrace_line
-
end
-
-
1
def default_error_message(expectation, expected_args, actual_args)
-
"#{intro} received #{expectation.message.inspect} #{unexpected_arguments_message(expected_args, actual_args)}"
-
end
-
-
# rubocop:disable Style/ParameterLists
-
# @private
-
1
def raise_expectation_error(message, expected_received_count, argument_list_matcher,
-
actual_received_count, expectation_count_type, args,
-
backtrace_line=nil, source_id=nil)
-
expected_part = expected_part_of_expectation_error(expected_received_count, expectation_count_type, argument_list_matcher)
-
received_part = received_part_of_expectation_error(actual_received_count, args)
-
__raise "(#{intro(:unwrapped)}).#{message}#{format_args(args)}\n #{expected_part}\n #{received_part}", backtrace_line, source_id
-
end
-
# rubocop:enable Style/ParameterLists
-
-
# @private
-
1
def raise_unimplemented_error(doubled_module, method_name, object)
-
message = case object
-
when InstanceVerifyingDouble
-
"the %s class does not implement the instance method: %s" <<
-
if ObjectMethodReference.for(doubled_module, method_name).implemented?
-
". Perhaps you meant to use `class_double` instead?"
-
else
-
""
-
end
-
when ClassVerifyingDouble
-
"the %s class does not implement the class method: %s" <<
-
if InstanceMethodReference.for(doubled_module, method_name).implemented?
-
". Perhaps you meant to use `instance_double` instead?"
-
else
-
""
-
end
-
else
-
"%s does not implement: %s"
-
end
-
-
__raise message % [doubled_module.description, method_name]
-
end
-
-
# @private
-
1
def raise_non_public_error(method_name, visibility)
-
raise NoMethodError, "%s method `%s' called on %s" % [
-
visibility, method_name, intro
-
]
-
end
-
-
# @private
-
1
def raise_invalid_arguments_error(verifier)
-
__raise verifier.error_message
-
end
-
-
# @private
-
1
def raise_expired_test_double_error
-
raise ExpiredTestDoubleError,
-
"#{intro} was originally created in one example but has leaked into " \
-
"another example and can no longer be used. rspec-mocks' doubles are " \
-
"designed to only last for one example, and you need to create a new " \
-
"one in each example you wish to use it for."
-
end
-
-
# @private
-
1
def describe_expectation(verb, message, expected_received_count, _actual_received_count, args)
-
"#{verb} #{message}#{format_args(args)} #{count_message(expected_received_count)}"
-
end
-
-
# @private
-
1
def raise_out_of_order_error(message)
-
__raise "#{intro} received :#{message} out of order"
-
end
-
-
# @private
-
1
def raise_missing_block_error(args_to_yield)
-
__raise "#{intro} asked to yield |#{arg_list(args_to_yield)}| but no block was passed"
-
end
-
-
# @private
-
1
def raise_wrong_arity_error(args_to_yield, signature)
-
__raise "#{intro} yielded |#{arg_list(args_to_yield)}| to block with #{signature.description}"
-
end
-
-
# @private
-
1
def raise_only_valid_on_a_partial_double(method)
-
__raise "#{intro} is a pure test double. `#{method}` is only " \
-
"available on a partial double."
-
end
-
-
# @private
-
1
def raise_expectation_on_unstubbed_method(method)
-
__raise "#{intro} expected to have received #{method}, but that " \
-
"object is not a spy or method has not been stubbed."
-
end
-
-
# @private
-
1
def raise_expectation_on_mocked_method(method)
-
__raise "#{intro} expected to have received #{method}, but that " \
-
"method has been mocked instead of stubbed or spied."
-
end
-
-
# @private
-
1
def raise_double_negation_error(wrapped_expression)
-
__raise "Isn't life confusing enough? You've already set a " \
-
"negative message expectation and now you are trying to " \
-
"negate it again with `never`. What does an expression like " \
-
"`#{wrapped_expression}.not_to receive(:msg).never` even mean?"
-
end
-
-
# @private
-
1
def raise_verifying_double_not_defined_error(ref)
-
notify(VerifyingDoubleNotDefinedError.new(
-
"#{ref.description.inspect} is not a defined constant. " \
-
"Perhaps you misspelt it? " \
-
"Disable check with `verify_doubled_constant_names` configuration option."
-
))
-
end
-
-
# @private
-
1
def raise_have_received_disallowed(type, reason)
-
__raise "Using #{type}(...) with the `have_received` " \
-
"matcher is not supported#{reason}."
-
end
-
-
# @private
-
1
def raise_cant_constrain_count_for_negated_have_received_error(count_constraint)
-
__raise "can't use #{count_constraint} when negative"
-
end
-
-
# @private
-
1
def raise_method_not_stubbed_error(method_name)
-
__raise "The method `#{method_name}` was not stubbed or was already unstubbed"
-
end
-
-
# @private
-
1
def raise_already_invoked_error(message, calling_customization)
-
error_message = "The message expectation for #{intro}.#{message} has already been invoked " \
-
"and cannot be modified further (e.g. using `#{calling_customization}`). All message expectation " \
-
"customizations must be applied before it is used for the first time."
-
-
notify MockExpectationAlreadyInvokedError.new(error_message)
-
end
-
-
1
def raise_expectation_on_nil_error(method_name)
-
__raise expectation_on_nil_message(method_name)
-
end
-
-
1
def expectation_on_nil_message(method_name)
-
"An expectation of `:#{method_name}` was set on `nil`. " \
-
"To allow expectations on `nil` and suppress this message, set `config.allow_expectations_on_nil` to `true`. " \
-
"To disallow expectations on `nil`, set `config.allow_expectations_on_nil` to `false`"
-
end
-
-
1
private
-
-
1
def received_part_of_expectation_error(actual_received_count, args)
-
"received: #{count_message(actual_received_count)}" +
-
method_call_args_description(args) do
-
actual_received_count > 0 && args.length > 0
-
end
-
end
-
-
1
def expected_part_of_expectation_error(expected_received_count, expectation_count_type, argument_list_matcher)
-
"expected: #{count_message(expected_received_count, expectation_count_type)}" +
-
method_call_args_description(argument_list_matcher.expected_args) do
-
argument_list_matcher.expected_args.length > 0
-
end
-
end
-
-
1
def method_call_args_description(args)
-
case args.first
-
when ArgumentMatchers::AnyArgsMatcher then " with any arguments"
-
when ArgumentMatchers::NoArgsMatcher then " with no arguments"
-
else
-
if yield
-
" with arguments: #{format_args(args)}"
-
else
-
""
-
end
-
end
-
end
-
-
1
def unexpected_arguments_message(expected_args_string, actual_args_string)
-
"with unexpected arguments\n expected: #{expected_args_string}\n got: #{actual_args_string}"
-
end
-
-
1
def error_message(expectation, args_for_multiple_calls)
-
expected_args = format_args(expectation.expected_args)
-
actual_args = format_received_args(args_for_multiple_calls)
-
message = default_error_message(expectation, expected_args, actual_args)
-
-
if args_for_multiple_calls.one?
-
diff = diff_message(expectation.expected_args, args_for_multiple_calls.first)
-
message << "\nDiff:#{diff}" unless diff.strip.empty?
-
end
-
-
message
-
end
-
-
1
def diff_message(expected_args, actual_args)
-
formatted_expected_args = expected_args.map do |x|
-
RSpec::Support.rspec_description_for_object(x)
-
end
-
-
formatted_expected_args, actual_args = unpack_string_args(formatted_expected_args, actual_args)
-
-
differ.diff(actual_args, formatted_expected_args)
-
end
-
-
1
def unpack_string_args(formatted_expected_args, actual_args)
-
if [formatted_expected_args, actual_args].all? { |x| list_of_exactly_one_string?(x) }
-
[formatted_expected_args.first, actual_args.first]
-
else
-
[formatted_expected_args, actual_args]
-
end
-
end
-
-
1
def list_of_exactly_one_string?(args)
-
Array === args && args.count == 1 && String === args.first
-
end
-
-
1
def differ
-
RSpec::Support::Differ.new(:color => RSpec::Mocks.configuration.color?)
-
end
-
-
1
def intro(unwrapped=false)
-
case @target
-
when TestDouble then TestDoubleFormatter.format(@target, unwrapped)
-
when Class then
-
formatted = "#{@target.inspect} (class)"
-
return formatted if unwrapped
-
"#<#{formatted}>"
-
when NilClass then "nil"
-
else @target
-
end
-
end
-
-
1
def __raise(message, backtrace_line=nil, source_id=nil)
-
message = opts[:message] unless opts[:message].nil?
-
exception = RSpec::Mocks::MockExpectationError.new(message)
-
prepend_to_backtrace(exception, backtrace_line) if backtrace_line
-
notify exception, :source_id => source_id
-
end
-
-
1
if RSpec::Support::Ruby.jruby?
-
def prepend_to_backtrace(exception, line)
-
raise exception
-
rescue RSpec::Mocks::MockExpectationError => with_backtrace
-
with_backtrace.backtrace.unshift(line)
-
end
-
else
-
1
def prepend_to_backtrace(exception, line)
-
exception.set_backtrace(caller.unshift line)
-
end
-
end
-
-
1
def notify(*args)
-
RSpec::Support.notify_failure(*args)
-
end
-
-
1
def format_args(args)
-
return "(no args)" if args.empty?
-
"(#{arg_list(args)})"
-
end
-
-
1
def arg_list(args)
-
args.map { |arg| RSpec::Support::ObjectFormatter.format(arg) }.join(", ")
-
end
-
-
1
def format_received_args(args_for_multiple_calls)
-
grouped_args(args_for_multiple_calls).map do |args_for_one_call, index|
-
"#{format_args(args_for_one_call)}#{group_count(index, args_for_multiple_calls)}"
-
end.join("\n ")
-
end
-
-
1
def count_message(count, expectation_count_type=nil)
-
return "at least #{times(count.abs)}" if count < 0 || expectation_count_type == :at_least
-
return "at most #{times(count)}" if expectation_count_type == :at_most
-
times(count)
-
end
-
-
1
def times(count)
-
"#{count} time#{count == 1 ? '' : 's'}"
-
end
-
-
1
def grouped_args(args)
-
Hash[args.group_by { |x| x }.map { |k, v| [k, v.count] }]
-
end
-
-
1
def group_count(index, args)
-
" (#{times(index)})" if args.size > 1 || index > 1
-
end
-
end
-
-
# @private
-
1
def self.error_generator
-
@error_generator ||= ErrorGenerator.new
-
end
-
end
-
end
-
1
RSpec::Support.require_rspec_mocks 'object_reference'
-
-
1
module RSpec
-
1
module Mocks
-
# Contains methods intended to be used from within code examples.
-
# Mix this in to your test context (such as a test framework base class)
-
# to use rspec-mocks with your test framework. If you're using rspec-core,
-
# it'll take care of doing this for you.
-
1
module ExampleMethods
-
1
include RSpec::Mocks::ArgumentMatchers
-
-
# @overload double()
-
# @overload double(name)
-
# @param name [String/Symbol] name or description to be used in failure messages
-
# @overload double(stubs)
-
# @param stubs (Hash) hash of message/return-value pairs
-
# @overload double(name, stubs)
-
# @param name [String/Symbol] name or description to be used in failure messages
-
# @param stubs (Hash) hash of message/return-value pairs
-
# @return (Double)
-
#
-
# Constructs an instance of [RSpec::Mocks::Double](RSpec::Mocks::Double) configured
-
# with an optional name, used for reporting in failure messages, and an optional
-
# hash of message/return-value pairs.
-
#
-
# @example
-
# book = double("book", :title => "The RSpec Book")
-
# book.title #=> "The RSpec Book"
-
#
-
# card = double("card", :suit => "Spades", :rank => "A")
-
# card.suit #=> "Spades"
-
# card.rank #=> "A"
-
#
-
1
def double(*args)
-
ExampleMethods.declare_double(Double, *args)
-
end
-
-
# @overload instance_double(doubled_class)
-
# @param doubled_class [String, Class]
-
# @overload instance_double(doubled_class, name)
-
# @param doubled_class [String, Class]
-
# @param name [String/Symbol] name or description to be used in failure messages
-
# @overload instance_double(doubled_class, stubs)
-
# @param doubled_class [String, Class]
-
# @param stubs [Hash] hash of message/return-value pairs
-
# @overload instance_double(doubled_class, name, stubs)
-
# @param doubled_class [String, Class]
-
# @param name [String/Symbol] name or description to be used in failure messages
-
# @param stubs [Hash] hash of message/return-value pairs
-
# @return InstanceVerifyingDouble
-
#
-
# Constructs a test double against a specific class. If the given class
-
# name has been loaded, only instance methods defined on the class are
-
# allowed to be stubbed. In all other ways it behaves like a
-
# [double](double).
-
1
def instance_double(doubled_class, *args)
-
ref = ObjectReference.for(doubled_class)
-
ExampleMethods.declare_verifying_double(InstanceVerifyingDouble, ref, *args)
-
end
-
-
# @overload class_double(doubled_class)
-
# @param doubled_class [String, Module]
-
# @overload class_double(doubled_class, name)
-
# @param doubled_class [String, Module]
-
# @param name [String/Symbol] name or description to be used in failure messages
-
# @overload class_double(doubled_class, stubs)
-
# @param doubled_class [String, Module]
-
# @param stubs [Hash] hash of message/return-value pairs
-
# @overload class_double(doubled_class, name, stubs)
-
# @param doubled_class [String, Module]
-
# @param name [String/Symbol] name or description to be used in failure messages
-
# @param stubs [Hash] hash of message/return-value pairs
-
# @return ClassVerifyingDouble
-
#
-
# Constructs a test double against a specific class. If the given class
-
# name has been loaded, only class methods defined on the class are
-
# allowed to be stubbed. In all other ways it behaves like a
-
# [double](double).
-
1
def class_double(doubled_class, *args)
-
ref = ObjectReference.for(doubled_class)
-
ExampleMethods.declare_verifying_double(ClassVerifyingDouble, ref, *args)
-
end
-
-
# @overload object_double(object_or_name)
-
# @param object_or_name [String, Object]
-
# @overload object_double(object_or_name, name)
-
# @param object_or_name [String, Object]
-
# @param name [String/Symbol] name or description to be used in failure messages
-
# @overload object_double(object_or_name, stubs)
-
# @param object_or_name [String, Object]
-
# @param stubs [Hash] hash of message/return-value pairs
-
# @overload object_double(object_or_name, name, stubs)
-
# @param object_or_name [String, Object]
-
# @param name [String/Symbol] name or description to be used in failure messages
-
# @param stubs [Hash] hash of message/return-value pairs
-
# @return ObjectVerifyingDouble
-
#
-
# Constructs a test double against a specific object. Only the methods
-
# the object responds to are allowed to be stubbed. If a String argument
-
# is provided, it is assumed to reference a constant object which is used
-
# for verification. In all other ways it behaves like a [double](double).
-
1
def object_double(object_or_name, *args)
-
ref = ObjectReference.for(object_or_name, :allow_direct_object_refs)
-
ExampleMethods.declare_verifying_double(ObjectVerifyingDouble, ref, *args)
-
end
-
-
# @overload spy()
-
# @overload spy(name)
-
# @param name [String/Symbol] name or description to be used in failure messages
-
# @overload spy(stubs)
-
# @param stubs (Hash) hash of message/return-value pairs
-
# @overload spy(name, stubs)
-
# @param name [String/Symbol] name or description to be used in failure messages
-
# @param stubs (Hash) hash of message/return-value pairs
-
# @return (Double)
-
#
-
# Constructs a test double that is optimized for use with
-
# `have_received`. With a normal double one has to stub methods in order
-
# to be able to spy them. A spy automatically spies on all methods.
-
1
def spy(*args)
-
double(*args).as_null_object
-
end
-
-
# @overload instance_spy(doubled_class)
-
# @param doubled_class [String, Class]
-
# @overload instance_spy(doubled_class, name)
-
# @param doubled_class [String, Class]
-
# @param name [String/Symbol] name or description to be used in failure messages
-
# @overload instance_spy(doubled_class, stubs)
-
# @param doubled_class [String, Class]
-
# @param stubs [Hash] hash of message/return-value pairs
-
# @overload instance_spy(doubled_class, name, stubs)
-
# @param doubled_class [String, Class]
-
# @param name [String/Symbol] name or description to be used in failure messages
-
# @param stubs [Hash] hash of message/return-value pairs
-
# @return InstanceVerifyingDouble
-
#
-
# Constructs a test double that is optimized for use with `have_received`
-
# against a specific class. If the given class name has been loaded, only
-
# instance methods defined on the class are allowed to be stubbed. With
-
# a normal double one has to stub methods in order to be able to spy
-
# them. An instance_spy automatically spies on all instance methods to
-
# which the class responds.
-
1
def instance_spy(*args)
-
instance_double(*args).as_null_object
-
end
-
-
# @overload object_spy(object_or_name)
-
# @param object_or_name [String, Object]
-
# @overload object_spy(object_or_name, name)
-
# @param object_or_name [String, Class]
-
# @param name [String/Symbol] name or description to be used in failure messages
-
# @overload object_spy(object_or_name, stubs)
-
# @param object_or_name [String, Object]
-
# @param stubs [Hash] hash of message/return-value pairs
-
# @overload object_spy(object_or_name, name, stubs)
-
# @param object_or_name [String, Class]
-
# @param name [String/Symbol] name or description to be used in failure messages
-
# @param stubs [Hash] hash of message/return-value pairs
-
# @return ObjectVerifyingDouble
-
#
-
# Constructs a test double that is optimized for use with `have_received`
-
# against a specific object. Only instance methods defined on the object
-
# are allowed to be stubbed. With a normal double one has to stub
-
# methods in order to be able to spy them. An object_spy automatically
-
# spies on all methods to which the object responds.
-
1
def object_spy(*args)
-
object_double(*args).as_null_object
-
end
-
-
# @overload class_spy(doubled_class)
-
# @param doubled_class [String, Module]
-
# @overload class_spy(doubled_class, name)
-
# @param doubled_class [String, Class]
-
# @param name [String/Symbol] name or description to be used in failure messages
-
# @overload class_spy(doubled_class, stubs)
-
# @param doubled_class [String, Module]
-
# @param stubs [Hash] hash of message/return-value pairs
-
# @overload class_spy(doubled_class, name, stubs)
-
# @param doubled_class [String, Class]
-
# @param name [String/Symbol] name or description to be used in failure messages
-
# @param stubs [Hash] hash of message/return-value pairs
-
# @return ClassVerifyingDouble
-
#
-
# Constructs a test double that is optimized for use with `have_received`
-
# against a specific class. If the given class name has been loaded,
-
# only class methods defined on the class are allowed to be stubbed.
-
# With a normal double one has to stub methods in order to be able to spy
-
# them. An class_spy automatically spies on all class methods to which the
-
# class responds.
-
1
def class_spy(*args)
-
class_double(*args).as_null_object
-
end
-
-
# Disables warning messages about expectations being set on nil.
-
#
-
# By default warning messages are issued when expectations are set on
-
# nil. This is to prevent false-positives and to catch potential bugs
-
# early on.
-
# @deprecated Use {RSpec::Mocks::Configuration#allow_message_expectations_on_nil} instead.
-
1
def allow_message_expectations_on_nil
-
RSpec::Mocks.space.proxy_for(nil).warn_about_expectations = false
-
end
-
-
# Stubs the named constant with the given value.
-
# Like method stubs, the constant will be restored
-
# to its original value (or lack of one, if it was
-
# undefined) when the example completes.
-
#
-
# @param constant_name [String] The fully qualified name of the constant. The current
-
# constant scoping at the point of call is not considered.
-
# @param value [Object] The value to make the constant refer to. When the
-
# example completes, the constant will be restored to its prior state.
-
# @param options [Hash] Stubbing options.
-
# @option options :transfer_nested_constants [Boolean, Array<Symbol>] Determines
-
# what nested constants, if any, will be transferred from the original value
-
# of the constant to the new value of the constant. This only works if both
-
# the original and new values are modules (or classes).
-
# @return [Object] the stubbed value of the constant
-
#
-
# @example
-
# stub_const("MyClass", Class.new) # => Replaces (or defines) MyClass with a new class object.
-
# stub_const("SomeModel::PER_PAGE", 5) # => Sets SomeModel::PER_PAGE to 5.
-
#
-
# class CardDeck
-
# SUITS = [:Spades, :Diamonds, :Clubs, :Hearts]
-
# NUM_CARDS = 52
-
# end
-
#
-
# stub_const("CardDeck", Class.new)
-
# CardDeck::SUITS # => uninitialized constant error
-
# CardDeck::NUM_CARDS # => uninitialized constant error
-
#
-
# stub_const("CardDeck", Class.new, :transfer_nested_constants => true)
-
# CardDeck::SUITS # => our suits array
-
# CardDeck::NUM_CARDS # => 52
-
#
-
# stub_const("CardDeck", Class.new, :transfer_nested_constants => [:SUITS])
-
# CardDeck::SUITS # => our suits array
-
# CardDeck::NUM_CARDS # => uninitialized constant error
-
1
def stub_const(constant_name, value, options={})
-
ConstantMutator.stub(constant_name, value, options)
-
end
-
-
# Hides the named constant with the given value. The constant will be
-
# undefined for the duration of the test.
-
#
-
# Like method stubs, the constant will be restored to its original value
-
# when the example completes.
-
#
-
# @param constant_name [String] The fully qualified name of the constant.
-
# The current constant scoping at the point of call is not considered.
-
#
-
# @example
-
# hide_const("MyClass") # => MyClass is now an undefined constant
-
1
def hide_const(constant_name)
-
ConstantMutator.hide(constant_name)
-
end
-
-
# Verifies that the given object received the expected message during the
-
# course of the test. On a spy objects or as null object doubles this
-
# works for any method, on other objects the method must have
-
# been stubbed beforehand in order for messages to be verified.
-
#
-
# Stubbing and verifying messages received in this way implements the
-
# Test Spy pattern.
-
#
-
# @param method_name [Symbol] name of the method expected to have been
-
# called.
-
#
-
# @example
-
# invitation = double('invitation', accept: true)
-
# user.accept_invitation(invitation)
-
# expect(invitation).to have_received(:accept)
-
#
-
# # You can also use most message expectations:
-
# expect(invitation).to have_received(:accept).with(mailer).once
-
#
-
# @note `have_received(...).with(...)` is unable to work properly when
-
# passed arguments are mutated after the spy records the received message.
-
1
def have_received(method_name, &block)
-
Matchers::HaveReceived.new(method_name, &block)
-
end
-
-
# @method expect
-
# Used to wrap an object in preparation for setting a mock expectation
-
# on it.
-
#
-
# @example
-
# expect(obj).to receive(:foo).with(5).and_return(:return_value)
-
#
-
# @note This method is usually provided by rspec-expectations. However,
-
# if you use rspec-mocks without rspec-expectations, there's a definition
-
# of it that is made available here. If you disable the `:expect` syntax
-
# this method will be undefined.
-
-
# @method allow
-
# Used to wrap an object in preparation for stubbing a method
-
# on it.
-
#
-
# @example
-
# allow(dbl).to receive(:foo).with(5).and_return(:return_value)
-
#
-
# @note If you disable the `:expect` syntax this method will be undefined.
-
-
# @method expect_any_instance_of
-
# Used to wrap a class in preparation for setting a mock expectation
-
# on instances of it.
-
#
-
# @example
-
# expect_any_instance_of(MyClass).to receive(:foo)
-
#
-
# @note If you disable the `:expect` syntax this method will be undefined.
-
-
# @method allow_any_instance_of
-
# Used to wrap a class in preparation for stubbing a method
-
# on instances of it.
-
#
-
# @example
-
# allow_any_instance_of(MyClass).to receive(:foo)
-
#
-
# @note This is only available when you have enabled the `expect` syntax.
-
-
# @method receive
-
# Used to specify a message that you expect or allow an object
-
# to receive. The object returned by `receive` supports the same
-
# fluent interface that `should_receive` and `stub` have always
-
# supported, allowing you to constrain the arguments or number of
-
# times, and configure how the object should respond to the message.
-
#
-
# @example
-
# expect(obj).to receive(:hello).with("world").exactly(3).times
-
#
-
# @note If you disable the `:expect` syntax this method will be undefined.
-
-
# @method receive_messages
-
# Shorthand syntax used to setup message(s), and their return value(s),
-
# that you expect or allow an object to receive. The method takes a hash
-
# of messages and their respective return values. Unlike with `receive`,
-
# you cannot apply further customizations using a block or the fluent
-
# interface.
-
#
-
# @example
-
# allow(obj).to receive_messages(:speak => "Hello World")
-
# allow(obj).to receive_messages(:speak => "Hello", :meow => "Meow")
-
#
-
# @note If you disable the `:expect` syntax this method will be undefined.
-
-
# @method receive_message_chain
-
# @overload receive_message_chain(method1, method2)
-
# @overload receive_message_chain("method1.method2")
-
# @overload receive_message_chain(method1, method_to_value_hash)
-
#
-
# stubs/mocks a chain of messages on an object or test double.
-
#
-
# ## Warning:
-
#
-
# Chains can be arbitrarily long, which makes it quite painless to
-
# violate the Law of Demeter in violent ways, so you should consider any
-
# use of `receive_message_chain` a code smell. Even though not all code smells
-
# indicate real problems (think fluent interfaces), `receive_message_chain` still
-
# results in brittle examples. For example, if you write
-
# `allow(foo).to receive_message_chain(:bar, :baz => 37)` in a spec and then the
-
# implementation calls `foo.baz.bar`, the stub will not work.
-
#
-
# @example
-
# allow(double).to receive_message_chain("foo.bar") { :baz }
-
# allow(double).to receive_message_chain(:foo, :bar => :baz)
-
# allow(double).to receive_message_chain(:foo, :bar) { :baz }
-
#
-
# # Given any of ^^ these three forms ^^:
-
# double.foo.bar # => :baz
-
#
-
# # Common use in Rails/ActiveRecord:
-
# allow(Article).to receive_message_chain("recent.published") { [Article.new] }
-
#
-
# @note If you disable the `:expect` syntax this method will be undefined.
-
-
# @private
-
1
def self.included(klass)
-
1
klass.class_exec do
-
# This gets mixed in so that if `RSpec::Matchers` is included in
-
# `klass` later, it's definition of `expect` will take precedence.
-
1
include ExpectHost unless method_defined?(:expect)
-
end
-
end
-
-
# @private
-
1
def self.extended(object)
-
# This gets extended in so that if `RSpec::Matchers` is included in
-
# `klass` later, it's definition of `expect` will take precedence.
-
object.extend ExpectHost unless object.respond_to?(:expect)
-
end
-
-
# @private
-
1
def self.declare_verifying_double(type, ref, *args)
-
if RSpec::Mocks.configuration.verify_doubled_constant_names? &&
-
!ref.defined?
-
-
RSpec::Mocks.error_generator.raise_verifying_double_not_defined_error(ref)
-
end
-
-
RSpec::Mocks.configuration.verifying_double_callbacks.each do |block|
-
block.call(ref)
-
end
-
-
declare_double(type, ref, *args)
-
end
-
-
# @private
-
1
def self.declare_double(type, *args)
-
args << {} unless Hash === args.last
-
type.new(*args)
-
end
-
-
# This module exists to host the `expect` method for cases where
-
# rspec-mocks is used w/o rspec-expectations.
-
1
module ExpectHost
-
end
-
end
-
end
-
end
-
1
module RSpec
-
1
module Mocks
-
# @private
-
1
class InstanceMethodStasher
-
1
def initialize(object, method)
-
@object = object
-
@method = method
-
@klass = (class << object; self; end)
-
-
@original_method = nil
-
@method_is_stashed = false
-
end
-
-
1
attr_reader :original_method
-
-
1
if RUBY_VERSION.to_f < 1.9
-
# @private
-
def method_is_stashed?
-
@method_is_stashed
-
end
-
-
# @private
-
def stash
-
return if !method_defined_directly_on_klass? || @method_is_stashed
-
-
@klass.__send__(:alias_method, stashed_method_name, @method)
-
@method_is_stashed = true
-
end
-
-
# @private
-
def stashed_method_name
-
"obfuscated_by_rspec_mocks__#{@method}"
-
end
-
-
# @private
-
def restore
-
return unless @method_is_stashed
-
-
if @klass.__send__(:method_defined?, @method)
-
@klass.__send__(:undef_method, @method)
-
end
-
@klass.__send__(:alias_method, @method, stashed_method_name)
-
@klass.__send__(:remove_method, stashed_method_name)
-
@method_is_stashed = false
-
end
-
else
-
-
# @private
-
1
def method_is_stashed?
-
!!@original_method
-
end
-
-
# @private
-
1
def stash
-
return unless method_defined_directly_on_klass?
-
@original_method ||= ::RSpec::Support.method_handle_for(@object, @method)
-
@klass.__send__(:undef_method, @method)
-
end
-
-
# @private
-
1
def restore
-
return unless @original_method
-
-
if @klass.__send__(:method_defined?, @method)
-
@klass.__send__(:undef_method, @method)
-
end
-
-
handle_restoration_failures do
-
@klass.__send__(:define_method, @method, @original_method)
-
end
-
-
@original_method = nil
-
end
-
end
-
-
1
if RUBY_DESCRIPTION.include?('2.0.0p247') || RUBY_DESCRIPTION.include?('2.0.0p195')
-
# ruby 2.0.0-p247 and 2.0.0-p195 both have a bug that we can't work around :(.
-
# https://bugs.ruby-lang.org/issues/8686
-
def handle_restoration_failures
-
yield
-
rescue TypeError
-
RSpec.warn_with(
-
"RSpec failed to properly restore a partial double (#{@object.inspect}) " \
-
"to its original state due to a known bug in MRI 2.0.0-p195 & p247 " \
-
"(https://bugs.ruby-lang.org/issues/8686). This object may remain " \
-
"screwed up for the rest of this process. Please upgrade to 2.0.0-p353 or above.",
-
:call_site => nil, :use_spec_location_as_call_site => true
-
)
-
end
-
else
-
1
def handle_restoration_failures
-
# No known reasons for restoration to fail on other rubies.
-
yield
-
end
-
end
-
-
1
private
-
-
# @private
-
1
def method_defined_directly_on_klass?
-
method_defined_on_klass? && method_owned_by_klass?
-
end
-
-
# @private
-
1
def method_defined_on_klass?(klass=@klass)
-
MethodReference.method_defined_at_any_visibility?(klass, @method)
-
end
-
-
1
def method_owned_by_klass?
-
owner = @klass.instance_method(@method).owner
-
-
# On Ruby 2.0.0+ the owner of a method on a class which has been
-
# `prepend`ed may actually be an instance, e.g.
-
# `#<MyClass:0x007fbb94e3cd10>`, rather than the expected `MyClass`.
-
owner = owner.class unless Module === owner
-
-
# On some 1.9s (e.g. rubinius) aliased methods
-
# can report the wrong owner. Example:
-
# class MyClass
-
# class << self
-
# alias alternate_new new
-
# end
-
# end
-
#
-
# MyClass.owner(:alternate_new) returns `Class` when incorrect,
-
# but we need to consider the owner to be `MyClass` because
-
# it is not actually available on `Class` but is on `MyClass`.
-
# Hence, we verify that the owner actually has the method defined.
-
# If the given owner does not have the method defined, we assume
-
# that the method is actually owned by @klass.
-
owner == @klass || !(method_defined_on_klass?(owner))
-
end
-
end
-
end
-
end
-
1
module RSpec
-
1
module Mocks
-
# A message expectation that only allows concrete return values to be set
-
# for a message. While this same effect can be achieved using a standard
-
# MessageExpectation, this version is much faster and so can be used as an
-
# optimization.
-
#
-
# @private
-
1
class SimpleMessageExpectation
-
1
def initialize(message, response, error_generator, backtrace_line=nil)
-
@message, @response, @error_generator, @backtrace_line = message.to_sym, response, error_generator, backtrace_line
-
@received = false
-
end
-
-
1
def invoke(*_)
-
@received = true
-
@response
-
end
-
-
1
def matches?(message, *_)
-
@message == message.to_sym
-
end
-
-
1
def called_max_times?
-
false
-
end
-
-
1
def verify_messages_received
-
return if @received
-
@error_generator.raise_expectation_error(
-
@message, 1, ArgumentListMatcher::MATCH_ALL, 0, nil, [], @backtrace_line
-
)
-
end
-
-
1
def unadvise(_)
-
end
-
end
-
-
# Represents an individual method stub or message expectation. The methods
-
# defined here can be used to configure how it behaves. The methods return
-
# `self` so that they can be chained together to form a fluent interface.
-
1
class MessageExpectation
-
# @!group Configuring Responses
-
-
# @overload and_return(value)
-
# @overload and_return(first_value, second_value)
-
#
-
# Tells the object to return a value when it receives the message. Given
-
# more than one value, the first value is returned the first time the
-
# message is received, the second value is returned the next time, etc,
-
# etc.
-
#
-
# If the message is received more times than there are values, the last
-
# value is received for every subsequent call.
-
#
-
# @return [nil] No further chaining is supported after this.
-
# @example
-
# allow(counter).to receive(:count).and_return(1)
-
# counter.count # => 1
-
# counter.count # => 1
-
#
-
# allow(counter).to receive(:count).and_return(1,2,3)
-
# counter.count # => 1
-
# counter.count # => 2
-
# counter.count # => 3
-
# counter.count # => 3
-
# counter.count # => 3
-
# # etc
-
1
def and_return(first_value, *values)
-
raise_already_invoked_error_if_necessary(__method__)
-
if negative?
-
raise "`and_return` is not supported with negative message expectations"
-
end
-
-
if block_given?
-
raise ArgumentError, "Implementation blocks aren't supported with `and_return`"
-
end
-
-
values.unshift(first_value)
-
@expected_received_count = [@expected_received_count, values.size].max unless ignoring_args? || (@expected_received_count == 0 && @at_least)
-
self.terminal_implementation_action = AndReturnImplementation.new(values)
-
-
nil
-
end
-
-
# Tells the object to delegate to the original unmodified method
-
# when it receives the message.
-
#
-
# @note This is only available on partial doubles.
-
#
-
# @return [nil] No further chaining is supported after this.
-
# @example
-
# expect(counter).to receive(:increment).and_call_original
-
# original_count = counter.count
-
# counter.increment
-
# expect(counter.count).to eq(original_count + 1)
-
1
def and_call_original
-
and_wrap_original do |original, *args, &block|
-
original.call(*args, &block)
-
end
-
end
-
-
# Decorates the stubbed method with the supplied block. The original
-
# unmodified method is passed to the block along with any method call
-
# arguments so you can delegate to it, whilst still being able to
-
# change what args are passed to it and/or change the return value.
-
#
-
# @note This is only available on partial doubles.
-
#
-
# @return [nil] No further chaining is supported after this.
-
# @example
-
# expect(api).to receive(:large_list).and_wrap_original do |original_method, *args, &block|
-
# original_method.call(*args, &block).first(10)
-
# end
-
1
def and_wrap_original(&block)
-
if RSpec::Mocks::TestDouble === @method_double.object
-
@error_generator.raise_only_valid_on_a_partial_double(:and_call_original)
-
else
-
warn_about_stub_override if implementation.inner_action
-
@implementation = AndWrapOriginalImplementation.new(@method_double.original_implementation_callable, block)
-
@yield_receiver_to_implementation_block = false
-
end
-
-
nil
-
end
-
-
# @overload and_raise
-
# @overload and_raise(ExceptionClass)
-
# @overload and_raise(ExceptionClass, message)
-
# @overload and_raise(exception_instance)
-
#
-
# Tells the object to raise an exception when the message is received.
-
#
-
# @return [nil] No further chaining is supported after this.
-
# @note
-
# When you pass an exception class, the MessageExpectation will raise
-
# an instance of it, creating it with `exception` and passing `message`
-
# if specified. If the exception class initializer requires more than
-
# one parameters, you must pass in an instance and not the class,
-
# otherwise this method will raise an ArgumentError exception.
-
#
-
# @example
-
# allow(car).to receive(:go).and_raise
-
# allow(car).to receive(:go).and_raise(OutOfGas)
-
# allow(car).to receive(:go).and_raise(OutOfGas, "At least 2 oz of gas needed to drive")
-
# allow(car).to receive(:go).and_raise(OutOfGas.new(2, :oz))
-
1
def and_raise(*args)
-
raise_already_invoked_error_if_necessary(__method__)
-
self.terminal_implementation_action = Proc.new { raise(*args) }
-
nil
-
end
-
-
# @overload and_throw(symbol)
-
# @overload and_throw(symbol, object)
-
#
-
# Tells the object to throw a symbol (with the object if that form is
-
# used) when the message is received.
-
#
-
# @return [nil] No further chaining is supported after this.
-
# @example
-
# allow(car).to receive(:go).and_throw(:out_of_gas)
-
# allow(car).to receive(:go).and_throw(:out_of_gas, :level => 0.1)
-
1
def and_throw(*args)
-
raise_already_invoked_error_if_necessary(__method__)
-
self.terminal_implementation_action = Proc.new { throw(*args) }
-
nil
-
end
-
-
# Tells the object to yield one or more args to a block when the message
-
# is received.
-
#
-
# @return [MessageExpectation] self, to support further chaining.
-
# @example
-
# stream.stub(:open).and_yield(StringIO.new)
-
1
def and_yield(*args, &block)
-
raise_already_invoked_error_if_necessary(__method__)
-
yield @eval_context = Object.new if block
-
-
# Initialize args to yield now that it's being used, see also: comment
-
# in constructor.
-
@args_to_yield ||= []
-
-
@args_to_yield << args
-
self.initial_implementation_action = AndYieldImplementation.new(@args_to_yield, @eval_context, @error_generator)
-
self
-
end
-
# @!endgroup
-
-
# @!group Constraining Receive Counts
-
-
# Constrain a message expectation to be received a specific number of
-
# times.
-
#
-
# @return [MessageExpectation] self, to support further chaining.
-
# @example
-
# expect(dealer).to receive(:deal_card).exactly(10).times
-
1
def exactly(n, &block)
-
raise_already_invoked_error_if_necessary(__method__)
-
self.inner_implementation_action = block
-
set_expected_received_count :exactly, n
-
self
-
end
-
-
# Constrain a message expectation to be received at least a specific
-
# number of times.
-
#
-
# @return [MessageExpectation] self, to support further chaining.
-
# @example
-
# expect(dealer).to receive(:deal_card).at_least(9).times
-
1
def at_least(n, &block)
-
raise_already_invoked_error_if_necessary(__method__)
-
set_expected_received_count :at_least, n
-
-
if n == 0
-
raise "at_least(0) has been removed, use allow(...).to receive(:message) instead"
-
end
-
-
self.inner_implementation_action = block
-
-
self
-
end
-
-
# Constrain a message expectation to be received at most a specific
-
# number of times.
-
#
-
# @return [MessageExpectation] self, to support further chaining.
-
# @example
-
# expect(dealer).to receive(:deal_card).at_most(10).times
-
1
def at_most(n, &block)
-
raise_already_invoked_error_if_necessary(__method__)
-
self.inner_implementation_action = block
-
set_expected_received_count :at_most, n
-
self
-
end
-
-
# Syntactic sugar for `exactly`, `at_least` and `at_most`
-
#
-
# @return [MessageExpectation] self, to support further chaining.
-
# @example
-
# expect(dealer).to receive(:deal_card).exactly(10).times
-
# expect(dealer).to receive(:deal_card).at_least(10).times
-
# expect(dealer).to receive(:deal_card).at_most(10).times
-
1
def times(&block)
-
self.inner_implementation_action = block
-
self
-
end
-
-
# Expect a message not to be received at all.
-
#
-
# @return [MessageExpectation] self, to support further chaining.
-
# @example
-
# expect(car).to receive(:stop).never
-
1
def never
-
error_generator.raise_double_negation_error("expect(obj)") if negative?
-
@expected_received_count = 0
-
self
-
end
-
-
# Expect a message to be received exactly one time.
-
#
-
# @return [MessageExpectation] self, to support further chaining.
-
# @example
-
# expect(car).to receive(:go).once
-
1
def once(&block)
-
self.inner_implementation_action = block
-
set_expected_received_count :exactly, 1
-
self
-
end
-
-
# Expect a message to be received exactly two times.
-
#
-
# @return [MessageExpectation] self, to support further chaining.
-
# @example
-
# expect(car).to receive(:go).twice
-
1
def twice(&block)
-
self.inner_implementation_action = block
-
set_expected_received_count :exactly, 2
-
self
-
end
-
-
# Expect a message to be received exactly three times.
-
#
-
# @return [MessageExpectation] self, to support further chaining.
-
# @example
-
# expect(car).to receive(:go).thrice
-
1
def thrice(&block)
-
self.inner_implementation_action = block
-
set_expected_received_count :exactly, 3
-
self
-
end
-
# @!endgroup
-
-
# @!group Other Constraints
-
-
# Constrains a stub or message expectation to invocations with specific
-
# arguments.
-
#
-
# With a stub, if the message might be received with other args as well,
-
# you should stub a default value first, and then stub or mock the same
-
# message using `with` to constrain to specific arguments.
-
#
-
# A message expectation will fail if the message is received with different
-
# arguments.
-
#
-
# @return [MessageExpectation] self, to support further chaining.
-
# @example
-
# allow(cart).to receive(:add) { :failure }
-
# allow(cart).to receive(:add).with(Book.new(:isbn => 1934356379)) { :success }
-
# cart.add(Book.new(:isbn => 1234567890))
-
# # => :failure
-
# cart.add(Book.new(:isbn => 1934356379))
-
# # => :success
-
#
-
# expect(cart).to receive(:add).with(Book.new(:isbn => 1934356379)) { :success }
-
# cart.add(Book.new(:isbn => 1234567890))
-
# # => failed expectation
-
# cart.add(Book.new(:isbn => 1934356379))
-
# # => passes
-
1
def with(*args, &block)
-
raise_already_invoked_error_if_necessary(__method__)
-
if args.empty?
-
raise ArgumentError,
-
"`with` must have at least one argument. Use `no_args` matcher to set the expectation of receiving no arguments."
-
end
-
-
self.inner_implementation_action = block
-
@argument_list_matcher = ArgumentListMatcher.new(*args)
-
self
-
end
-
-
# Expect messages to be received in a specific order.
-
#
-
# @return [MessageExpectation] self, to support further chaining.
-
# @example
-
# expect(api).to receive(:prepare).ordered
-
# expect(api).to receive(:run).ordered
-
# expect(api).to receive(:finish).ordered
-
1
def ordered(&block)
-
self.inner_implementation_action = block
-
additional_expected_calls.times do
-
@order_group.register(self)
-
end
-
@ordered = true
-
self
-
end
-
-
# @private
-
# Contains the parts of `MessageExpectation` that aren't part of
-
# rspec-mocks' public API. The class is very big and could really use
-
# some collaborators it delegates to for this stuff but for now this was
-
# the simplest way to split the public from private stuff to make it
-
# easier to publish the docs for the APIs we want published.
-
1
module ImplementationDetails
-
1
attr_accessor :error_generator, :implementation
-
1
attr_reader :message
-
1
attr_reader :orig_object
-
1
attr_writer :expected_received_count, :expected_from, :argument_list_matcher
-
1
protected :expected_received_count=, :expected_from=, :error_generator, :error_generator=, :implementation=
-
-
# rubocop:disable Style/ParameterLists
-
1
def initialize(error_generator, expectation_ordering, expected_from, method_double,
-
type=:expectation, opts={}, &implementation_block)
-
@error_generator = error_generator
-
@error_generator.opts = opts
-
@expected_from = expected_from
-
@method_double = method_double
-
@orig_object = @method_double.object
-
@message = @method_double.method_name
-
@actual_received_count = 0
-
@expected_received_count = type == :expectation ? 1 : :any
-
@argument_list_matcher = ArgumentListMatcher::MATCH_ALL
-
@order_group = expectation_ordering
-
@order_group.register(self) unless type == :stub
-
@expectation_type = type
-
@ordered = false
-
@at_least = @at_most = @exactly = nil
-
-
# Initialized to nil so that we don't allocate an array for every
-
# mock or stub. See also comment in `and_yield`.
-
@args_to_yield = nil
-
@eval_context = nil
-
@yield_receiver_to_implementation_block = false
-
-
@implementation = Implementation.new
-
self.inner_implementation_action = implementation_block
-
end
-
# rubocop:enable Style/ParameterLists
-
-
1
def expected_args
-
@argument_list_matcher.expected_args
-
end
-
-
1
def and_yield_receiver_to_implementation
-
@yield_receiver_to_implementation_block = true
-
self
-
end
-
-
1
def yield_receiver_to_implementation_block?
-
@yield_receiver_to_implementation_block
-
end
-
-
1
def matches?(message, *args)
-
@message == message && @argument_list_matcher.args_match?(*args)
-
end
-
-
1
def safe_invoke(parent_stub, *args, &block)
-
invoke_incrementing_actual_calls_by(1, false, parent_stub, *args, &block)
-
end
-
-
1
def invoke(parent_stub, *args, &block)
-
invoke_incrementing_actual_calls_by(1, true, parent_stub, *args, &block)
-
end
-
-
1
def invoke_without_incrementing_received_count(parent_stub, *args, &block)
-
invoke_incrementing_actual_calls_by(0, true, parent_stub, *args, &block)
-
end
-
-
1
def negative?
-
@expected_received_count == 0 && !@at_least
-
end
-
-
1
def called_max_times?
-
@expected_received_count != :any &&
-
!@at_least &&
-
@expected_received_count > 0 &&
-
@actual_received_count >= @expected_received_count
-
end
-
-
1
def matches_name_but_not_args(message, *args)
-
@message == message && !@argument_list_matcher.args_match?(*args)
-
end
-
-
1
def verify_messages_received
-
return if expected_messages_received?
-
generate_error
-
end
-
-
1
def expected_messages_received?
-
ignoring_args? || matches_exact_count? || matches_at_least_count? || matches_at_most_count?
-
end
-
-
1
def ensure_expected_ordering_received!
-
@order_group.verify_invocation_order(self) if @ordered
-
true
-
end
-
-
1
def ignoring_args?
-
@expected_received_count == :any
-
end
-
-
1
def matches_at_least_count?
-
@at_least && @actual_received_count >= @expected_received_count
-
end
-
-
1
def matches_at_most_count?
-
@at_most && @actual_received_count <= @expected_received_count
-
end
-
-
1
def matches_exact_count?
-
@expected_received_count == @actual_received_count
-
end
-
-
1
def similar_messages
-
@similar_messages ||= []
-
end
-
-
1
def advise(*args)
-
similar_messages << args
-
end
-
-
1
def unadvise(args)
-
similar_messages.delete_if { |message| args.include?(message) }
-
end
-
-
1
def generate_error
-
if similar_messages.empty?
-
@error_generator.raise_expectation_error(
-
@message, @expected_received_count, @argument_list_matcher,
-
@actual_received_count, expectation_count_type, expected_args,
-
@expected_from, exception_source_id
-
)
-
else
-
@error_generator.raise_similar_message_args_error(
-
self, @similar_messages, @expected_from
-
)
-
end
-
end
-
-
1
def raise_unexpected_message_args_error(args_for_multiple_calls)
-
@error_generator.raise_unexpected_message_args_error(self, args_for_multiple_calls, exception_source_id)
-
end
-
-
1
def expectation_count_type
-
return :at_least if @at_least
-
return :at_most if @at_most
-
nil
-
end
-
-
1
def description_for(verb)
-
@error_generator.describe_expectation(
-
verb, @message, @expected_received_count,
-
@actual_received_count, expected_args
-
)
-
end
-
-
1
def raise_out_of_order_error
-
@error_generator.raise_out_of_order_error @message
-
end
-
-
1
def additional_expected_calls
-
return 0 if @expectation_type == :stub || !@exactly
-
@expected_received_count - 1
-
end
-
-
1
def ordered?
-
@ordered
-
end
-
-
1
def negative_expectation_for?(message)
-
@message == message && negative?
-
end
-
-
1
def actual_received_count_matters?
-
@at_least || @at_most || @exactly
-
end
-
-
1
def increase_actual_received_count!
-
@actual_received_count += 1
-
end
-
-
1
private
-
-
1
def exception_source_id
-
@exception_source_id ||= "#{self.class.name} #{__id__}"
-
end
-
-
1
def invoke_incrementing_actual_calls_by(increment, allowed_to_fail, parent_stub, *args, &block)
-
args.unshift(orig_object) if yield_receiver_to_implementation_block?
-
-
if negative? || (allowed_to_fail && (@exactly || @at_most) && (@actual_received_count == @expected_received_count))
-
# args are the args we actually received, @argument_list_matcher is the
-
# list of args we were expecting
-
@error_generator.raise_expectation_error(
-
@message, @expected_received_count,
-
@argument_list_matcher,
-
@actual_received_count + increment,
-
expectation_count_type, args, nil, exception_source_id
-
)
-
end
-
-
@order_group.handle_order_constraint self
-
-
if implementation.present?
-
implementation.call(*args, &block)
-
elsif parent_stub
-
parent_stub.invoke(nil, *args, &block)
-
end
-
ensure
-
@actual_received_count += increment
-
end
-
-
1
def has_been_invoked?
-
@actual_received_count > 0
-
end
-
-
1
def raise_already_invoked_error_if_necessary(calling_customization)
-
return unless has_been_invoked?
-
-
error_generator.raise_already_invoked_error(message, calling_customization)
-
end
-
-
1
def set_expected_received_count(relativity, n)
-
@at_least = (relativity == :at_least)
-
@at_most = (relativity == :at_most)
-
@exactly = (relativity == :exactly)
-
@expected_received_count = case n
-
when Numeric then n
-
when :once then 1
-
when :twice then 2
-
when :thrice then 3
-
end
-
end
-
-
1
def initial_implementation_action=(action)
-
implementation.initial_action = action
-
end
-
-
1
def inner_implementation_action=(action)
-
return unless action
-
warn_about_stub_override if implementation.inner_action
-
implementation.inner_action = action
-
end
-
-
1
def terminal_implementation_action=(action)
-
implementation.terminal_action = action
-
end
-
-
1
def warn_about_stub_override
-
RSpec.warning(
-
"You're overriding a previous stub implementation of `#{@message}`. " \
-
"Called from #{CallerFilter.first_non_rspec_line}."
-
)
-
end
-
end
-
-
1
include ImplementationDetails
-
end
-
-
# Handles the implementation of an `and_yield` declaration.
-
# @private
-
1
class AndYieldImplementation
-
1
def initialize(args_to_yield, eval_context, error_generator)
-
@args_to_yield = args_to_yield
-
@eval_context = eval_context
-
@error_generator = error_generator
-
end
-
-
1
def call(*_args_to_ignore, &block)
-
return if @args_to_yield.empty? && @eval_context.nil?
-
-
@error_generator.raise_missing_block_error @args_to_yield unless block
-
value = nil
-
block_signature = Support::BlockSignature.new(block)
-
-
@args_to_yield.each do |args|
-
unless Support::StrictSignatureVerifier.new(block_signature, args).valid?
-
@error_generator.raise_wrong_arity_error(args, block_signature)
-
end
-
-
value = @eval_context ? @eval_context.instance_exec(*args, &block) : block.call(*args)
-
end
-
value
-
end
-
end
-
-
# Handles the implementation of an `and_return` implementation.
-
# @private
-
1
class AndReturnImplementation
-
1
def initialize(values_to_return)
-
@values_to_return = values_to_return
-
end
-
-
1
def call(*_args_to_ignore, &_block)
-
if @values_to_return.size > 1
-
@values_to_return.shift
-
else
-
@values_to_return.first
-
end
-
end
-
end
-
-
# Represents a configured implementation. Takes into account
-
# any number of sub-implementations.
-
# @private
-
1
class Implementation
-
1
attr_accessor :initial_action, :inner_action, :terminal_action
-
-
1
def call(*args, &block)
-
actions.map do |action|
-
action.call(*args, &block)
-
end.last
-
end
-
-
1
def present?
-
actions.any?
-
end
-
-
1
private
-
-
1
def actions
-
[initial_action, inner_action, terminal_action].compact
-
end
-
end
-
-
# Represents an `and_call_original` implementation.
-
# @private
-
1
class AndWrapOriginalImplementation
-
1
def initialize(method, block)
-
@method = method
-
@block = block
-
end
-
-
1
CannotModifyFurtherError = Class.new(StandardError)
-
-
1
def initial_action=(_value)
-
raise cannot_modify_further_error
-
end
-
-
1
def inner_action=(_value)
-
raise cannot_modify_further_error
-
end
-
-
1
def terminal_action=(_value)
-
raise cannot_modify_further_error
-
end
-
-
1
def present?
-
true
-
end
-
-
1
def inner_action
-
true
-
end
-
-
1
def call(*args, &block)
-
@block.call(@method, *args, &block)
-
end
-
-
1
private
-
-
1
def cannot_modify_further_error
-
CannotModifyFurtherError.new "This method has already been configured " \
-
"to call the original implementation, and cannot be modified further."
-
end
-
end
-
end
-
end
-
1
module RSpec
-
1
module Mocks
-
# @private
-
1
class MethodDouble
-
# @private
-
1
attr_reader :method_name, :object, :expectations, :stubs, :method_stasher
-
-
# @private
-
1
def initialize(object, method_name, proxy)
-
@method_name = method_name
-
@object = object
-
@proxy = proxy
-
-
@original_visibility = nil
-
@method_stasher = InstanceMethodStasher.new(object, method_name)
-
@method_is_proxied = false
-
@expectations = []
-
@stubs = []
-
end
-
-
1
def original_implementation_callable
-
# If original method is not present, uses the `method_missing`
-
# handler of the object. This accounts for cases where the user has not
-
# correctly defined `respond_to?`, and also 1.8 which does not provide
-
# method handles for missing methods even if `respond_to?` is correct.
-
@original_implementation_callable ||= original_method ||
-
Proc.new do |*args, &block|
-
@object.__send__(:method_missing, @method_name, *args, &block)
-
end
-
end
-
-
1
alias_method :save_original_implementation_callable!, :original_implementation_callable
-
-
1
def original_method
-
@original_method ||=
-
@method_stasher.original_method ||
-
@proxy.original_method_handle_for(method_name)
-
end
-
-
# @private
-
1
def visibility
-
@proxy.visibility_for(@method_name)
-
end
-
-
# @private
-
1
def object_singleton_class
-
class << @object; self; end
-
end
-
-
# @private
-
1
def configure_method
-
@original_visibility = visibility
-
@method_stasher.stash unless @method_is_proxied
-
define_proxy_method
-
end
-
-
# @private
-
1
def define_proxy_method
-
return if @method_is_proxied
-
-
save_original_implementation_callable!
-
definition_target.class_exec(self, method_name, visibility) do |method_double, method_name, visibility|
-
define_method(method_name) do |*args, &block|
-
method_double.proxy_method_invoked(self, *args, &block)
-
end
-
__send__(visibility, method_name)
-
end
-
-
@method_is_proxied = true
-
end
-
-
# The implementation of the proxied method. Subclasses may override this
-
# method to perform additional operations.
-
#
-
# @private
-
1
def proxy_method_invoked(_obj, *args, &block)
-
@proxy.message_received method_name, *args, &block
-
end
-
-
# @private
-
1
def restore_original_method
-
return show_frozen_warning if object_singleton_class.frozen?
-
return unless @method_is_proxied
-
-
remove_method_from_definition_target
-
@method_stasher.restore if @method_stasher.method_is_stashed?
-
restore_original_visibility
-
-
@method_is_proxied = false
-
end
-
-
# @private
-
1
def show_frozen_warning
-
RSpec.warn_with(
-
"WARNING: rspec-mocks was unable to restore the original `#{@method_name}` " \
-
"method on #{@object.inspect} because it has been frozen. If you reuse this " \
-
"object, `#{@method_name}` will continue to respond with its stub implementation.",
-
:call_site => nil,
-
:use_spec_location_as_call_site => true
-
)
-
end
-
-
# @private
-
1
def restore_original_visibility
-
return unless @original_visibility &&
-
MethodReference.method_defined_at_any_visibility?(object_singleton_class, @method_name)
-
-
object_singleton_class.__send__(@original_visibility, method_name)
-
end
-
-
# @private
-
1
def verify
-
expectations.each { |e| e.verify_messages_received }
-
end
-
-
# @private
-
1
def reset
-
restore_original_method
-
clear
-
end
-
-
# @private
-
1
def clear
-
expectations.clear
-
stubs.clear
-
end
-
-
# The type of message expectation to create has been extracted to its own
-
# method so that subclasses can override it.
-
#
-
# @private
-
1
def message_expectation_class
-
MessageExpectation
-
end
-
-
# @private
-
1
def add_expectation(error_generator, expectation_ordering, expected_from, opts, &implementation)
-
configure_method
-
expectation = message_expectation_class.new(error_generator, expectation_ordering,
-
expected_from, self, :expectation, opts, &implementation)
-
expectations << expectation
-
expectation
-
end
-
-
# @private
-
1
def build_expectation(error_generator, expectation_ordering)
-
expected_from = IGNORED_BACKTRACE_LINE
-
message_expectation_class.new(error_generator, expectation_ordering, expected_from, self)
-
end
-
-
# @private
-
1
def add_stub(error_generator, expectation_ordering, expected_from, opts={}, &implementation)
-
configure_method
-
stub = message_expectation_class.new(error_generator, expectation_ordering, expected_from,
-
self, :stub, opts, &implementation)
-
stubs.unshift stub
-
stub
-
end
-
-
# A simple stub can only return a concrete value for a message, and
-
# cannot match on arguments. It is used as an optimization over
-
# `add_stub` / `add_expectation` where it is known in advance that this
-
# is all that will be required of a stub, such as when passing attributes
-
# to the `double` example method. They do not stash or restore existing method
-
# definitions.
-
#
-
# @private
-
1
def add_simple_stub(method_name, response)
-
setup_simple_method_double method_name, response, stubs
-
end
-
-
# @private
-
1
def add_simple_expectation(method_name, response, error_generator, backtrace_line)
-
setup_simple_method_double method_name, response, expectations, error_generator, backtrace_line
-
end
-
-
# @private
-
1
def setup_simple_method_double(method_name, response, collection, error_generator=nil, backtrace_line=nil)
-
define_proxy_method
-
-
me = SimpleMessageExpectation.new(method_name, response, error_generator, backtrace_line)
-
collection.unshift me
-
me
-
end
-
-
# @private
-
1
def add_default_stub(*args, &implementation)
-
return if stubs.any?
-
add_stub(*args, &implementation)
-
end
-
-
# @private
-
1
def remove_stub
-
raise_method_not_stubbed_error if stubs.empty?
-
remove_stub_if_present
-
end
-
-
# @private
-
1
def remove_stub_if_present
-
expectations.empty? ? reset : stubs.clear
-
end
-
-
# @private
-
1
def raise_method_not_stubbed_error
-
RSpec::Mocks.error_generator.raise_method_not_stubbed_error(method_name)
-
end
-
-
# In Ruby 2.0.0 and above prepend will alter the method lookup chain.
-
# We use an object's singleton class to define method doubles upon,
-
# however if the object has had it's singleton class (as opposed to
-
# it's actual class) prepended too then the the method lookup chain
-
# will look in the prepended module first, **before** the singleton
-
# class.
-
#
-
# This code works around that by providing a mock definition target
-
# that is either the singleton class, or if necessary, a prepended module
-
# of our own.
-
#
-
1
if Support::RubyFeatures.module_prepends_supported?
-
-
1
private
-
-
# We subclass `Module` in order to be able to easily detect our prepended module.
-
1
RSpecPrependedModule = Class.new(Module)
-
-
1
def definition_target
-
@definition_target ||= usable_rspec_prepended_module || object_singleton_class
-
end
-
-
1
def usable_rspec_prepended_module
-
@proxy.prepended_modules_of_singleton_class.each do |mod|
-
# If we have one of our modules prepended before one of the user's
-
# modules that defines the method, use that, since our module's
-
# definition will take precedence.
-
return mod if RSpecPrependedModule === mod
-
-
# If we hit a user module with the method defined first,
-
# we must create a new prepend module, even if one exists later,
-
# because ours will only take precedence if it comes first.
-
return new_rspec_prepended_module if mod.method_defined?(method_name)
-
end
-
-
nil
-
end
-
-
1
def new_rspec_prepended_module
-
RSpecPrependedModule.new.tap do |mod|
-
object_singleton_class.__send__ :prepend, mod
-
end
-
end
-
-
else
-
-
private
-
-
def definition_target
-
object_singleton_class
-
end
-
-
end
-
-
1
private
-
-
1
def remove_method_from_definition_target
-
definition_target.__send__(:remove_method, @method_name)
-
rescue NameError
-
# This can happen when the method has been monkeyed with by
-
# something outside RSpec. This happens, for example, when
-
# `file.write` has been stubbed, and then `file.reopen(other_io)`
-
# is later called, as `File#reopen` appears to redefine `write`.
-
#
-
# Note: we could avoid rescuing this by checking
-
# `definition_target.instance_method(@method_name).owner == definition_target`,
-
# saving us from the cost of the expensive exception, but this error is
-
# extremely rare (it was discovered on 2014-12-30, only happens on
-
# RUBY_VERSION < 2.0 and our spec suite only hits this condition once),
-
# so we'd rather avoid the cost of that check for every method double,
-
# and risk the rare situation where this exception will get raised.
-
RSpec.warn_with(
-
"WARNING: RSpec could not fully restore #{@object.inspect}." \
-
"#{@method_name}, possibly because the method has been redefined " \
-
"by something outside of RSpec."
-
)
-
end
-
end
-
end
-
end
-
1
module RSpec
-
1
module Mocks
-
# Represents a method on an object that may or may not be defined.
-
# The method may be an instance method on a module or a method on
-
# any object.
-
#
-
# @private
-
1
class MethodReference
-
1
def self.for(object_reference, method_name)
-
new(object_reference, method_name)
-
end
-
-
1
def initialize(object_reference, method_name)
-
@object_reference = object_reference
-
@method_name = method_name
-
end
-
-
# A method is implemented if sending the message does not result in
-
# a `NoMethodError`. It might be dynamically implemented by
-
# `method_missing`.
-
1
def implemented?
-
@object_reference.when_loaded do |m|
-
method_implemented?(m)
-
end
-
end
-
-
# Returns true if we definitively know that sending the method
-
# will result in a `NoMethodError`.
-
#
-
# This is not simply the inverse of `implemented?`: there are
-
# cases when we don't know if a method is implemented and
-
# both `implemented?` and `unimplemented?` will return false.
-
1
def unimplemented?
-
@object_reference.when_loaded do |_m|
-
return !implemented?
-
end
-
-
# If it's not loaded, then it may be implemented but we can't check.
-
false
-
end
-
-
# A method is defined if we are able to get a `Method` object for it.
-
# In that case, we can assert against metadata like the arity.
-
1
def defined?
-
@object_reference.when_loaded do |m|
-
method_defined?(m)
-
end
-
end
-
-
1
def with_signature
-
return unless (original = original_method)
-
yield Support::MethodSignature.new(original)
-
end
-
-
1
def visibility
-
@object_reference.when_loaded do |m|
-
return visibility_from(m)
-
end
-
-
# When it's not loaded, assume it's public. We don't want to
-
# wrongly treat the method as private.
-
:public
-
end
-
-
1
private
-
-
1
def original_method
-
@object_reference.when_loaded do |m|
-
self.defined? && find_method(m)
-
end
-
end
-
-
1
def self.instance_method_visibility_for(klass, method_name)
-
if klass.public_method_defined?(method_name)
-
:public
-
elsif klass.private_method_defined?(method_name)
-
:private
-
elsif klass.protected_method_defined?(method_name)
-
:protected
-
end
-
end
-
-
1
class << self
-
1
alias method_defined_at_any_visibility? instance_method_visibility_for
-
end
-
-
1
def self.method_visibility_for(object, method_name)
-
instance_method_visibility_for(class << object; self; end, method_name).tap do |vis|
-
# If the method is not defined on the class, `instance_method_visibility_for`
-
# returns `nil`. However, it may be handled dynamically by `method_missing`,
-
# so here we check `respond_to` (passing false to not check private methods).
-
#
-
# This only considers the public case, but I don't think it's possible to
-
# write `method_missing` in such a way that it handles a dynamic message
-
# with private or protected visibility. Ruby doesn't provide you with
-
# the caller info.
-
return :public if vis.nil? && object.respond_to?(method_name, false)
-
end
-
end
-
end
-
-
# @private
-
1
class InstanceMethodReference < MethodReference
-
1
private
-
-
1
def method_implemented?(mod)
-
MethodReference.method_defined_at_any_visibility?(mod, @method_name)
-
end
-
-
# Ideally, we'd use `respond_to?` for `method_implemented?` but we need a
-
# reference to an instance to do that and we don't have one. Note that
-
# we may get false negatives: if the method is implemented via
-
# `method_missing`, we'll return `false` even though it meets our
-
# definition of "implemented". However, it's the best we can do.
-
1
alias method_defined? method_implemented?
-
-
# works around the fact that repeated calls for method parameters will
-
# falsely return empty arrays on JRuby in certain circumstances, this
-
# is necessary here because we can't dup/clone UnboundMethods.
-
#
-
# This is necessary due to a bug in JRuby prior to 1.7.5 fixed in:
-
# https://github.com/jruby/jruby/commit/99a0613fe29935150d76a9a1ee4cf2b4f63f4a27
-
1
if RUBY_PLATFORM == 'java' && JRUBY_VERSION.split('.')[-1].to_i < 5
-
def find_method(mod)
-
mod.dup.instance_method(@method_name)
-
end
-
else
-
1
def find_method(mod)
-
mod.instance_method(@method_name)
-
end
-
end
-
-
1
def visibility_from(mod)
-
MethodReference.instance_method_visibility_for(mod, @method_name)
-
end
-
end
-
-
# @private
-
1
class ObjectMethodReference < MethodReference
-
1
def self.for(object_reference, method_name)
-
if ClassNewMethodReference.applies_to?(method_name) { object_reference.when_loaded { |o| o } }
-
ClassNewMethodReference.new(object_reference, method_name)
-
else
-
super
-
end
-
end
-
-
1
private
-
-
1
def method_implemented?(object)
-
object.respond_to?(@method_name, true)
-
end
-
-
1
def method_defined?(object)
-
(class << object; self; end).method_defined?(@method_name)
-
end
-
-
1
def find_method(object)
-
object.method(@method_name)
-
end
-
-
1
def visibility_from(object)
-
MethodReference.method_visibility_for(object, @method_name)
-
end
-
end
-
-
# When a class's `.new` method is stubbed, we want to use the method
-
# signature from `#initialize` because `.new`'s signature is a generic
-
# `def new(*args)` and it simply delegates to `#initialize` and forwards
-
# all args...so the method with the actually used signature is `#initialize`.
-
#
-
# This method reference implementation handles that specific case.
-
# @private
-
1
class ClassNewMethodReference < ObjectMethodReference
-
1
def self.applies_to?(method_name)
-
return false unless method_name == :new
-
klass = yield
-
return false unless klass.respond_to?(:new, true)
-
-
# We only want to apply our special logic to normal `new` methods.
-
# Methods that the user has monkeyed with should be left as-is.
-
klass.method(:new).owner == ::Class
-
end
-
-
1
def with_signature
-
@object_reference.when_loaded do |klass|
-
yield Support::MethodSignature.new(klass.instance_method(:initialize))
-
end
-
end
-
end
-
end
-
end
-
1
RSpec::Support.require_rspec_support 'recursive_const_methods'
-
-
1
module RSpec
-
1
module Mocks
-
# Provides information about constants that may (or may not)
-
# have been mutated by rspec-mocks.
-
1
class Constant
-
1
extend Support::RecursiveConstMethods
-
-
# @api private
-
1
def initialize(name)
-
@name = name
-
@previously_defined = false
-
@stubbed = false
-
@hidden = false
-
@valid_name = true
-
yield self if block_given?
-
end
-
-
# @return [String] The fully qualified name of the constant.
-
1
attr_reader :name
-
-
# @return [Object, nil] The original value (e.g. before it
-
# was mutated by rspec-mocks) of the constant, or
-
# nil if the constant was not previously defined.
-
1
attr_accessor :original_value
-
-
# @private
-
1
attr_writer :previously_defined, :stubbed, :hidden, :valid_name
-
-
# @return [Boolean] Whether or not the constant was defined
-
# before the current example.
-
1
def previously_defined?
-
@previously_defined
-
end
-
-
# @return [Boolean] Whether or not rspec-mocks has mutated
-
# (stubbed or hidden) this constant.
-
1
def mutated?
-
@stubbed || @hidden
-
end
-
-
# @return [Boolean] Whether or not rspec-mocks has stubbed
-
# this constant.
-
1
def stubbed?
-
@stubbed
-
end
-
-
# @return [Boolean] Whether or not rspec-mocks has hidden
-
# this constant.
-
1
def hidden?
-
@hidden
-
end
-
-
# @return [Boolean] Whether or not the provided constant name
-
# is a valid Ruby constant name.
-
1
def valid_name?
-
@valid_name
-
end
-
-
# The default `to_s` isn't very useful, so a custom version is provided.
-
1
def to_s
-
"#<#{self.class.name} #{name}>"
-
end
-
1
alias inspect to_s
-
-
# @private
-
1
def self.unmutated(name)
-
previously_defined = recursive_const_defined?(name)
-
rescue NameError
-
new(name) do |c|
-
c.valid_name = false
-
end
-
else
-
new(name) do |const|
-
const.previously_defined = previously_defined
-
const.original_value = recursive_const_get(name) if previously_defined
-
end
-
end
-
-
# Queries rspec-mocks to find out information about the named constant.
-
#
-
# @param [String] name the name of the constant
-
# @return [Constant] an object contaning information about the named
-
# constant.
-
1
def self.original(name)
-
mutator = ::RSpec::Mocks.space.constant_mutator_for(name)
-
mutator ? mutator.to_constant : unmutated(name)
-
end
-
end
-
-
# Provides a means to stub constants.
-
1
class ConstantMutator
-
1
extend Support::RecursiveConstMethods
-
-
# Stubs a constant.
-
#
-
# @param (see ExampleMethods#stub_const)
-
# @option (see ExampleMethods#stub_const)
-
# @return (see ExampleMethods#stub_const)
-
#
-
# @see ExampleMethods#stub_const
-
# @note It's recommended that you use `stub_const` in your
-
# examples. This is an alternate public API that is provided
-
# so you can stub constants in other contexts (e.g. helper
-
# classes).
-
1
def self.stub(constant_name, value, options={})
-
mutator = if recursive_const_defined?(constant_name, &raise_on_invalid_const)
-
DefinedConstantReplacer
-
else
-
UndefinedConstantSetter
-
end
-
-
mutate(mutator.new(constant_name, value, options[:transfer_nested_constants]))
-
value
-
end
-
-
# Hides a constant.
-
#
-
# @param (see ExampleMethods#hide_const)
-
#
-
# @see ExampleMethods#hide_const
-
# @note It's recommended that you use `hide_const` in your
-
# examples. This is an alternate public API that is provided
-
# so you can hide constants in other contexts (e.g. helper
-
# classes).
-
1
def self.hide(constant_name)
-
mutate(ConstantHider.new(constant_name, nil, {}))
-
nil
-
end
-
-
# Contains common functionality used by all of the constant mutators.
-
#
-
# @private
-
1
class BaseMutator
-
1
include Support::RecursiveConstMethods
-
-
1
attr_reader :original_value, :full_constant_name
-
-
1
def initialize(full_constant_name, mutated_value, transfer_nested_constants)
-
@full_constant_name = normalize_const_name(full_constant_name)
-
@mutated_value = mutated_value
-
@transfer_nested_constants = transfer_nested_constants
-
@context_parts = @full_constant_name.split('::')
-
@const_name = @context_parts.pop
-
@reset_performed = false
-
end
-
-
1
def to_constant
-
const = Constant.new(full_constant_name)
-
const.original_value = original_value
-
-
const
-
end
-
-
1
def idempotently_reset
-
reset unless @reset_performed
-
@reset_performed = true
-
end
-
end
-
-
# Hides a defined constant for the duration of an example.
-
#
-
# @private
-
1
class ConstantHider < BaseMutator
-
1
def mutate
-
return unless (@defined = recursive_const_defined?(full_constant_name))
-
@context = recursive_const_get(@context_parts.join('::'))
-
@original_value = get_const_defined_on(@context, @const_name)
-
-
@context.__send__(:remove_const, @const_name)
-
end
-
-
1
def to_constant
-
return Constant.unmutated(full_constant_name) unless @defined
-
-
const = super
-
const.hidden = true
-
const.previously_defined = true
-
-
const
-
end
-
-
1
def reset
-
return unless @defined
-
@context.const_set(@const_name, @original_value)
-
end
-
end
-
-
# Replaces a defined constant for the duration of an example.
-
#
-
# @private
-
1
class DefinedConstantReplacer < BaseMutator
-
1
def initialize(*args)
-
super
-
@constants_to_transfer = []
-
end
-
-
1
def mutate
-
@context = recursive_const_get(@context_parts.join('::'))
-
@original_value = get_const_defined_on(@context, @const_name)
-
-
@constants_to_transfer = verify_constants_to_transfer!
-
-
@context.__send__(:remove_const, @const_name)
-
@context.const_set(@const_name, @mutated_value)
-
-
transfer_nested_constants
-
end
-
-
1
def to_constant
-
const = super
-
const.stubbed = true
-
const.previously_defined = true
-
-
const
-
end
-
-
1
def reset
-
@constants_to_transfer.each do |const|
-
@mutated_value.__send__(:remove_const, const)
-
end
-
-
@context.__send__(:remove_const, @const_name)
-
@context.const_set(@const_name, @original_value)
-
end
-
-
1
def transfer_nested_constants
-
@constants_to_transfer.each do |const|
-
@mutated_value.const_set(const, get_const_defined_on(original_value, const))
-
end
-
end
-
-
1
def verify_constants_to_transfer!
-
return [] unless should_transfer_nested_constants?
-
-
{ @original_value => "the original value", @mutated_value => "the stubbed value" }.each do |value, description|
-
next if value.respond_to?(:constants)
-
-
raise ArgumentError,
-
"Cannot transfer nested constants for #{@full_constant_name} " \
-
"since #{description} is not a class or module and only classes " \
-
"and modules support nested constants."
-
end
-
-
if Array === @transfer_nested_constants
-
@transfer_nested_constants = @transfer_nested_constants.map(&:to_s) if RUBY_VERSION == '1.8.7'
-
undefined_constants = @transfer_nested_constants - constants_defined_on(@original_value)
-
-
if undefined_constants.any?
-
available_constants = constants_defined_on(@original_value) - @transfer_nested_constants
-
raise ArgumentError,
-
"Cannot transfer nested constant(s) #{undefined_constants.join(' and ')} " \
-
"for #{@full_constant_name} since they are not defined. Did you mean " \
-
"#{available_constants.join(' or ')}?"
-
end
-
-
@transfer_nested_constants
-
else
-
constants_defined_on(@original_value)
-
end
-
end
-
-
1
def should_transfer_nested_constants?
-
return true if @transfer_nested_constants
-
return false unless RSpec::Mocks.configuration.transfer_nested_constants?
-
@original_value.respond_to?(:constants) && @mutated_value.respond_to?(:constants)
-
end
-
end
-
-
# Sets an undefined constant for the duration of an example.
-
#
-
# @private
-
1
class UndefinedConstantSetter < BaseMutator
-
1
def mutate
-
@parent = @context_parts.inject(Object) do |klass, name|
-
if const_defined_on?(klass, name)
-
get_const_defined_on(klass, name)
-
else
-
ConstantMutator.stub(name_for(klass, name), Module.new)
-
end
-
end
-
-
@parent.const_set(@const_name, @mutated_value)
-
end
-
-
1
def to_constant
-
const = super
-
const.stubbed = true
-
const.previously_defined = false
-
-
const
-
end
-
-
1
def reset
-
@parent.__send__(:remove_const, @const_name)
-
end
-
-
1
private
-
-
1
def name_for(parent, name)
-
root = if parent == Object
-
''
-
else
-
parent.name
-
end
-
root + '::' + name
-
end
-
end
-
-
# Uses the mutator to mutate (stub or hide) a constant. Ensures that
-
# the mutator is correctly registered so it can be backed out at the end
-
# of the test.
-
#
-
# @private
-
1
def self.mutate(mutator)
-
::RSpec::Mocks.space.register_constant_mutator(mutator)
-
mutator.mutate
-
end
-
-
# Used internally by the constant stubbing to raise a helpful
-
# error when a constant like "A::B::C" is stubbed and A::B is
-
# not a module (and thus, it's impossible to define "A::B::C"
-
# since only modules can have nested constants).
-
#
-
# @api private
-
1
def self.raise_on_invalid_const
-
lambda do |const_name, failed_name|
-
raise "Cannot stub constant #{failed_name} on #{const_name} " \
-
"since #{const_name} is not a module."
-
end
-
end
-
end
-
end
-
end
-
1
module RSpec
-
1
module Mocks
-
# @private
-
1
class ObjectReference
-
# Returns an appropriate Object or Module reference based
-
# on the given argument.
-
1
def self.for(object_module_or_name, allow_direct_object_refs=false)
-
case object_module_or_name
-
when Module
-
if anonymous_module?(object_module_or_name)
-
DirectObjectReference.new(object_module_or_name)
-
else
-
# Use a `NamedObjectReference` if it has a name because this
-
# will use the original value of the constant in case it has
-
# been stubbed.
-
NamedObjectReference.new(name_of(object_module_or_name))
-
end
-
when String
-
NamedObjectReference.new(object_module_or_name)
-
else
-
if allow_direct_object_refs
-
DirectObjectReference.new(object_module_or_name)
-
else
-
raise ArgumentError,
-
"Module or String expected, got #{object_module_or_name.inspect}"
-
end
-
end
-
end
-
-
1
if Module.new.name.nil?
-
1
def self.anonymous_module?(mod)
-
!name_of(mod)
-
end
-
else # 1.8.7
-
def self.anonymous_module?(mod)
-
name_of(mod) == ""
-
end
-
end
-
1
private_class_method :anonymous_module?
-
-
1
def self.name_of(mod)
-
MODULE_NAME_METHOD.bind(mod).call
-
end
-
1
private_class_method :name_of
-
-
# @private
-
1
MODULE_NAME_METHOD = Module.instance_method(:name)
-
end
-
-
# An implementation of rspec-mocks' reference interface.
-
# Used when an object is passed to {ExampleMethods#object_double}, or
-
# an anonymous class or module is passed to {ExampleMethods#instance_double}
-
# or {ExampleMethods#class_double}.
-
# Represents a reference to that object.
-
# @see NamedObjectReference
-
1
class DirectObjectReference
-
# @param object [Object] the object to which this refers
-
1
def initialize(object)
-
@object = object
-
end
-
-
# @return [String] the object's description (via `#inspect`).
-
1
def description
-
@object.inspect
-
end
-
-
# Defined for interface parity with the other object reference
-
# implementations. Raises an `ArgumentError` to indicate that `as_stubbed_const`
-
# is invalid when passing an object argument to `object_double`.
-
1
def const_to_replace
-
raise ArgumentError,
-
"Can not perform constant replacement with an anonymous object."
-
end
-
-
# The target of the verifying double (the object itself).
-
#
-
# @return [Object]
-
1
def target
-
@object
-
end
-
-
# Always returns true for an object as the class is defined.
-
#
-
# @return [true]
-
1
def defined?
-
true
-
end
-
-
# Yields if the reference target is loaded, providing a generic mechanism
-
# to optionally run a bit of code only when a reference's target is
-
# loaded.
-
#
-
# This specific implementation always yields because direct references
-
# are always loaded.
-
#
-
# @yield [Object] the target of this reference.
-
1
def when_loaded
-
yield @object
-
end
-
end
-
-
# An implementation of rspec-mocks' reference interface.
-
# Used when a string is passed to {ExampleMethods#object_double},
-
# and when a string, named class or named module is passed to
-
# {ExampleMethods#instance_double}, or {ExampleMethods#class_double}.
-
# Represents a reference to the object named (via a constant lookup)
-
# by the string.
-
# @see DirectObjectReference
-
1
class NamedObjectReference
-
# @param const_name [String] constant name
-
1
def initialize(const_name)
-
@const_name = const_name
-
end
-
-
# @return [Boolean] true if the named constant is defined, false otherwise.
-
1
def defined?
-
!!object
-
end
-
-
# @return [String] the constant name to replace with a double.
-
1
def const_to_replace
-
@const_name
-
end
-
1
alias description const_to_replace
-
-
# @return [Object, nil] the target of the verifying double (the named object), or
-
# nil if it is not defined.
-
1
def target
-
object
-
end
-
-
# Yields if the reference target is loaded, providing a generic mechanism
-
# to optionally run a bit of code only when a reference's target is
-
# loaded.
-
#
-
# @yield [Object] the target object
-
1
def when_loaded
-
yield object if object
-
end
-
-
1
private
-
-
1
def object
-
return @object if defined?(@object)
-
@object = Constant.original(@const_name).original_value
-
end
-
end
-
end
-
end
-
1
module RSpec
-
1
module Mocks
-
# @private
-
1
class OrderGroup
-
1
def initialize
-
21
@expectations = []
-
21
@invocation_order = []
-
21
@index = 0
-
end
-
-
# @private
-
1
def register(expectation)
-
@expectations << expectation
-
end
-
-
1
def invoked(message)
-
@invocation_order << message
-
end
-
-
# @private
-
1
def ready_for?(expectation)
-
remaining_expectations.find(&:ordered?) == expectation
-
end
-
-
# @private
-
1
def consume
-
remaining_expectations.each_with_index do |expectation, index|
-
next unless expectation.ordered?
-
-
@index += index + 1
-
return expectation
-
end
-
nil
-
end
-
-
# @private
-
1
def handle_order_constraint(expectation)
-
return unless expectation.ordered? && remaining_expectations.include?(expectation)
-
return consume if ready_for?(expectation)
-
expectation.raise_out_of_order_error
-
end
-
-
1
def verify_invocation_order(expectation)
-
expectation.raise_out_of_order_error unless expectations_invoked_in_order?
-
true
-
end
-
-
1
def clear
-
@index = 0
-
@invocation_order.clear
-
@expectations.clear
-
end
-
-
1
def empty?
-
@expectations.empty?
-
end
-
-
1
private
-
-
1
def remaining_expectations
-
@expectations[@index..-1] || []
-
end
-
-
1
def expectations_invoked_in_order?
-
invoked_expectations == expected_invocations
-
end
-
-
1
def invoked_expectations
-
@expectations.select { |e| e.ordered? && @invocation_order.include?(e) }
-
end
-
-
1
def expected_invocations
-
@invocation_order.map { |invocation| expectation_for(invocation) }.compact
-
end
-
-
1
def expectation_for(message)
-
@expectations.find { |e| message == e }
-
end
-
end
-
end
-
end
-
1
module RSpec
-
1
module Mocks
-
# @private
-
1
class Proxy
-
1
SpecificMessage = Struct.new(:object, :message, :args) do
-
1
def ==(expectation)
-
expectation.orig_object == object && expectation.matches?(message, *args)
-
end
-
end
-
-
# @private
-
1
def ensure_implemented(*_args)
-
# noop for basic proxies, see VerifyingProxy for behaviour.
-
end
-
-
# @private
-
1
def initialize(object, order_group, options={})
-
@object = object
-
@order_group = order_group
-
@error_generator = ErrorGenerator.new(object)
-
@messages_received = []
-
@options = options
-
@null_object = false
-
@method_doubles = Hash.new { |h, k| h[k] = MethodDouble.new(@object, k, self) }
-
end
-
-
# @private
-
1
attr_reader :object
-
-
# @private
-
1
def null_object?
-
@null_object
-
end
-
-
# @private
-
# Tells the object to ignore any messages that aren't explicitly set as
-
# stubs or message expectations.
-
1
def as_null_object
-
@null_object = true
-
@object
-
end
-
-
# @private
-
1
def original_method_handle_for(_message)
-
nil
-
end
-
-
1
DEFAULT_MESSAGE_EXPECTATION_OPTS = {}.freeze
-
-
# @private
-
1
def add_message_expectation(method_name, opts=DEFAULT_MESSAGE_EXPECTATION_OPTS, &block)
-
location = opts.fetch(:expected_from) { CallerFilter.first_non_rspec_line }
-
meth_double = method_double_for(method_name)
-
-
if null_object? && !block
-
meth_double.add_default_stub(@error_generator, @order_group, location, opts) do
-
@object
-
end
-
end
-
-
meth_double.add_expectation @error_generator, @order_group, location, opts, &block
-
end
-
-
# @private
-
1
def add_simple_expectation(method_name, response, location)
-
method_double_for(method_name).add_simple_expectation method_name, response, @error_generator, location
-
end
-
-
# @private
-
1
def build_expectation(method_name)
-
meth_double = method_double_for(method_name)
-
-
meth_double.build_expectation(
-
@error_generator,
-
@order_group
-
)
-
end
-
-
# @private
-
1
def replay_received_message_on(expectation, &block)
-
expected_method_name = expectation.message
-
meth_double = method_double_for(expected_method_name)
-
-
if meth_double.expectations.any?
-
@error_generator.raise_expectation_on_mocked_method(expected_method_name)
-
end
-
-
unless null_object? || meth_double.stubs.any?
-
@error_generator.raise_expectation_on_unstubbed_method(expected_method_name)
-
end
-
-
@messages_received.each do |(actual_method_name, args, received_block)|
-
next unless expectation.matches?(actual_method_name, *args)
-
-
expectation.safe_invoke(nil)
-
block.call(*args, &received_block) if block
-
end
-
end
-
-
# @private
-
1
def check_for_unexpected_arguments(expectation)
-
return if @messages_received.empty?
-
-
return if @messages_received.any? { |method_name, args, _| expectation.matches?(method_name, *args) }
-
-
name_but_not_args, others = @messages_received.partition do |(method_name, args, _)|
-
expectation.matches_name_but_not_args(method_name, *args)
-
end
-
-
return if name_but_not_args.empty? && !others.empty?
-
-
expectation.raise_unexpected_message_args_error(name_but_not_args.map { |args| args[1] })
-
end
-
-
# @private
-
1
def add_stub(method_name, opts={}, &implementation)
-
location = opts.fetch(:expected_from) { CallerFilter.first_non_rspec_line }
-
method_double_for(method_name).add_stub @error_generator, @order_group, location, opts, &implementation
-
end
-
-
# @private
-
1
def add_simple_stub(method_name, response)
-
method_double_for(method_name).add_simple_stub method_name, response
-
end
-
-
# @private
-
1
def remove_stub(method_name)
-
method_double_for(method_name).remove_stub
-
end
-
-
# @private
-
1
def remove_stub_if_present(method_name)
-
method_double_for(method_name).remove_stub_if_present
-
end
-
-
# @private
-
1
def verify
-
@method_doubles.each_value { |d| d.verify }
-
end
-
-
# @private
-
1
def reset
-
@messages_received.clear
-
end
-
-
# @private
-
1
def received_message?(method_name, *args, &block)
-
@messages_received.any? { |array| array == [method_name, args, block] }
-
end
-
-
# @private
-
1
def messages_arg_list
-
@messages_received.map { |_, args, _| args }
-
end
-
-
# @private
-
1
def has_negative_expectation?(message)
-
method_double_for(message).expectations.find { |expectation| expectation.negative_expectation_for?(message) }
-
end
-
-
# @private
-
1
def record_message_received(message, *args, &block)
-
@order_group.invoked SpecificMessage.new(object, message, args)
-
@messages_received << [message, args, block]
-
end
-
-
# @private
-
1
def message_received(message, *args, &block)
-
record_message_received message, *args, &block
-
-
expectation = find_matching_expectation(message, *args)
-
stub = find_matching_method_stub(message, *args)
-
-
if (stub && expectation && expectation.called_max_times?) || (stub && !expectation)
-
expectation.increase_actual_received_count! if expectation && expectation.actual_received_count_matters?
-
if (expectation = find_almost_matching_expectation(message, *args))
-
expectation.advise(*args) unless expectation.expected_messages_received?
-
end
-
stub.invoke(nil, *args, &block)
-
elsif expectation
-
expectation.unadvise(messages_arg_list)
-
expectation.invoke(stub, *args, &block)
-
elsif (expectation = find_almost_matching_expectation(message, *args))
-
expectation.advise(*args) if null_object? unless expectation.expected_messages_received?
-
-
if null_object? || !has_negative_expectation?(message)
-
expectation.raise_unexpected_message_args_error([args])
-
end
-
elsif (stub = find_almost_matching_stub(message, *args))
-
stub.advise(*args)
-
raise_missing_default_stub_error(stub, [args])
-
elsif Class === @object
-
@object.superclass.__send__(message, *args, &block)
-
else
-
@object.__send__(:method_missing, message, *args, &block)
-
end
-
end
-
-
# @private
-
1
def raise_unexpected_message_error(method_name, args)
-
@error_generator.raise_unexpected_message_error method_name, args
-
end
-
-
# @private
-
1
def raise_missing_default_stub_error(expectation, args_for_multiple_calls)
-
@error_generator.raise_missing_default_stub_error(expectation, args_for_multiple_calls)
-
end
-
-
# @private
-
1
def visibility_for(_method_name)
-
# This is the default (for test doubles). Subclasses override this.
-
:public
-
end
-
-
1
if Support::RubyFeatures.module_prepends_supported?
-
1
def self.prepended_modules_of(klass)
-
ancestors = klass.ancestors
-
-
# `|| 0` is necessary for Ruby 2.0, where the singleton class
-
# is only in the ancestor list when there are prepended modules.
-
singleton_index = ancestors.index(klass) || 0
-
-
ancestors[0, singleton_index]
-
end
-
-
1
def prepended_modules_of_singleton_class
-
@prepended_modules_of_singleton_class ||= RSpec::Mocks::Proxy.prepended_modules_of(@object.singleton_class)
-
end
-
end
-
-
1
private
-
-
1
def method_double_for(message)
-
@method_doubles[message.to_sym]
-
end
-
-
1
def find_matching_expectation(method_name, *args)
-
find_best_matching_expectation_for(method_name) do |expectation|
-
expectation.matches?(method_name, *args)
-
end
-
end
-
-
1
def find_almost_matching_expectation(method_name, *args)
-
find_best_matching_expectation_for(method_name) do |expectation|
-
expectation.matches_name_but_not_args(method_name, *args)
-
end
-
end
-
-
1
def find_best_matching_expectation_for(method_name)
-
first_match = nil
-
-
method_double_for(method_name).expectations.each do |expectation|
-
next unless yield expectation
-
return expectation unless expectation.called_max_times?
-
first_match ||= expectation
-
end
-
-
first_match
-
end
-
-
1
def find_matching_method_stub(method_name, *args)
-
method_double_for(method_name).stubs.find { |stub| stub.matches?(method_name, *args) }
-
end
-
-
1
def find_almost_matching_stub(method_name, *args)
-
method_double_for(method_name).stubs.find { |stub| stub.matches_name_but_not_args(method_name, *args) }
-
end
-
end
-
-
# @private
-
1
class TestDoubleProxy < Proxy
-
1
def reset
-
@method_doubles.clear
-
object.__disallow_further_usage!
-
super
-
end
-
end
-
-
# @private
-
1
class PartialDoubleProxy < Proxy
-
1
def original_method_handle_for(message)
-
if any_instance_class_recorder_observing_method?(@object.class, message)
-
message = ::RSpec::Mocks.space.
-
any_instance_recorder_for(@object.class).
-
build_alias_method_name(message)
-
end
-
-
::RSpec::Support.method_handle_for(@object, message)
-
rescue NameError
-
nil
-
end
-
-
# @private
-
1
def add_simple_expectation(method_name, response, location)
-
method_double_for(method_name).configure_method
-
super
-
end
-
-
# @private
-
1
def add_simple_stub(method_name, response)
-
method_double_for(method_name).configure_method
-
super
-
end
-
-
# @private
-
1
def visibility_for(method_name)
-
# We fall back to :public because by default we allow undefined methods
-
# to be stubbed, and when we do so, we make them public.
-
MethodReference.method_visibility_for(@object, method_name) || :public
-
end
-
-
1
def reset
-
@method_doubles.each_value { |d| d.reset }
-
super
-
end
-
-
1
def message_received(message, *args, &block)
-
RSpec::Mocks.space.any_instance_recorders_from_ancestry_of(object).each do |subscriber|
-
subscriber.notify_received_message(object, message, args, block)
-
end
-
super
-
end
-
-
1
private
-
-
1
def any_instance_class_recorder_observing_method?(klass, method_name)
-
only_return_existing = true
-
recorder = ::RSpec::Mocks.space.any_instance_recorder_for(klass, only_return_existing)
-
return true if recorder && recorder.already_observing?(method_name)
-
-
superklass = klass.superclass
-
return false if superklass.nil?
-
any_instance_class_recorder_observing_method?(superklass, method_name)
-
end
-
end
-
-
# @private
-
# When we mock or stub a method on a class, we have to treat it a bit different,
-
# because normally singleton method definitions only affect the object on which
-
# they are defined, but on classes they affect subclasses, too. As a result,
-
# we need some special handling to get the original method.
-
1
module PartialClassDoubleProxyMethods
-
1
def initialize(source_space, *args)
-
@source_space = source_space
-
super(*args)
-
end
-
-
# Consider this situation:
-
#
-
# class A; end
-
# class B < A; end
-
#
-
# allow(A).to receive(:new)
-
# expect(B).to receive(:new).and_call_original
-
#
-
# When getting the original definition for `B.new`, we cannot rely purely on
-
# using `B.method(:new)` before our redefinition is defined on `B`, because
-
# `B.method(:new)` will return a method that will execute the stubbed version
-
# of the method on `A` since singleton methods on classes are in the lookup
-
# hierarchy.
-
#
-
# To do it properly, we need to find the original definition of `new` from `A`
-
# from _before_ `A` was stubbed, and we need to rebind it to `B` so that it will
-
# run with the proper `self`.
-
#
-
# That's what this method (together with `original_unbound_method_handle_from_ancestor_for`)
-
# does.
-
1
def original_method_handle_for(message)
-
unbound_method = superclass_proxy &&
-
superclass_proxy.original_unbound_method_handle_from_ancestor_for(message.to_sym)
-
-
return super unless unbound_method
-
unbound_method.bind(object)
-
# :nocov:
-
skipped
rescue TypeError
-
skipped
if RUBY_VERSION == '1.8.7'
-
skipped
# In MRI 1.8.7, a singleton method on a class cannot be rebound to its subclass
-
skipped
if unbound_method && unbound_method.owner.ancestors.first != unbound_method.owner
-
skipped
# This is a singleton method; we can't do anything with it
-
skipped
# But we can work around this using a different implementation
-
skipped
double = method_double_from_ancestor_for(message)
-
skipped
return object.method(double.method_stasher.stashed_method_name)
-
skipped
end
-
skipped
end
-
skipped
raise
-
# :nocov:
-
end
-
-
1
protected
-
-
1
def original_unbound_method_handle_from_ancestor_for(message)
-
double = method_double_from_ancestor_for(message)
-
double && double.original_method.unbind
-
end
-
-
1
def method_double_from_ancestor_for(message)
-
@method_doubles.fetch(message) do
-
# The fact that there is no method double for this message indicates
-
# that it has not been redefined by rspec-mocks. We need to continue
-
# looking up the ancestor chain.
-
return superclass_proxy &&
-
superclass_proxy.method_double_from_ancestor_for(message)
-
end
-
end
-
-
1
def superclass_proxy
-
return @superclass_proxy if defined?(@superclass_proxy)
-
-
if (superclass = object.superclass)
-
@superclass_proxy = @source_space.superclass_proxy_for(superclass)
-
else
-
@superclass_proxy = nil
-
end
-
end
-
end
-
-
# @private
-
1
class PartialClassDoubleProxy < PartialDoubleProxy
-
1
include PartialClassDoubleProxyMethods
-
end
-
-
# @private
-
1
class ProxyForNil < PartialDoubleProxy
-
1
def initialize(order_group)
-
set_expectation_behavior
-
super(nil, order_group)
-
end
-
-
1
attr_accessor :disallow_expectations
-
1
attr_accessor :warn_about_expectations
-
-
1
def add_message_expectation(method_name, opts={}, &block)
-
warn_or_raise!(method_name)
-
super
-
end
-
-
1
def add_negative_message_expectation(location, method_name, &implementation)
-
warn_or_raise!(method_name)
-
super
-
end
-
-
1
def add_stub(method_name, opts={}, &implementation)
-
warn_or_raise!(method_name)
-
super
-
end
-
-
1
private
-
-
1
def set_expectation_behavior
-
case RSpec::Mocks.configuration.allow_message_expectations_on_nil
-
when false
-
@warn_about_expectations = false
-
@disallow_expectations = true
-
when true
-
@warn_about_expectations = false
-
@disallow_expectations = false
-
else
-
@warn_about_expectations = true
-
@disallow_expectations = false
-
end
-
end
-
-
1
def warn_or_raise!(method_name)
-
# This method intentionally swallows the message when
-
# neither disallow_expectations nor warn_about_expectations
-
# are set to true.
-
if disallow_expectations
-
raise_error(method_name)
-
elsif warn_about_expectations
-
warn(method_name)
-
end
-
end
-
-
1
def warn(method_name)
-
warning_msg = @error_generator.expectation_on_nil_message(method_name)
-
RSpec.warning(warning_msg)
-
end
-
-
1
def raise_error(method_name)
-
@error_generator.raise_expectation_on_nil_error(method_name)
-
end
-
end
-
end
-
end
-
1
RSpec::Support.require_rspec_support 'reentrant_mutex'
-
-
1
module RSpec
-
1
module Mocks
-
# @private
-
# Provides a default space implementation for outside
-
# the scope of an example. Called "root" because it serves
-
# as the root of the space stack.
-
1
class RootSpace
-
1
def proxy_for(*_args)
-
raise_lifecycle_message
-
end
-
-
1
def any_instance_recorder_for(*_args)
-
raise_lifecycle_message
-
end
-
-
1
def any_instance_proxy_for(*_args)
-
raise_lifecycle_message
-
end
-
-
1
def register_constant_mutator(_mutator)
-
raise_lifecycle_message
-
end
-
-
1
def any_instance_recorders_from_ancestry_of(_object)
-
raise_lifecycle_message
-
end
-
-
1
def reset_all
-
end
-
-
1
def verify_all
-
end
-
-
1
def registered?(_object)
-
false
-
end
-
-
1
def superclass_proxy_for(*_args)
-
raise_lifecycle_message
-
end
-
-
1
def new_scope
-
21
Space.new
-
end
-
-
1
private
-
-
1
def raise_lifecycle_message
-
raise OutsideOfExampleError,
-
"The use of doubles or partial doubles from rspec-mocks outside of the per-test lifecycle is not supported."
-
end
-
end
-
-
# @private
-
1
class Space
-
1
attr_reader :proxies, :any_instance_recorders, :proxy_mutex, :any_instance_mutex
-
-
1
def initialize
-
21
@proxies = {}
-
21
@any_instance_recorders = {}
-
21
@constant_mutators = []
-
21
@expectation_ordering = OrderGroup.new
-
21
@proxy_mutex = new_mutex
-
21
@any_instance_mutex = new_mutex
-
end
-
-
1
def new_scope
-
NestedSpace.new(self)
-
end
-
-
1
def verify_all
-
21
proxies.values.each { |proxy| proxy.verify }
-
21
any_instance_recorders.each_value { |recorder| recorder.verify }
-
end
-
-
1
def reset_all
-
21
proxies.each_value { |proxy| proxy.reset }
-
21
@constant_mutators.reverse.each { |mut| mut.idempotently_reset }
-
21
any_instance_recorders.each_value { |recorder| recorder.stop_all_observation! }
-
21
any_instance_recorders.clear
-
end
-
-
1
def register_constant_mutator(mutator)
-
@constant_mutators << mutator
-
end
-
-
1
def constant_mutator_for(name)
-
@constant_mutators.find { |m| m.full_constant_name == name }
-
end
-
-
1
def any_instance_recorder_for(klass, only_return_existing=false)
-
any_instance_mutex.synchronize do
-
id = klass.__id__
-
any_instance_recorders.fetch(id) do
-
return nil if only_return_existing
-
any_instance_recorder_not_found_for(id, klass)
-
end
-
end
-
end
-
-
1
def any_instance_proxy_for(klass)
-
AnyInstance::Proxy.new(any_instance_recorder_for(klass), proxies_of(klass))
-
end
-
-
1
def proxies_of(klass)
-
proxies.values.select { |proxy| klass === proxy.object }
-
end
-
-
1
def proxy_for(object)
-
proxy_mutex.synchronize do
-
id = id_for(object)
-
proxies.fetch(id) { proxy_not_found_for(id, object) }
-
end
-
end
-
-
1
def superclass_proxy_for(klass)
-
proxy_mutex.synchronize do
-
id = id_for(klass)
-
proxies.fetch(id) { superclass_proxy_not_found_for(id, klass) }
-
end
-
end
-
-
1
alias ensure_registered proxy_for
-
-
1
def registered?(object)
-
proxies.key?(id_for object)
-
end
-
-
1
def any_instance_recorders_from_ancestry_of(object)
-
# Optimization: `any_instance` is a feature we generally
-
# recommend not using, so we can often early exit here
-
# without doing an O(N) linear search over the number of
-
# ancestors in the object's class hierarchy.
-
return [] if any_instance_recorders.empty?
-
-
# We access the ancestors through the singleton class, to avoid calling
-
# `class` in case `class` has been stubbed.
-
(class << object; ancestors; end).map do |klass|
-
any_instance_recorders[klass.__id__]
-
end.compact
-
end
-
-
1
private
-
-
1
def new_mutex
-
42
Support::ReentrantMutex.new
-
end
-
-
1
def proxy_not_found_for(id, object)
-
proxies[id] = case object
-
when NilClass then ProxyForNil.new(@expectation_ordering)
-
when TestDouble then object.__build_mock_proxy_unless_expired(@expectation_ordering)
-
when Class
-
class_proxy_with_callback_verification_strategy(object, CallbackInvocationStrategy.new)
-
else
-
if RSpec::Mocks.configuration.verify_partial_doubles?
-
VerifyingPartialDoubleProxy.new(object, @expectation_ordering)
-
else
-
PartialDoubleProxy.new(object, @expectation_ordering)
-
end
-
end
-
end
-
-
1
def superclass_proxy_not_found_for(id, object)
-
raise "superclass_proxy_not_found_for called with something that is not a class" unless Class === object
-
proxies[id] = class_proxy_with_callback_verification_strategy(object, NoCallbackInvocationStrategy.new)
-
end
-
-
1
def class_proxy_with_callback_verification_strategy(object, strategy)
-
if RSpec::Mocks.configuration.verify_partial_doubles?
-
VerifyingPartialClassDoubleProxy.new(
-
self,
-
object,
-
@expectation_ordering,
-
strategy
-
)
-
else
-
PartialClassDoubleProxy.new(self, object, @expectation_ordering)
-
end
-
end
-
-
1
def any_instance_recorder_not_found_for(id, klass)
-
any_instance_recorders[id] = AnyInstance::Recorder.new(klass)
-
end
-
-
1
if defined?(::BasicObject) && !::BasicObject.method_defined?(:__id__) # for 1.9.2
-
require 'securerandom'
-
-
def id_for(object)
-
id = object.__id__
-
-
return id if object.equal?(::ObjectSpace._id2ref(id))
-
# this suggests that object.__id__ is proxying through to some wrapped object
-
-
object.instance_exec do
-
@__id_for_rspec_mocks_space ||= ::SecureRandom.uuid
-
end
-
end
-
else
-
1
def id_for(object)
-
object.__id__
-
end
-
end
-
end
-
-
# @private
-
1
class NestedSpace < Space
-
1
def initialize(parent)
-
@parent = parent
-
super()
-
end
-
-
1
def proxies_of(klass)
-
super + @parent.proxies_of(klass)
-
end
-
-
1
def constant_mutator_for(name)
-
super || @parent.constant_mutator_for(name)
-
end
-
-
1
def registered?(object)
-
super || @parent.registered?(object)
-
end
-
-
1
private
-
-
1
def proxy_not_found_for(id, object)
-
@parent.proxies[id] || super
-
end
-
-
1
def any_instance_recorder_not_found_for(id, klass)
-
@parent.any_instance_recorders[id] || super
-
end
-
end
-
end
-
end
-
1
module RSpec
-
1
module Mocks
-
# @api private
-
# Provides methods for enabling and disabling the available syntaxes
-
# provided by rspec-mocks.
-
1
module Syntax
-
# @private
-
1
def self.warn_about_should!
-
1
@warn_about_should = true
-
end
-
-
# @private
-
1
def self.warn_unless_should_configured(method_name , replacement="the new `:expect` syntax or explicitly enable `:should`")
-
if @warn_about_should
-
RSpec.deprecate(
-
"Using `#{method_name}` from rspec-mocks' old `:should` syntax without explicitly enabling the syntax",
-
:replacement => replacement
-
)
-
-
@warn_about_should = false
-
end
-
end
-
-
# @api private
-
# Enables the should syntax (`dbl.stub`, `dbl.should_receive`, etc).
-
1
def self.enable_should(syntax_host=default_should_syntax_host)
-
1
@warn_about_should = false if syntax_host == default_should_syntax_host
-
1
return if should_enabled?(syntax_host)
-
-
1
syntax_host.class_exec do
-
1
def should_receive(message, opts={}, &block)
-
::RSpec::Mocks::Syntax.warn_unless_should_configured(__method__)
-
::RSpec::Mocks.expect_message(self, message, opts, &block)
-
end
-
-
1
def should_not_receive(message, &block)
-
::RSpec::Mocks::Syntax.warn_unless_should_configured(__method__)
-
::RSpec::Mocks.expect_message(self, message, {}, &block).never
-
end
-
-
1
def stub(message_or_hash, opts={}, &block)
-
::RSpec::Mocks::Syntax.warn_unless_should_configured(__method__)
-
if ::Hash === message_or_hash
-
message_or_hash.each { |message, value| stub(message).and_return value }
-
else
-
::RSpec::Mocks.allow_message(self, message_or_hash, opts, &block)
-
end
-
end
-
-
1
def unstub(message)
-
::RSpec::Mocks::Syntax.warn_unless_should_configured(__method__, "`allow(...).to receive(...).and_call_original` or explicitly enable `:should`")
-
::RSpec::Mocks.space.proxy_for(self).remove_stub(message)
-
end
-
-
1
def stub_chain(*chain, &blk)
-
::RSpec::Mocks::Syntax.warn_unless_should_configured(__method__)
-
::RSpec::Mocks::StubChain.stub_chain_on(self, *chain, &blk)
-
end
-
-
1
def as_null_object
-
::RSpec::Mocks::Syntax.warn_unless_should_configured(__method__)
-
@_null_object = true
-
::RSpec::Mocks.space.proxy_for(self).as_null_object
-
end
-
-
1
def null_object?
-
::RSpec::Mocks::Syntax.warn_unless_should_configured(__method__)
-
defined?(@_null_object)
-
end
-
-
1
def received_message?(message, *args, &block)
-
::RSpec::Mocks::Syntax.warn_unless_should_configured(__method__)
-
::RSpec::Mocks.space.proxy_for(self).received_message?(message, *args, &block)
-
end
-
-
1
unless Class.respond_to? :any_instance
-
1
Class.class_exec do
-
1
def any_instance
-
::RSpec::Mocks::Syntax.warn_unless_should_configured(__method__)
-
::RSpec::Mocks.space.any_instance_proxy_for(self)
-
end
-
end
-
end
-
end
-
end
-
-
# @api private
-
# Disables the should syntax (`dbl.stub`, `dbl.should_receive`, etc).
-
1
def self.disable_should(syntax_host=default_should_syntax_host)
-
return unless should_enabled?(syntax_host)
-
-
syntax_host.class_exec do
-
undef should_receive
-
undef should_not_receive
-
undef stub
-
undef unstub
-
undef stub_chain
-
undef as_null_object
-
undef null_object?
-
undef received_message?
-
end
-
-
Class.class_exec do
-
undef any_instance
-
end
-
end
-
-
# @api private
-
# Enables the expect syntax (`expect(dbl).to receive`, `allow(dbl).to receive`, etc).
-
1
def self.enable_expect(syntax_host=::RSpec::Mocks::ExampleMethods)
-
1
return if expect_enabled?(syntax_host)
-
-
1
syntax_host.class_exec do
-
1
def receive(method_name, &block)
-
Matchers::Receive.new(method_name, block)
-
end
-
-
1
def receive_messages(message_return_value_hash)
-
matcher = Matchers::ReceiveMessages.new(message_return_value_hash)
-
matcher.warn_about_block if block_given?
-
matcher
-
end
-
-
1
def receive_message_chain(*messages, &block)
-
Matchers::ReceiveMessageChain.new(messages, &block)
-
end
-
-
1
def allow(target)
-
AllowanceTarget.new(target)
-
end
-
-
1
def expect_any_instance_of(klass)
-
AnyInstanceExpectationTarget.new(klass)
-
end
-
-
1
def allow_any_instance_of(klass)
-
AnyInstanceAllowanceTarget.new(klass)
-
end
-
end
-
-
1
RSpec::Mocks::ExampleMethods::ExpectHost.class_exec do
-
1
def expect(target)
-
ExpectationTarget.new(target)
-
end
-
end
-
end
-
-
# @api private
-
# Disables the expect syntax (`expect(dbl).to receive`, `allow(dbl).to receive`, etc).
-
1
def self.disable_expect(syntax_host=::RSpec::Mocks::ExampleMethods)
-
return unless expect_enabled?(syntax_host)
-
-
syntax_host.class_exec do
-
undef receive
-
undef receive_messages
-
undef receive_message_chain
-
undef allow
-
undef expect_any_instance_of
-
undef allow_any_instance_of
-
end
-
-
RSpec::Mocks::ExampleMethods::ExpectHost.class_exec do
-
undef expect
-
end
-
end
-
-
# @api private
-
# Indicates whether or not the should syntax is enabled.
-
1
def self.should_enabled?(syntax_host=default_should_syntax_host)
-
1
syntax_host.method_defined?(:should_receive)
-
end
-
-
# @api private
-
# Indicates whether or not the expect syntax is enabled.
-
1
def self.expect_enabled?(syntax_host=::RSpec::Mocks::ExampleMethods)
-
1
syntax_host.method_defined?(:allow)
-
end
-
-
# @api private
-
# Determines where the methods like `should_receive`, and `stub` are added.
-
1
def self.default_should_syntax_host
-
# JRuby 1.7.4 introduces a regression whereby `defined?(::BasicObject) => nil`
-
# yet `BasicObject` still exists and patching onto ::Object breaks things
-
# e.g. SimpleDelegator expectations won't work
-
#
-
# See: https://github.com/jruby/jruby/issues/814
-
2
if defined?(JRUBY_VERSION) && JRUBY_VERSION == '1.7.4' && RUBY_VERSION.to_f > 1.8
-
return ::BasicObject
-
end
-
-
# On 1.8.7, Object.ancestors.last == Kernel but
-
# things blow up if we include `RSpec::Mocks::Methods`
-
# into Kernel...not sure why.
-
2
return Object unless defined?(::BasicObject)
-
-
# MacRuby has BasicObject but it's not the root class.
-
2
return Object unless Object.ancestors.last == ::BasicObject
-
-
2
::BasicObject
-
end
-
end
-
end
-
end
-
-
1
if defined?(BasicObject)
-
# The legacy `:should` syntax adds the following methods directly to
-
# `BasicObject` so that they are available off of any object. Note, however,
-
# that this syntax does not always play nice with delegate/proxy objects.
-
# We recommend you use the non-monkeypatching `:expect` syntax instead.
-
# @see Class
-
1
class BasicObject
-
# @method should_receive
-
# Sets an expectation that this object should receive a message before
-
# the end of the example.
-
#
-
# @example
-
# logger = double('logger')
-
# thing_that_logs = ThingThatLogs.new(logger)
-
# logger.should_receive(:log)
-
# thing_that_logs.do_something_that_logs_a_message
-
#
-
# @note This is only available when you have enabled the `should` syntax.
-
# @see RSpec::Mocks::ExampleMethods#expect
-
-
# @method should_not_receive
-
# Sets and expectation that this object should _not_ receive a message
-
# during this example.
-
# @see RSpec::Mocks::ExampleMethods#expect
-
-
# @method stub
-
# Tells the object to respond to the message with the specified value.
-
#
-
# @example
-
# counter.stub(:count).and_return(37)
-
# counter.stub(:count => 37)
-
# counter.stub(:count) { 37 }
-
#
-
# @note This is only available when you have enabled the `should` syntax.
-
# @see RSpec::Mocks::ExampleMethods#allow
-
-
# @method unstub
-
# Removes a stub. On a double, the object will no longer respond to
-
# `message`. On a real object, the original method (if it exists) is
-
# restored.
-
#
-
# This is rarely used, but can be useful when a stub is set up during a
-
# shared `before` hook for the common case, but you want to replace it
-
# for a special case.
-
#
-
# @note This is only available when you have enabled the `should` syntax.
-
-
# @method stub_chain
-
# @overload stub_chain(method1, method2)
-
# @overload stub_chain("method1.method2")
-
# @overload stub_chain(method1, method_to_value_hash)
-
#
-
# Stubs a chain of methods.
-
#
-
# ## Warning:
-
#
-
# Chains can be arbitrarily long, which makes it quite painless to
-
# violate the Law of Demeter in violent ways, so you should consider any
-
# use of `stub_chain` a code smell. Even though not all code smells
-
# indicate real problems (think fluent interfaces), `stub_chain` still
-
# results in brittle examples. For example, if you write
-
# `foo.stub_chain(:bar, :baz => 37)` in a spec and then the
-
# implementation calls `foo.baz.bar`, the stub will not work.
-
#
-
# @example
-
# double.stub_chain("foo.bar") { :baz }
-
# double.stub_chain(:foo, :bar => :baz)
-
# double.stub_chain(:foo, :bar) { :baz }
-
#
-
# # Given any of ^^ these three forms ^^:
-
# double.foo.bar # => :baz
-
#
-
# # Common use in Rails/ActiveRecord:
-
# Article.stub_chain("recent.published") { [Article.new] }
-
#
-
# @note This is only available when you have enabled the `should` syntax.
-
# @see RSpec::Mocks::ExampleMethods#receive_message_chain
-
-
# @method as_null_object
-
# Tells the object to respond to all messages. If specific stub values
-
# are declared, they'll work as expected. If not, the receiver is
-
# returned.
-
#
-
# @note This is only available when you have enabled the `should` syntax.
-
-
# @method null_object?
-
# Returns true if this object has received `as_null_object`
-
#
-
# @note This is only available when you have enabled the `should` syntax.
-
end
-
end
-
-
# The legacy `:should` syntax adds the `any_instance` to `Class`.
-
# We generally recommend you use the newer `:expect` syntax instead,
-
# which allows you to stub any instance of a class using
-
# `allow_any_instance_of(klass)` or mock any instance using
-
# `expect_any_instance_of(klass)`.
-
# @see BasicObject
-
1
class Class
-
# @method any_instance
-
# Used to set stubs and message expectations on any instance of a given
-
# class. Returns a [Recorder](Recorder), which records messages like
-
# `stub` and `should_receive` for later playback on instances of the
-
# class.
-
#
-
# @example
-
# Car.any_instance.should_receive(:go)
-
# race = Race.new
-
# race.cars << Car.new
-
# race.go # assuming this delegates to all of its cars
-
# # this example would pass
-
#
-
# Account.any_instance.stub(:balance) { Money.new(:USD, 25) }
-
# Account.new.balance # => Money.new(:USD, 25))
-
#
-
# @return [Recorder]
-
#
-
# @note This is only available when you have enabled the `should` syntax.
-
# @see RSpec::Mocks::ExampleMethods#expect_any_instance_of
-
# @see RSpec::Mocks::ExampleMethods#allow_any_instance_of
-
end
-
1
module RSpec
-
1
module Mocks
-
# @private
-
1
class TargetBase
-
1
def initialize(target)
-
@target = target
-
end
-
-
1
def self.delegate_to(matcher_method)
-
4
define_method(:to) do |matcher, &block|
-
unless matcher_allowed?(matcher)
-
raise_unsupported_matcher(:to, matcher)
-
end
-
define_matcher(matcher, matcher_method, &block)
-
end
-
end
-
-
1
def self.delegate_not_to(matcher_method, options={})
-
4
method_name = options.fetch(:from)
-
4
define_method(method_name) do |matcher, &block|
-
case matcher
-
when Matchers::Receive, Matchers::HaveReceived
-
define_matcher(matcher, matcher_method, &block)
-
when Matchers::ReceiveMessages, Matchers::ReceiveMessageChain
-
raise_negation_unsupported(method_name, matcher)
-
else
-
raise_unsupported_matcher(method_name, matcher)
-
end
-
end
-
end
-
-
1
def self.disallow_negation(method_name)
-
4
define_method(method_name) do |matcher, *_args|
-
raise_negation_unsupported(method_name, matcher)
-
end
-
end
-
-
1
private
-
-
1
def matcher_allowed?(matcher)
-
matcher.class.name.start_with?("RSpec::Mocks::Matchers".freeze)
-
end
-
-
1
def define_matcher(matcher, name, &block)
-
matcher.__send__(name, @target, &block)
-
end
-
-
1
def raise_unsupported_matcher(method_name, matcher)
-
raise UnsupportedMatcherError,
-
"only the `receive`, `have_received` and `receive_messages` matchers are supported " \
-
"with `#{expression}(...).#{method_name}`, but you have provided: #{matcher}"
-
end
-
-
1
def raise_negation_unsupported(method_name, matcher)
-
raise NegationUnsupportedError,
-
"`#{expression}(...).#{method_name} #{matcher.name}` is not supported since it " \
-
"doesn't really make sense. What would it even mean?"
-
end
-
-
1
def expression
-
self.class::EXPRESSION
-
end
-
end
-
-
# @private
-
1
class AllowanceTarget < TargetBase
-
1
EXPRESSION = :allow
-
1
delegate_to :setup_allowance
-
1
disallow_negation :not_to
-
1
disallow_negation :to_not
-
end
-
-
# @private
-
1
class ExpectationTarget < TargetBase
-
1
EXPRESSION = :expect
-
1
delegate_to :setup_expectation
-
1
delegate_not_to :setup_negative_expectation, :from => :not_to
-
1
delegate_not_to :setup_negative_expectation, :from => :to_not
-
end
-
-
# @private
-
1
class AnyInstanceAllowanceTarget < TargetBase
-
1
EXPRESSION = :allow_any_instance_of
-
1
delegate_to :setup_any_instance_allowance
-
1
disallow_negation :not_to
-
1
disallow_negation :to_not
-
end
-
-
# @private
-
1
class AnyInstanceExpectationTarget < TargetBase
-
1
EXPRESSION = :expect_any_instance_of
-
1
delegate_to :setup_any_instance_expectation
-
1
delegate_not_to :setup_any_instance_negative_expectation, :from => :not_to
-
1
delegate_not_to :setup_any_instance_negative_expectation, :from => :to_not
-
end
-
end
-
end
-
1
module RSpec
-
1
module Mocks
-
# Implements the methods needed for a pure test double. RSpec::Mocks::Double
-
# includes this module, and it is provided for cases where you want a
-
# pure test double without subclassing RSpec::Mocks::Double.
-
1
module TestDouble
-
# Creates a new test double with a `name` (that will be used in error
-
# messages only)
-
1
def initialize(name=nil, stubs={})
-
@__expired = false
-
if Hash === name && stubs.empty?
-
stubs = name
-
@name = nil
-
else
-
@name = name
-
end
-
assign_stubs(stubs)
-
end
-
-
# Tells the object to respond to all messages. If specific stub values
-
# are declared, they'll work as expected. If not, the receiver is
-
# returned.
-
1
def as_null_object
-
__mock_proxy.as_null_object
-
end
-
-
# Returns true if this object has received `as_null_object`
-
1
def null_object?
-
__mock_proxy.null_object?
-
end
-
-
# This allows for comparing the mock to other objects that proxy such as
-
# ActiveRecords belongs_to proxy objects. By making the other object run
-
# the comparison, we're sure the call gets delegated to the proxy
-
# target.
-
1
def ==(other)
-
other == __mock_proxy
-
end
-
-
# @private
-
1
def inspect
-
TestDoubleFormatter.format(self)
-
end
-
-
# @private
-
1
def to_s
-
inspect.gsub('<', '[').gsub('>', ']')
-
end
-
-
# @private
-
1
def respond_to?(message, incl_private=false)
-
__mock_proxy.null_object? ? true : super
-
end
-
-
# @private
-
1
def __build_mock_proxy_unless_expired(order_group)
-
__raise_expired_error || __build_mock_proxy(order_group)
-
end
-
-
# @private
-
1
def __disallow_further_usage!
-
@__expired = true
-
end
-
-
# Override for default freeze implementation to prevent freezing of test
-
# doubles.
-
1
def freeze
-
RSpec.warn_with("WARNING: you attempted to freeze a test double. This is explicitly a no-op as freezing doubles can lead to undesired behaviour when resetting tests.")
-
end
-
-
1
private
-
-
1
def method_missing(message, *args, &block)
-
proxy = __mock_proxy
-
proxy.record_message_received(message, *args, &block)
-
-
if proxy.null_object?
-
case message
-
when :to_int then return 0
-
when :to_a, :to_ary then return nil
-
when :to_str then return to_s
-
else return self
-
end
-
end
-
-
# Defined private and protected methods will still trigger `method_missing`
-
# when called publicly. We want ruby's method visibility error to get raised,
-
# so we simply delegate to `super` in that case.
-
# ...well, we would delegate to `super`, but there's a JRuby
-
# bug, so we raise our own visibility error instead:
-
# https://github.com/jruby/jruby/issues/1398
-
visibility = proxy.visibility_for(message)
-
if visibility == :private || visibility == :protected
-
ErrorGenerator.new(self).raise_non_public_error(
-
message, visibility
-
)
-
end
-
-
# Required wrapping doubles in an Array on Ruby 1.9.2
-
raise NoMethodError if [:to_a, :to_ary].include? message
-
proxy.raise_unexpected_message_error(message, args)
-
end
-
-
1
def assign_stubs(stubs)
-
stubs.each_pair do |message, response|
-
__mock_proxy.add_simple_stub(message, response)
-
end
-
end
-
-
1
def __mock_proxy
-
::RSpec::Mocks.space.proxy_for(self)
-
end
-
-
1
def __build_mock_proxy(order_group)
-
TestDoubleProxy.new(self, order_group)
-
end
-
-
1
def __raise_expired_error
-
return false unless @__expired
-
ErrorGenerator.new(self).raise_expired_test_double_error
-
end
-
-
1
def initialize_copy(other)
-
as_null_object if other.null_object?
-
super
-
end
-
end
-
-
# A generic test double object. `double`, `instance_double` and friends
-
# return an instance of this.
-
1
class Double
-
1
include TestDouble
-
end
-
-
# @private
-
1
module TestDoubleFormatter
-
1
def self.format(dbl, unwrap=false)
-
format = "#{type_desc(dbl)}#{verified_module_desc(dbl)} #{name_desc(dbl)}"
-
return format if unwrap
-
"#<#{format}>"
-
end
-
-
1
class << self
-
1
private
-
-
1
def type_desc(dbl)
-
case dbl
-
when InstanceVerifyingDouble then "InstanceDouble"
-
when ClassVerifyingDouble then "ClassDouble"
-
when ObjectVerifyingDouble then "ObjectDouble"
-
else "Double"
-
end
-
end
-
-
# @private
-
1
IVAR_GET = Object.instance_method(:instance_variable_get)
-
-
1
def verified_module_desc(dbl)
-
return nil unless VerifyingDouble === dbl
-
"(#{IVAR_GET.bind(dbl).call(:@doubled_module).description})"
-
end
-
-
1
def name_desc(dbl)
-
return "(anonymous)" unless (name = IVAR_GET.bind(dbl).call(:@name))
-
name.inspect
-
end
-
end
-
end
-
end
-
end
-
1
RSpec::Support.require_rspec_mocks 'verifying_proxy'
-
-
1
module RSpec
-
1
module Mocks
-
# @private
-
1
module VerifyingDouble
-
1
def respond_to?(message, include_private=false)
-
return super unless null_object?
-
-
method_ref = __mock_proxy.method_reference[message]
-
-
case method_ref.visibility
-
when :public then true
-
when :private then include_private
-
when :protected then include_private || RUBY_VERSION.to_f < 2.0
-
else !method_ref.unimplemented?
-
end
-
end
-
-
1
def method_missing(message, *args, &block)
-
# Null object conditional is an optimization. If not a null object,
-
# validity of method expectations will have been checked at definition
-
# time.
-
if null_object?
-
if @__sending_message == message
-
__mock_proxy.ensure_implemented(message)
-
else
-
__mock_proxy.ensure_publicly_implemented(message, self)
-
end
-
-
__mock_proxy.validate_arguments!(message, args)
-
end
-
-
super
-
end
-
-
# @private
-
1
module SilentIO
-
1
def self.method_missing(*); end
-
1
def self.respond_to?(*)
-
1
true
-
end
-
end
-
-
# Redefining `__send__` causes ruby to issue a warning.
-
1
old, $stderr = $stderr, SilentIO
-
1
def __send__(name, *args, &block)
-
@__sending_message = name
-
super
-
ensure
-
@__sending_message = nil
-
end
-
1
$stderr = old
-
-
1
def send(name, *args, &block)
-
__send__(name, *args, &block)
-
end
-
-
1
def initialize(doubled_module, *args)
-
@doubled_module = doubled_module
-
-
possible_name = args.first
-
name = if String === possible_name || Symbol === possible_name
-
args.shift
-
end
-
-
super(name, *args)
-
@__sending_message = nil
-
end
-
end
-
-
# A mock providing a custom proxy that can verify the validity of any
-
# method stubs or expectations against the public instance methods of the
-
# given class.
-
#
-
# @private
-
1
class InstanceVerifyingDouble
-
1
include TestDouble
-
1
include VerifyingDouble
-
-
1
def __build_mock_proxy(order_group)
-
VerifyingProxy.new(self, order_group,
-
@doubled_module,
-
InstanceMethodReference
-
)
-
end
-
end
-
-
# An awkward module necessary because we cannot otherwise have
-
# ClassVerifyingDouble inherit from Module and still share these methods.
-
#
-
# @private
-
1
module ObjectVerifyingDoubleMethods
-
1
include TestDouble
-
1
include VerifyingDouble
-
-
1
def as_stubbed_const(options={})
-
ConstantMutator.stub(@doubled_module.const_to_replace, self, options)
-
self
-
end
-
-
1
private
-
-
1
def __build_mock_proxy(order_group)
-
VerifyingProxy.new(self, order_group,
-
@doubled_module,
-
ObjectMethodReference
-
)
-
end
-
end
-
-
# Similar to an InstanceVerifyingDouble, except that it verifies against
-
# public methods of the given object.
-
#
-
# @private
-
1
class ObjectVerifyingDouble
-
1
include ObjectVerifyingDoubleMethods
-
end
-
-
# Effectively the same as an ObjectVerifyingDouble (since a class is a type
-
# of object), except with Module in the inheritance chain so that
-
# transferring nested constants to work.
-
#
-
# @private
-
1
class ClassVerifyingDouble < Module
-
1
include ObjectVerifyingDoubleMethods
-
end
-
end
-
end
-
1
RSpec::Support.require_rspec_support 'method_signature_verifier'
-
-
1
module RSpec
-
1
module Mocks
-
# A message expectation that knows about the real implementation of the
-
# message being expected, so that it can verify that any expectations
-
# have the valid arguments.
-
# @api private
-
1
class VerifyingMessageExpectation < MessageExpectation
-
# A level of indirection is used here rather than just passing in the
-
# method itself, since method look up is expensive and we only want to
-
# do it if actually needed.
-
#
-
# Conceptually the method reference makes more sense as a constructor
-
# argument since it should be immutable, but it is significantly more
-
# straight forward to build the object in pieces so for now it stays as
-
# an accessor.
-
1
attr_accessor :method_reference
-
-
1
def initialize(*args)
-
super
-
end
-
-
# @private
-
1
def with(*args, &block)
-
super(*args, &block).tap do
-
validate_expected_arguments! do |signature|
-
example_call_site_args = [:an_arg] * signature.min_non_kw_args
-
example_call_site_args << :kw_args_hash if signature.required_kw_args.any?
-
@argument_list_matcher.resolve_expected_args_based_on(example_call_site_args)
-
end
-
end
-
end
-
-
1
private
-
-
1
def validate_expected_arguments!
-
return if method_reference.nil?
-
-
method_reference.with_signature do |signature|
-
args = yield signature
-
verifier = Support::LooseSignatureVerifier.new(signature, args)
-
-
unless verifier.valid?
-
# Fail fast is required, otherwise the message expectation will fail
-
# as well ("expected method not called") and clobber this one.
-
@failed_fast = true
-
@error_generator.raise_invalid_arguments_error(verifier)
-
end
-
end
-
end
-
end
-
end
-
end
-
1
RSpec::Support.require_rspec_mocks 'verifying_message_expectation'
-
1
RSpec::Support.require_rspec_mocks 'method_reference'
-
-
1
module RSpec
-
1
module Mocks
-
# @private
-
1
class CallbackInvocationStrategy
-
1
def call(doubled_module)
-
RSpec::Mocks.configuration.verifying_double_callbacks.each do |block|
-
block.call doubled_module
-
end
-
end
-
end
-
-
# @private
-
1
class NoCallbackInvocationStrategy
-
1
def call(_doubled_module)
-
end
-
end
-
-
# @private
-
1
module VerifyingProxyMethods
-
1
def add_stub(method_name, opts={}, &implementation)
-
ensure_implemented(method_name)
-
super
-
end
-
-
1
def add_simple_stub(method_name, *args)
-
ensure_implemented(method_name)
-
super
-
end
-
-
1
def add_message_expectation(method_name, opts={}, &block)
-
ensure_implemented(method_name)
-
super
-
end
-
-
1
def ensure_implemented(method_name)
-
return unless method_reference[method_name].unimplemented?
-
-
@error_generator.raise_unimplemented_error(
-
@doubled_module,
-
method_name,
-
@object
-
)
-
end
-
-
1
def ensure_publicly_implemented(method_name, _object)
-
ensure_implemented(method_name)
-
visibility = method_reference[method_name].visibility
-
-
return if visibility == :public
-
@error_generator.raise_non_public_error(method_name, visibility)
-
end
-
end
-
-
# A verifying proxy mostly acts like a normal proxy, except that it
-
# contains extra logic to try and determine the validity of any expectation
-
# set on it. This includes whether or not methods have been defined and the
-
# validatiy of arguments on method calls.
-
#
-
# In all other ways this behaves like a normal proxy. It only adds the
-
# verification behaviour to specific methods then delegates to the parent
-
# implementation.
-
#
-
# These checks are only activated if the doubled class has already been
-
# loaded, otherwise they are disabled. This allows for testing in
-
# isolation.
-
#
-
# @private
-
1
class VerifyingProxy < TestDoubleProxy
-
1
include VerifyingProxyMethods
-
-
1
def initialize(object, order_group, doubled_module, method_reference_class)
-
super(object, order_group)
-
@object = object
-
@doubled_module = doubled_module
-
@method_reference_class = method_reference_class
-
-
# A custom method double is required to pass through a way to lookup
-
# methods to determine their parameters. This is only relevant if the doubled
-
# class is loaded.
-
@method_doubles = Hash.new do |h, k|
-
h[k] = VerifyingMethodDouble.new(@object, k, self, method_reference[k])
-
end
-
end
-
-
1
def method_reference
-
@method_reference ||= Hash.new do |h, k|
-
h[k] = @method_reference_class.for(@doubled_module, k)
-
end
-
end
-
-
1
def visibility_for(method_name)
-
method_reference[method_name].visibility
-
end
-
-
1
def validate_arguments!(method_name, args)
-
@method_doubles[method_name].validate_arguments!(args)
-
end
-
end
-
-
# @private
-
1
DEFAULT_CALLBACK_INVOCATION_STRATEGY = CallbackInvocationStrategy.new
-
-
# @private
-
1
class VerifyingPartialDoubleProxy < PartialDoubleProxy
-
1
include VerifyingProxyMethods
-
-
1
def initialize(object, expectation_ordering, optional_callback_invocation_strategy=DEFAULT_CALLBACK_INVOCATION_STRATEGY)
-
super(object, expectation_ordering)
-
@doubled_module = DirectObjectReference.new(object)
-
-
# A custom method double is required to pass through a way to lookup
-
# methods to determine their parameters.
-
@method_doubles = Hash.new do |h, k|
-
h[k] = VerifyingExistingMethodDouble.for(object, k, self)
-
end
-
-
optional_callback_invocation_strategy.call(@doubled_module)
-
end
-
-
1
def method_reference
-
@method_doubles
-
end
-
end
-
-
# @private
-
1
class VerifyingPartialClassDoubleProxy < VerifyingPartialDoubleProxy
-
1
include PartialClassDoubleProxyMethods
-
end
-
-
# @private
-
1
class VerifyingMethodDouble < MethodDouble
-
1
def initialize(object, method_name, proxy, method_reference)
-
super(object, method_name, proxy)
-
@method_reference = method_reference
-
end
-
-
1
def message_expectation_class
-
VerifyingMessageExpectation
-
end
-
-
1
def add_expectation(*args, &block)
-
# explict params necessary for 1.8.7 see #626
-
super(*args, &block).tap { |x| x.method_reference = @method_reference }
-
end
-
-
1
def add_stub(*args, &block)
-
# explict params necessary for 1.8.7 see #626
-
super(*args, &block).tap { |x| x.method_reference = @method_reference }
-
end
-
-
1
def proxy_method_invoked(obj, *args, &block)
-
validate_arguments!(args)
-
super
-
end
-
-
1
def validate_arguments!(actual_args)
-
@method_reference.with_signature do |signature|
-
verifier = Support::StrictSignatureVerifier.new(signature, actual_args)
-
raise ArgumentError, verifier.error_message unless verifier.valid?
-
end
-
end
-
end
-
-
# A VerifyingMethodDouble fetches the method to verify against from the
-
# original object, using a MethodReference. This works for pure doubles,
-
# but when the original object is itself the one being modified we need to
-
# collapse the reference and the method double into a single object so that
-
# we can access the original pristine method definition.
-
#
-
# @private
-
1
class VerifyingExistingMethodDouble < VerifyingMethodDouble
-
1
def initialize(object, method_name, proxy)
-
super(object, method_name, proxy, self)
-
-
@valid_method = object.respond_to?(method_name, true)
-
-
# Trigger an eager find of the original method since if we find it any
-
# later we end up getting a stubbed method with incorrect arity.
-
save_original_implementation_callable!
-
end
-
-
1
def with_signature
-
yield Support::MethodSignature.new(original_implementation_callable)
-
end
-
-
1
def unimplemented?
-
!@valid_method
-
end
-
-
1
def self.for(object, method_name, proxy)
-
if ClassNewMethodReference.applies_to?(method_name) { object }
-
VerifyingExistingClassNewMethodDouble
-
else
-
self
-
end.new(object, method_name, proxy)
-
end
-
end
-
-
# Used in place of a `VerifyingExistingMethodDouble` for the specific case
-
# of mocking or stubbing a `new` method on a class. In this case, we substitute
-
# the method signature from `#initialize` since new's signature is just `*args`.
-
#
-
# @private
-
1
class VerifyingExistingClassNewMethodDouble < VerifyingExistingMethodDouble
-
1
def with_signature
-
yield Support::MethodSignature.new(object.instance_method(:initialize))
-
end
-
end
-
end
-
end
-
1
module RSpec
-
1
module Mocks
-
# Version information for RSpec mocks.
-
1
module Version
-
# Version of RSpec mocks currently in use in SemVer format.
-
1
STRING = '3.4.1'
-
end
-
end
-
end
-
2
require 'rspec/rails/feature_check'
-
-
# Namespace for all core RSpec projects.
-
2
module RSpec
-
# Namespace for rspec-rails code.
-
2
module Rails
-
# Railtie to hook into Rails.
-
2
class Railtie < ::Rails::Railtie
-
# Rails-3.0.1 requires config.app_generators instead of 3.0.0's config.generators
-
2
generators = config.respond_to?(:app_generators) ? config.app_generators : config.generators
-
2
generators.integration_tool :rspec
-
2
generators.test_framework :rspec
-
-
2
generators do
-
::Rails::Generators.hidden_namespaces.reject! { |namespace| namespace.to_s.start_with?("rspec") }
-
end
-
-
2
rake_tasks do
-
load "rspec/rails/tasks/rspec.rake"
-
end
-
-
# This is called after the environment has been loaded but before Rails
-
# sets the default for the `preview_path`
-
2
initializer "rspec_rails.action_mailer",
-
:before => "action_mailer.set_configs" do |app|
-
2
setup_preview_path(app)
-
end
-
-
2
private
-
-
2
def setup_preview_path(app)
-
2
return unless supports_action_mailer_previews?(app.config)
-
2
options = app.config.action_mailer
-
2
config_default_preview_path(options) if config_preview_path?(options)
-
end
-
-
2
def config_preview_path?(options)
-
# We cannot use `respond_to?(:show_previews)` here as it will always
-
# return `true`.
-
2
if ::Rails::VERSION::STRING < '4.2'
-
2
::Rails.env.development?
-
elsif options.show_previews.nil?
-
options.show_previews = ::Rails.env.development?
-
else
-
options.show_previews
-
end
-
end
-
-
2
def config_default_preview_path(options)
-
return unless options.preview_path.blank?
-
options.preview_path = "#{::Rails.root}/spec/mailers/previews"
-
end
-
-
2
def supports_action_mailer_previews?(config)
-
# These checks avoid loading `ActionMailer`. Using `defined?` has the
-
# side-effect of the class getting loaded if it is available. This is
-
# problematic because loading `ActionMailer::Base` will cause it to
-
# read the config settings; this is the only time the config is read.
-
# If the config is loaded now, any settings declared in a config block
-
# in an initializer will be ignored.
-
#
-
# If the action mailer railtie has not been loaded then `config` will
-
# not respond to the method. However, we cannot use
-
# `config.action_mailer.respond_to?(:preview_path)` here as it will
-
# always return `true`.
-
2
config.respond_to?(:action_mailer) && ::Rails::VERSION::STRING > '4.1'
-
end
-
end
-
end
-
end
-
1
require 'rspec/core'
-
1
require 'rails/version'
-
-
# Load any of our adapters and extensions early in the process
-
1
require 'rspec/rails/adapters'
-
1
require 'rspec/rails/extensions'
-
-
# Load the rspec-rails parts
-
1
require 'rspec/rails/view_rendering'
-
1
require 'rspec/rails/matchers'
-
1
require 'rspec/rails/fixture_support'
-
1
require 'rspec/rails/example'
-
1
require 'rspec/rails/vendor/capybara'
-
1
require 'rspec/rails/configuration'
-
1
require 'rspec/rails/active_record'
-
1
require 'rspec/rails/feature_check'
-
1
module RSpec
-
1
module Rails
-
# Fake class to document RSpec ActiveRecord configuration options. In practice,
-
# these are dynamically added to the normal RSpec configuration object.
-
1
class ActiveRecordConfiguration
-
# @private
-
1
def self.initialize_activerecord_configuration(config)
-
1
config.before :suite do
-
# This allows dynamic columns etc to be used on ActiveRecord models when creating instance_doubles
-
1
if defined?(ActiveRecord) && defined?(::RSpec::Mocks)
-
1
::RSpec::Mocks.configuration.when_declaring_verifying_double do |possible_model|
-
target = possible_model.target
-
-
if Class === target && ActiveRecord::Base > target && !target.abstract_class?
-
target.define_attribute_methods
-
end
-
end
-
end
-
end
-
end
-
-
1
initialize_activerecord_configuration RSpec.configuration
-
end
-
end
-
end
-
1
require 'delegate'
-
1
require 'active_support'
-
1
require 'active_support/concern'
-
1
require 'active_support/core_ext/string'
-
-
1
module RSpec
-
1
module Rails
-
# @private
-
1
def self.disable_testunit_autorun
-
# `Test::Unit::AutoRunner.need_auto_run=` was introduced to the test-unit
-
# gem in version 2.4.9. Previous to this version `Test::Unit.run=` was
-
# used. The implementation of test-unit included with Ruby has neither
-
# method.
-
if defined?(Test::Unit::AutoRunner.need_auto_run = ())
-
Test::Unit::AutoRunner.need_auto_run = false
-
elsif defined?(Test::Unit.run = ())
-
Test::Unit.run = false
-
end
-
end
-
1
private_class_method :disable_testunit_autorun
-
-
1
if ::Rails::VERSION::STRING >= '4.1.0'
-
1
if defined?(Kernel.gem)
-
1
gem 'minitest'
-
else
-
require 'minitest'
-
end
-
1
require 'minitest/assertions'
-
# Constant aliased to either Minitest or TestUnit, depending on what is
-
# loaded.
-
1
Assertions = Minitest::Assertions
-
elsif RUBY_VERSION >= '2.2.0'
-
# Minitest / TestUnit has been removed from ruby core. However, we are
-
# on an old Rails version and must load the appropriate gem
-
if ::Rails::VERSION::STRING >= '4.0.0'
-
# ActiveSupport 4.0.x has the minitest '~> 4.2' gem as a dependency
-
# This gem has no `lib/minitest.rb` file.
-
gem 'minitest' if defined?(Kernel.gem)
-
require 'minitest/unit'
-
Assertions = MiniTest::Assertions
-
elsif ::Rails::VERSION::STRING >= '3.2.21'
-
# TODO: Change the above check to >= '3.2.22' once it's released
-
begin
-
# Test::Unit "helpfully" sets up autoload for its `AutoRunner`.
-
# While we do not reference it directly, when we load the `TestCase`
-
# classes from AS (ActiveSupport), AS kindly references `AutoRunner`
-
# for everyone.
-
#
-
# To handle this we need to pre-emptively load 'test/unit' and make
-
# sure the version installed has `AutoRunner` (the 3.x line does to
-
# date). If so, we turn the auto runner off.
-
require 'test/unit'
-
require 'test/unit/assertions'
-
disable_testunit_autorun
-
rescue LoadError => e
-
raise LoadError, <<-ERR.squish, e.backtrace
-
Ruby 2.2+ has removed test/unit from the core library. Rails
-
requires this as a dependency. Please add test-unit gem to your
-
Gemfile: `gem 'test-unit', '~> 3.0'` (#{e.message})"
-
ERR
-
end
-
Assertions = Test::Unit::Assertions
-
else
-
abort <<-MSG.squish
-
Ruby 2.2+ is not supported on Rails #{::Rails::VERSION::STRING}.
-
Check the Rails release notes for the appropriate update with
-
support.
-
MSG
-
end
-
else
-
begin
-
require 'test/unit/assertions'
-
rescue LoadError
-
# work around for Rubinius not having a std std-lib
-
require 'rubysl-test-unit' if defined?(RUBY_ENGINE) && RUBY_ENGINE == 'rbx'
-
require 'test/unit/assertions'
-
end
-
# Turn off test unit's auto runner for those using the gem
-
disable_testunit_autorun
-
# Constant aliased to either Minitest or TestUnit, depending on what is
-
# loaded.
-
Assertions = Test::Unit::Assertions
-
end
-
-
# @private
-
1
class AssertionDelegator < Module
-
1
def initialize(*assertion_modules)
-
2
assertion_class = Class.new(SimpleDelegator) do
-
2
include ::RSpec::Rails::Assertions
-
2
include ::RSpec::Rails::MinitestCounters
-
4
assertion_modules.each { |mod| include mod }
-
end
-
-
2
super() do
-
2
define_method :build_assertion_instance do
-
15
assertion_class.new(self)
-
end
-
-
2
def assertion_instance
-
15
@assertion_instance ||= build_assertion_instance
-
end
-
-
2
assertion_modules.each do |mod|
-
2
mod.public_instance_methods.each do |method|
-
10
next if method == :method_missing || method == "method_missing"
-
8
define_method(method.to_sym) do |*args, &block|
-
assertion_instance.send(method.to_sym, *args, &block)
-
end
-
end
-
end
-
end
-
end
-
end
-
-
# Adapts example groups for `Minitest::Test::LifecycleHooks`
-
#
-
# @private
-
1
module MinitestLifecycleAdapter
-
1
extend ActiveSupport::Concern
-
-
1
included do |group|
-
33
group.before { after_setup }
-
33
group.after { before_teardown }
-
-
12
group.around do |example|
-
21
before_setup
-
21
example.run
-
21
after_teardown
-
end
-
end
-
-
1
def before_setup
-
end
-
-
1
def after_setup
-
end
-
-
1
def before_teardown
-
end
-
-
1
def after_teardown
-
end
-
end
-
-
# @private
-
1
module MinitestCounters
-
1
attr_writer :assertions
-
1
def assertions
-
4
@assertions ||= 0
-
end
-
end
-
-
# @private
-
1
module SetupAndTeardownAdapter
-
1
extend ActiveSupport::Concern
-
-
1
module ClassMethods
-
# Wraps `setup` calls from within Rails' testing framework in `before`
-
# hooks.
-
1
def setup(*methods)
-
12
methods.each do |method|
-
12
if method.to_s =~ /^setup_(with_controller|fixtures|controller_request_and_response)$/
-
21
prepend_before { __send__ method }
-
else
-
21
before { __send__ method }
-
end
-
end
-
end
-
-
# @api private
-
#
-
# Wraps `teardown` calls from within Rails' testing framework in
-
# `after` hooks.
-
1
def teardown(*methods)
-
27
methods.each { |method| after { __send__ method } }
-
end
-
end
-
-
1
def initialize(*args)
-
87
super
-
87
@example = nil
-
end
-
-
1
def method_name
-
42
@example
-
end
-
end
-
-
# @private
-
1
module MinitestAssertionAdapter
-
1
extend ActiveSupport::Concern
-
-
# @private
-
1
module ClassMethods
-
# Returns the names of assertion methods that we want to expose to
-
# examples without exposing non-assertion methods in Test::Unit or
-
# Minitest.
-
1
def assertion_method_names
-
12
methods = ::RSpec::Rails::Assertions.
-
public_instance_methods.
-
select do |m|
-
540
m.to_s =~ /^(assert|flunk|refute)/
-
end
-
12
methods + [:build_message]
-
end
-
-
1
def define_assertion_delegators
-
12
assertion_method_names.each do |m|
-
420
define_method(m.to_sym) do |*args, &block|
-
4
assertion_delegator.send(m.to_sym, *args, &block)
-
end
-
end
-
end
-
end
-
-
1
class AssertionDelegator
-
1
include ::RSpec::Rails::Assertions
-
1
include ::RSpec::Rails::MinitestCounters
-
end
-
-
1
def assertion_delegator
-
4
@assertion_delegator ||= AssertionDelegator.new
-
end
-
-
1
included do
-
12
define_assertion_delegators
-
end
-
end
-
-
# Backwards compatibility. It's unlikely that anyone is using this
-
# constant, but we had forgotten to mark it as `@private` earlier
-
#
-
# @private
-
1
TestUnitAssertionAdapter = MinitestAssertionAdapter
-
end
-
end
-
1
module RSpec
-
1
module Rails
-
# Fake class to document RSpec Rails configuration options. In practice,
-
# these are dynamically added to the normal RSpec configuration object.
-
1
class Configuration
-
# @!method infer_spec_type_from_file_location!
-
# Automatically tag specs in conventional directories with matching `type`
-
# metadata so that they have relevant helpers available to them. See
-
# `RSpec::Rails::DIRECTORY_MAPPINGS` for details on which metadata is
-
# applied to each directory.
-
-
# @!method render_views=(val)
-
#
-
# When set to `true`, controller specs will render the relevant view as
-
# well. Defaults to `false`.
-
-
# @!method render_views(val)
-
# Enables view rendering for controllers specs.
-
-
# @!method render_views?
-
# Reader for currently value of `render_views` setting.
-
end
-
-
# Mappings used by `infer_spec_type_from_file_location!`.
-
#
-
# @api private
-
1
DIRECTORY_MAPPINGS = {
-
:controller => %w[spec controllers],
-
:helper => %w[spec helpers],
-
:job => %w[spec jobs],
-
:mailer => %w[spec mailers],
-
:model => %w[spec models],
-
:request => %w[spec (requests|integration|api)],
-
:routing => %w[spec routing],
-
:view => %w[spec views],
-
:feature => %w[spec features]
-
}
-
-
# @private
-
1
def self.initialize_configuration(config)
-
1
config.backtrace_exclusion_patterns << /vendor\//
-
1
config.backtrace_exclusion_patterns << %r{lib/rspec/rails}
-
-
# controller settings
-
1
config.add_setting :infer_base_class_for_anonymous_controllers, :default => true
-
-
# fixture support
-
1
config.add_setting :use_transactional_fixtures, :alias_with => :use_transactional_examples
-
1
config.add_setting :use_instantiated_fixtures
-
1
config.add_setting :global_fixtures
-
1
config.add_setting :fixture_path
-
1
config.include RSpec::Rails::FixtureSupport, :use_fixtures
-
-
# We'll need to create a deprecated module in order to properly report to
-
# gems / projects which are relying on this being loaded globally.
-
#
-
# See rspec/rspec-rails#1355 for history
-
#
-
# @deprecated Include `RSpec::Rails::RailsExampleGroup` or
-
# `RSpec::Rails::FixtureSupport` directly instead
-
1
config.include RSpec::Rails::FixtureSupport
-
-
# This allows us to expose `render_views` as a config option even though it
-
# breaks the convention of other options by using `render_views` as a
-
# command (i.e. `render_views = true`), where it would normally be used
-
# as a getter. This makes it easier for rspec-rails users because we use
-
# `render_views` directly in example groups, so this aligns the two APIs,
-
# but requires this workaround:
-
1
config.add_setting :rendering_views, :default => false
-
-
1
config.instance_exec do
-
1
def render_views=(val)
-
self.rendering_views = val
-
end
-
-
1
def render_views
-
self.rendering_views = true
-
end
-
-
1
def render_views?
-
30
rendering_views
-
end
-
-
1
def infer_spec_type_from_file_location!
-
DIRECTORY_MAPPINGS.each do |type, dir_parts|
-
escaped_path = Regexp.compile(dir_parts.join('[\\\/]') + '[\\\/]')
-
define_derived_metadata(:file_path => escaped_path) do |metadata|
-
metadata[:type] ||= type
-
end
-
end
-
end
-
-
# Adds exclusion filters for gems included with Rails
-
1
def filter_rails_from_backtrace!
-
filter_gems_from_backtrace "actionmailer", "actionpack", "actionview"
-
filter_gems_from_backtrace "activemodel", "activerecord",
-
"activesupport", "activejob"
-
end
-
end
-
-
1
config.include RSpec::Rails::ControllerExampleGroup, :type => :controller
-
1
config.include RSpec::Rails::HelperExampleGroup, :type => :helper
-
1
config.include RSpec::Rails::ModelExampleGroup, :type => :model
-
1
config.include RSpec::Rails::RequestExampleGroup, :type => :request
-
1
config.include RSpec::Rails::RoutingExampleGroup, :type => :routing
-
1
config.include RSpec::Rails::ViewExampleGroup, :type => :view
-
1
config.include RSpec::Rails::FeatureExampleGroup, :type => :feature
-
-
1
if defined?(ActionMailer)
-
1
config.include RSpec::Rails::MailerExampleGroup, :type => :mailer
-
end
-
-
1
if defined?(ActiveJob)
-
config.include RSpec::Rails::JobExampleGroup, :type => :job
-
end
-
end
-
-
1
initialize_configuration RSpec.configuration
-
end
-
end
-
1
require 'rspec/rails/example/rails_example_group'
-
1
require 'rspec/rails/example/controller_example_group'
-
1
require 'rspec/rails/example/request_example_group'
-
1
require 'rspec/rails/example/helper_example_group'
-
1
require 'rspec/rails/example/view_example_group'
-
1
require 'rspec/rails/example/mailer_example_group'
-
1
require 'rspec/rails/example/routing_example_group'
-
1
require 'rspec/rails/example/model_example_group'
-
1
require 'rspec/rails/example/job_example_group'
-
1
require 'rspec/rails/example/feature_example_group'
-
1
module RSpec
-
1
module Rails
-
# @private
-
1
ControllerAssertionDelegator = RSpec::Rails::AssertionDelegator.new(
-
ActionDispatch::Assertions::RoutingAssertions
-
)
-
-
# @api public
-
# Container module for controller spec functionality.
-
1
module ControllerExampleGroup
-
1
extend ActiveSupport::Concern
-
1
include RSpec::Rails::RailsExampleGroup
-
1
include ActionController::TestCase::Behavior
-
1
include RSpec::Rails::ViewRendering
-
1
include RSpec::Rails::Matchers::RedirectTo
-
1
include RSpec::Rails::Matchers::RenderTemplate
-
1
include RSpec::Rails::Matchers::RoutingMatchers
-
1
include ControllerAssertionDelegator
-
-
# Class-level DSL for controller specs.
-
1
module ClassMethods
-
# @private
-
1
def controller_class
-
15
described_class
-
end
-
-
# Supports a simple DSL for specifying behavior of ApplicationController.
-
# Creates an anonymous subclass of ApplicationController and evals the
-
# `body` in that context. Also sets up implicit routes for this
-
# controller, that are separate from those defined in "config/routes.rb".
-
#
-
# @note Due to Ruby 1.8 scoping rules in anonymous subclasses, constants
-
# defined in `ApplicationController` must be fully qualified (e.g.
-
# `ApplicationController::AccessDenied`) in the block passed to the
-
# `controller` method. Any instance methods, filters, etc, that are
-
# defined in `ApplicationController`, however, are accessible from
-
# within the block.
-
#
-
# @example
-
# describe ApplicationController do
-
# controller do
-
# def index
-
# raise ApplicationController::AccessDenied
-
# end
-
# end
-
#
-
# describe "handling AccessDenied exceptions" do
-
# it "redirects to the /401.html page" do
-
# get :index
-
# response.should redirect_to("/401.html")
-
# end
-
# end
-
# end
-
#
-
# If you would like to spec a subclass of ApplicationController, call
-
# controller like so:
-
#
-
# controller(ApplicationControllerSubclass) do
-
# # ....
-
# end
-
1
def controller(base_class = nil, &body)
-
if RSpec.configuration.infer_base_class_for_anonymous_controllers?
-
base_class ||= controller_class
-
end
-
base_class ||= defined?(ApplicationController) ? ApplicationController : ActionController::Base
-
-
new_controller_class = Class.new(base_class) do
-
def self.name
-
root_controller = defined?(ApplicationController) ? ApplicationController : ActionController::Base
-
if superclass == root_controller || superclass.abstract?
-
"AnonymousController"
-
else
-
superclass.name
-
end
-
end
-
end
-
new_controller_class.class_exec(&body)
-
(class << self; self; end).__send__(:define_method, :controller_class) { new_controller_class }
-
-
before do
-
@orig_routes = routes
-
resource_name = if @controller.respond_to?(:controller_name)
-
@controller.controller_name.to_sym
-
else
-
:anonymous
-
end
-
resource_path = if @controller.respond_to?(:controller_path)
-
@controller.controller_path
-
else
-
resource_name.to_s
-
end
-
resource_module = resource_path.rpartition('/').first.presence
-
resource_as = 'anonymous_' + resource_path.tr('/', '_')
-
self.routes = ActionDispatch::Routing::RouteSet.new.tap do |r|
-
r.draw do
-
resources resource_name,
-
:as => resource_as,
-
:module => resource_module,
-
:path => resource_path
-
end
-
end
-
end
-
-
after do
-
self.routes = @orig_routes
-
@orig_routes = nil
-
end
-
end
-
-
# Specifies the routeset that will be used for the example group. This
-
# is most useful when testing Rails engines.
-
#
-
# @example
-
# describe MyEngine::PostsController do
-
# routes { MyEngine::Engine.routes }
-
#
-
# # ...
-
# end
-
1
def routes
-
before do
-
self.routes = yield
-
end
-
end
-
end
-
-
# @!attribute [r]
-
# Returns the controller object instance under test.
-
1
attr_reader :controller
-
-
# @!attribute [r]
-
# Returns the Rails routes used for the spec.
-
1
attr_reader :routes
-
-
# @private
-
#
-
# RSpec Rails uses this to make Rails routes easily available to specs.
-
1
def routes=(routes)
-
15
@routes = routes
-
15
assertion_instance.instance_variable_set(:@routes, routes)
-
end
-
-
# @private
-
1
module BypassRescue
-
1
def rescue_with_handler(exception)
-
raise exception
-
end
-
end
-
-
# Extends the controller with a module that overrides
-
# `rescue_with_handler` to raise the exception passed to it. Use this to
-
# specify that an action _should_ raise an exception given appropriate
-
# conditions.
-
#
-
# @example
-
# describe ProfilesController do
-
# it "raises a 403 when a non-admin user tries to view another user's profile" do
-
# profile = create_profile
-
# login_as profile.user
-
#
-
# expect do
-
# bypass_rescue
-
# get :show, :id => profile.id + 1
-
# end.to raise_error(/403 Forbidden/)
-
# end
-
# end
-
1
def bypass_rescue
-
controller.extend(BypassRescue)
-
end
-
-
# If method is a named_route, delegates to the RouteSet associated with
-
# this controller.
-
1
def method_missing(method, *args, &block)
-
11
if route_available?(method)
-
controller.send(method, *args, &block)
-
else
-
11
super
-
end
-
end
-
-
1
included do
-
6
subject { controller }
-
-
6
before do
-
15
self.routes = ::Rails.application.routes
-
end
-
-
6
around do |ex|
-
15
previous_allow_forgery_protection_value = ActionController::Base.allow_forgery_protection
-
15
begin
-
15
ActionController::Base.allow_forgery_protection = false
-
15
ex.call
-
ensure
-
15
ActionController::Base.allow_forgery_protection = previous_allow_forgery_protection_value
-
end
-
end
-
end
-
-
1
private
-
-
1
def route_available?(method)
-
11
(defined?(@routes) && route_defined?(routes, method)) ||
-
22
(defined?(@orig_routes) && route_defined?(@orig_routes, method))
-
end
-
-
1
def route_defined?(routes, method)
-
11
return false if routes.nil?
-
-
11
if routes.named_routes.respond_to?(:route_defined?)
-
routes.named_routes.route_defined?(method)
-
else
-
11
routes.named_routes.helpers.include?(method)
-
end
-
end
-
end
-
end
-
end
-
1
module RSpec
-
1
module Rails
-
# @api public
-
# Container module for routing spec functionality.
-
1
module FeatureExampleGroup
-
1
extend ActiveSupport::Concern
-
1
include RSpec::Rails::RailsExampleGroup
-
-
# Default host to be used in Rails route helpers if none is specified.
-
1
DEFAULT_HOST = "www.example.com"
-
-
1
included do
-
app = ::Rails.application
-
if app.respond_to?(:routes)
-
include app.routes.url_helpers if app.routes.respond_to?(:url_helpers)
-
include app.routes.mounted_helpers if app.routes.respond_to?(:mounted_helpers)
-
-
if respond_to?(:default_url_options)
-
default_url_options[:host] ||= ::RSpec::Rails::FeatureExampleGroup::DEFAULT_HOST
-
end
-
end
-
end
-
-
# Shim to check for presence of Capybara. Will delegate if present, raise
-
# if not. We assume here that in most cases `visit` will be the first
-
# Capybara method called in a spec.
-
1
def visit(*)
-
if defined?(super)
-
super
-
else
-
raise "Capybara not loaded, please add it to your Gemfile:\n\ngem \"capybara\""
-
end
-
end
-
end
-
end
-
end
-
-
1
unless RSpec.respond_to?(:feature)
-
1
opts = {
-
:capybara_feature => true,
-
:type => :feature,
-
:skip => <<-EOT.squish
-
Feature specs require the Capybara (http://github.com/jnicklas/capybara)
-
gem, version 2.2.0 or later. We recommend version 2.4.0 or later to avoid
-
some deprecation warnings and have support for
-
`config.expose_dsl_globally = false`.
-
EOT
-
}
-
-
# Capybara's monkey patching causes us to have to jump through some hoops
-
1
top_level = self
-
1
main_feature = nil
-
1
if defined?(Capybara) && ::Capybara::VERSION.to_f < 2.4
-
# Capybara 2.2 and 2.3 do not use `alias_example_xyz`
-
opts[:skip] = <<-EOT.squish
-
Capybara < 2.4.0 does not support RSpec's namespace or
-
`config.expose_dsl_globally = false`. Upgrade to Capybara >= 2.4.0.
-
EOT
-
main_feature = top_level.method(:feature) if top_level.respond_to?(:feature)
-
end
-
-
1
RSpec.configure do |c|
-
1
main_feature = nil unless c.expose_dsl_globally?
-
1
c.alias_example_group_to :feature, opts
-
1
c.alias_example_to :scenario
-
1
c.alias_example_to :xscenario
-
end
-
-
# Due to load order issues and `config.expose_dsl_globally?` defaulting to
-
# `true` we need to put Capybara's monkey patch method back. Otherwise,
-
# app upgrades have a high likelyhood of having all feature specs skipped.
-
1
top_level.define_singleton_method(:feature, &main_feature) if main_feature
-
end
-
1
require 'rspec/rails/view_assigns'
-
-
1
module RSpec
-
1
module Rails
-
# @api public
-
# Container module for helper specs.
-
1
module HelperExampleGroup
-
1
extend ActiveSupport::Concern
-
1
include RSpec::Rails::RailsExampleGroup
-
1
include ActionView::TestCase::Behavior
-
1
include RSpec::Rails::ViewAssigns
-
-
# @private
-
1
module ClassMethods
-
1
def determine_default_helper_class(_ignore)
-
described_class
-
end
-
end
-
-
# Returns an instance of ActionView::Base with the helper being specified
-
# mixed in, along with any of the built-in rails helpers.
-
1
def helper
-
_view.tap do |v|
-
v.extend(ApplicationHelper) if defined?(ApplicationHelper)
-
v.assign(view_assigns)
-
end
-
end
-
-
1
private
-
-
1
def _controller_path(example)
-
example.example_group.described_class.to_s.sub(/Helper/, '').underscore
-
end
-
-
1
included do
-
before do |example|
-
controller.controller_path = _controller_path(example)
-
end
-
end
-
end
-
end
-
end
-
1
module RSpec
-
1
module Rails
-
# @api public
-
# Container module for job spec functionality. It is only available if
-
# ActiveJob has been loaded before it.
-
1
module JobExampleGroup
-
# This blank module is only necessary for YARD processing. It doesn't
-
# handle the conditional `defined?` check below very well.
-
end
-
end
-
end
-
-
1
if defined?(ActiveJob)
-
module RSpec
-
module Rails
-
# Container module for job spec functionality.
-
module JobExampleGroup
-
extend ActiveSupport::Concern
-
include RSpec::Rails::RailsExampleGroup
-
end
-
end
-
end
-
end
-
1
module RSpec
-
1
module Rails
-
# @api public
-
# Container module for mailer spec functionality. It is only available if
-
# ActionMailer has been loaded before it.
-
1
module MailerExampleGroup
-
# This blank module is only necessary for YARD processing. It doesn't
-
# handle the conditional `defined?` check below very well.
-
end
-
end
-
end
-
-
1
if defined?(ActionMailer)
-
1
module RSpec
-
1
module Rails
-
# Container module for mailer spec functionality.
-
1
module MailerExampleGroup
-
1
extend ActiveSupport::Concern
-
1
include RSpec::Rails::RailsExampleGroup
-
1
include ActionMailer::TestCase::Behavior
-
-
1
included do
-
include ::Rails.application.routes.url_helpers
-
options = ::Rails.configuration.action_mailer.default_url_options
-
options.each { |key, value| default_url_options[key] = value } if options
-
end
-
-
# Class-level DSL for mailer specs.
-
1
module ClassMethods
-
# Alias for `described_class`.
-
1
def mailer_class
-
described_class
-
end
-
end
-
end
-
end
-
end
-
end
-
1
module RSpec
-
1
module Rails
-
# @api public
-
# Container class for model spec functionality. Does not provide anything
-
# special over the common RailsExampleGroup currently.
-
1
module ModelExampleGroup
-
1
extend ActiveSupport::Concern
-
1
include RSpec::Rails::RailsExampleGroup
-
end
-
end
-
end
-
# Temporary workaround to resolve circular dependency between rspec-rails' spec
-
# suite and ammeter.
-
1
require 'rspec/rails/matchers'
-
-
1
module RSpec
-
1
module Rails
-
# @api public
-
# Common rails example functionality.
-
1
module RailsExampleGroup
-
1
extend ActiveSupport::Concern
-
1
include RSpec::Rails::SetupAndTeardownAdapter
-
1
include RSpec::Rails::MinitestLifecycleAdapter if ::Rails::VERSION::STRING >= '4'
-
1
include RSpec::Rails::MinitestAssertionAdapter
-
1
include RSpec::Rails::Matchers
-
1
include RSpec::Rails::FixtureSupport
-
end
-
end
-
end
-
1
module RSpec
-
1
module Rails
-
# @api public
-
# Container class for request spec functionality.
-
1
module RequestExampleGroup
-
1
extend ActiveSupport::Concern
-
1
include RSpec::Rails::RailsExampleGroup
-
1
include ActionDispatch::Integration::Runner
-
1
include ActionDispatch::Assertions
-
1
include RSpec::Rails::Matchers::RedirectTo
-
1
include RSpec::Rails::Matchers::RenderTemplate
-
1
include ActionController::TemplateAssertions
-
-
# Delegates to `Rails.application`.
-
1
def app
-
::Rails.application
-
end
-
-
1
included do
-
before do
-
@routes = ::Rails.application.routes
-
end
-
end
-
end
-
end
-
end
-
1
require "action_dispatch/testing/assertions/routing"
-
-
1
module RSpec
-
1
module Rails
-
# @private
-
1
RoutingAssertionDelegator = RSpec::Rails::AssertionDelegator.new(
-
ActionDispatch::Assertions::RoutingAssertions
-
)
-
-
# @api public
-
# Container module for routing spec functionality.
-
1
module RoutingExampleGroup
-
1
extend ActiveSupport::Concern
-
1
include RSpec::Rails::RailsExampleGroup
-
1
include RSpec::Rails::Matchers::RoutingMatchers
-
1
include RSpec::Rails::Matchers::RoutingMatchers::RouteHelpers
-
1
include RSpec::Rails::RoutingAssertionDelegator
-
-
# Class-level DSL for route specs.
-
1
module ClassMethods
-
# Specifies the routeset that will be used for the example group. This
-
# is most useful when testing Rails engines.
-
#
-
# @example
-
# describe MyEngine::PostsController do
-
# routes { MyEngine::Engine.routes }
-
#
-
# it "routes posts#index" do
-
# expect(:get => "/posts").to
-
# route_to(:controller => "my_engine/posts", :action => "index")
-
# end
-
# end
-
1
def routes
-
before do
-
self.routes = yield
-
end
-
end
-
end
-
-
1
included do
-
before do
-
self.routes = ::Rails.application.routes
-
end
-
end
-
-
# @!attribute [r]
-
# @private
-
1
attr_reader :routes
-
-
# @private
-
1
def routes=(routes)
-
@routes = routes
-
assertion_instance.instance_variable_set(:@routes, routes)
-
end
-
-
1
private
-
-
1
def method_missing(m, *args, &block)
-
routes.url_helpers.respond_to?(m) ? routes.url_helpers.send(m, *args) : super
-
end
-
end
-
end
-
end
-
1
require 'rspec/rails/view_assigns'
-
-
1
module RSpec
-
1
module Rails
-
# @api public
-
# Container class for view spec functionality.
-
1
module ViewExampleGroup
-
1
extend ActiveSupport::Concern
-
1
include RSpec::Rails::RailsExampleGroup
-
1
include ActionView::TestCase::Behavior
-
1
include RSpec::Rails::ViewAssigns
-
1
include RSpec::Rails::Matchers::RenderTemplate
-
-
# @private
-
1
module ClassMethods
-
1
def _default_helper
-
base = metadata[:description].split('/')[0..-2].join('/')
-
(base.camelize + 'Helper').constantize unless base.to_s.empty?
-
rescue NameError
-
nil
-
end
-
-
1
def _default_helpers
-
helpers = [_default_helper].compact
-
helpers << ApplicationHelper if Object.const_defined?('ApplicationHelper')
-
helpers
-
end
-
end
-
-
# DSL exposed to view specs.
-
1
module ExampleMethods
-
# @overload render
-
# @overload render({:partial => path_to_file})
-
# @overload render({:partial => path_to_file}, {... locals ...})
-
# @overload render({:partial => path_to_file}, {... locals ...}) do ... end
-
#
-
# Delegates to ActionView::Base#render, so see documentation on that
-
# for more info.
-
#
-
# The only addition is that you can call render with no arguments, and
-
# RSpec will pass the top level description to render:
-
#
-
# describe "widgets/new.html.erb" do
-
# it "shows all the widgets" do
-
# render # => view.render(:file => "widgets/new.html.erb")
-
# # ...
-
# end
-
# end
-
1
def render(options = {}, local_assigns = {}, &block)
-
options = _default_render_options if Hash === options && options.empty?
-
super(options, local_assigns, &block)
-
end
-
-
# The instance of `ActionView::Base` that is used to render the template.
-
# Use this to stub methods _before_ calling `render`.
-
#
-
# describe "widgets/new.html.erb" do
-
# it "shows all the widgets" do
-
# view.stub(:foo) { "foo" }
-
# render
-
# # ...
-
# end
-
# end
-
1
def view
-
_view
-
end
-
-
# Simulates the presence of a template on the file system by adding a
-
# Rails' FixtureResolver to the front of the view_paths list. Designed to
-
# help isolate view examples from partials rendered by the view template
-
# that is the subject of the example.
-
#
-
# stub_template("widgets/_widget.html.erb" => "This content.")
-
1
def stub_template(hash)
-
view.view_paths.unshift(ActionView::FixtureResolver.new(hash))
-
end
-
-
# Provides access to the params hash that will be available within the
-
# view.
-
#
-
# params[:foo] = 'bar'
-
1
def params
-
controller.params
-
end
-
-
# @deprecated Use `view` instead.
-
1
def template
-
RSpec.deprecate("template", :replacement => "view")
-
view
-
end
-
-
# @deprecated Use `rendered` instead.
-
1
def response
-
# `assert_template` expects `response` to implement a #body method
-
# like an `ActionDispatch::Response` does to force the view to
-
# render. For backwards compatibility, we use #response as an alias
-
# for #rendered, but it needs to implement #body to avoid
-
# `assert_template` raising a `NoMethodError`.
-
unless rendered.respond_to?(:body)
-
def rendered.body
-
self
-
end
-
end
-
-
rendered
-
end
-
-
1
private
-
-
1
def _default_render_options
-
if ::Rails::VERSION::STRING >= '3.2'
-
# pluck the handler, format, and locale out of, eg, posts/index.de.html.haml
-
template, *components = _default_file_to_render.split('.')
-
handler, format, locale = *components.reverse
-
-
render_options = { :template => template }
-
render_options[:handlers] = [handler] if handler
-
render_options[:formats] = [format.to_sym] if format
-
render_options[:locales] = [locale] if locale
-
-
render_options
-
else
-
{ :template => _default_file_to_render }
-
end
-
end
-
-
1
def _path_parts
-
_default_file_to_render.split("/")
-
end
-
-
1
def _controller_path
-
_path_parts[0..-2].join("/")
-
end
-
-
1
def _inferred_action
-
_path_parts.last.split(".").first
-
end
-
-
1
def _include_controller_helpers
-
helpers = controller._helpers
-
view.singleton_class.class_exec do
-
include helpers unless included_modules.include?(helpers)
-
end
-
end
-
end
-
-
1
included do
-
include ExampleMethods
-
-
helper(*_default_helpers)
-
-
before do
-
_include_controller_helpers
-
if view.lookup_context.respond_to?(:prefixes)
-
# rails 3.1
-
view.lookup_context.prefixes << _controller_path
-
end
-
-
controller.controller_path = _controller_path
-
controller.request.path_parameters[:controller] = _controller_path
-
controller.request.path_parameters[:action] = _inferred_action unless _inferred_action =~ /^_/
-
end
-
-
let(:_default_file_to_render) do |example|
-
example.example_group.top_level_description
-
end
-
end
-
end
-
end
-
end
-
1
require 'rspec/rails/extensions/active_record/proxy'
-
1
RSpec.configure do |rspec|
-
# Delay this in order to give users a chance to configure `expect_with`...
-
1
rspec.before(:suite) do
-
1
if defined?(RSpec::Matchers) && RSpec::Matchers.configuration.syntax.include?(:should) && defined?(ActiveRecord::Associations)
-
# In Rails 3.0, it was AssociationProxy.
-
# In 3.1+, it's CollectionProxy.
-
1
const_name = [:CollectionProxy, :AssociationProxy].find do |const|
-
1
ActiveRecord::Associations.const_defined?(const)
-
end
-
-
1
proxy_class = ActiveRecord::Associations.const_get(const_name)
-
-
1
RSpec::Matchers.configuration.add_should_and_should_not_to proxy_class
-
end
-
end
-
end
-
2
module RSpec
-
2
module Rails
-
# @private
-
# Disable some cops until https://github.com/bbatsov/rubocop/issues/1310
-
# rubocop:disable Style/IndentationConsistency
-
2
module FeatureCheck
-
# rubocop:disable Style/IndentationWidth
-
2
module_function
-
# rubocop:enable Style/IndentationWidth
-
-
2
def can_check_pending_migrations?
-
has_active_record_migration? &&
-
::ActiveRecord::Migration.respond_to?(:check_pending!)
-
end
-
-
2
def can_maintain_test_schema?
-
has_active_record_migration? &&
-
::ActiveRecord::Migration.respond_to?(:maintain_test_schema!)
-
end
-
-
2
def has_active_job?
-
1
defined?(::ActiveJob)
-
end
-
-
2
def has_active_record?
-
defined?(::ActiveRecord)
-
end
-
-
2
def has_active_record_migration?
-
has_active_record? && defined?(::ActiveRecord::Migration)
-
end
-
-
2
def has_action_mailer?
-
defined?(::ActionMailer)
-
end
-
-
2
def has_action_mailer_preview?
-
has_action_mailer? && defined?(::ActionMailer::Preview)
-
end
-
-
2
def has_action_mailer_show_preview?
-
has_action_mailer_preview? &&
-
::ActionMailer::Base.respond_to?(:show_previews=)
-
end
-
-
2
def has_1_9_hash_syntax?
-
::Rails::VERSION::STRING > '4.0'
-
end
-
-
2
def type_metatag(type)
-
if has_1_9_hash_syntax?
-
"type: :#{type}"
-
else
-
":type => :#{type}"
-
end
-
end
-
end
-
# rubocop:enable Style/IndentationConsistency
-
end
-
end
-
1
module RSpec
-
1
module Rails
-
# @private
-
1
module FixtureSupport
-
1
if defined?(ActiveRecord::TestFixtures)
-
1
extend ActiveSupport::Concern
-
1
include RSpec::Rails::SetupAndTeardownAdapter
-
1
include RSpec::Rails::MinitestLifecycleAdapter if ::ActiveRecord::VERSION::STRING > '4'
-
1
include RSpec::Rails::MinitestAssertionAdapter
-
1
include ActiveRecord::TestFixtures
-
-
1
included do
-
# TODO: (DC 2011-06-25) this is necessary because fixture_file_upload
-
# accesses fixture_path directly on ActiveSupport::TestCase. This is
-
# fixed in rails by https://github.com/rails/rails/pull/1861, which
-
# should be part of the 3.1 release, at which point we can include
-
# these lines for rails < 3.1.
-
12
ActiveSupport::TestCase.class_exec do
-
12
include ActiveRecord::TestFixtures
-
12
self.fixture_path = RSpec.configuration.fixture_path
-
end
-
# /TODO
-
-
12
self.fixture_path = RSpec.configuration.fixture_path
-
12
self.use_transactional_fixtures = RSpec.configuration.use_transactional_fixtures
-
12
self.use_instantiated_fixtures = RSpec.configuration.use_instantiated_fixtures
-
12
fixtures RSpec.configuration.global_fixtures if RSpec.configuration.global_fixtures
-
end
-
end
-
end
-
end
-
end
-
1
require 'rspec/core/warnings'
-
1
require 'rspec/expectations'
-
1
require 'rspec/rails/feature_check'
-
-
1
module RSpec
-
1
module Rails
-
# @api public
-
# Container module for Rails specific matchers.
-
1
module Matchers
-
end
-
end
-
end
-
-
1
require 'rspec/rails/matchers/have_rendered'
-
1
require 'rspec/rails/matchers/redirect_to'
-
1
require 'rspec/rails/matchers/routing_matchers'
-
1
require 'rspec/rails/matchers/be_new_record'
-
1
require 'rspec/rails/matchers/be_a_new'
-
1
require 'rspec/rails/matchers/relation_match_array'
-
1
require 'rspec/rails/matchers/be_valid'
-
1
require 'rspec/rails/matchers/have_http_status'
-
1
if RSpec::Rails::FeatureCheck.has_active_job?
-
require 'rspec/rails/matchers/active_job'
-
end
-
1
module RSpec
-
1
module Rails
-
1
module Matchers
-
# @api private
-
#
-
# Matcher class for `be_a_new`. Should not be instantiated directly.
-
#
-
# @see RSpec::Rails::Matchers#be_a_new
-
1
class BeANew < RSpec::Matchers::BuiltIn::BaseMatcher
-
# @private
-
1
def initialize(expected)
-
@expected = expected
-
end
-
-
# @private
-
1
def matches?(actual)
-
@actual = actual
-
actual.is_a?(expected) && actual.new_record? && attributes_match?(actual)
-
end
-
-
# @api public
-
# @see RSpec::Rails::Matchers#be_a_new
-
1
def with(expected_attributes)
-
attributes.merge!(expected_attributes)
-
self
-
end
-
-
# @private
-
1
def failure_message
-
[].tap do |message|
-
unless actual.is_a?(expected) && actual.new_record?
-
message << "expected #{actual.inspect} to be a new #{expected.inspect}"
-
end
-
unless attributes_match?(actual)
-
if unmatched_attributes.size > 1
-
message << "attributes #{unmatched_attributes.inspect} were not set on #{actual.inspect}"
-
else
-
message << "attribute #{unmatched_attributes.inspect} was not set on #{actual.inspect}"
-
end
-
end
-
end.join(' and ')
-
end
-
-
1
private
-
-
1
def attributes
-
@attributes ||= {}
-
end
-
-
1
def attributes_match?(actual)
-
attributes.stringify_keys.all? do |key, value|
-
actual.attributes[key].eql?(value)
-
end
-
end
-
-
1
def unmatched_attributes
-
attributes.stringify_keys.reject do |key, value|
-
actual.attributes[key].eql?(value)
-
end
-
end
-
end
-
-
# @api public
-
# Passes if actual is an instance of `model_class` and returns `false` for
-
# `persisted?`. Typically used to specify instance variables assigned to
-
# views by controller actions
-
#
-
# Use the `with` method to specify the specific attributes to match on the
-
# new record.
-
#
-
# @example
-
# get :new
-
# assigns(:thing).should be_a_new(Thing)
-
#
-
# post :create, :thing => { :name => "Illegal Value" }
-
# assigns(:thing).should be_a_new(Thing).with(:name => nil)
-
1
def be_a_new(model_class)
-
BeANew.new(model_class)
-
end
-
end
-
end
-
end
-
1
module RSpec
-
1
module Rails
-
1
module Matchers
-
# @private
-
1
class BeANewRecord < RSpec::Matchers::BuiltIn::BaseMatcher
-
1
def matches?(actual)
-
!actual.persisted?
-
end
-
-
1
def failure_message
-
"expected #{actual.inspect} to be a new record, but was persisted"
-
end
-
-
1
def failure_message_when_negated
-
"expected #{actual.inspect} to be persisted, but was a new record"
-
end
-
end
-
-
# @api public
-
# Passes if actual returns `false` for `persisted?`.
-
#
-
# @example
-
# get :new
-
# expect(assigns(:thing)).to be_new_record
-
1
def be_new_record
-
BeANewRecord.new
-
end
-
end
-
end
-
end
-
1
module RSpec
-
1
module Rails
-
1
module Matchers
-
# @private
-
1
class BeValid < RSpec::Matchers::BuiltIn::Be
-
1
def initialize(*args)
-
@args = args
-
end
-
-
1
def matches?(actual)
-
@actual = actual
-
actual.valid?(*@args)
-
end
-
-
1
def failure_message
-
message = "expected #{actual.inspect} to be valid"
-
-
if actual.respond_to?(:errors)
-
errors = if actual.errors.respond_to?(:full_messages)
-
actual.errors.full_messages
-
else
-
actual.errors
-
end
-
-
message << ", but got errors: #{errors.map(&:to_s).join(', ')}"
-
end
-
-
message
-
end
-
-
1
def failure_message_when_negated
-
"expected #{actual.inspect} not to be valid"
-
end
-
end
-
-
# @api public
-
# Passes if the given model instance's `valid?` method is true, meaning
-
# all of the `ActiveModel::Validations` passed and no errors exist. If a
-
# message is not given, a default message is shown listing each error.
-
#
-
# @example
-
# thing = Thing.new
-
# expect(thing).to be_valid
-
1
def be_valid(*args)
-
BeValid.new(*args)
-
end
-
end
-
end
-
end
-
# The following code inspired and modified from Rails' `assert_response`:
-
#
-
# https://github.com/rails/rails/blob/master/actionpack/lib/action_dispatch/testing/assertions/response.rb#L22-L38
-
#
-
# Thank you to all the Rails devs who did the heavy lifting on this!
-
-
1
module RSpec
-
1
module Rails
-
1
module Matchers
-
# Namespace for various implementations of `have_http_status`.
-
#
-
# @api private
-
1
module HaveHttpStatus
-
# Instantiates an instance of the proper matcher based on the provided
-
# `target`.
-
#
-
# @param target [Object] expected http status or code
-
# @return response matcher instance
-
1
def self.matcher_for_status(target)
-
if GenericStatus.valid_statuses.include?(target)
-
GenericStatus.new(target)
-
elsif Symbol === target
-
SymbolicStatus.new(target)
-
else
-
NumericCode.new(target)
-
end
-
end
-
-
# @api private
-
# Conversion function to coerce the provided object into an
-
# `ActionDispatch::TestResponse`.
-
#
-
# @param obj [Object] object to convert to a response
-
# @return [ActionDispatch::TestResponse]
-
1
def as_test_response(obj)
-
if ::ActionDispatch::Response === obj
-
::ActionDispatch::TestResponse.from_response(obj)
-
elsif ::ActionDispatch::TestResponse === obj
-
obj
-
elsif obj.respond_to?(:status_code) && obj.respond_to?(:response_headers)
-
# Acts As Capybara Session
-
# Hack to support `Capybara::Session` without having to load
-
# Capybara or catch `NameError`s for the undefined constants
-
::ActionDispatch::TestResponse.new.tap do |resp|
-
resp.status = obj.status_code
-
resp.headers = obj.response_headers
-
resp.body = obj.body
-
end
-
else
-
raise TypeError, "Invalid response type: #{obj}"
-
end
-
end
-
1
module_function :as_test_response
-
-
# @return [String, nil] a formatted failure message if
-
# `@invalid_response` is present, `nil` otherwise
-
1
def invalid_response_type_message
-
return unless @invalid_response
-
"expected a response object, but an instance of " \
-
"#{@invalid_response.class} was received"
-
end
-
-
# @api private
-
# Provides an implementation for `have_http_status` matching against
-
# numeric http status codes.
-
#
-
# Not intended to be instantiated directly.
-
#
-
# @example
-
# expect(response).to have_http_status(404)
-
#
-
# @see RSpec::Rails::Matchers.have_http_status
-
1
class NumericCode < RSpec::Matchers::BuiltIn::BaseMatcher
-
1
include HaveHttpStatus
-
-
1
def initialize(code)
-
@expected = code.to_i
-
@actual = nil
-
@invalid_response = nil
-
end
-
-
# @param [Object] response object providing an http code to match
-
# @return [Boolean] `true` if the numeric code matched the `response` code
-
1
def matches?(response)
-
test_response = as_test_response(response)
-
@actual = test_response.response_code
-
expected == @actual
-
rescue TypeError => _ignored
-
@invalid_response = response
-
false
-
end
-
-
# @return [String]
-
1
def description
-
"respond with numeric status code #{expected}"
-
end
-
-
# @return [String] explaining why the match failed
-
1
def failure_message
-
invalid_response_type_message ||
-
"expected the response to have status code #{expected.inspect}" \
-
" but it was #{actual.inspect}"
-
end
-
-
# @return [String] explaining why the match failed
-
1
def failure_message_when_negated
-
invalid_response_type_message ||
-
"expected the response not to have status code " \
-
"#{expected.inspect} but it did"
-
end
-
end
-
-
# @api private
-
# Provides an implementation for `have_http_status` matching against
-
# Rack symbol http status codes.
-
#
-
# Not intended to be instantiated directly.
-
#
-
# @example
-
# expect(response).to have_http_status(:created)
-
#
-
# @see RSpec::Rails::Matchers.have_http_status
-
# @see https://github.com/rack/rack/blob/master/lib/rack/utils.rb `Rack::Utils::SYMBOL_TO_STATUS_CODE`
-
1
class SymbolicStatus < RSpec::Matchers::BuiltIn::BaseMatcher
-
1
include HaveHttpStatus
-
-
1
def initialize(status)
-
@expected_status = status
-
@actual = nil
-
@invalid_response = nil
-
set_expected_code!
-
end
-
-
# @param [Object] response object providing an http code to match
-
# @return [Boolean] `true` if Rack's associated numeric HTTP code matched
-
# the `response` code
-
1
def matches?(response)
-
test_response = as_test_response(response)
-
@actual = test_response.response_code
-
expected == @actual
-
rescue TypeError => _ignored
-
@invalid_response = response
-
false
-
end
-
-
# @return [String]
-
1
def description
-
"respond with status code #{pp_expected}"
-
end
-
-
# @return [String] explaining why the match failed
-
1
def failure_message
-
invalid_response_type_message ||
-
"expected the response to have status code #{pp_expected} but it" \
-
" was #{pp_actual}"
-
end
-
-
# @return [String] explaining why the match failed
-
1
def failure_message_when_negated
-
invalid_response_type_message ||
-
"expected the response not to have status code #{pp_expected} " \
-
"but it did"
-
end
-
-
# The initialized expected status symbol
-
1
attr_reader :expected_status
-
1
private :expected_status
-
-
1
private
-
-
# @return [Symbol] representing the actual http numeric code
-
1
def actual_status
-
return unless actual
-
@actual_status ||= compute_status_from(actual)
-
end
-
-
# Reverse lookup of the Rack status code symbol based on the numeric
-
# http code
-
#
-
# @param code [Fixnum] http status code to look up
-
# @return [Symbol] representing the http numeric code
-
1
def compute_status_from(code)
-
status, _ = Rack::Utils::SYMBOL_TO_STATUS_CODE.find do |_, c|
-
c == code
-
end
-
status
-
end
-
-
# @return [String] pretty format the actual response status
-
1
def pp_actual
-
pp_status(actual_status, actual)
-
end
-
-
# @return [String] pretty format the expected status and associated code
-
1
def pp_expected
-
pp_status(expected_status, expected)
-
end
-
-
# @return [String] pretty format the actual response status
-
1
def pp_status(status, code)
-
if status
-
"#{status.inspect} (#{code})"
-
else
-
code.to_s
-
end
-
end
-
-
# Sets `expected` to the numeric http code based on the Rack
-
# `expected_status` status
-
#
-
# @see Rack::Utils::SYMBOL_TO_STATUS_CODE
-
# @raise [ArgumentError] if an associated code could not be found
-
1
def set_expected_code!
-
@expected ||=
-
Rack::Utils::SYMBOL_TO_STATUS_CODE.fetch(expected_status) do
-
raise ArgumentError,
-
"Invalid HTTP status: #{expected_status.inspect}"
-
end
-
end
-
end
-
-
# @api private
-
# Provides an implementation for `have_http_status` matching against
-
# `ActionDispatch::TestResponse` http status category queries.
-
#
-
# Not intended to be instantiated directly.
-
#
-
# @example
-
# expect(response).to have_http_status(:success)
-
# expect(response).to have_http_status(:error)
-
# expect(response).to have_http_status(:missing)
-
# expect(response).to have_http_status(:redirect)
-
#
-
# @see RSpec::Rails::Matchers.have_http_status
-
# @see ActionDispatch::TestResponse
-
1
class GenericStatus < RSpec::Matchers::BuiltIn::BaseMatcher
-
1
include HaveHttpStatus
-
-
# @return [Array<Symbol>] of status codes which represent a HTTP status
-
# code "group"
-
# @see https://github.com/rails/rails/blob/master/actionpack/lib/action_dispatch/testing/test_response.rb `ActionDispatch::TestResponse`
-
1
def self.valid_statuses
-
[:error, :success, :missing, :redirect]
-
end
-
-
1
def initialize(type)
-
unless self.class.valid_statuses.include?(type)
-
raise ArgumentError, "Invalid generic HTTP status: #{type.inspect}"
-
end
-
@expected = type
-
@actual = nil
-
@invalid_response = nil
-
end
-
-
# @return [Boolean] `true` if Rack's associated numeric HTTP code matched
-
# the `response` code
-
1
def matches?(response)
-
test_response = as_test_response(response)
-
@actual = test_response.response_code
-
test_response.send("#{expected}?")
-
rescue TypeError => _ignored
-
@invalid_response = response
-
false
-
end
-
-
# @return [String]
-
1
def description
-
"respond with #{type_message}"
-
end
-
-
# @return [String] explaining why the match failed
-
1
def failure_message
-
invalid_response_type_message ||
-
"expected the response to have #{type_message} but it was #{actual}"
-
end
-
-
# @return [String] explaining why the match failed
-
1
def failure_message_when_negated
-
invalid_response_type_message ||
-
"expected the response not to have #{type_message} but it was #{actual}"
-
end
-
-
1
private
-
-
# @return [String] formating the expected status and associated code(s)
-
1
def type_message
-
@type_message ||= (expected == :error ? "an error" : "a #{expected}") +
-
" status code (#{type_codes})"
-
end
-
-
# @return [String] formatting the associated code(s) for the various
-
# status code "groups"
-
# @see https://github.com/rails/rails/blob/master/actionpack/lib/action_dispatch/testing/test_response.rb `ActionDispatch::TestResponse`
-
# @see https://github.com/rack/rack/blob/master/lib/rack/response.rb `Rack::Response`
-
1
def type_codes
-
# At the time of this commit the most recent version of
-
# `ActionDispatch::TestResponse` defines the following aliases:
-
#
-
# alias_method :success?, :successful?
-
# alias_method :missing?, :not_found?
-
# alias_method :redirect?, :redirection?
-
# alias_method :error?, :server_error?
-
#
-
# It's parent `ActionDispatch::Response` includes
-
# `Rack::Response::Helpers` which defines the aliased methods as:
-
#
-
# def successful?; status >= 200 && status < 300; end
-
# def redirection?; status >= 300 && status < 400; end
-
# def server_error?; status >= 500 && status < 600; end
-
# def not_found?; status == 404; end
-
#
-
# @see https://github.com/rails/rails/blob/ca200378/actionpack/lib/action_dispatch/testing/test_response.rb#L17-L27
-
# @see https://github.com/rails/rails/blob/ca200378/actionpack/lib/action_dispatch/http/response.rb#L74
-
# @see https://github.com/rack/rack/blob/ce4a3959/lib/rack/response.rb#L119-L122
-
@type_codes ||= case expected
-
when :error
-
"5xx"
-
when :success
-
"2xx"
-
when :missing
-
"404"
-
when :redirect
-
"3xx"
-
end
-
end
-
end
-
end
-
-
# @api public
-
# Passes if `response` has a matching HTTP status code.
-
#
-
# The following symbolic status codes are allowed:
-
#
-
# - `Rack::Utils::SYMBOL_TO_STATUS_CODE`
-
# - One of the defined `ActionDispatch::TestResponse` aliases:
-
# - `:error`
-
# - `:missing`
-
# - `:redirect`
-
# - `:success`
-
#
-
# @example Accepts numeric and symbol statuses
-
# expect(response).to have_http_status(404)
-
# expect(response).to have_http_status(:created)
-
# expect(response).to have_http_status(:success)
-
# expect(response).to have_http_status(:error)
-
# expect(response).to have_http_status(:missing)
-
# expect(response).to have_http_status(:redirect)
-
#
-
# @example Works with standard `response` objects and Capybara's `page`
-
# expect(response).to have_http_status(404)
-
# expect(page).to have_http_status(:created)
-
#
-
# @see https://github.com/rails/rails/blob/master/actionpack/lib/action_dispatch/testing/test_response.rb `ActionDispatch::TestResponse`
-
# @see https://github.com/rack/rack/blob/master/lib/rack/utils.rb `Rack::Utils::SYMBOL_TO_STATUS_CODE`
-
1
def have_http_status(target)
-
raise ArgumentError, "Invalid HTTP status: nil" unless target
-
HaveHttpStatus.matcher_for_status(target)
-
end
-
end
-
end
-
end
-
1
module RSpec
-
1
module Rails
-
1
module Matchers
-
# Matcher for template rendering.
-
1
module RenderTemplate
-
# @private
-
1
class RenderTemplateMatcher < RSpec::Matchers::BuiltIn::BaseMatcher
-
1
def initialize(scope, expected, message = nil)
-
@expected = Symbol === expected ? expected.to_s : expected
-
@message = message
-
@scope = scope
-
@redirect_is = nil
-
end
-
-
# @api private
-
1
def matches?(*)
-
match_check = match_unless_raises ActiveSupport::TestCase::Assertion do
-
@scope.assert_template expected, @message
-
end
-
check_redirect unless match_check
-
match_check
-
end
-
-
# Uses normalize_argument_to_redirection to find and format
-
# the redirect location. normalize_argument_to_redirection is private
-
# in ActionDispatch::Assertions::ResponseAssertions so we call it
-
# here using #send. This will keep the error message format consistent
-
# @api private
-
1
def check_redirect
-
response = @scope.response
-
return unless response.respond_to?(:redirect?) && response.redirect?
-
@redirect_is = @scope.send(:normalize_argument_to_redirection, response.location)
-
end
-
-
# @api private
-
1
def failure_message
-
if @redirect_is
-
rescued_exception.message[/.* but /] +
-
"was a redirect to <#{@redirect_is}>"
-
else
-
rescued_exception.message
-
end
-
end
-
-
# @api private
-
1
def failure_message_when_negated
-
"expected not to render #{expected.inspect}, but did"
-
end
-
end
-
-
# Delegates to `assert_template`.
-
#
-
# @example
-
# expect(response).to have_rendered("new")
-
1
def have_rendered(options, message = nil)
-
RenderTemplateMatcher.new(self, options, message)
-
end
-
-
1
alias_method :render_template, :have_rendered
-
end
-
end
-
end
-
end
-
1
module RSpec
-
1
module Rails
-
1
module Matchers
-
# Matcher for redirects.
-
1
module RedirectTo
-
# @private
-
1
class RedirectTo < RSpec::Matchers::BuiltIn::BaseMatcher
-
1
def initialize(scope, expected)
-
@expected = expected
-
@scope = scope
-
end
-
-
1
def matches?(_)
-
match_unless_raises ActiveSupport::TestCase::Assertion do
-
@scope.assert_redirected_to(@expected)
-
end
-
end
-
-
1
def failure_message
-
rescued_exception.message
-
end
-
-
1
def failure_message_when_negated
-
"expected not to redirect to #{@expected.inspect}, but did"
-
end
-
end
-
-
# Delegates to `assert_redirected_to`.
-
#
-
# @example
-
# expect(response).to redirect_to(:action => "new")
-
1
def redirect_to(target)
-
RedirectTo.new(self, target)
-
end
-
end
-
end
-
end
-
end
-
1
if defined?(ActiveRecord::Relation)
-
1
RSpec::Matchers::BuiltIn::OperatorMatcher.register(ActiveRecord::Relation, '=~', RSpec::Matchers::BuiltIn::ContainExactly)
-
end
-
1
module RSpec
-
1
module Rails
-
1
module Matchers
-
# Matchers to help with specs for routing code.
-
1
module RoutingMatchers
-
1
extend RSpec::Matchers::DSL
-
-
# @private
-
1
class RouteToMatcher < RSpec::Matchers::BuiltIn::BaseMatcher
-
1
def initialize(scope, *expected)
-
@scope = scope
-
@expected = expected[1] || {}
-
if Hash === expected[0]
-
@expected.merge!(expected[0])
-
else
-
controller, action = expected[0].split('#')
-
@expected.merge!(:controller => controller, :action => action)
-
end
-
end
-
-
1
def matches?(verb_to_path_map)
-
@actual = @verb_to_path_map = verb_to_path_map
-
# assert_recognizes does not consider ActionController::RoutingError an
-
# assertion failure, so we have to capture that and Assertion here.
-
match_unless_raises ActiveSupport::TestCase::Assertion, ActionController::RoutingError do
-
path, query = *verb_to_path_map.values.first.split('?')
-
@scope.assert_recognizes(
-
@expected,
-
{ :method => verb_to_path_map.keys.first, :path => path },
-
Rack::Utils.parse_nested_query(query)
-
)
-
end
-
end
-
-
1
def failure_message
-
rescued_exception.message
-
end
-
-
1
def failure_message_when_negated
-
"expected #{@actual.inspect} not to route to #{@expected.inspect}"
-
end
-
-
1
def description
-
"route #{@actual.inspect} to #{@expected.inspect}"
-
end
-
end
-
-
# Delegates to `assert_recognizes`. Supports short-hand controller/action
-
# declarations (e.g. `"controller#action"`).
-
#
-
# @example
-
#
-
# expect(:get => "/things/special").to route_to(
-
# :controller => "things",
-
# :action => "special"
-
# )
-
#
-
# expect(:get => "/things/special").to route_to("things#special")
-
#
-
# @see http://api.rubyonrails.org/classes/ActionDispatch/Assertions/RoutingAssertions.html#method-i-assert_recognizes
-
1
def route_to(*expected)
-
RouteToMatcher.new(self, *expected)
-
end
-
-
# @private
-
1
class BeRoutableMatcher < RSpec::Matchers::BuiltIn::BaseMatcher
-
1
def initialize(scope)
-
@scope = scope
-
end
-
-
1
def matches?(path)
-
@actual = path
-
match_unless_raises ActionController::RoutingError do
-
@routing_options = @scope.routes.recognize_path(
-
path.values.first, :method => path.keys.first
-
)
-
end
-
end
-
-
1
def failure_message
-
"expected #{@actual.inspect} to be routable"
-
end
-
-
1
def failure_message_when_negated
-
"expected #{@actual.inspect} not to be routable, but it routes to #{@routing_options.inspect}"
-
end
-
-
1
def description
-
"be routable"
-
end
-
end
-
-
# Passes if the route expression is recognized by the Rails router based on
-
# the declarations in `config/routes.rb`. Delegates to
-
# `RouteSet#recognize_path`.
-
#
-
# @example You can use route helpers provided by rspec-rails.
-
# expect(:get => "/a/path").to be_routable
-
# expect(:post => "/another/path").to be_routable
-
# expect(:put => "/yet/another/path").to be_routable
-
1
def be_routable
-
BeRoutableMatcher.new(self)
-
end
-
-
# Helpers for matching different route types.
-
1
module RouteHelpers
-
# @!method get
-
# @!method post
-
# @!method put
-
# @!method patch
-
# @!method delete
-
# @!method options
-
# @!method head
-
#
-
# Shorthand method for matching this type of route.
-
1
%w[get post put patch delete options head].each do |method|
-
7
define_method method do |path|
-
{ method.to_sym => path }
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
1
begin
-
1
require 'capybara/rspec'
-
rescue LoadError
-
end
-
-
1
begin
-
1
require 'capybara/rails'
-
rescue LoadError
-
end
-
-
1
if defined?(Capybara)
-
1
require 'rspec/support/version_checker'
-
1
RSpec::Support::VersionChecker.new('capybara', Capybara::VERSION, '2.2.0').check_version!
-
-
1
RSpec.configure do |c|
-
1
if defined?(Capybara::DSL)
-
1
c.include Capybara::DSL, :type => :feature
-
end
-
-
1
if defined?(Capybara::RSpecMatchers)
-
1
c.include Capybara::RSpecMatchers, :type => :view
-
1
c.include Capybara::RSpecMatchers, :type => :helper
-
1
c.include Capybara::RSpecMatchers, :type => :mailer
-
1
c.include Capybara::RSpecMatchers, :type => :controller
-
1
c.include Capybara::RSpecMatchers, :type => :feature
-
end
-
-
1
unless defined?(Capybara::RSpecMatchers) || defined?(Capybara::DSL)
-
c.include Capybara, :type => :request
-
c.include Capybara, :type => :controller
-
end
-
end
-
end
-
1
module RSpec
-
1
module Rails
-
# Helpers for making instance variables available to views.
-
1
module ViewAssigns
-
# Assigns a value to an instance variable in the scope of the
-
# view being rendered.
-
#
-
# @example
-
#
-
# assign(:widget, stub_model(Widget))
-
1
def assign(key, value)
-
_encapsulated_assigns[key] = value
-
end
-
-
# Compat-shim for AbstractController::Rendering#view_assigns
-
#
-
# _assigns was deprecated in favor of view_assigns after
-
# Rails-3.0.0 was released. Since we are not able to predict when
-
# the _assigns/view_assigns patch will be released (I thought it
-
# would have been in 3.0.1, but 3.0.1 bypassed this change for a
-
# security fix), this bit ensures that we do the right thing without
-
# knowing anything about the Rails version we are dealing with.
-
#
-
# Once that change _is_ released, this can be changed to something
-
# that checks for the Rails version when the module is being
-
# interpreted, as it was before commit dd0095.
-
1
def view_assigns
-
super.merge(_encapsulated_assigns)
-
rescue
-
_assigns
-
end
-
-
# @private
-
1
def _assigns
-
super.merge(_encapsulated_assigns)
-
end
-
-
1
private
-
-
1
def _encapsulated_assigns
-
@_encapsulated_assigns ||= {}
-
end
-
end
-
end
-
end
-
1
module RSpec
-
1
module Support
-
# @api private
-
#
-
# Defines a helper method that is optimized to require files from the
-
# named lib. The passed block MUST be `{ |f| require_relative f }`
-
# because for `require_relative` to work properly from within the named
-
# lib the line of code must be IN that lib.
-
#
-
# `require_relative` is preferred when available because it is always O(1),
-
# regardless of the number of dirs in $LOAD_PATH. `require`, on the other
-
# hand, does a linear O(N) search over the dirs in the $LOAD_PATH until
-
# it can resolve the file relative to one of the dirs.
-
1
def self.define_optimized_require_for_rspec(lib, &require_relative)
-
4
name = "require_rspec_#{lib}"
-
-
4
if Kernel.respond_to?(:require_relative)
-
8
(class << self; self; end).__send__(:define_method, name) do |f|
-
69
require_relative.call("#{lib}/#{f}")
-
end
-
else
-
(class << self; self; end).__send__(:define_method, name) do |f|
-
require "rspec/#{lib}/#{f}"
-
end
-
end
-
end
-
-
17
define_optimized_require_for_rspec(:support) { |f| require_relative(f) }
-
1
require_rspec_support "version"
-
1
require_rspec_support "ruby_features"
-
-
# @api private
-
1
KERNEL_METHOD_METHOD = ::Kernel.instance_method(:method)
-
-
# @api private
-
#
-
# Used internally to get a method handle for a particular object
-
# and method name.
-
#
-
# Includes handling for a few special cases:
-
#
-
# - Objects that redefine #method (e.g. an HTTPRequest struct)
-
# - BasicObject subclasses that mixin a Kernel dup (e.g. SimpleDelegator)
-
# - Objects that undefine method and delegate everything to another
-
# object (e.g. Mongoid association objects)
-
1
if RubyFeatures.supports_rebinding_module_methods?
-
1
def self.method_handle_for(object, method_name)
-
KERNEL_METHOD_METHOD.bind(object).call(method_name)
-
rescue NameError => original
-
begin
-
handle = object.method(method_name)
-
raise original unless handle.is_a? Method
-
handle
-
rescue Support::AllExceptionsExceptOnesWeMustNotRescue
-
raise original
-
end
-
end
-
else
-
def self.method_handle_for(object, method_name)
-
if ::Kernel === object
-
KERNEL_METHOD_METHOD.bind(object).call(method_name)
-
else
-
object.method(method_name)
-
end
-
rescue NameError => original
-
begin
-
handle = object.method(method_name)
-
raise original unless handle.is_a? Method
-
handle
-
rescue Support::AllExceptionsExceptOnesWeMustNotRescue
-
raise original
-
end
-
end
-
end
-
-
# A single thread local variable so we don't excessively pollute that namespace.
-
1
def self.thread_local_data
-
Thread.current[:__rspec] ||= {}
-
end
-
-
# @api private
-
1
def self.failure_notifier=(callable)
-
thread_local_data[:failure_notifier] = callable
-
end
-
-
# @private
-
1
DEFAULT_FAILURE_NOTIFIER = lambda { |failure, _opts| raise failure }
-
-
# @api private
-
1
def self.failure_notifier
-
thread_local_data[:failure_notifier] || DEFAULT_FAILURE_NOTIFIER
-
end
-
-
# @api private
-
1
def self.notify_failure(failure, options={})
-
failure_notifier.call(failure, options)
-
end
-
-
# @api private
-
1
def self.with_failure_notifier(callable)
-
orig_notifier = failure_notifier
-
self.failure_notifier = callable
-
yield
-
ensure
-
self.failure_notifier = orig_notifier
-
end
-
-
1
class << self
-
# @api private
-
1
attr_writer :warning_notifier
-
end
-
-
# @private
-
1
DEFAULT_WARNING_NOTIFIER = lambda { |warning| ::Kernel.warn warning }
-
-
# @api private
-
1
def self.warning_notifier
-
@warning_notifier ||= DEFAULT_WARNING_NOTIFIER
-
end
-
-
# @private
-
1
module AllExceptionsExceptOnesWeMustNotRescue
-
# These exceptions are dangerous to rescue as rescuing them
-
# would interfere with things we should not interfere with.
-
1
AVOID_RESCUING = [NoMemoryError, SignalException, Interrupt, SystemExit]
-
-
1
def self.===(exception)
-
AVOID_RESCUING.none? { |ar| ar === exception }
-
end
-
end
-
-
# The Differ is only needed when a a spec fails with a diffable failure.
-
# In the more common case of all specs passing or the only failures being
-
# non-diffable, we can avoid the extra cost of loading the differ, diff-lcs,
-
# pp, etc by avoiding an unnecessary require. Instead, autoload will take
-
# care of loading the differ on first use.
-
1
autoload :Differ, "rspec/support/differ"
-
end
-
end
-
1
RSpec::Support.require_rspec_support "ruby_features"
-
-
1
module RSpec
-
# Consistent implementation for "cleaning" the caller method to strip out
-
# non-rspec lines. This enables errors to be reported at the call site in
-
# the code using the library, which is far more useful than the particular
-
# internal method that raised an error.
-
1
class CallerFilter
-
1
RSPEC_LIBS = %w[
-
core
-
mocks
-
expectations
-
support
-
matchers
-
rails
-
]
-
-
1
ADDITIONAL_TOP_LEVEL_FILES = %w[ autorun ]
-
-
1
LIB_REGEX = %r{/lib/rspec/(#{(RSPEC_LIBS + ADDITIONAL_TOP_LEVEL_FILES).join('|')})(\.rb|/)}
-
-
# rubygems/core_ext/kernel_require.rb isn't actually part of rspec (obviously) but we want
-
# it ignored when we are looking for the first meaningful line of the backtrace outside
-
# of RSpec. It can show up in the backtrace as the immediate first caller
-
# when `CallerFilter.first_non_rspec_line` is called from the top level of a required
-
# file, but it depends on if rubygems is loaded or not. We don't want to have to deal
-
# with this complexity in our `RSpec.deprecate` calls, so we ignore it here.
-
1
IGNORE_REGEX = Regexp.union(LIB_REGEX, "rubygems/core_ext/kernel_require.rb")
-
-
1
if RSpec::Support::RubyFeatures.caller_locations_supported?
-
# This supports args because it's more efficient when the caller specifies
-
# these. It allows us to skip frames the caller knows are part of RSpec,
-
# and to decrease the increment size if the caller is confident the line will
-
# be found in a small number of stack frames from `skip_frames`.
-
#
-
# Note that there is a risk to passing a `skip_frames` value that is too high:
-
# If it skippped the first non-rspec line, then this method would return the
-
# 2nd or 3rd (or whatever) non-rspec line. Thus, you generally shouldn't pass
-
# values for these parameters, particularly since most places that use this are
-
# not hot spots (generally it gets used for deprecation warnings). However,
-
# if you do have a hot spot that calls this, passing `skip_frames` can make
-
# a significant difference. Just make sure that that particular use is tested
-
# so that if the provided `skip_frames` changes to no longer be accurate in
-
# such a way that would return the wrong stack frame, a test will fail to tell you.
-
#
-
# See benchmarks/skip_frames_for_caller_filter.rb for measurements.
-
1
def self.first_non_rspec_line(skip_frames=3, increment=5)
-
# Why a default `skip_frames` of 3?
-
# By the time `caller_locations` is called below, the first 3 frames are:
-
# lib/rspec/support/caller_filter.rb:63:in `block in first_non_rspec_line'
-
# lib/rspec/support/caller_filter.rb:62:in `loop'
-
# lib/rspec/support/caller_filter.rb:62:in `first_non_rspec_line'
-
-
# `caller` is an expensive method that scales linearly with the size of
-
# the stack. The performance hit for fetching it in chunks is small,
-
# and since the target line is probably near the top of the stack, the
-
# overall improvement of a chunked search like this is significant.
-
#
-
# See benchmarks/caller.rb for measurements.
-
-
# The default increment of 5 for this method are mostly arbitrary, but
-
# is chosen to give good performance on the common case of creating a double.
-
-
loop do
-
stack = caller_locations(skip_frames, increment)
-
raise "No non-lib lines in stack" unless stack
-
-
line = stack.find { |l| l.path !~ IGNORE_REGEX }
-
return line.to_s if line
-
-
skip_frames += increment
-
increment *= 2 # The choice of two here is arbitrary.
-
end
-
end
-
else
-
# Earlier rubies do not support the two argument form of `caller`. This
-
# fallback is logically the same, but slower.
-
def self.first_non_rspec_line(*)
-
caller.find { |line| line !~ IGNORE_REGEX }
-
end
-
end
-
end
-
end
-
1
module RSpec
-
1
module Support
-
# @private
-
1
class ComparableVersion
-
1
include Comparable
-
-
1
attr_reader :string
-
-
1
def initialize(string)
-
2
@string = string
-
end
-
-
1
def <=>(other)
-
1
other = self.class.new(other) unless other.is_a?(self.class)
-
-
1
return 0 if string == other.string
-
-
3
longer_segment_count = [self, other].map { |version| version.segments.count }.max
-
-
1
longer_segment_count.times do |index|
-
1
self_segment = segments[index] || 0
-
1
other_segment = other.segments[index] || 0
-
-
1
if self_segment.class == other_segment.class
-
1
result = self_segment <=> other_segment
-
1
return result unless result == 0
-
else
-
return self_segment.is_a?(String) ? -1 : 1
-
end
-
end
-
-
0
-
end
-
-
1
def segments
-
@segments ||= string.scan(/[a-z]+|\d+/i).map do |segment|
-
6
if segment =~ /\A\d+\z/
-
6
segment.to_i
-
else
-
segment
-
end
-
4
end
-
end
-
end
-
end
-
end
-
1
RSpec::Support.require_rspec_support 'ruby_features'
-
-
1
module RSpec
-
1
module Support
-
# @api private
-
#
-
# Replacement for fileutils#mkdir_p because we don't want to require parts
-
# of stdlib in RSpec.
-
1
class DirectoryMaker
-
# @api private
-
#
-
# Implements nested directory construction
-
1
def self.mkdir_p(path)
-
stack = generate_stack(path)
-
path.split(File::SEPARATOR).each do |part|
-
stack = generate_path(stack, part)
-
begin
-
Dir.mkdir(stack) unless directory_exists?(stack)
-
rescue Errno::EEXIST => e
-
raise e unless directory_exists?(stack)
-
rescue Errno::ENOTDIR => e
-
raise Errno::EEXIST, e.message
-
end
-
end
-
end
-
-
1
if OS.windows_file_path?
-
def self.generate_stack(path)
-
if path.start_with?(File::SEPARATOR)
-
File::SEPARATOR
-
elsif path[1] == ':'
-
''
-
else
-
'.'
-
end
-
end
-
def self.generate_path(stack, part)
-
if stack == ''
-
part
-
elsif stack == File::SEPARATOR
-
File.join('', part)
-
else
-
File.join(stack, part)
-
end
-
end
-
else
-
1
def self.generate_stack(path)
-
path.start_with?(File::SEPARATOR) ? File::SEPARATOR : "."
-
end
-
1
def self.generate_path(stack, part)
-
File.join(stack, part)
-
end
-
end
-
-
1
def self.directory_exists?(dirname)
-
File.exist?(dirname) && File.directory?(dirname)
-
end
-
1
private_class_method :directory_exists?
-
1
private_class_method :generate_stack
-
1
private_class_method :generate_path
-
end
-
end
-
end
-
1
module RSpec
-
1
module Support
-
# @private
-
1
class EncodedString
-
# Reduce allocations by storing constants.
-
1
UTF_8 = "UTF-8"
-
1
US_ASCII = "US-ASCII"
-
#
-
# In MRI 2.1 'invalid: :replace' changed to also replace an invalid byte sequence
-
# see https://github.com/ruby/ruby/blob/v2_1_0/NEWS#L176
-
# https://www.ruby-forum.com/topic/6861247
-
# https://twitter.com/nalsh/status/553413844685438976
-
#
-
# For example, given:
-
# "\x80".force_encoding("Emacs-Mule").encode(:invalid => :replace).bytes.to_a
-
#
-
# On MRI 2.1 or above: 63 # '?'
-
# else : 128 # "\x80"
-
#
-
# Ruby's default replacement string is:
-
# U+FFFD ("\xEF\xBF\xBD"), for Unicode encoding forms, else
-
# ? ("\x3F")
-
1
REPLACE = "?"
-
1
ENCODE_UNCONVERTABLE_BYTES = {
-
:invalid => :replace,
-
:undef => :replace,
-
:replace => REPLACE
-
}
-
1
ENCODE_NO_CONVERTER = {
-
:invalid => :replace,
-
:replace => REPLACE
-
}
-
-
1
def initialize(string, encoding=nil)
-
@encoding = encoding
-
@source_encoding = detect_source_encoding(string)
-
@string = matching_encoding(string)
-
end
-
1
attr_reader :source_encoding
-
-
1
delegated_methods = String.instance_methods.map(&:to_s) & %w[eql? lines == encoding empty?]
-
1
delegated_methods.each do |name|
-
5
define_method(name) { |*args, &block| @string.__send__(name, *args, &block) }
-
end
-
-
1
def <<(string)
-
@string << matching_encoding(string)
-
end
-
-
1
def split(regex_or_string)
-
@string.split(matching_encoding(regex_or_string))
-
end
-
-
1
def to_s
-
@string
-
end
-
1
alias :to_str :to_s
-
-
1
if String.method_defined?(:encoding)
-
-
1
private
-
-
# Encoding Exceptions:
-
#
-
# Raised by Encoding and String methods:
-
# Encoding::UndefinedConversionError:
-
# when a transcoding operation fails
-
# if the String contains characters invalid for the target encoding
-
# e.g. "\x80".encode('UTF-8','ASCII-8BIT')
-
# vs "\x80".encode('UTF-8','ASCII-8BIT', undef: :replace, replace: '<undef>')
-
# # => '<undef>'
-
# Encoding::CompatibilityError
-
# when Encoding.compatibile?(str1, str2) is nil
-
# e.g. utf_16le_emoji_string.split("\n")
-
# e.g. valid_unicode_string.encode(utf8_encoding) << ascii_string
-
# Encoding::InvalidByteSequenceError:
-
# when the string being transcoded contains a byte invalid for
-
# either the source or target encoding
-
# e.g. "\x80".encode('UTF-8','US-ASCII')
-
# vs "\x80".encode('UTF-8','US-ASCII', invalid: :replace, replace: '<byte>')
-
# # => '<byte>'
-
# ArgumentError
-
# when operating on a string with invalid bytes
-
# e.g."\x80".split("\n")
-
# TypeError
-
# when a symbol is passed as an encoding
-
# Encoding.find(:"UTF-8")
-
# when calling force_encoding on an object
-
# that doesn't respond to #to_str
-
#
-
# Raised by transcoding methods:
-
# Encoding::ConverterNotFoundError:
-
# when a named encoding does not correspond with a known converter
-
# e.g. 'abc'.force_encoding('UTF-8').encode('foo')
-
# or a converter path cannot be found
-
# e.g. "\x80".force_encoding('ASCII-8BIT').encode('Emacs-Mule')
-
#
-
# Raised by byte <-> char conversions
-
# RangeError: out of char range
-
# e.g. the UTF-16LE emoji: 128169.chr
-
1
def matching_encoding(string)
-
string = remove_invalid_bytes(string)
-
string.encode(@encoding)
-
rescue Encoding::UndefinedConversionError, Encoding::InvalidByteSequenceError
-
string.encode(@encoding, ENCODE_UNCONVERTABLE_BYTES)
-
rescue Encoding::ConverterNotFoundError
-
string.dup.force_encoding(@encoding).encode(ENCODE_NO_CONVERTER)
-
end
-
-
# Prevents raising ArgumentError
-
1
if String.method_defined?(:scrub)
-
# https://github.com/ruby/ruby/blob/eeb05e8c11/doc/NEWS-2.1.0#L120-L123
-
# https://github.com/ruby/ruby/blob/v2_1_0/string.c#L8242
-
# https://github.com/hsbt/string-scrub
-
# https://github.com/rubinius/rubinius/blob/v2.5.2/kernel/common/string.rb#L1913-L1972
-
1
def remove_invalid_bytes(string)
-
string.scrub(REPLACE)
-
end
-
else
-
# http://stackoverflow.com/a/8711118/879854
-
# Loop over chars in a string replacing chars
-
# with invalid encoding, which is a pretty good proxy
-
# for the invalid byte sequence that causes an ArgumentError
-
def remove_invalid_bytes(string)
-
string.chars.map do |char|
-
char.valid_encoding? ? char : REPLACE
-
end.join
-
end
-
end
-
-
1
def detect_source_encoding(string)
-
string.encoding
-
end
-
-
1
def self.pick_encoding(source_a, source_b)
-
Encoding.compatible?(source_a, source_b) || Encoding.default_external
-
end
-
else
-
-
def self.pick_encoding(_source_a, _source_b)
-
end
-
-
private
-
-
def matching_encoding(string)
-
string
-
end
-
-
def detect_source_encoding(_string)
-
US_ASCII
-
end
-
end
-
end
-
end
-
end
-
2
module RSpec
-
2
module Support
-
# Provides a means to fuzzy-match between two arbitrary objects.
-
# Understands array/hash nesting. Uses `===` or `==` to
-
# perform the matching.
-
2
module FuzzyMatcher
-
# @api private
-
2
def self.values_match?(expected, actual)
-
if Hash === actual
-
return hashes_match?(expected, actual) if Hash === expected
-
elsif Array === expected && Enumerable === actual && !(Struct === actual)
-
return arrays_match?(expected, actual.to_a)
-
end
-
-
return true if expected == actual
-
-
begin
-
expected === actual
-
rescue ArgumentError
-
# Some objects, like 0-arg lambdas on 1.9+, raise
-
# ArgumentError for `expected === actual`.
-
false
-
end
-
end
-
-
# @private
-
2
def self.arrays_match?(expected_list, actual_list)
-
return false if expected_list.size != actual_list.size
-
-
expected_list.zip(actual_list).all? do |expected, actual|
-
values_match?(expected, actual)
-
end
-
end
-
-
# @private
-
2
def self.hashes_match?(expected_hash, actual_hash)
-
return false if expected_hash.size != actual_hash.size
-
-
expected_hash.all? do |expected_key, expected_value|
-
actual_value = actual_hash.fetch(expected_key) { return false }
-
values_match?(expected_value, actual_value)
-
end
-
end
-
-
2
private_class_method :arrays_match?, :hashes_match?
-
end
-
end
-
end
-
2
module RSpec
-
2
module Support
-
# @private
-
2
def self.matcher_definitions
-
3
@matcher_definitions ||= []
-
end
-
-
# Used internally to break cyclic dependency between mocks, expectations,
-
# and support. We don't currently have a consistent implementation of our
-
# matchers, though we are considering changing that:
-
# https://github.com/rspec/rspec-mocks/issues/513
-
#
-
# @private
-
2
def self.register_matcher_definition(&block)
-
3
matcher_definitions << block
-
end
-
-
# Remove a previously registered matcher. Useful for cleaning up after
-
# yourself in specs.
-
#
-
# @private
-
2
def self.deregister_matcher_definition(&block)
-
matcher_definitions.delete(block)
-
end
-
-
# @private
-
2
def self.is_a_matcher?(object)
-
matcher_definitions.any? { |md| md.call(object) }
-
end
-
-
# @api private
-
#
-
# gives a string representation of an object for use in RSpec descriptions
-
2
def self.rspec_description_for_object(object)
-
if RSpec::Support.is_a_matcher?(object) && object.respond_to?(:description)
-
object.description
-
else
-
object
-
end
-
end
-
end
-
end
-
1
require 'rspec/support'
-
1
RSpec::Support.require_rspec_support "ruby_features"
-
1
RSpec::Support.require_rspec_support "matcher_definition"
-
-
1
module RSpec
-
1
module Support
-
# Extracts info about the number of arguments and allowed/required
-
# keyword args of a given method.
-
#
-
# @private
-
1
class MethodSignature
-
1
attr_reader :min_non_kw_args, :max_non_kw_args, :optional_kw_args, :required_kw_args
-
-
1
def initialize(method)
-
@method = method
-
@optional_kw_args = []
-
@required_kw_args = []
-
classify_parameters
-
end
-
-
1
def non_kw_args_arity_description
-
case max_non_kw_args
-
when min_non_kw_args then min_non_kw_args.to_s
-
when INFINITY then "#{min_non_kw_args} or more"
-
else "#{min_non_kw_args} to #{max_non_kw_args}"
-
end
-
end
-
-
1
def valid_non_kw_args?(positional_arg_count)
-
min_non_kw_args <= positional_arg_count &&
-
positional_arg_count <= max_non_kw_args
-
end
-
-
1
if RubyFeatures.optional_and_splat_args_supported?
-
1
def description
-
@description ||= begin
-
parts = []
-
-
unless non_kw_args_arity_description == "0"
-
parts << "arity of #{non_kw_args_arity_description}"
-
end
-
-
if @optional_kw_args.any?
-
parts << "optional keyword args (#{@optional_kw_args.map(&:inspect).join(", ")})"
-
end
-
-
if @required_kw_args.any?
-
parts << "required keyword args (#{@required_kw_args.map(&:inspect).join(", ")})"
-
end
-
-
parts << "any additional keyword args" if @allows_any_kw_args
-
-
parts.join(" and ")
-
end
-
end
-
-
1
def missing_kw_args_from(given_kw_args)
-
@required_kw_args - given_kw_args
-
end
-
-
1
def invalid_kw_args_from(given_kw_args)
-
return [] if @allows_any_kw_args
-
given_kw_args - @allowed_kw_args
-
end
-
-
1
def has_kw_args_in?(args)
-
Hash === args.last && could_contain_kw_args?(args)
-
end
-
-
# Without considering what the last arg is, could it
-
# contain keyword arguments?
-
1
def could_contain_kw_args?(args)
-
return false if args.count <= min_non_kw_args
-
@allows_any_kw_args || @allowed_kw_args.any?
-
end
-
-
1
def classify_parameters
-
optional_non_kw_args = @min_non_kw_args = 0
-
@allows_any_kw_args = false
-
-
@method.parameters.each do |(type, name)|
-
case type
-
# def foo(a:)
-
when :keyreq then @required_kw_args << name
-
# def foo(a: 1)
-
when :key then @optional_kw_args << name
-
# def foo(**kw_args)
-
when :keyrest then @allows_any_kw_args = true
-
# def foo(a)
-
when :req then @min_non_kw_args += 1
-
# def foo(a = 1)
-
when :opt then optional_non_kw_args += 1
-
# def foo(*a)
-
when :rest then optional_non_kw_args = INFINITY
-
end
-
end
-
-
@max_non_kw_args = @min_non_kw_args + optional_non_kw_args
-
@allowed_kw_args = @required_kw_args + @optional_kw_args
-
end
-
else
-
def description
-
"arity of #{non_kw_args_arity_description}"
-
end
-
-
def missing_kw_args_from(_given_kw_args)
-
[]
-
end
-
-
def invalid_kw_args_from(_given_kw_args)
-
[]
-
end
-
-
def has_kw_args_in?(_args)
-
false
-
end
-
-
def could_contain_kw_args?(*)
-
false
-
end
-
-
def classify_parameters
-
arity = @method.arity
-
if arity < 0
-
# `~` inverts the one's complement and gives us the
-
# number of required args
-
@min_non_kw_args = ~arity
-
@max_non_kw_args = INFINITY
-
else
-
@min_non_kw_args = arity
-
@max_non_kw_args = arity
-
end
-
end
-
end
-
-
1
INFINITY = 1 / 0.0
-
end
-
-
# Some versions of JRuby have a nasty bug we have to work around :(.
-
# https://github.com/jruby/jruby/issues/2816
-
if RSpec::Support::Ruby.jruby? &&
-
1
RubyFeatures.optional_and_splat_args_supported? &&
-
Class.new { attr_writer :foo }.instance_method(:foo=).parameters == []
-
-
class MethodSignature < remove_const(:MethodSignature)
-
private
-
-
def classify_parameters
-
super
-
return unless @method.parameters == [] && @method.arity == 1
-
@max_non_kw_args = @min_non_kw_args = 1
-
end
-
end
-
end
-
-
# Deals with the slightly different semantics of block arguments.
-
# For methods, arguments are required unless a default value is provided.
-
# For blocks, arguments are optional, even if no default value is provided.
-
#
-
# However, we want to treat block args as required since you virtually
-
# always want to pass a value for each received argument and our
-
# `and_yield` has treated block args as required for many years.
-
#
-
# @api private
-
1
class BlockSignature < MethodSignature
-
1
if RubyFeatures.optional_and_splat_args_supported?
-
1
def classify_parameters
-
super
-
@min_non_kw_args = @max_non_kw_args unless @max_non_kw_args == INFINITY
-
end
-
end
-
end
-
-
# Abstract base class for signature verifiers.
-
#
-
# @api private
-
1
class MethodSignatureVerifier
-
1
attr_reader :non_kw_args, :kw_args
-
-
1
def initialize(signature, args)
-
@signature = signature
-
@non_kw_args, @kw_args = split_args(*args)
-
end
-
-
1
def valid?
-
missing_kw_args.empty? &&
-
invalid_kw_args.empty? &&
-
valid_non_kw_args?
-
end
-
-
1
def error_message
-
if missing_kw_args.any?
-
"Missing required keyword arguments: %s" % [
-
missing_kw_args.join(", ")
-
]
-
elsif invalid_kw_args.any?
-
"Invalid keyword arguments provided: %s" % [
-
invalid_kw_args.join(", ")
-
]
-
elsif !valid_non_kw_args?
-
"Wrong number of arguments. Expected %s, got %s." % [
-
@signature.non_kw_args_arity_description,
-
non_kw_args.length
-
]
-
end
-
end
-
-
1
private
-
-
1
def valid_non_kw_args?
-
@signature.valid_non_kw_args?(non_kw_args.length)
-
end
-
-
1
def missing_kw_args
-
@signature.missing_kw_args_from(kw_args)
-
end
-
-
1
def invalid_kw_args
-
@signature.invalid_kw_args_from(kw_args)
-
end
-
-
1
def split_args(*args)
-
kw_args = if @signature.has_kw_args_in?(args)
-
args.pop.keys
-
else
-
[]
-
end
-
-
[args, kw_args]
-
end
-
end
-
-
# Figures out wether a given method can accept various arguments.
-
# Surprisingly non-trivial.
-
#
-
# @private
-
1
StrictSignatureVerifier = MethodSignatureVerifier
-
-
# Allows matchers to be used instead of providing keyword arguments. In
-
# practice, when this happens only the arity of the method is verified.
-
#
-
# @private
-
1
class LooseSignatureVerifier < MethodSignatureVerifier
-
1
private
-
-
1
def split_args(*args)
-
if RSpec::Support.is_a_matcher?(args.last) && @signature.could_contain_kw_args?(args)
-
args.pop
-
@signature = SignatureWithKeywordArgumentsMatcher.new(@signature)
-
end
-
-
super(*args)
-
end
-
-
# If a matcher is used in a signature in place of keyword arguments, all
-
# keyword argument validation needs to be skipped since the matcher is
-
# opaque.
-
#
-
# Instead, keyword arguments will be validated when the method is called
-
# and they are actually known.
-
#
-
# @private
-
1
class SignatureWithKeywordArgumentsMatcher
-
1
def initialize(signature)
-
@signature = signature
-
end
-
-
1
def missing_kw_args_from(_kw_args)
-
[]
-
end
-
-
1
def invalid_kw_args_from(_kw_args)
-
[]
-
end
-
-
1
def non_kw_args_arity_description
-
@signature.non_kw_args_arity_description
-
end
-
-
1
def valid_non_kw_args?(*args)
-
@signature.valid_non_kw_args?(*args)
-
end
-
-
1
def has_kw_args_in?(args)
-
@signature.has_kw_args_in?(args)
-
end
-
end
-
end
-
end
-
end
-
1
module RSpec
-
1
module Support
-
# Provides recursive constant lookup methods useful for
-
# constant stubbing.
-
1
module RecursiveConstMethods
-
# We only want to consider constants that are defined directly on a
-
# particular module, and not include top-level/inherited constants.
-
# Unfortunately, the constant API changed between 1.8 and 1.9, so
-
# we need to conditionally define methods to ignore the top-level/inherited
-
# constants.
-
#
-
# Given:
-
# class A; B = 1; end
-
# class C < A; end
-
#
-
# On 1.8:
-
# - C.const_get("Hash") # => ::Hash
-
# - C.const_defined?("Hash") # => false
-
# - C.constants # => ["B"]
-
# - None of these methods accept the extra `inherit` argument
-
# On 1.9:
-
# - C.const_get("Hash") # => ::Hash
-
# - C.const_defined?("Hash") # => true
-
# - C.const_get("Hash", false) # => raises NameError
-
# - C.const_defined?("Hash", false) # => false
-
# - C.constants # => [:B]
-
# - C.constants(false) #=> []
-
1
if Module.method(:const_defined?).arity == 1
-
def const_defined_on?(mod, const_name)
-
mod.const_defined?(const_name)
-
end
-
-
def get_const_defined_on(mod, const_name)
-
return mod.const_get(const_name) if const_defined_on?(mod, const_name)
-
-
raise NameError, "uninitialized constant #{mod.name}::#{const_name}"
-
end
-
-
def constants_defined_on(mod)
-
mod.constants.select { |c| const_defined_on?(mod, c) }
-
end
-
else
-
1
def const_defined_on?(mod, const_name)
-
mod.const_defined?(const_name, false)
-
end
-
-
1
def get_const_defined_on(mod, const_name)
-
mod.const_get(const_name, false)
-
end
-
-
1
def constants_defined_on(mod)
-
mod.constants(false)
-
end
-
end
-
-
1
def recursive_const_get(const_name)
-
normalize_const_name(const_name).split('::').inject(Object) do |mod, name|
-
get_const_defined_on(mod, name)
-
end
-
end
-
-
1
def recursive_const_defined?(const_name)
-
parts = normalize_const_name(const_name).split('::')
-
parts.inject([Object, '']) do |(mod, full_name), name|
-
yield(full_name, name) if block_given? && !(Module === mod)
-
return false unless const_defined_on?(mod, name)
-
[get_const_defined_on(mod, name), [mod, name].join('::')]
-
end
-
end
-
-
1
def normalize_const_name(const_name)
-
const_name.sub(/\A::/, '')
-
end
-
end
-
end
-
end
-
1
module RSpec
-
1
module Support
-
# Allows a thread to lock out other threads from a critical section of code,
-
# while allowing the thread with the lock to reenter that section.
-
#
-
# Based on Monitor as of 2.2 -
-
# https://github.com/ruby/ruby/blob/eb7ddaa3a47bf48045d26c72eb0f263a53524ebc/lib/monitor.rb#L9
-
#
-
# Depends on Mutex, but Mutex is only available as part of core since 1.9.1:
-
# exists - http://ruby-doc.org/core-1.9.1/Mutex.html
-
# dne - http://ruby-doc.org/core-1.9.0/Mutex.html
-
#
-
# @private
-
1
class ReentrantMutex
-
1
def initialize
-
@owner = nil
-
@count = 0
-
@mutex = Mutex.new
-
end
-
-
1
def synchronize
-
enter
-
yield
-
ensure
-
exit
-
end
-
-
1
private
-
-
1
def enter
-
@mutex.lock if @owner != Thread.current
-
@owner = Thread.current
-
@count += 1
-
end
-
-
1
def exit
-
@count -= 1
-
return unless @count == 0
-
@owner = nil
-
@mutex.unlock
-
end
-
end
-
-
1
if defined? ::Mutex
-
# On 1.9 and up, this is in core, so we just use the real one
-
1
Mutex = ::Mutex
-
else # For 1.8.7
-
# :nocov:
-
skipped
RSpec::Support.require_rspec_support "mutex"
-
# :nocov:
-
end
-
end
-
end
-
1
module RSpec
-
1
module Support
-
1
module Version
-
1
STRING = '3.4.1'
-
end
-
end
-
end
-
1
module RSpec
-
1
module Support
-
1
LibraryVersionTooLowError = Class.new(StandardError)
-
-
# @private
-
1
class VersionChecker
-
1
def initialize(library_name, library_version, min_patch_level)
-
1
@library_name, @library_version = library_name, library_version
-
1
@min_patch_level = min_patch_level
-
-
1
@major, @minor, @patch = parse_version(library_version)
-
1
@min_major, @min_minor, @min_patch = parse_version(min_patch_level)
-
-
1
@comparison_result = compare_version
-
end
-
-
1
def check_version!
-
1
raise_too_low_error if too_low?
-
end
-
-
1
private
-
-
1
def too_low?
-
1
@comparison_result == :too_low
-
end
-
-
1
def raise_too_low_error
-
raise LibraryVersionTooLowError,
-
"You are using #{@library_name} #{@library_version}. " \
-
"RSpec requires version #{version_requirement}."
-
end
-
-
1
def compare_version
-
case
-
when @major < @min_major then :too_low
-
when @major > @min_major then :ok
-
when @minor < @min_minor then :too_low
-
1
when @minor > @min_minor then :ok
-
when @patch < @min_patch then :too_low
-
else :ok
-
1
end
-
end
-
-
1
def version_requirement
-
">= #{@min_patch_level}"
-
end
-
-
1
def parse_version(version)
-
8
version.split('.').map { |v| v.to_i }
-
end
-
end
-
end
-
end
-
1
require 'rspec/support'
-
1
RSpec::Support.require_rspec_support "caller_filter"
-
-
1
module RSpec
-
1
module Support
-
1
module Warnings
-
1
def deprecate(deprecated, options={})
-
warn_with "DEPRECATION: #{deprecated} is deprecated.", options
-
end
-
-
# @private
-
#
-
# Used internally to print deprecation warnings
-
# when rspec-core isn't loaded
-
1
def warn_deprecation(message, options={})
-
warn_with "DEPRECATION: \n #{message}", options
-
end
-
-
# @private
-
#
-
# Used internally to print warnings
-
1
def warning(text, options={})
-
warn_with "WARNING: #{text}.", options
-
end
-
-
# @private
-
#
-
# Used internally to print longer warnings
-
1
def warn_with(message, options={})
-
call_site = options.fetch(:call_site) { CallerFilter.first_non_rspec_line }
-
message << " Use #{options[:replacement]} instead." if options[:replacement]
-
message << " Called from #{call_site}." if call_site
-
Support.warning_notifier.call message
-
end
-
end
-
end
-
-
1
extend RSpec::Support::Warnings
-
end
-
2
require 'delegate'
-
2
require 'singleton'
-
2
require 'tempfile'
-
2
require 'tmpdir'
-
2
require 'fileutils'
-
2
require 'stringio'
-
2
require 'zlib'
-
2
require 'zip/dos_time'
-
2
require 'zip/ioextras'
-
2
require 'rbconfig'
-
2
require 'zip/entry'
-
2
require 'zip/extra_field'
-
2
require 'zip/entry_set'
-
2
require 'zip/central_directory'
-
2
require 'zip/file'
-
2
require 'zip/input_stream'
-
2
require 'zip/output_stream'
-
2
require 'zip/decompressor'
-
2
require 'zip/compressor'
-
2
require 'zip/null_decompressor'
-
2
require 'zip/null_compressor'
-
2
require 'zip/null_input_stream'
-
2
require 'zip/pass_thru_compressor'
-
2
require 'zip/pass_thru_decompressor'
-
2
require 'zip/crypto/encryption'
-
2
require 'zip/crypto/null_encryption'
-
2
require 'zip/crypto/traditional_encryption'
-
2
require 'zip/inflater'
-
2
require 'zip/deflater'
-
2
require 'zip/streamable_stream'
-
2
require 'zip/streamable_directory'
-
2
require 'zip/constants'
-
2
require 'zip/errors'
-
-
2
module Zip
-
2
extend self
-
2
attr_accessor :unicode_names, :on_exists_proc, :continue_on_exists_proc, :sort_entries, :default_compression, :write_zip64_support, :warn_invalid_date, :case_insensitive_match
-
-
2
def reset!
-
2
@_ran_once = false
-
2
@unicode_names = false
-
2
@on_exists_proc = false
-
2
@continue_on_exists_proc = false
-
2
@sort_entries = false
-
2
@default_compression = ::Zlib::DEFAULT_COMPRESSION
-
2
@write_zip64_support = false
-
2
@warn_invalid_date = true
-
2
@case_insensitive_match = false
-
end
-
-
2
def setup
-
yield self unless @_ran_once
-
@_ran_once = true
-
end
-
-
2
reset!
-
end
-
-
# Copyright (C) 2002, 2003 Thomas Sondergaard
-
# rubyzip is free software; you can redistribute it and/or
-
# modify it under the terms of the ruby license.
-
2
module Zip
-
2
class CentralDirectory
-
2
include Enumerable
-
-
2
END_OF_CDS = 0x06054b50
-
2
ZIP64_END_OF_CDS = 0x06064b50
-
2
ZIP64_EOCD_LOCATOR = 0x07064b50
-
2
MAX_END_OF_CDS_SIZE = 65_536 + 18
-
2
STATIC_EOCD_SIZE = 22
-
-
2
attr_reader :comment
-
-
# Returns an Enumerable containing the entries.
-
2
def entries
-
@entry_set.entries
-
end
-
-
2
def initialize(entries = EntrySet.new, comment = '') #:nodoc:
-
super()
-
@entry_set = entries.kind_of?(EntrySet) ? entries : EntrySet.new(entries)
-
@comment = comment
-
end
-
-
2
def write_to_stream(io) #:nodoc:
-
cdir_offset = io.tell
-
@entry_set.each { |entry| entry.write_c_dir_entry(io) }
-
eocd_offset = io.tell
-
cdir_size = eocd_offset - cdir_offset
-
if ::Zip.write_zip64_support
-
need_zip64_eocd = cdir_offset > 0xFFFFFFFF || cdir_size > 0xFFFFFFFF || @entry_set.size > 0xFFFF
-
need_zip64_eocd ||= @entry_set.any? { |entry| entry.extra['Zip64'] }
-
if need_zip64_eocd
-
write_64_e_o_c_d(io, cdir_offset, cdir_size)
-
write_64_eocd_locator(io, eocd_offset)
-
end
-
end
-
write_e_o_c_d(io, cdir_offset, cdir_size)
-
end
-
-
2
def write_e_o_c_d(io, offset, cdir_size) #:nodoc:
-
tmp = [
-
END_OF_CDS,
-
0, # @numberOfThisDisk
-
0, # @numberOfDiskWithStartOfCDir
-
@entry_set ? [@entry_set.size, 0xFFFF].min : 0,
-
@entry_set ? [@entry_set.size, 0xFFFF].min : 0,
-
[cdir_size, 0xFFFFFFFF].min,
-
[offset, 0xFFFFFFFF].min,
-
@comment ? @comment.bytesize : 0
-
]
-
io << tmp.pack('VvvvvVVv')
-
io << @comment
-
end
-
-
2
private :write_e_o_c_d
-
-
2
def write_64_e_o_c_d(io, offset, cdir_size) #:nodoc:
-
tmp = [
-
ZIP64_END_OF_CDS,
-
44, # size of zip64 end of central directory record (excludes signature and field itself)
-
VERSION_MADE_BY,
-
VERSION_NEEDED_TO_EXTRACT_ZIP64,
-
0, # @numberOfThisDisk
-
0, # @numberOfDiskWithStartOfCDir
-
@entry_set ? @entry_set.size : 0, # number of entries on this disk
-
@entry_set ? @entry_set.size : 0, # number of entries total
-
cdir_size, # size of central directory
-
offset, # offset of start of central directory in its disk
-
]
-
io << tmp.pack('VQ<vvVVQ<Q<Q<Q<')
-
end
-
-
2
private :write_64_e_o_c_d
-
-
2
def write_64_eocd_locator(io, zip64_eocd_offset)
-
tmp = [
-
ZIP64_EOCD_LOCATOR,
-
0, # number of disk containing the start of zip64 eocd record
-
zip64_eocd_offset, # offset of the start of zip64 eocd record in its disk
-
1 # total number of disks
-
]
-
io << tmp.pack('VVQ<V')
-
end
-
-
2
private :write_64_eocd_locator
-
-
2
def read_64_e_o_c_d(buf) #:nodoc:
-
buf = get_64_e_o_c_d(buf)
-
@size_of_zip64_e_o_c_d = Entry.read_zip_64_long(buf)
-
@version_made_by = Entry.read_zip_short(buf)
-
@version_needed_for_extract = Entry.read_zip_short(buf)
-
@number_of_this_disk = Entry.read_zip_long(buf)
-
@number_of_disk_with_start_of_cdir = Entry.read_zip_long(buf)
-
@total_number_of_entries_in_cdir_on_this_disk = Entry.read_zip_64_long(buf)
-
@size = Entry.read_zip_64_long(buf)
-
@size_in_bytes = Entry.read_zip_64_long(buf)
-
@cdir_offset = Entry.read_zip_64_long(buf)
-
@zip_64_extensible = buf.slice!(0, buf.bytesize)
-
raise Error, 'Zip consistency problem while reading eocd structure' unless buf.size == 0
-
end
-
-
2
def read_e_o_c_d(buf) #:nodoc:
-
buf = get_e_o_c_d(buf)
-
@number_of_this_disk = Entry.read_zip_short(buf)
-
@number_of_disk_with_start_of_cdir = Entry.read_zip_short(buf)
-
@total_number_of_entries_in_cdir_on_this_disk = Entry.read_zip_short(buf)
-
@size = Entry.read_zip_short(buf)
-
@size_in_bytes = Entry.read_zip_long(buf)
-
@cdir_offset = Entry.read_zip_long(buf)
-
comment_length = Entry.read_zip_short(buf)
-
@comment = if comment_length.to_i <= 0
-
buf.slice!(0, buf.size)
-
else
-
buf.read(comment_length)
-
end
-
raise Error, 'Zip consistency problem while reading eocd structure' unless buf.size == 0
-
end
-
-
2
def read_central_directory_entries(io) #:nodoc:
-
begin
-
io.seek(@cdir_offset, IO::SEEK_SET)
-
rescue Errno::EINVAL
-
raise Error, 'Zip consistency problem while reading central directory entry'
-
end
-
@entry_set = EntrySet.new
-
@size.times do
-
@entry_set << Entry.read_c_dir_entry(io)
-
end
-
end
-
-
2
def read_from_stream(io) #:nodoc:
-
buf = start_buf(io)
-
if self.zip64_file?(buf)
-
read_64_e_o_c_d(buf)
-
else
-
read_e_o_c_d(buf)
-
end
-
read_central_directory_entries(io)
-
end
-
-
2
def get_e_o_c_d(buf) #:nodoc:
-
sig_index = buf.rindex([END_OF_CDS].pack('V'))
-
raise Error, 'Zip end of central directory signature not found' unless sig_index
-
buf = buf.slice!((sig_index + 4)..(buf.bytesize))
-
-
def buf.read(count)
-
slice!(0, count)
-
end
-
-
buf
-
end
-
-
2
def zip64_file?(buf)
-
buf.rindex([ZIP64_END_OF_CDS].pack('V')) && buf.rindex([ZIP64_EOCD_LOCATOR].pack('V'))
-
end
-
-
2
def start_buf(io)
-
begin
-
io.seek(-MAX_END_OF_CDS_SIZE, IO::SEEK_END)
-
rescue Errno::EINVAL
-
io.seek(0, IO::SEEK_SET)
-
end
-
io.read
-
end
-
-
2
def get_64_e_o_c_d(buf) #:nodoc:
-
zip_64_start = buf.rindex([ZIP64_END_OF_CDS].pack('V'))
-
raise Error, 'Zip64 end of central directory signature not found' unless zip_64_start
-
zip_64_locator = buf.rindex([ZIP64_EOCD_LOCATOR].pack('V'))
-
raise Error, 'Zip64 end of central directory signature locator not found' unless zip_64_locator
-
buf = buf.slice!((zip_64_start + 4)..zip_64_locator)
-
-
def buf.read(count)
-
slice!(0, count)
-
end
-
-
buf
-
end
-
-
# For iterating over the entries.
-
2
def each(&proc)
-
@entry_set.each(&proc)
-
end
-
-
# Returns the number of entries in the central directory (and
-
# consequently in the zip archive).
-
2
def size
-
@entry_set.size
-
end
-
-
2
def self.read_from_stream(io) #:nodoc:
-
cdir = new
-
cdir.read_from_stream(io)
-
return cdir
-
rescue Error
-
return nil
-
end
-
-
2
def ==(other) #:nodoc:
-
return false unless other.kind_of?(CentralDirectory)
-
@entry_set.entries.sort == other.entries.sort && comment == other.comment
-
end
-
end
-
end
-
-
# Copyright (C) 2002, 2003 Thomas Sondergaard
-
# rubyzip is free software; you can redistribute it and/or
-
# modify it under the terms of the ruby license.
-
2
module Zip
-
2
class Compressor #:nodoc:all
-
2
def finish
-
end
-
end
-
end
-
-
# Copyright (C) 2002, 2003 Thomas Sondergaard
-
# rubyzip is free software; you can redistribute it and/or
-
# modify it under the terms of the ruby license.
-
2
module Zip
-
2
RUNNING_ON_WINDOWS = RbConfig::CONFIG['host_os'] =~ /mswin|mingw|cygwin/i
-
-
2
CENTRAL_DIRECTORY_ENTRY_SIGNATURE = 0x02014b50
-
2
CDIR_ENTRY_STATIC_HEADER_LENGTH = 46
-
-
2
LOCAL_ENTRY_SIGNATURE = 0x04034b50
-
2
LOCAL_ENTRY_STATIC_HEADER_LENGTH = 30
-
2
LOCAL_ENTRY_TRAILING_DESCRIPTOR_LENGTH = 4 + 4 + 4
-
2
VERSION_MADE_BY = 52 # this library's version
-
2
VERSION_NEEDED_TO_EXTRACT = 20
-
2
VERSION_NEEDED_TO_EXTRACT_ZIP64 = 45
-
-
2
FILE_TYPE_FILE = 010
-
2
FILE_TYPE_DIR = 004
-
2
FILE_TYPE_SYMLINK = 012
-
-
2
FSTYPE_FAT = 0
-
2
FSTYPE_AMIGA = 1
-
2
FSTYPE_VMS = 2
-
2
FSTYPE_UNIX = 3
-
2
FSTYPE_VM_CMS = 4
-
2
FSTYPE_ATARI = 5
-
2
FSTYPE_HPFS = 6
-
2
FSTYPE_MAC = 7
-
2
FSTYPE_Z_SYSTEM = 8
-
2
FSTYPE_CPM = 9
-
2
FSTYPE_TOPS20 = 10
-
2
FSTYPE_NTFS = 11
-
2
FSTYPE_QDOS = 12
-
2
FSTYPE_ACORN = 13
-
2
FSTYPE_VFAT = 14
-
2
FSTYPE_MVS = 15
-
2
FSTYPE_BEOS = 16
-
2
FSTYPE_TANDEM = 17
-
2
FSTYPE_THEOS = 18
-
2
FSTYPE_MAC_OSX = 19
-
2
FSTYPE_ATHEOS = 30
-
-
2
FSTYPES = {
-
FSTYPE_FAT => 'FAT'.freeze,
-
FSTYPE_AMIGA => 'Amiga'.freeze,
-
FSTYPE_VMS => 'VMS (Vax or Alpha AXP)'.freeze,
-
FSTYPE_UNIX => 'Unix'.freeze,
-
FSTYPE_VM_CMS => 'VM/CMS'.freeze,
-
FSTYPE_ATARI => 'Atari ST'.freeze,
-
FSTYPE_HPFS => 'OS/2 or NT HPFS'.freeze,
-
FSTYPE_MAC => 'Macintosh'.freeze,
-
FSTYPE_Z_SYSTEM => 'Z-System'.freeze,
-
FSTYPE_CPM => 'CP/M'.freeze,
-
FSTYPE_TOPS20 => 'TOPS-20'.freeze,
-
FSTYPE_NTFS => 'NTFS'.freeze,
-
FSTYPE_QDOS => 'SMS/QDOS'.freeze,
-
FSTYPE_ACORN => 'Acorn RISC OS'.freeze,
-
FSTYPE_VFAT => 'Win32 VFAT'.freeze,
-
FSTYPE_MVS => 'MVS'.freeze,
-
FSTYPE_BEOS => 'BeOS'.freeze,
-
FSTYPE_TANDEM => 'Tandem NSK'.freeze,
-
FSTYPE_THEOS => 'Theos'.freeze,
-
FSTYPE_MAC_OSX => 'Mac OS/X (Darwin)'.freeze,
-
FSTYPE_ATHEOS => 'AtheOS'.freeze
-
}.freeze
-
end
-
2
module Zip
-
2
class Encrypter #:nodoc:all
-
end
-
-
2
class Decrypter
-
end
-
end
-
-
# Copyright (C) 2002, 2003 Thomas Sondergaard
-
# rubyzip is free software; you can redistribute it and/or
-
# modify it under the terms of the ruby license.
-
2
module Zip
-
2
module NullEncryption
-
2
def header_bytesize
-
0
-
end
-
-
2
def gp_flags
-
0
-
end
-
end
-
-
2
class NullEncrypter < Encrypter
-
2
include NullEncryption
-
-
2
def header(_mtime)
-
''
-
end
-
-
2
def encrypt(data)
-
data
-
end
-
-
2
def data_descriptor(_crc32, _compressed_size, _uncomprssed_size)
-
''
-
end
-
-
2
def reset!
-
end
-
end
-
-
2
class NullDecrypter < Decrypter
-
2
include NullEncryption
-
-
2
def decrypt(data)
-
data
-
end
-
-
2
def reset!(_header)
-
end
-
end
-
end
-
-
# Copyright (C) 2002, 2003 Thomas Sondergaard
-
# rubyzip is free software; you can redistribute it and/or
-
# modify it under the terms of the ruby license.
-
2
module Zip
-
2
module TraditionalEncryption
-
2
def initialize(password)
-
@password = password
-
reset_keys!
-
end
-
-
2
def header_bytesize
-
12
-
end
-
-
2
def gp_flags
-
0x0001 | 0x0008
-
end
-
-
2
protected
-
-
2
def reset_keys!
-
@key0 = 0x12345678
-
@key1 = 0x23456789
-
@key2 = 0x34567890
-
@password.each_byte do |byte|
-
update_keys(byte.chr)
-
end
-
end
-
-
2
def update_keys(n)
-
@key0 = ~Zlib.crc32(n, ~@key0)
-
@key1 = ((@key1 + (@key0 & 0xff)) * 134_775_813 + 1) & 0xffffffff
-
@key2 = ~Zlib.crc32((@key1 >> 24).chr, ~@key2)
-
end
-
-
2
def decrypt_byte
-
temp = (@key2 & 0xffff) | 2
-
((temp * (temp ^ 1)) >> 8) & 0xff
-
end
-
end
-
-
2
class TraditionalEncrypter < Encrypter
-
2
include TraditionalEncryption
-
-
2
def header(mtime)
-
[].tap do |header|
-
(header_bytesize - 2).times do
-
header << Random.rand(0..255)
-
end
-
header << (mtime.to_binary_dos_time & 0xff)
-
header << (mtime.to_binary_dos_time >> 8)
-
end.map { |x| encode x }.pack('C*')
-
end
-
-
2
def encrypt(data)
-
data.unpack('C*').map { |x| encode x }.pack('C*')
-
end
-
-
2
def data_descriptor(crc32, compressed_size, uncomprssed_size)
-
[0x08074b50, crc32, compressed_size, uncomprssed_size].pack('VVVV')
-
end
-
-
2
def reset!
-
reset_keys!
-
end
-
-
2
private
-
-
2
def encode(n)
-
t = decrypt_byte
-
update_keys(n.chr)
-
t ^ n
-
end
-
end
-
-
2
class TraditionalDecrypter < Decrypter
-
2
include TraditionalEncryption
-
-
2
def decrypt(data)
-
data.unpack('C*').map { |x| decode x }.pack('C*')
-
end
-
-
2
def reset!(header)
-
reset_keys!
-
header.each_byte do |x|
-
decode x
-
end
-
end
-
-
2
private
-
-
2
def decode(n)
-
n ^= decrypt_byte
-
update_keys(n.chr)
-
n
-
end
-
end
-
end
-
-
# Copyright (C) 2002, 2003 Thomas Sondergaard
-
# rubyzip is free software; you can redistribute it and/or
-
# modify it under the terms of the ruby license.
-
2
module Zip
-
2
class Decompressor #:nodoc:all
-
2
CHUNK_SIZE = 32_768
-
2
def initialize(input_stream)
-
super()
-
@input_stream = input_stream
-
end
-
end
-
end
-
-
# Copyright (C) 2002, 2003 Thomas Sondergaard
-
# rubyzip is free software; you can redistribute it and/or
-
# modify it under the terms of the ruby license.
-
2
module Zip
-
2
class Deflater < Compressor #:nodoc:all
-
2
def initialize(output_stream, level = Zip.default_compression, encrypter = NullEncrypter.new)
-
super()
-
@output_stream = output_stream
-
@zlib_deflater = ::Zlib::Deflate.new(level, -::Zlib::MAX_WBITS)
-
@size = 0
-
@crc = ::Zlib.crc32
-
@encrypter = encrypter
-
end
-
-
2
def <<(data)
-
val = data.to_s
-
@crc = Zlib.crc32(val, @crc)
-
@size += val.bytesize
-
buffer = @zlib_deflater.deflate(data)
-
if buffer.empty?
-
@output_stream
-
else
-
@output_stream << @encrypter.encrypt(buffer)
-
end
-
end
-
-
2
def finish
-
@output_stream << @encrypter.encrypt(@zlib_deflater.finish) until @zlib_deflater.finished?
-
end
-
-
2
attr_reader :size, :crc
-
end
-
end
-
-
# Copyright (C) 2002, 2003 Thomas Sondergaard
-
# rubyzip is free software; you can redistribute it and/or
-
# modify it under the terms of the ruby license.
-
2
module Zip
-
2
class DOSTime < Time #:nodoc:all
-
# MS-DOS File Date and Time format as used in Interrupt 21H Function 57H:
-
-
# Register CX, the Time:
-
# Bits 0-4 2 second increments (0-29)
-
# Bits 5-10 minutes (0-59)
-
# bits 11-15 hours (0-24)
-
-
# Register DX, the Date:
-
# Bits 0-4 day (1-31)
-
# bits 5-8 month (1-12)
-
# bits 9-15 year (four digit year minus 1980)
-
-
2
def to_binary_dos_time
-
(sec / 2) +
-
(min << 5) +
-
(hour << 11)
-
end
-
-
2
def to_binary_dos_date
-
(day) +
-
(month << 5) +
-
((year - 1980) << 9)
-
end
-
-
# Dos time is only stored with two seconds accuracy
-
2
def dos_equals(other)
-
to_i / 2 == other.to_i / 2
-
end
-
-
2
def self.parse_binary_dos_format(binaryDosDate, binaryDosTime)
-
second = 2 * (0b11111 & binaryDosTime)
-
minute = (0b11111100000 & binaryDosTime) >> 5
-
hour = (0b1111100000000000 & binaryDosTime) >> 11
-
day = (0b11111 & binaryDosDate)
-
month = (0b111100000 & binaryDosDate) >> 5
-
year = ((0b1111111000000000 & binaryDosDate) >> 9) + 1980
-
begin
-
local(year, month, day, hour, minute, second)
-
end
-
end
-
end
-
end
-
-
# Copyright (C) 2002, 2003 Thomas Sondergaard
-
# rubyzip is free software; you can redistribute it and/or
-
# modify it under the terms of the ruby license.
-
2
module Zip
-
2
class Entry
-
2
STORED = 0
-
2
DEFLATED = 8
-
# Language encoding flag (EFS) bit
-
2
EFS = 0b100000000000
-
-
2
attr_accessor :comment, :compressed_size, :crc, :extra, :compression_method,
-
:name, :size, :local_header_offset, :zipfile, :fstype, :external_file_attributes,
-
:gp_flags, :header_signature, :follow_symlinks,
-
:restore_times, :restore_permissions, :restore_ownership,
-
:unix_uid, :unix_gid, :unix_perms,
-
:dirty
-
2
attr_reader :ftype, :filepath # :nodoc:
-
-
2
def set_default_vars_values
-
@local_header_offset = 0
-
@local_header_size = nil # not known until local entry is created or read
-
@internal_file_attributes = 1
-
@external_file_attributes = 0
-
@header_signature = ::Zip::CENTRAL_DIRECTORY_ENTRY_SIGNATURE
-
-
@version_needed_to_extract = VERSION_NEEDED_TO_EXTRACT
-
@version = VERSION_MADE_BY
-
-
@ftype = nil # unspecified or unknown
-
@filepath = nil
-
@gp_flags = 0
-
if ::Zip.unicode_names
-
@gp_flags |= EFS
-
@version = 63
-
end
-
@follow_symlinks = false
-
-
@restore_times = true
-
@restore_permissions = false
-
@restore_ownership = false
-
# BUG: need an extra field to support uid/gid's
-
@unix_uid = nil
-
@unix_gid = nil
-
@unix_perms = nil
-
# @posix_acl = nil
-
# @ntfs_acl = nil
-
@dirty = false
-
end
-
-
2
def check_name(name)
-
return unless name.start_with?('/')
-
raise ::Zip::EntryNameError, "Illegal ZipEntry name '#{name}', name must not start with /"
-
end
-
-
2
def initialize(*args)
-
name = args[1] || ''
-
check_name(name)
-
-
set_default_vars_values
-
@fstype = ::Zip::RUNNING_ON_WINDOWS ? ::Zip::FSTYPE_FAT : ::Zip::FSTYPE_UNIX
-
-
@zipfile = args[0] || ''
-
@name = name
-
@comment = args[2] || ''
-
@extra = args[3] || ''
-
@compressed_size = args[4] || 0
-
@crc = args[5] || 0
-
@compression_method = args[6] || ::Zip::Entry::DEFLATED
-
@size = args[7] || 0
-
@time = args[8] || ::Zip::DOSTime.now
-
-
@ftype = name_is_directory? ? :directory : :file
-
@extra = ::Zip::ExtraField.new(@extra.to_s) unless @extra.is_a?(::Zip::ExtraField)
-
end
-
-
2
def time
-
if @extra['UniversalTime']
-
@extra['UniversalTime'].mtime
-
elsif @extra['NTFS']
-
@extra['NTFS'].mtime
-
else
-
# Standard time field in central directory has local time
-
# under archive creator. Then, we can't get timezone.
-
@time
-
end
-
end
-
-
2
alias mtime time
-
-
2
def time=(value)
-
unless @extra.member?('UniversalTime') || @extra.member?('NTFS')
-
@extra.create('UniversalTime')
-
end
-
(@extra['UniversalTime'] || @extra['NTFS']).mtime = value
-
@time = value
-
end
-
-
2
def file_type_is?(type)
-
raise InternalError, "current filetype is unknown: #{inspect}" unless @ftype
-
@ftype == type
-
end
-
-
# Dynamic checkers
-
2
%w(directory file symlink).each do |k|
-
6
define_method "#{k}?" do
-
file_type_is?(k.to_sym)
-
end
-
end
-
-
2
def name_is_directory? #:nodoc:all
-
@name.end_with?('/')
-
end
-
-
2
def local_entry_offset #:nodoc:all
-
local_header_offset + @local_header_size
-
end
-
-
2
def name_size
-
@name ? @name.bytesize : 0
-
end
-
-
2
def extra_size
-
@extra ? @extra.local_size : 0
-
end
-
-
2
def comment_size
-
@comment ? @comment.bytesize : 0
-
end
-
-
2
def calculate_local_header_size #:nodoc:all
-
LOCAL_ENTRY_STATIC_HEADER_LENGTH + name_size + extra_size
-
end
-
-
# check before rewriting an entry (after file sizes are known)
-
# that we didn't change the header size (and thus clobber file data or something)
-
2
def verify_local_header_size!
-
return if @local_header_size.nil?
-
new_size = calculate_local_header_size
-
raise Error, "local header size changed (#{@local_header_size} -> #{new_size})" if @local_header_size != new_size
-
end
-
-
2
def cdir_header_size #:nodoc:all
-
CDIR_ENTRY_STATIC_HEADER_LENGTH + name_size +
-
(@extra ? @extra.c_dir_size : 0) + comment_size
-
end
-
-
2
def next_header_offset #:nodoc:all
-
local_entry_offset + compressed_size + data_descriptor_size
-
end
-
-
# Extracts entry to file dest_path (defaults to @name).
-
2
def extract(dest_path = @name, &block)
-
block ||= proc { ::Zip.on_exists_proc }
-
-
if directory? || file? || symlink?
-
__send__("create_#{@ftype}", dest_path, &block)
-
else
-
raise "unknown file type #{inspect}"
-
end
-
-
self
-
end
-
-
2
def to_s
-
@name
-
end
-
-
2
class << self
-
2
def read_zip_short(io) # :nodoc:
-
io.read(2).unpack('v')[0]
-
end
-
-
2
def read_zip_long(io) # :nodoc:
-
io.read(4).unpack('V')[0]
-
end
-
-
2
def read_zip_64_long(io) # :nodoc:
-
io.read(8).unpack('Q<')[0]
-
end
-
-
2
def read_c_dir_entry(io) #:nodoc:all
-
path = if io.respond_to?(:path)
-
io.path
-
else
-
io
-
end
-
entry = new(path)
-
entry.read_c_dir_entry(io)
-
entry
-
rescue Error
-
nil
-
end
-
-
2
def read_local_entry(io)
-
entry = new(io)
-
entry.read_local_entry(io)
-
entry
-
rescue Error
-
nil
-
end
-
end
-
-
2
public
-
-
2
def unpack_local_entry(buf)
-
@header_signature,
-
@version,
-
@fstype,
-
@gp_flags,
-
@compression_method,
-
@last_mod_time,
-
@last_mod_date,
-
@crc,
-
@compressed_size,
-
@size,
-
@name_length,
-
@extra_length = buf.unpack('VCCvvvvVVVvv')
-
end
-
-
2
def read_local_entry(io) #:nodoc:all
-
@local_header_offset = io.tell
-
-
static_sized_fields_buf = io.read(::Zip::LOCAL_ENTRY_STATIC_HEADER_LENGTH) || ''
-
-
unless static_sized_fields_buf.bytesize == ::Zip::LOCAL_ENTRY_STATIC_HEADER_LENGTH
-
raise Error, 'Premature end of file. Not enough data for zip entry local header'
-
end
-
-
unpack_local_entry(static_sized_fields_buf)
-
-
unless @header_signature == ::Zip::LOCAL_ENTRY_SIGNATURE
-
raise ::Zip::Error, "Zip local header magic not found at location '#{local_header_offset}'"
-
end
-
set_time(@last_mod_date, @last_mod_time)
-
-
@name = io.read(@name_length)
-
extra = io.read(@extra_length)
-
-
@name.gsub!('\\', '/')
-
-
if extra && extra.bytesize != @extra_length
-
raise ::Zip::Error, 'Truncated local zip entry header'
-
else
-
if @extra.is_a?(::Zip::ExtraField)
-
@extra.merge(extra) if extra
-
else
-
@extra = ::Zip::ExtraField.new(extra)
-
end
-
end
-
parse_zip64_extra(true)
-
@local_header_size = calculate_local_header_size
-
end
-
-
2
def pack_local_entry
-
zip64 = @extra['Zip64']
-
[::Zip::LOCAL_ENTRY_SIGNATURE,
-
@version_needed_to_extract, # version needed to extract
-
@gp_flags, # @gp_flags ,
-
@compression_method,
-
@time.to_binary_dos_time, # @last_mod_time ,
-
@time.to_binary_dos_date, # @last_mod_date ,
-
@crc,
-
(zip64 && zip64.compressed_size) ? 0xFFFFFFFF : @compressed_size,
-
(zip64 && zip64.original_size) ? 0xFFFFFFFF : @size,
-
name_size,
-
@extra ? @extra.local_size : 0].pack('VvvvvvVVVvv')
-
end
-
-
2
def write_local_entry(io, rewrite = false) #:nodoc:all
-
prep_zip64_extra(true)
-
verify_local_header_size! if rewrite
-
@local_header_offset = io.tell
-
-
io << pack_local_entry
-
-
io << @name
-
io << @extra.to_local_bin if @extra
-
@local_header_size = io.tell - @local_header_offset
-
end
-
-
2
def unpack_c_dir_entry(buf)
-
@header_signature,
-
@version, # version of encoding software
-
@fstype, # filesystem type
-
@version_needed_to_extract,
-
@gp_flags,
-
@compression_method,
-
@last_mod_time,
-
@last_mod_date,
-
@crc,
-
@compressed_size,
-
@size,
-
@name_length,
-
@extra_length,
-
@comment_length,
-
_, # diskNumberStart
-
@internal_file_attributes,
-
@external_file_attributes,
-
@local_header_offset,
-
@name,
-
@extra,
-
@comment = buf.unpack('VCCvvvvvVVVvvvvvVV')
-
end
-
-
2
def set_ftype_from_c_dir_entry
-
@ftype = case @fstype
-
when ::Zip::FSTYPE_UNIX
-
@unix_perms = (@external_file_attributes >> 16) & 07777
-
case (@external_file_attributes >> 28)
-
when ::Zip::FILE_TYPE_DIR
-
:directory
-
when ::Zip::FILE_TYPE_FILE
-
:file
-
when ::Zip::FILE_TYPE_SYMLINK
-
:symlink
-
else
-
# best case guess for whether it is a file or not
-
# Otherwise this would be set to unknown and that entry would never be able to extracted
-
if name_is_directory?
-
:directory
-
else
-
:file
-
end
-
end
-
else
-
if name_is_directory?
-
:directory
-
else
-
:file
-
end
-
end
-
end
-
-
2
def check_c_dir_entry_static_header_length(buf)
-
return if buf.bytesize == ::Zip::CDIR_ENTRY_STATIC_HEADER_LENGTH
-
raise Error, 'Premature end of file. Not enough data for zip cdir entry header'
-
end
-
-
2
def check_c_dir_entry_signature
-
return if header_signature == ::Zip::CENTRAL_DIRECTORY_ENTRY_SIGNATURE
-
raise Error, "Zip local header magic not found at location '#{local_header_offset}'"
-
end
-
-
2
def check_c_dir_entry_comment_size
-
return if @comment && @comment.bytesize == @comment_length
-
raise ::Zip::Error, 'Truncated cdir zip entry header'
-
end
-
-
2
def read_c_dir_extra_field(io)
-
if @extra.is_a?(::Zip::ExtraField)
-
@extra.merge(io.read(@extra_length))
-
else
-
@extra = ::Zip::ExtraField.new(io.read(@extra_length))
-
end
-
end
-
-
2
def read_c_dir_entry(io) #:nodoc:all
-
static_sized_fields_buf = io.read(::Zip::CDIR_ENTRY_STATIC_HEADER_LENGTH)
-
check_c_dir_entry_static_header_length(static_sized_fields_buf)
-
unpack_c_dir_entry(static_sized_fields_buf)
-
check_c_dir_entry_signature
-
set_time(@last_mod_date, @last_mod_time)
-
@name = io.read(@name_length).tr('\\', '/')
-
read_c_dir_extra_field(io)
-
@comment = io.read(@comment_length)
-
check_c_dir_entry_comment_size
-
set_ftype_from_c_dir_entry
-
parse_zip64_extra(false)
-
end
-
-
2
def file_stat(path) # :nodoc:
-
if @follow_symlinks
-
::File.stat(path)
-
else
-
::File.lstat(path)
-
end
-
end
-
-
2
def get_extra_attributes_from_path(path) # :nodoc:
-
return if Zip::RUNNING_ON_WINDOWS
-
stat = file_stat(path)
-
@unix_uid = stat.uid
-
@unix_gid = stat.gid
-
@unix_perms = stat.mode & 07777
-
end
-
-
2
def set_unix_permissions_on_path(dest_path)
-
# BUG: does not update timestamps into account
-
# ignore setuid/setgid bits by default. honor if @restore_ownership
-
unix_perms_mask = 01777
-
unix_perms_mask = 07777 if @restore_ownership
-
::FileUtils.chmod(@unix_perms & unix_perms_mask, dest_path) if @restore_permissions && @unix_perms
-
::FileUtils.chown(@unix_uid, @unix_gid, dest_path) if @restore_ownership && @unix_uid && @unix_gid && ::Process.egid == 0
-
# File::utimes()
-
end
-
-
2
def set_extra_attributes_on_path(dest_path) # :nodoc:
-
return unless file? || directory?
-
-
case @fstype
-
when ::Zip::FSTYPE_UNIX
-
set_unix_permissions_on_path(dest_path)
-
end
-
end
-
-
2
def pack_c_dir_entry
-
zip64 = @extra['Zip64']
-
[
-
@header_signature,
-
@version, # version of encoding software
-
@fstype, # filesystem type
-
@version_needed_to_extract, # @versionNeededToExtract ,
-
@gp_flags, # @gp_flags ,
-
@compression_method,
-
@time.to_binary_dos_time, # @last_mod_time ,
-
@time.to_binary_dos_date, # @last_mod_date ,
-
@crc,
-
(zip64 && zip64.compressed_size) ? 0xFFFFFFFF : @compressed_size,
-
(zip64 && zip64.original_size) ? 0xFFFFFFFF : @size,
-
name_size,
-
@extra ? @extra.c_dir_size : 0,
-
comment_size,
-
(zip64 && zip64.disk_start_number) ? 0xFFFF : 0, # disk number start
-
@internal_file_attributes, # file type (binary=0, text=1)
-
@external_file_attributes, # native filesystem attributes
-
(zip64 && zip64.relative_header_offset) ? 0xFFFFFFFF : @local_header_offset,
-
@name,
-
@extra,
-
@comment
-
].pack('VCCvvvvvVVVvvvvvVV')
-
end
-
-
2
def write_c_dir_entry(io) #:nodoc:all
-
prep_zip64_extra(false)
-
case @fstype
-
when ::Zip::FSTYPE_UNIX
-
ft = case @ftype
-
when :file
-
@unix_perms ||= 0644
-
::Zip::FILE_TYPE_FILE
-
when :directory
-
@unix_perms ||= 0755
-
::Zip::FILE_TYPE_DIR
-
when :symlink
-
@unix_perms ||= 0755
-
::Zip::FILE_TYPE_SYMLINK
-
end
-
-
unless ft.nil?
-
@external_file_attributes = (ft << 12 | (@unix_perms & 07777)) << 16
-
end
-
end
-
-
io << pack_c_dir_entry
-
-
io << @name
-
io << (@extra ? @extra.to_c_dir_bin : '')
-
io << @comment
-
end
-
-
2
def ==(other)
-
return false unless other.class == self.class
-
# Compares contents of local entry and exposed fields
-
keys_equal = %w(compression_method crc compressed_size size name extra filepath).all? do |k|
-
other.__send__(k.to_sym) == __send__(k.to_sym)
-
end
-
keys_equal && time.dos_equals(other.time)
-
end
-
-
2
def <=>(other)
-
to_s <=> other.to_s
-
end
-
-
# Returns an IO like object for the given ZipEntry.
-
# Warning: may behave weird with symlinks.
-
2
def get_input_stream(&block)
-
if @ftype == :directory
-
yield ::Zip::NullInputStream if block_given?
-
::Zip::NullInputStream
-
elsif @filepath
-
case @ftype
-
when :file
-
::File.open(@filepath, 'rb', &block)
-
when :symlink
-
linkpath = ::File.readlink(@filepath)
-
stringio = ::StringIO.new(linkpath)
-
yield(stringio) if block_given?
-
stringio
-
else
-
raise "unknown @file_type #{@ftype}"
-
end
-
else
-
zis = ::Zip::InputStream.new(@zipfile, local_header_offset)
-
zis.instance_variable_set(:@internal, true)
-
zis.get_next_entry
-
if block_given?
-
begin
-
yield(zis)
-
ensure
-
zis.close
-
end
-
else
-
zis
-
end
-
end
-
end
-
-
2
def gather_fileinfo_from_srcpath(src_path) # :nodoc:
-
stat = file_stat(src_path)
-
@ftype = case stat.ftype
-
when 'file'
-
if name_is_directory?
-
raise ArgumentError,
-
"entry name '#{newEntry}' indicates directory entry, but " \
-
"'#{src_path}' is not a directory"
-
end
-
:file
-
when 'directory'
-
@name += '/' unless name_is_directory?
-
:directory
-
when 'link'
-
if name_is_directory?
-
raise ArgumentError,
-
"entry name '#{newEntry}' indicates directory entry, but " \
-
"'#{src_path}' is not a directory"
-
end
-
:symlink
-
else
-
raise "unknown file type: #{src_path.inspect} #{stat.inspect}"
-
end
-
-
@filepath = src_path
-
get_extra_attributes_from_path(@filepath)
-
end
-
-
2
def write_to_zip_output_stream(zip_output_stream) #:nodoc:all
-
if @ftype == :directory
-
zip_output_stream.put_next_entry(self, nil, nil, ::Zip::Entry::STORED)
-
elsif @filepath
-
zip_output_stream.put_next_entry(self, nil, nil, compression_method || ::Zip::Entry::DEFLATED)
-
get_input_stream { |is| ::Zip::IOExtras.copy_stream(zip_output_stream, is) }
-
else
-
zip_output_stream.copy_raw_entry(self)
-
end
-
end
-
-
2
def parent_as_string
-
entry_name = name.chomp('/')
-
slash_index = entry_name.rindex('/')
-
slash_index ? entry_name.slice(0, slash_index + 1) : nil
-
end
-
-
2
def get_raw_input_stream(&block)
-
if @zipfile.respond_to?(:seek) && @zipfile.respond_to?(:read)
-
yield @zipfile
-
else
-
::File.open(@zipfile, 'rb', &block)
-
end
-
end
-
-
2
def clean_up
-
# By default, do nothing
-
end
-
-
2
private
-
-
2
def set_time(binary_dos_date, binary_dos_time)
-
@time = ::Zip::DOSTime.parse_binary_dos_format(binary_dos_date, binary_dos_time)
-
rescue ArgumentError
-
warn 'Invalid date/time in zip entry' if ::Zip.warn_invalid_date
-
end
-
-
2
def create_file(dest_path, _continue_on_exists_proc = proc { Zip.continue_on_exists_proc })
-
if ::File.exist?(dest_path) && !yield(self, dest_path)
-
raise ::Zip::DestinationFileExistsError,
-
"Destination '#{dest_path}' already exists"
-
end
-
::File.open(dest_path, 'wb') do |os|
-
get_input_stream do |is|
-
set_extra_attributes_on_path(dest_path)
-
-
buf = ''
-
while (buf = is.sysread(::Zip::Decompressor::CHUNK_SIZE, buf))
-
os << buf
-
end
-
end
-
end
-
end
-
-
2
def create_directory(dest_path)
-
return if ::File.directory?(dest_path)
-
if ::File.exist?(dest_path)
-
if block_given? && yield(self, dest_path)
-
::FileUtils.rm_f dest_path
-
else
-
raise ::Zip::DestinationFileExistsError,
-
"Cannot create directory '#{dest_path}'. " \
-
'A file already exists with that name'
-
end
-
end
-
::FileUtils.mkdir_p(dest_path)
-
set_extra_attributes_on_path(dest_path)
-
end
-
-
# BUG: create_symlink() does not use &block
-
2
def create_symlink(dest_path)
-
stat = nil
-
begin
-
stat = ::File.lstat(dest_path)
-
rescue Errno::ENOENT
-
end
-
-
io = get_input_stream
-
linkto = io.read
-
-
if stat
-
if stat.symlink?
-
if ::File.readlink(dest_path) == linkto
-
return
-
else
-
raise ::Zip::DestinationFileExistsError,
-
"Cannot create symlink '#{dest_path}'. " \
-
'A symlink already exists with that name'
-
end
-
else
-
raise ::Zip::DestinationFileExistsError,
-
"Cannot create symlink '#{dest_path}'. " \
-
'A file already exists with that name'
-
end
-
end
-
-
::File.symlink(linkto, dest_path)
-
end
-
-
# apply missing data from the zip64 extra information field, if present
-
# (required when file sizes exceed 2**32, but can be used for all files)
-
2
def parse_zip64_extra(for_local_header) #:nodoc:all
-
return if @extra['Zip64'].nil?
-
if for_local_header
-
@size, @compressed_size = @extra['Zip64'].parse(@size, @compressed_size)
-
else
-
@size, @compressed_size, @local_header_offset = @extra['Zip64'].parse(@size, @compressed_size, @local_header_offset)
-
end
-
end
-
-
2
def data_descriptor_size
-
(@gp_flags & 0x0008) > 0 ? 16 : 0
-
end
-
-
# create a zip64 extra information field if we need one
-
2
def prep_zip64_extra(for_local_header) #:nodoc:all
-
return unless ::Zip.write_zip64_support
-
need_zip64 = @size >= 0xFFFFFFFF || @compressed_size >= 0xFFFFFFFF
-
need_zip64 ||= @local_header_offset >= 0xFFFFFFFF unless for_local_header
-
if need_zip64
-
@version_needed_to_extract = VERSION_NEEDED_TO_EXTRACT_ZIP64
-
@extra.delete('Zip64Placeholder')
-
zip64 = @extra.create('Zip64')
-
if for_local_header
-
# local header always includes size and compressed size
-
zip64.original_size = @size
-
zip64.compressed_size = @compressed_size
-
else
-
# central directory entry entries include whichever fields are necessary
-
zip64.original_size = @size if @size >= 0xFFFFFFFF
-
zip64.compressed_size = @compressed_size if @compressed_size >= 0xFFFFFFFF
-
zip64.relative_header_offset = @local_header_offset if @local_header_offset >= 0xFFFFFFFF
-
end
-
else
-
@extra.delete('Zip64')
-
-
# if this is a local header entry, create a placeholder
-
# so we have room to write a zip64 extra field afterward
-
# (we won't know if it's needed until the file data is written)
-
if for_local_header
-
@extra.create('Zip64Placeholder')
-
else
-
@extra.delete('Zip64Placeholder')
-
end
-
end
-
end
-
end
-
end
-
-
# Copyright (C) 2002, 2003 Thomas Sondergaard
-
# rubyzip is free software; you can redistribute it and/or
-
# modify it under the terms of the ruby license.
-
2
module Zip
-
2
class EntrySet #:nodoc:all
-
2
include Enumerable
-
2
attr_accessor :entry_set, :entry_order
-
-
2
def initialize(an_enumerable = [])
-
super()
-
@entry_set = {}
-
an_enumerable.each { |o| push(o) }
-
end
-
-
2
def include?(entry)
-
@entry_set.include?(to_key(entry))
-
end
-
-
2
def find_entry(entry)
-
@entry_set[to_key(entry)]
-
end
-
-
2
def <<(entry)
-
@entry_set[to_key(entry)] = entry if entry
-
end
-
-
2
alias push <<
-
-
2
def size
-
@entry_set.size
-
end
-
-
2
alias length size
-
-
2
def delete(entry)
-
entry if @entry_set.delete(to_key(entry))
-
end
-
-
2
def each(&block)
-
@entry_set = sorted_entries.dup.each do |_, value|
-
block.call(value)
-
end
-
end
-
-
2
def entries
-
sorted_entries.values
-
end
-
-
# deep clone
-
2
def dup
-
EntrySet.new(@entry_set.values.map(&:dup))
-
end
-
-
2
def ==(other)
-
return false unless other.kind_of?(EntrySet)
-
@entry_set.values == other.entry_set.values
-
end
-
-
2
def parent(entry)
-
@entry_set[to_key(entry.parent_as_string)]
-
end
-
-
2
def glob(pattern, flags = ::File::FNM_PATHNAME | ::File::FNM_DOTMATCH)
-
entries.map do |entry|
-
next nil unless ::File.fnmatch(pattern, entry.name.chomp('/'), flags)
-
yield(entry) if block_given?
-
entry
-
end.compact
-
end
-
-
2
protected
-
-
2
def sorted_entries
-
::Zip.sort_entries ? Hash[@entry_set.sort] : @entry_set
-
end
-
-
2
private
-
-
2
def to_key(entry)
-
k = entry.to_s.chomp('/')
-
k.downcase! if ::Zip.case_insensitive_match
-
k
-
end
-
end
-
end
-
-
# Copyright (C) 2002, 2003 Thomas Sondergaard
-
# rubyzip is free software; you can redistribute it and/or
-
# modify it under the terms of the ruby license.
-
2
module Zip
-
2
class Error < StandardError; end
-
2
class EntryExistsError < Error; end
-
2
class DestinationFileExistsError < Error; end
-
2
class CompressionMethodError < Error; end
-
2
class EntryNameError < Error; end
-
2
class InternalError < Error; end
-
2
class GPFBit3Error < Error; end
-
-
# Backwards compatibility with v1 (delete in v2)
-
2
ZipError = Error
-
2
ZipEntryExistsError = EntryExistsError
-
2
ZipDestinationFileExistsError = DestinationFileExistsError
-
2
ZipCompressionMethodError = CompressionMethodError
-
2
ZipEntryNameError = EntryNameError
-
2
ZipInternalError = InternalError
-
end
-
2
module Zip
-
2
class ExtraField < Hash
-
2
ID_MAP = {}
-
-
2
def initialize(binstr = nil)
-
merge(binstr) if binstr
-
end
-
-
2
def extra_field_type_exist(binstr, id, len, i)
-
field_name = ID_MAP[id].name
-
if self.member?(field_name)
-
self[field_name].merge(binstr[i, len + 4])
-
else
-
field_obj = ID_MAP[id].new(binstr[i, len + 4])
-
self[field_name] = field_obj
-
end
-
end
-
-
2
def extra_field_type_unknown(binstr, len, i)
-
create_unknown_item unless self['Unknown']
-
if !len || len + 4 > binstr[i..-1].bytesize
-
self['Unknown'] << binstr[i..-1]
-
return
-
end
-
self['Unknown'] << binstr[i, len + 4]
-
end
-
-
2
def create_unknown_item
-
s = ''
-
class << s
-
alias_method :to_c_dir_bin, :to_s
-
alias_method :to_local_bin, :to_s
-
end
-
self['Unknown'] = s
-
end
-
-
2
def merge(binstr)
-
return if binstr.empty?
-
i = 0
-
while i < binstr.bytesize
-
id = binstr[i, 2]
-
len = binstr[i + 2, 2].to_s.unpack('v').first
-
if id && ID_MAP.member?(id)
-
extra_field_type_exist(binstr, id, len, i)
-
elsif id
-
create_unknown_item unless self['Unknown']
-
break unless extra_field_type_unknown(binstr, len, i)
-
end
-
i += len + 4
-
end
-
end
-
-
2
def create(name)
-
unless (field_class = ID_MAP.values.find { |k| k.name == name })
-
raise Error, "Unknown extra field '#{name}'"
-
end
-
self[name] = field_class.new
-
end
-
-
# place Unknown last, so "extra" data that is missing the proper signature/size
-
# does not prevent known fields from being read back in
-
2
def ordered_values
-
result = []
-
each { |k, v| k == 'Unknown' ? result.push(v) : result.unshift(v) }
-
result
-
end
-
-
2
def to_local_bin
-
ordered_values.map! { |v| v.to_local_bin.force_encoding('BINARY') }.join
-
end
-
-
2
alias to_s to_local_bin
-
-
2
def to_c_dir_bin
-
ordered_values.map! { |v| v.to_c_dir_bin.force_encoding('BINARY') }.join
-
end
-
-
2
def c_dir_size
-
to_c_dir_bin.bytesize
-
end
-
-
2
def local_size
-
to_local_bin.bytesize
-
end
-
-
2
alias length local_size
-
2
alias size local_size
-
end
-
end
-
-
2
require 'zip/extra_field/generic'
-
2
require 'zip/extra_field/universal_time'
-
2
require 'zip/extra_field/old_unix'
-
2
require 'zip/extra_field/unix'
-
2
require 'zip/extra_field/zip64'
-
2
require 'zip/extra_field/zip64_placeholder'
-
2
require 'zip/extra_field/ntfs'
-
-
# Copyright (C) 2002, 2003 Thomas Sondergaard
-
# rubyzip is free software; you can redistribute it and/or
-
# modify it under the terms of the ruby license.
-
2
module Zip
-
2
class ExtraField::Generic
-
2
def self.register_map
-
12
if self.const_defined?(:HEADER_ID)
-
12
::Zip::ExtraField::ID_MAP[const_get(:HEADER_ID)] = self
-
end
-
end
-
-
2
def self.name
-
@name ||= to_s.split('::')[-1]
-
end
-
-
# return field [size, content] or false
-
2
def initial_parse(binstr)
-
if !binstr
-
# If nil, start with empty.
-
return false
-
elsif binstr[0, 2] != self.class.const_get(:HEADER_ID)
-
$stderr.puts 'Warning: weired extra feild header ID. skip parsing'
-
return false
-
end
-
[binstr[2, 2].unpack('v')[0], binstr[4..-1]]
-
end
-
-
2
def ==(other)
-
return false if self.class != other.class
-
each do |k, v|
-
return false if v != other[k]
-
end
-
true
-
end
-
-
2
def to_local_bin
-
s = pack_for_local
-
self.class.const_get(:HEADER_ID) + [s.bytesize].pack('v') << s
-
end
-
-
2
def to_c_dir_bin
-
s = pack_for_c_dir
-
self.class.const_get(:HEADER_ID) + [s.bytesize].pack('v') << s
-
end
-
end
-
end
-
2
module Zip
-
# PKWARE NTFS Extra Field (0x000a)
-
# Only Tag 0x0001 is supported
-
2
class ExtraField::NTFS < ExtraField::Generic
-
2
HEADER_ID = [0x000A].pack('v')
-
2
register_map
-
-
2
WINDOWS_TICK = 10_000_000.0
-
2
SEC_TO_UNIX_EPOCH = 11_644_473_600
-
-
2
def initialize(binstr = nil)
-
@ctime = nil
-
@mtime = nil
-
@atime = nil
-
binstr && merge(binstr)
-
end
-
-
2
attr_accessor :atime, :ctime, :mtime
-
-
2
def merge(binstr)
-
return if binstr.empty?
-
size, content = initial_parse(binstr)
-
(size && content) || return
-
-
content = content[4..-1]
-
tags = parse_tags(content)
-
-
tag1 = tags[1]
-
return unless tag1
-
ntfs_mtime, ntfs_atime, ntfs_ctime = tag1.unpack('Q<Q<Q<')
-
ntfs_mtime && @mtime ||= from_ntfs_time(ntfs_mtime)
-
ntfs_atime && @atime ||= from_ntfs_time(ntfs_atime)
-
ntfs_ctime && @ctime ||= from_ntfs_time(ntfs_ctime)
-
end
-
-
2
def ==(other)
-
@mtime == other.mtime &&
-
@atime == other.atime &&
-
@ctime == other.ctime
-
end
-
-
# Info-ZIP note states this extra field is stored at local header
-
2
def pack_for_local
-
pack_for_c_dir
-
end
-
-
# But 7-zip for Windows only stores at central dir
-
2
def pack_for_c_dir
-
# reserved 0 and tag 1
-
s = [0, 1].pack('Vv')
-
-
tag1 = ''.force_encoding(Encoding::BINARY)
-
if @mtime
-
tag1 << [to_ntfs_time(@mtime)].pack('Q<')
-
if @atime
-
tag1 << [to_ntfs_time(@atime)].pack('Q<')
-
tag1 << [to_ntfs_time(@ctime)].pack('Q<') if @ctime
-
end
-
end
-
s << [tag1.bytesize].pack('v') << tag1
-
s
-
end
-
-
2
private
-
-
2
def parse_tags(content)
-
return {} if content.nil?
-
tags = {}
-
i = 0
-
while i < content.bytesize
-
tag, size = content[i, 4].unpack('vv')
-
i += 4
-
break unless tag && size
-
value = content[i, size]
-
i += size
-
tags[tag] = value
-
end
-
-
tags
-
end
-
-
2
def from_ntfs_time(ntfs_time)
-
::Zip::DOSTime.at(ntfs_time / WINDOWS_TICK - SEC_TO_UNIX_EPOCH)
-
end
-
-
2
def to_ntfs_time(time)
-
((time.to_f + SEC_TO_UNIX_EPOCH) * WINDOWS_TICK).to_i
-
end
-
end
-
end
-
2
module Zip
-
# Olf Info-ZIP Extra for UNIX uid/gid and file timestampes
-
2
class ExtraField::OldUnix < ExtraField::Generic
-
2
HEADER_ID = 'UX'
-
2
register_map
-
-
2
def initialize(binstr = nil)
-
@uid = 0
-
@gid = 0
-
@atime = nil
-
@mtime = nil
-
binstr && merge(binstr)
-
end
-
-
2
attr_accessor :uid, :gid, :atime, :mtime
-
-
2
def merge(binstr)
-
return if binstr.empty?
-
size, content = initial_parse(binstr)
-
# size: 0 for central directory. 4 for local header
-
return if !size || size == 0
-
atime, mtime, uid, gid = content.unpack('VVvv')
-
@uid ||= uid
-
@gid ||= gid
-
@atime ||= atime
-
@mtime ||= mtime
-
end
-
-
2
def ==(other)
-
@uid == other.uid &&
-
@gid == other.gid &&
-
@atime == other.atime &&
-
@mtime == other.mtime
-
end
-
-
2
def pack_for_local
-
[@atime, @mtime, @uid, @gid].pack('VVvv')
-
end
-
-
2
def pack_for_c_dir
-
[@atime, @mtime].pack('VV')
-
end
-
end
-
end
-
2
module Zip
-
# Info-ZIP Additional timestamp field
-
2
class ExtraField::UniversalTime < ExtraField::Generic
-
2
HEADER_ID = 'UT'
-
2
register_map
-
-
2
def initialize(binstr = nil)
-
@ctime = nil
-
@mtime = nil
-
@atime = nil
-
@flag = nil
-
binstr && merge(binstr)
-
end
-
-
2
attr_accessor :atime, :ctime, :mtime, :flag
-
-
2
def merge(binstr)
-
return if binstr.empty?
-
size, content = initial_parse(binstr)
-
size || return
-
@flag, mtime, atime, ctime = content.unpack('CVVV')
-
mtime && @mtime ||= ::Zip::DOSTime.at(mtime)
-
atime && @atime ||= ::Zip::DOSTime.at(atime)
-
ctime && @ctime ||= ::Zip::DOSTime.at(ctime)
-
end
-
-
2
def ==(other)
-
@mtime == other.mtime &&
-
@atime == other.atime &&
-
@ctime == other.ctime
-
end
-
-
2
def pack_for_local
-
s = [@flag].pack('C')
-
@flag & 1 != 0 && s << [@mtime.to_i].pack('V')
-
@flag & 2 != 0 && s << [@atime.to_i].pack('V')
-
@flag & 4 != 0 && s << [@ctime.to_i].pack('V')
-
s
-
end
-
-
2
def pack_for_c_dir
-
s = [@flag].pack('C')
-
@flag & 1 == 1 && s << [@mtime.to_i].pack('V')
-
s
-
end
-
end
-
end
-
2
module Zip
-
# Info-ZIP Extra for UNIX uid/gid
-
2
class ExtraField::IUnix < ExtraField::Generic
-
2
HEADER_ID = 'Ux'
-
2
register_map
-
-
2
def initialize(binstr = nil)
-
@uid = 0
-
@gid = 0
-
binstr && merge(binstr)
-
end
-
-
2
attr_accessor :uid, :gid
-
-
2
def merge(binstr)
-
return if binstr.empty?
-
size, content = initial_parse(binstr)
-
# size: 0 for central directory. 4 for local header
-
return if !size || size == 0
-
uid, gid = content.unpack('vv')
-
@uid ||= uid
-
@gid ||= gid
-
end
-
-
2
def ==(other)
-
@uid == other.uid && @gid == other.gid
-
end
-
-
2
def pack_for_local
-
[@uid, @gid].pack('vv')
-
end
-
-
2
def pack_for_c_dir
-
''
-
end
-
end
-
end
-
2
module Zip
-
# Info-ZIP Extra for Zip64 size
-
2
class ExtraField::Zip64 < ExtraField::Generic
-
2
attr_accessor :original_size, :compressed_size, :relative_header_offset, :disk_start_number
-
2
HEADER_ID = ['0100'].pack('H*')
-
2
register_map
-
-
2
def initialize(binstr = nil)
-
# unparsed binary; we don't actually know what this contains
-
# without looking for FFs in the associated file header
-
# call parse after initializing with a binary string
-
@content = nil
-
@original_size = nil
-
@compressed_size = nil
-
@relative_header_offset = nil
-
@disk_start_number = nil
-
binstr && merge(binstr)
-
end
-
-
2
def ==(other)
-
other.original_size == @original_size &&
-
other.compressed_size == @compressed_size &&
-
other.relative_header_offset == @relative_header_offset &&
-
other.disk_start_number == @disk_start_number
-
end
-
-
2
def merge(binstr)
-
return if binstr.empty?
-
_, @content = initial_parse(binstr)
-
end
-
-
# pass the values from the base entry (if applicable)
-
# wider values are only present in the extra field for base values set to all FFs
-
# returns the final values for the four attributes (from the base or zip64 extra record)
-
2
def parse(original_size, compressed_size, relative_header_offset = nil, disk_start_number = nil)
-
@original_size = extract(8, 'Q<') if original_size == 0xFFFFFFFF
-
@compressed_size = extract(8, 'Q<') if compressed_size == 0xFFFFFFFF
-
@relative_header_offset = extract(8, 'Q<') if relative_header_offset && relative_header_offset == 0xFFFFFFFF
-
@disk_start_number = extract(4, 'V') if disk_start_number && disk_start_number == 0xFFFF
-
@content = nil
-
[@original_size || original_size,
-
@compressed_size || compressed_size,
-
@relative_header_offset || relative_header_offset,
-
@disk_start_number || disk_start_number]
-
end
-
-
2
def extract(size, format)
-
@content.slice!(0, size).unpack(format)[0]
-
end
-
2
private :extract
-
-
2
def pack_for_local
-
# local header entries must contain original size and compressed size; other fields do not apply
-
return '' unless @original_size && @compressed_size
-
[@original_size, @compressed_size].pack('Q<Q<')
-
end
-
-
2
def pack_for_c_dir
-
# central directory entries contain only fields that didn't fit in the main entry part
-
packed = ''.force_encoding('BINARY')
-
packed << [@original_size].pack('Q<') if @original_size
-
packed << [@compressed_size].pack('Q<') if @compressed_size
-
packed << [@relative_header_offset].pack('Q<') if @relative_header_offset
-
packed << [@disk_start_number].pack('V') if @disk_start_number
-
packed
-
end
-
end
-
end
-
2
module Zip
-
# placeholder to reserve space for a Zip64 extra information record, for the
-
# local file header only, that we won't know if we'll need until after
-
# we write the file data
-
2
class ExtraField::Zip64Placeholder < ExtraField::Generic
-
2
HEADER_ID = ['9999'].pack('H*') # this ID is used by other libraries such as .NET's Ionic.zip
-
2
register_map
-
-
2
def initialize(_binstr = nil)
-
end
-
-
2
def pack_for_local
-
"\x00" * 16
-
end
-
end
-
end
-
2
module Zip
-
# ZipFile is modeled after java.util.zip.ZipFile from the Java SDK.
-
# The most important methods are those inherited from
-
# ZipCentralDirectory for accessing information about the entries in
-
# the archive and methods such as get_input_stream and
-
# get_output_stream for reading from and writing entries to the
-
# archive. The class includes a few convenience methods such as
-
# #extract for extracting entries to the filesystem, and #remove,
-
# #replace, #rename and #mkdir for making simple modifications to
-
# the archive.
-
#
-
# Modifications to a zip archive are not committed until #commit or
-
# #close is called. The method #open accepts a block following
-
# the pattern from File.open offering a simple way to
-
# automatically close the archive when the block returns.
-
#
-
# The following example opens zip archive <code>my.zip</code>
-
# (creating it if it doesn't exist) and adds an entry
-
# <code>first.txt</code> and a directory entry <code>a_dir</code>
-
# to it.
-
#
-
# require 'zip'
-
#
-
# Zip::File.open("my.zip", Zip::File::CREATE) {
-
# |zipfile|
-
# zipfile.get_output_stream("first.txt") { |f| f.puts "Hello from ZipFile" }
-
# zipfile.mkdir("a_dir")
-
# }
-
#
-
# The next example reopens <code>my.zip</code> writes the contents of
-
# <code>first.txt</code> to standard out and deletes the entry from
-
# the archive.
-
#
-
# require 'zip'
-
#
-
# Zip::File.open("my.zip", Zip::File::CREATE) {
-
# |zipfile|
-
# puts zipfile.read("first.txt")
-
# zipfile.remove("first.txt")
-
# }
-
#
-
# ZipFileSystem offers an alternative API that emulates ruby's
-
# interface for accessing the filesystem, ie. the File and Dir classes.
-
-
2
class File < CentralDirectory
-
2
CREATE = 1
-
2
SPLIT_SIGNATURE = 0x08074b50
-
2
ZIP64_EOCD_SIGNATURE = 0x06064b50
-
2
MAX_SEGMENT_SIZE = 3_221_225_472
-
2
MIN_SEGMENT_SIZE = 65_536
-
2
DATA_BUFFER_SIZE = 8192
-
2
IO_METHODS = [:tell, :seek, :read, :close]
-
-
2
attr_reader :name
-
-
# default -> false
-
2
attr_accessor :restore_ownership
-
# default -> false
-
2
attr_accessor :restore_permissions
-
# default -> true
-
2
attr_accessor :restore_times
-
# Returns the zip files comment, if it has one
-
2
attr_accessor :comment
-
-
# Opens a zip archive. Pass true as the second parameter to create
-
# a new archive if it doesn't exist already.
-
2
def initialize(file_name, create = nil, buffer = false, options = {})
-
super()
-
@name = file_name
-
@comment = ''
-
@create = create
-
case
-
when !buffer && ::File.size?(file_name)
-
@create = nil
-
@file_permissions = ::File.stat(file_name).mode
-
::File.open(name, 'rb') do |f|
-
read_from_stream(f)
-
end
-
when create
-
@file_permissions = create_file_permissions
-
@entry_set = EntrySet.new
-
when ::File.zero?(file_name)
-
raise Error, "File #{file_name} has zero size. Did you mean to pass the create flag?"
-
else
-
raise Error, "File #{file_name} not found"
-
end
-
@stored_entries = @entry_set.dup
-
@stored_comment = @comment
-
@restore_ownership = options[:restore_ownership] || false
-
@restore_permissions = options[:restore_permissions] || true
-
@restore_times = options[:restore_times] || true
-
end
-
-
2
class << self
-
# Same as #new. If a block is passed the ZipFile object is passed
-
# to the block and is automatically closed afterwards just as with
-
# ruby's builtin File.open method.
-
2
def open(file_name, create = nil)
-
zf = ::Zip::File.new(file_name, create)
-
return zf unless block_given?
-
begin
-
yield zf
-
ensure
-
zf.close
-
end
-
end
-
-
# Same as #open. But outputs data to a buffer instead of a file
-
2
def add_buffer
-
io = ::StringIO.new('')
-
zf = ::Zip::File.new(io, true, true)
-
yield zf
-
zf.write_buffer(io)
-
end
-
-
# Like #open, but reads zip archive contents from a String or open IO
-
# stream, and outputs data to a buffer.
-
# (This can be used to extract data from a
-
# downloaded zip archive without first saving it to disk.)
-
2
def open_buffer(io, options = {})
-
unless IO_METHODS.map { |method| io.respond_to?(method) }.all? || io.is_a?(String)
-
raise "Zip::File.open_buffer expects a String or IO-like argument (responds to #{IO_METHODS.join(', ')}). Found: #{io.class}"
-
end
-
if io.is_a?(::String)
-
require 'stringio'
-
io = ::StringIO.new(io)
-
elsif io.respond_to?(:binmode)
-
# https://github.com/rubyzip/rubyzip/issues/119
-
io.binmode
-
end
-
zf = ::Zip::File.new(io, true, true, options)
-
zf.read_from_stream(io)
-
yield zf
-
begin
-
zf.write_buffer(io)
-
rescue IOError => e
-
raise unless e.message == 'not opened for writing'
-
end
-
end
-
-
# Iterates over the contents of the ZipFile. This is more efficient
-
# than using a ZipInputStream since this methods simply iterates
-
# through the entries in the central directory structure in the archive
-
# whereas ZipInputStream jumps through the entire archive accessing the
-
# local entry headers (which contain the same information as the
-
# central directory).
-
2
def foreach(aZipFileName, &block)
-
open(aZipFileName) do |zipFile|
-
zipFile.each(&block)
-
end
-
end
-
-
2
def get_segment_size_for_split(segment_size)
-
case
-
when MIN_SEGMENT_SIZE > segment_size
-
MIN_SEGMENT_SIZE
-
when MAX_SEGMENT_SIZE < segment_size
-
MAX_SEGMENT_SIZE
-
else
-
segment_size
-
end
-
end
-
-
2
def get_partial_zip_file_name(zip_file_name, partial_zip_file_name)
-
partial_zip_file_name = zip_file_name.sub(/#{::File.basename(zip_file_name)}\z/,
-
partial_zip_file_name + ::File.extname(zip_file_name)) unless partial_zip_file_name.nil?
-
partial_zip_file_name ||= zip_file_name
-
partial_zip_file_name
-
end
-
-
2
def get_segment_count_for_split(zip_file_size, segment_size)
-
(zip_file_size / segment_size).to_i + (zip_file_size % segment_size == 0 ? 0 : 1)
-
end
-
-
2
def put_split_signature(szip_file, segment_size)
-
signature_packed = [SPLIT_SIGNATURE].pack('V')
-
szip_file << signature_packed
-
segment_size - signature_packed.size
-
end
-
-
#
-
# TODO: Make the code more understandable
-
#
-
2
def save_splited_part(zip_file, partial_zip_file_name, zip_file_size, szip_file_index, segment_size, segment_count)
-
ssegment_size = zip_file_size - zip_file.pos
-
ssegment_size = segment_size if ssegment_size > segment_size
-
szip_file_name = "#{partial_zip_file_name}.#{format('%03d', szip_file_index)}"
-
::File.open(szip_file_name, 'wb') do |szip_file|
-
if szip_file_index == 1
-
ssegment_size = put_split_signature(szip_file, segment_size)
-
end
-
chunk_bytes = 0
-
until ssegment_size == chunk_bytes || zip_file.eof?
-
segment_bytes_left = ssegment_size - chunk_bytes
-
buffer_size = segment_bytes_left < DATA_BUFFER_SIZE ? segment_bytes_left : DATA_BUFFER_SIZE
-
chunk = zip_file.read(buffer_size)
-
chunk_bytes += buffer_size
-
szip_file << chunk
-
# Info for track splitting
-
yield segment_count, szip_file_index, chunk_bytes, ssegment_size if block_given?
-
end
-
end
-
end
-
-
# Splits an archive into parts with segment size
-
2
def split(zip_file_name, segment_size = MAX_SEGMENT_SIZE, delete_zip_file = true, partial_zip_file_name = nil)
-
raise Error, "File #{zip_file_name} not found" unless ::File.exist?(zip_file_name)
-
raise Errno::ENOENT, zip_file_name unless ::File.readable?(zip_file_name)
-
zip_file_size = ::File.size(zip_file_name)
-
segment_size = get_segment_size_for_split(segment_size)
-
return if zip_file_size <= segment_size
-
segment_count = get_segment_count_for_split(zip_file_size, segment_size)
-
# Checking for correct zip structure
-
open(zip_file_name) {}
-
partial_zip_file_name = get_partial_zip_file_name(zip_file_name, partial_zip_file_name)
-
szip_file_index = 0
-
::File.open(zip_file_name, 'rb') do |zip_file|
-
until zip_file.eof?
-
szip_file_index += 1
-
save_splited_part(zip_file, partial_zip_file_name, zip_file_size, szip_file_index, segment_size, segment_count)
-
end
-
end
-
::File.delete(zip_file_name) if delete_zip_file
-
szip_file_index
-
end
-
end
-
-
# Returns an input stream to the specified entry. If a block is passed
-
# the stream object is passed to the block and the stream is automatically
-
# closed afterwards just as with ruby's builtin File.open method.
-
2
def get_input_stream(entry, &aProc)
-
get_entry(entry).get_input_stream(&aProc)
-
end
-
-
# Returns an output stream to the specified entry. If entry is not an instance
-
# of Zip::Entry, a new Zip::Entry will be initialized using the arguments
-
# specified. If a block is passed the stream object is passed to the block and
-
# the stream is automatically closed afterwards just as with ruby's builtin
-
# File.open method.
-
2
def get_output_stream(entry, permission_int = nil, comment = nil, extra = nil, compressed_size = nil, crc = nil, compression_method = nil, size = nil, time = nil, &aProc)
-
new_entry =
-
if entry.kind_of?(Entry)
-
entry
-
else
-
Entry.new(@name, entry.to_s, comment, extra, compressed_size, crc, compression_method, size, time)
-
end
-
if new_entry.directory?
-
raise ArgumentError,
-
"cannot open stream to directory entry - '#{new_entry}'"
-
end
-
new_entry.unix_perms = permission_int
-
zip_streamable_entry = StreamableStream.new(new_entry)
-
@entry_set << zip_streamable_entry
-
zip_streamable_entry.get_output_stream(&aProc)
-
end
-
-
# Returns the name of the zip archive
-
2
def to_s
-
@name
-
end
-
-
# Returns a string containing the contents of the specified entry
-
2
def read(entry)
-
get_input_stream(entry) { |is| is.read }
-
end
-
-
# Convenience method for adding the contents of a file to the archive
-
2
def add(entry, src_path, &continue_on_exists_proc)
-
continue_on_exists_proc ||= proc { ::Zip.continue_on_exists_proc }
-
check_entry_exists(entry, continue_on_exists_proc, 'add')
-
new_entry = entry.kind_of?(::Zip::Entry) ? entry : ::Zip::Entry.new(@name, entry.to_s)
-
new_entry.gather_fileinfo_from_srcpath(src_path)
-
new_entry.dirty = true
-
@entry_set << new_entry
-
end
-
-
# Removes the specified entry.
-
2
def remove(entry)
-
@entry_set.delete(get_entry(entry))
-
end
-
-
# Renames the specified entry.
-
2
def rename(entry, new_name, &continue_on_exists_proc)
-
foundEntry = get_entry(entry)
-
check_entry_exists(new_name, continue_on_exists_proc, 'rename')
-
@entry_set.delete(foundEntry)
-
foundEntry.name = new_name
-
@entry_set << foundEntry
-
end
-
-
# Replaces the specified entry with the contents of srcPath (from
-
# the file system).
-
2
def replace(entry, srcPath)
-
check_file(srcPath)
-
remove(entry)
-
add(entry, srcPath)
-
end
-
-
# Extracts entry to file dest_path.
-
2
def extract(entry, dest_path, &block)
-
block ||= proc { ::Zip.on_exists_proc }
-
found_entry = get_entry(entry)
-
found_entry.extract(dest_path, &block)
-
end
-
-
# Commits changes that has been made since the previous commit to
-
# the zip archive.
-
2
def commit
-
return unless commit_required?
-
on_success_replace do |tmp_file|
-
::Zip::OutputStream.open(tmp_file) do |zos|
-
@entry_set.each do |e|
-
e.write_to_zip_output_stream(zos)
-
e.dirty = false
-
e.clean_up
-
end
-
zos.comment = comment
-
end
-
true
-
end
-
initialize(name)
-
end
-
-
# Write buffer write changes to buffer and return
-
2
def write_buffer(io = ::StringIO.new(''))
-
::Zip::OutputStream.write_buffer(io) do |zos|
-
@entry_set.each { |e| e.write_to_zip_output_stream(zos) }
-
zos.comment = comment
-
end
-
end
-
-
# Closes the zip file committing any changes that has been made.
-
2
def close
-
commit
-
end
-
-
# Returns true if any changes has been made to this archive since
-
# the previous commit
-
2
def commit_required?
-
@entry_set.each do |e|
-
return true if e.dirty
-
end
-
@comment != @stored_comment || @entry_set != @stored_entries || @create == ::Zip::File::CREATE
-
end
-
-
# Searches for entry with the specified name. Returns nil if
-
# no entry is found. See also get_entry
-
2
def find_entry(entry_name)
-
@entry_set.find_entry(entry_name)
-
end
-
-
# Searches for entries given a glob
-
2
def glob(*args, &block)
-
@entry_set.glob(*args, &block)
-
end
-
-
# Searches for an entry just as find_entry, but throws Errno::ENOENT
-
# if no entry is found.
-
2
def get_entry(entry)
-
selected_entry = find_entry(entry)
-
raise Errno::ENOENT, entry unless selected_entry
-
selected_entry.restore_ownership = @restore_ownership
-
selected_entry.restore_permissions = @restore_permissions
-
selected_entry.restore_times = @restore_times
-
selected_entry
-
end
-
-
# Creates a directory
-
2
def mkdir(entryName, permissionInt = 0755)
-
raise Errno::EEXIST, "File exists - #{entryName}" if find_entry(entryName)
-
entryName = entryName.dup.to_s
-
entryName << '/' unless entryName.end_with?('/')
-
@entry_set << ::Zip::StreamableDirectory.new(@name, entryName, nil, permissionInt)
-
end
-
-
2
private
-
-
2
def directory?(newEntry, srcPath)
-
srcPathIsDirectory = ::File.directory?(srcPath)
-
if newEntry.directory? && !srcPathIsDirectory
-
raise ArgumentError,
-
"entry name '#{newEntry}' indicates directory entry, but " \
-
"'#{srcPath}' is not a directory"
-
elsif !newEntry.directory? && srcPathIsDirectory
-
newEntry.name += '/'
-
end
-
newEntry.directory? && srcPathIsDirectory
-
end
-
-
2
def check_entry_exists(entryName, continue_on_exists_proc, procedureName)
-
continue_on_exists_proc ||= proc { Zip.continue_on_exists_proc }
-
return unless @entry_set.include?(entryName)
-
if continue_on_exists_proc.call
-
remove get_entry(entryName)
-
else
-
raise ::Zip::EntryExistsError,
-
procedureName + " failed. Entry #{entryName} already exists"
-
end
-
end
-
-
2
def check_file(path)
-
raise Errno::ENOENT, path unless ::File.readable?(path)
-
end
-
-
2
def on_success_replace
-
tmp_filename = create_tmpname
-
if yield tmp_filename
-
::File.rename(tmp_filename, name)
-
::File.chmod(@file_permissions, name) if defined?(@file_permissions)
-
end
-
ensure
-
::File.unlink(tmp_filename) if ::File.exist?(tmp_filename)
-
end
-
-
2
def create_tmpname
-
dirname, basename = ::File.split(name)
-
::Dir::Tmpname.create(basename, dirname) do |tmpname|
-
opts = {perm: 0600, mode: ::File::CREAT | ::File::WRONLY | ::File::EXCL}
-
f = File.open(tmpname, opts)
-
f.close
-
end
-
end
-
-
2
def create_file_permissions
-
::Zip::RUNNING_ON_WINDOWS ? 0644 : 0666 - ::File.umask
-
end
-
end
-
end
-
-
# Copyright (C) 2002, 2003 Thomas Sondergaard
-
# rubyzip is free software; you can redistribute it and/or
-
# modify it under the terms of the ruby license.
-
2
module Zip
-
2
class Inflater < Decompressor #:nodoc:all
-
2
def initialize(input_stream, decrypter = NullDecrypter.new)
-
super(input_stream)
-
@zlib_inflater = ::Zlib::Inflate.new(-Zlib::MAX_WBITS)
-
@output_buffer = ''
-
@has_returned_empty_string = false
-
@decrypter = decrypter
-
end
-
-
2
def sysread(number_of_bytes = nil, buf = '')
-
readEverything = number_of_bytes.nil?
-
while readEverything || @output_buffer.bytesize < number_of_bytes
-
break if internal_input_finished?
-
@output_buffer << internal_produce_input(buf)
-
end
-
return value_when_finished if @output_buffer.bytesize == 0 && input_finished?
-
end_index = number_of_bytes.nil? ? @output_buffer.bytesize : number_of_bytes
-
@output_buffer.slice!(0...end_index)
-
end
-
-
2
def produce_input
-
if @output_buffer.empty?
-
internal_produce_input
-
else
-
@output_buffer.slice!(0...(@output_buffer.length))
-
end
-
end
-
-
# to be used with produce_input, not read (as read may still have more data cached)
-
# is data cached anywhere other than @outputBuffer? the comment above may be wrong
-
2
def input_finished?
-
@output_buffer.empty? && internal_input_finished?
-
end
-
-
2
alias :eof input_finished?
-
2
alias :eof? input_finished?
-
-
2
private
-
-
2
def internal_produce_input(buf = '')
-
retried = 0
-
begin
-
@zlib_inflater.inflate(@decrypter.decrypt(@input_stream.read(Decompressor::CHUNK_SIZE, buf)))
-
rescue Zlib::BufError
-
raise if retried >= 5 # how many times should we retry?
-
retried += 1
-
retry
-
end
-
end
-
-
2
def internal_input_finished?
-
@zlib_inflater.finished?
-
end
-
-
2
def value_when_finished # mimic behaviour of ruby File object.
-
return if @has_returned_empty_string
-
@has_returned_empty_string = true
-
''
-
end
-
end
-
end
-
-
# Copyright (C) 2002, 2003 Thomas Sondergaard
-
# rubyzip is free software; you can redistribute it and/or
-
# modify it under the terms of the ruby license.
-
2
module Zip
-
# InputStream is the basic class for reading zip entries in a
-
# zip file. It is possible to create a InputStream object directly,
-
# passing the zip file name to the constructor, but more often than not
-
# the InputStream will be obtained from a File (perhaps using the
-
# ZipFileSystem interface) object for a particular entry in the zip
-
# archive.
-
#
-
# A InputStream inherits IOExtras::AbstractInputStream in order
-
# to provide an IO-like interface for reading from a single zip
-
# entry. Beyond methods for mimicking an IO-object it contains
-
# the method get_next_entry for iterating through the entries of
-
# an archive. get_next_entry returns a Entry object that describes
-
# the zip entry the InputStream is currently reading from.
-
#
-
# Example that creates a zip archive with ZipOutputStream and reads it
-
# back again with a InputStream.
-
#
-
# require 'zip'
-
#
-
# Zip::OutputStream.open("my.zip") do |io|
-
#
-
# io.put_next_entry("first_entry.txt")
-
# io.write "Hello world!"
-
#
-
# io.put_next_entry("adir/first_entry.txt")
-
# io.write "Hello again!"
-
# end
-
#
-
#
-
# Zip::InputStream.open("my.zip") do |io|
-
#
-
# while (entry = io.get_next_entry)
-
# puts "Contents of #{entry.name}: '#{io.read}'"
-
# end
-
# end
-
#
-
# java.util.zip.ZipInputStream is the original inspiration for this
-
# class.
-
-
2
class InputStream
-
2
include ::Zip::IOExtras::AbstractInputStream
-
-
# Opens the indicated zip file. An exception is thrown
-
# if the specified offset in the specified filename is
-
# not a local zip entry header.
-
#
-
# @param context [String||IO||StringIO] file path or IO/StringIO object
-
# @param offset [Integer] offset in the IO/StringIO
-
2
def initialize(context, offset = 0, decrypter = nil)
-
super()
-
@archive_io = get_io(context, offset)
-
@decompressor = ::Zip::NullDecompressor
-
@decrypter = decrypter || ::Zip::NullDecrypter.new
-
@current_entry = nil
-
end
-
-
2
def close
-
@archive_io.close
-
end
-
-
# Returns a Entry object. It is necessary to call this
-
# method on a newly created InputStream before reading from
-
# the first entry in the archive. Returns nil when there are
-
# no more entries.
-
2
def get_next_entry
-
@archive_io.seek(@current_entry.next_header_offset, IO::SEEK_SET) if @current_entry
-
open_entry
-
end
-
-
# Rewinds the stream to the beginning of the current entry
-
2
def rewind
-
return if @current_entry.nil?
-
@lineno = 0
-
@pos = 0
-
@archive_io.seek(@current_entry.local_header_offset, IO::SEEK_SET)
-
open_entry
-
end
-
-
# Modeled after IO.sysread
-
2
def sysread(number_of_bytes = nil, buf = nil)
-
@decompressor.sysread(number_of_bytes, buf)
-
end
-
-
2
def eof
-
@output_buffer.empty? && @decompressor.eof
-
end
-
-
2
alias :eof? eof
-
-
2
class << self
-
# Same as #initialize but if a block is passed the opened
-
# stream is passed to the block and closed when the block
-
# returns.
-
2
def open(filename_or_io, offset = 0, decrypter = nil)
-
zio = new(filename_or_io, offset, decrypter)
-
return zio unless block_given?
-
begin
-
yield zio
-
ensure
-
zio.close if zio
-
end
-
end
-
-
2
def open_buffer(filename_or_io, offset = 0)
-
puts 'open_buffer is deprecated!!! Use open instead!'
-
open(filename_or_io, offset)
-
end
-
end
-
-
2
protected
-
-
2
def get_io(io_or_file, offset = 0)
-
if io_or_file.respond_to?(:seek)
-
io = io_or_file.dup
-
io.seek(offset, ::IO::SEEK_SET)
-
io
-
else
-
file = ::File.open(io_or_file, 'rb')
-
file.seek(offset, ::IO::SEEK_SET)
-
file
-
end
-
end
-
-
2
def open_entry
-
@current_entry = ::Zip::Entry.read_local_entry(@archive_io)
-
if @current_entry && @current_entry.gp_flags & 1 == 1 && @decrypter.is_a?(NullEncrypter)
-
raise Error, 'password required to decode zip file'
-
end
-
if @current_entry && @current_entry.gp_flags & 8 == 8 && @current_entry.crc == 0 \
-
&& @current_entry.compressed_size == 0 \
-
&& @current_entry.size == 0 && !@internal
-
raise GPFBit3Error,
-
'General purpose flag Bit 3 is set so not possible to get proper info from local header.' \
-
'Please use ::Zip::File instead of ::Zip::InputStream'
-
end
-
@decompressor = get_decompressor
-
flush
-
@current_entry
-
end
-
-
2
def get_decompressor
-
case
-
when @current_entry.nil?
-
::Zip::NullDecompressor
-
when @current_entry.compression_method == ::Zip::Entry::STORED
-
::Zip::PassThruDecompressor.new(@archive_io, @current_entry.size)
-
when @current_entry.compression_method == ::Zip::Entry::DEFLATED
-
header = @archive_io.read(@decrypter.header_bytesize)
-
@decrypter.reset!(header)
-
::Zip::Inflater.new(@archive_io, @decrypter)
-
else
-
raise ::Zip::CompressionMethodError,
-
"Unsupported compression method #{@current_entry.compression_method}"
-
end
-
end
-
-
2
def produce_input
-
@decompressor.produce_input
-
end
-
-
2
def input_finished?
-
@decompressor.input_finished?
-
end
-
end
-
end
-
-
# Copyright (C) 2002, 2003 Thomas Sondergaard
-
# rubyzip is free software; you can redistribute it and/or
-
# modify it under the terms of the ruby license.
-
2
module Zip
-
2
module IOExtras #:nodoc:
-
2
CHUNK_SIZE = 131_072
-
-
2
RANGE_ALL = 0..-1
-
-
2
class << self
-
2
def copy_stream(ostream, istream)
-
ostream.write(istream.read(CHUNK_SIZE, '')) until istream.eof?
-
end
-
-
2
def copy_stream_n(ostream, istream, nbytes)
-
toread = nbytes
-
while toread > 0 && !istream.eof?
-
tr = toread > CHUNK_SIZE ? CHUNK_SIZE : toread
-
ostream.write(istream.read(tr, ''))
-
toread -= tr
-
end
-
end
-
end
-
-
# Implements kind_of? in order to pretend to be an IO object
-
2
module FakeIO
-
2
def kind_of?(object)
-
object == IO || super
-
end
-
end
-
end # IOExtras namespace module
-
end
-
-
2
require 'zip/ioextras/abstract_input_stream'
-
2
require 'zip/ioextras/abstract_output_stream'
-
-
# Copyright (C) 2002-2004 Thomas Sondergaard
-
# rubyzip is free software; you can redistribute it and/or
-
# modify it under the terms of the ruby license.
-
2
module Zip
-
2
module IOExtras
-
# Implements many of the convenience methods of IO
-
# such as gets, getc, readline and readlines
-
# depends on: input_finished?, produce_input and read
-
2
module AbstractInputStream
-
2
include Enumerable
-
2
include FakeIO
-
-
2
def initialize
-
super
-
@lineno = 0
-
@pos = 0
-
@output_buffer = ''
-
end
-
-
2
attr_accessor :lineno
-
2
attr_reader :pos
-
-
2
def read(number_of_bytes = nil, buf = '')
-
tbuf = if @output_buffer.bytesize > 0
-
if number_of_bytes <= @output_buffer.bytesize
-
@output_buffer.slice!(0, number_of_bytes)
-
else
-
number_of_bytes -= @output_buffer.bytesize if number_of_bytes
-
rbuf = sysread(number_of_bytes, buf)
-
out = @output_buffer
-
out << rbuf if rbuf
-
@output_buffer = ''
-
out
-
end
-
else
-
sysread(number_of_bytes, buf)
-
end
-
-
if tbuf.nil? || tbuf.length == 0
-
return nil if number_of_bytes
-
return ''
-
end
-
-
@pos += tbuf.length
-
-
if buf
-
buf.replace(tbuf)
-
else
-
buf = tbuf
-
end
-
buf
-
end
-
-
2
def readlines(a_sep_string = $/)
-
ret_val = []
-
each_line(a_sep_string) { |line| ret_val << line }
-
ret_val
-
end
-
-
2
def gets(a_sep_string = $/, number_of_bytes = nil)
-
@lineno = @lineno.next
-
-
if number_of_bytes.respond_to?(:to_int)
-
number_of_bytes = number_of_bytes.to_int
-
a_sep_string = a_sep_string.to_str if a_sep_string
-
elsif a_sep_string.respond_to?(:to_int)
-
number_of_bytes = a_sep_string.to_int
-
a_sep_string = $/
-
else
-
number_of_bytes = nil
-
a_sep_string = a_sep_string.to_str if a_sep_string
-
end
-
-
return read(number_of_bytes) if a_sep_string.nil?
-
a_sep_string = "#{$/}#{$/}" if a_sep_string.empty?
-
-
buffer_index = 0
-
over_limit = (number_of_bytes && @output_buffer.bytesize >= number_of_bytes)
-
while (match_index = @output_buffer.index(a_sep_string, buffer_index)).nil? && !over_limit
-
buffer_index = [buffer_index, @output_buffer.bytesize - a_sep_string.bytesize].max
-
return @output_buffer.empty? ? nil : flush if input_finished?
-
@output_buffer << produce_input
-
over_limit = (number_of_bytes && @output_buffer.bytesize >= number_of_bytes)
-
end
-
sep_index = [match_index + a_sep_string.bytesize, number_of_bytes || @output_buffer.bytesize].min
-
@pos += sep_index
-
@output_buffer.slice!(0...sep_index)
-
end
-
-
2
def ungetc(byte)
-
@output_buffer = byte.chr + @output_buffer
-
end
-
-
2
def flush
-
ret_val = @output_buffer
-
@output_buffer = ''
-
ret_val
-
end
-
-
2
def readline(a_sep_string = $/)
-
ret_val = gets(a_sep_string)
-
raise EOFError unless ret_val
-
ret_val
-
end
-
-
2
def each_line(a_sep_string = $/)
-
yield readline(a_sep_string) while true
-
rescue EOFError
-
end
-
-
2
alias_method :each, :each_line
-
end
-
end
-
end
-
2
module Zip
-
2
module IOExtras
-
# Implements many of the output convenience methods of IO.
-
# relies on <<
-
2
module AbstractOutputStream
-
2
include FakeIO
-
-
2
def write(data)
-
self << data
-
data.to_s.bytesize
-
end
-
-
2
def print(*params)
-
self << params.join($,) << $\.to_s
-
end
-
-
2
def printf(a_format_string, *params)
-
self << sprintf(a_format_string, *params)
-
end
-
-
2
def putc(an_object)
-
self << case an_object
-
when Fixnum
-
an_object.chr
-
when String
-
an_object
-
else
-
raise TypeError, 'putc: Only Fixnum and String supported'
-
end
-
an_object
-
end
-
-
2
def puts(*params)
-
params << "\n" if params.empty?
-
params.flatten.each do |element|
-
val = element.to_s
-
self << val
-
self << "\n" unless val[-1, 1] == "\n"
-
end
-
end
-
end
-
end
-
end
-
2
module Zip
-
2
class NullCompressor < Compressor #:nodoc:all
-
2
include Singleton
-
-
2
def <<(_data)
-
raise IOError, 'closed stream'
-
end
-
-
2
attr_reader :size, :compressed_size
-
end
-
end
-
-
# Copyright (C) 2002, 2003 Thomas Sondergaard
-
# rubyzip is free software; you can redistribute it and/or
-
# modify it under the terms of the ruby license.
-
2
module Zip
-
2
module NullDecompressor #:nodoc:all
-
2
module_function
-
-
2
def sysread(_numberOfBytes = nil, _buf = nil)
-
nil
-
end
-
-
2
def produce_input
-
nil
-
end
-
-
2
def input_finished?
-
true
-
end
-
-
2
def eof
-
true
-
end
-
-
2
alias eof? eof
-
end
-
end
-
-
# Copyright (C) 2002, 2003 Thomas Sondergaard
-
# rubyzip is free software; you can redistribute it and/or
-
# modify it under the terms of the ruby license.
-
2
module Zip
-
2
module NullInputStream #:nodoc:all
-
2
include ::Zip::NullDecompressor
-
2
include ::Zip::IOExtras::AbstractInputStream
-
end
-
end
-
-
# Copyright (C) 2002, 2003 Thomas Sondergaard
-
# rubyzip is free software; you can redistribute it and/or
-
# modify it under the terms of the ruby license.
-
2
module Zip
-
# ZipOutputStream is the basic class for writing zip files. It is
-
# possible to create a ZipOutputStream object directly, passing
-
# the zip file name to the constructor, but more often than not
-
# the ZipOutputStream will be obtained from a ZipFile (perhaps using the
-
# ZipFileSystem interface) object for a particular entry in the zip
-
# archive.
-
#
-
# A ZipOutputStream inherits IOExtras::AbstractOutputStream in order
-
# to provide an IO-like interface for writing to a single zip
-
# entry. Beyond methods for mimicking an IO-object it contains
-
# the method put_next_entry that closes the current entry
-
# and creates a new.
-
#
-
# Please refer to ZipInputStream for example code.
-
#
-
# java.util.zip.ZipOutputStream is the original inspiration for this
-
# class.
-
-
2
class OutputStream
-
2
include ::Zip::IOExtras::AbstractOutputStream
-
-
2
attr_accessor :comment
-
-
# Opens the indicated zip file. If a file with that name already
-
# exists it will be overwritten.
-
2
def initialize(file_name, stream = false, encrypter = nil)
-
super()
-
@file_name = file_name
-
@output_stream = if stream
-
iostream = @file_name.dup
-
iostream.reopen(@file_name)
-
iostream.rewind
-
iostream
-
else
-
::File.new(@file_name, 'wb')
-
end
-
@entry_set = ::Zip::EntrySet.new
-
@compressor = ::Zip::NullCompressor.instance
-
@encrypter = encrypter || ::Zip::NullEncrypter.new
-
@closed = false
-
@current_entry = nil
-
@comment = nil
-
end
-
-
# Same as #initialize but if a block is passed the opened
-
# stream is passed to the block and closed when the block
-
# returns.
-
2
class << self
-
2
def open(file_name, encrypter = nil)
-
return new(file_name) unless block_given?
-
zos = new(file_name, false, encrypter)
-
yield zos
-
ensure
-
zos.close if zos
-
end
-
-
# Same as #open but writes to a filestream instead
-
2
def write_buffer(io = ::StringIO.new(''), encrypter = nil)
-
zos = new(io, true, encrypter)
-
yield zos
-
zos.close_buffer
-
end
-
end
-
-
# Closes the stream and writes the central directory to the zip file
-
2
def close
-
return if @closed
-
finalize_current_entry
-
update_local_headers
-
write_central_directory
-
@output_stream.close
-
@closed = true
-
end
-
-
# Closes the stream and writes the central directory to the zip file
-
2
def close_buffer
-
return @output_stream if @closed
-
finalize_current_entry
-
update_local_headers
-
write_central_directory
-
@closed = true
-
@output_stream
-
end
-
-
# Closes the current entry and opens a new for writing.
-
# +entry+ can be a ZipEntry object or a string.
-
2
def put_next_entry(entry_name, comment = nil, extra = nil, compression_method = Entry::DEFLATED, level = Zip.default_compression)
-
raise Error, 'zip stream is closed' if @closed
-
if entry_name.kind_of?(Entry)
-
new_entry = entry_name
-
else
-
new_entry = Entry.new(@file_name, entry_name.to_s)
-
end
-
new_entry.comment = comment unless comment.nil?
-
unless extra.nil?
-
new_entry.extra = extra.is_a?(ExtraField) ? extra : ExtraField.new(extra.to_s)
-
end
-
new_entry.compression_method = compression_method unless compression_method.nil?
-
init_next_entry(new_entry, level)
-
@current_entry = new_entry
-
end
-
-
2
def copy_raw_entry(entry)
-
entry = entry.dup
-
raise Error, 'zip stream is closed' if @closed
-
raise Error, 'entry is not a ZipEntry' unless entry.is_a?(Entry)
-
finalize_current_entry
-
@entry_set << entry
-
src_pos = entry.local_header_offset
-
entry.write_local_entry(@output_stream)
-
@compressor = NullCompressor.instance
-
entry.get_raw_input_stream do |is|
-
is.seek(src_pos, IO::SEEK_SET)
-
::Zip::Entry.read_local_entry(is)
-
IOExtras.copy_stream_n(@output_stream, is, entry.compressed_size)
-
end
-
@compressor = NullCompressor.instance
-
@current_entry = nil
-
end
-
-
2
private
-
-
2
def finalize_current_entry
-
return unless @current_entry
-
finish
-
@current_entry.compressed_size = @output_stream.tell - @current_entry.local_header_offset - @current_entry.calculate_local_header_size
-
@current_entry.size = @compressor.size
-
@current_entry.crc = @compressor.crc
-
@output_stream << @encrypter.data_descriptor(@current_entry.crc, @current_entry.compressed_size, @current_entry.size)
-
@current_entry.gp_flags |= @encrypter.gp_flags
-
@current_entry = nil
-
@compressor = ::Zip::NullCompressor.instance
-
end
-
-
2
def init_next_entry(entry, level = Zip.default_compression)
-
finalize_current_entry
-
@entry_set << entry
-
entry.write_local_entry(@output_stream)
-
@encrypter.reset!
-
@output_stream << @encrypter.header(entry.mtime)
-
@compressor = get_compressor(entry, level)
-
end
-
-
2
def get_compressor(entry, level)
-
case entry.compression_method
-
when Entry::DEFLATED then
-
::Zip::Deflater.new(@output_stream, level, @encrypter)
-
when Entry::STORED then
-
::Zip::PassThruCompressor.new(@output_stream)
-
else
-
raise ::Zip::CompressionMethodError,
-
"Invalid compression method: '#{entry.compression_method}'"
-
end
-
end
-
-
2
def update_local_headers
-
pos = @output_stream.pos
-
@entry_set.each do |entry|
-
@output_stream.pos = entry.local_header_offset
-
entry.write_local_entry(@output_stream, true)
-
end
-
@output_stream.pos = pos
-
end
-
-
2
def write_central_directory
-
cdir = CentralDirectory.new(@entry_set, @comment)
-
cdir.write_to_stream(@output_stream)
-
end
-
-
2
protected
-
-
2
def finish
-
@compressor.finish
-
end
-
-
2
public
-
-
# Modeled after IO.<<
-
2
def <<(data)
-
@compressor << data
-
self
-
end
-
end
-
end
-
-
# Copyright (C) 2002, 2003 Thomas Sondergaard
-
# rubyzip is free software; you can redistribute it and/or
-
# modify it under the terms of the ruby license.
-
2
module Zip
-
2
class PassThruCompressor < Compressor #:nodoc:all
-
2
def initialize(outputStream)
-
super()
-
@output_stream = outputStream
-
@crc = Zlib.crc32
-
@size = 0
-
end
-
-
2
def <<(data)
-
val = data.to_s
-
@crc = Zlib.crc32(val, @crc)
-
@size += val.bytesize
-
@output_stream << val
-
end
-
-
2
attr_reader :size, :crc
-
end
-
end
-
-
# Copyright (C) 2002, 2003 Thomas Sondergaard
-
# rubyzip is free software; you can redistribute it and/or
-
# modify it under the terms of the ruby license.
-
2
module Zip
-
2
class PassThruDecompressor < Decompressor #:nodoc:all
-
2
def initialize(input_stream, chars_to_read)
-
super(input_stream)
-
@chars_to_read = chars_to_read
-
@read_so_far = 0
-
@has_returned_empty_string = false
-
end
-
-
2
def sysread(number_of_bytes = nil, buf = '')
-
if input_finished?
-
has_returned_empty_string_val = @has_returned_empty_string
-
@has_returned_empty_string = true
-
return '' unless has_returned_empty_string_val
-
return
-
end
-
-
if number_of_bytes.nil? || @read_so_far + number_of_bytes > @chars_to_read
-
number_of_bytes = @chars_to_read - @read_so_far
-
end
-
@read_so_far += number_of_bytes
-
@input_stream.read(number_of_bytes, buf)
-
end
-
-
2
def produce_input
-
sysread(::Zip::Decompressor::CHUNK_SIZE)
-
end
-
-
2
def input_finished?
-
@read_so_far >= @chars_to_read
-
end
-
-
2
alias eof input_finished?
-
2
alias eof? input_finished?
-
end
-
end
-
-
# Copyright (C) 2002, 2003 Thomas Sondergaard
-
# rubyzip is free software; you can redistribute it and/or
-
# modify it under the terms of the ruby license.
-
2
module Zip
-
2
class StreamableDirectory < Entry
-
2
def initialize(zipfile, entry, srcPath = nil, permissionInt = nil)
-
super(zipfile, entry)
-
-
@ftype = :directory
-
entry.get_extra_attributes_from_path(srcPath) if srcPath
-
@unix_perms = permissionInt if permissionInt
-
end
-
end
-
end
-
-
# Copyright (C) 2002, 2003 Thomas Sondergaard
-
# rubyzip is free software; you can redistribute it and/or
-
# modify it under the terms of the ruby license.
-
2
module Zip
-
2
class StreamableStream < DelegateClass(Entry) # nodoc:all
-
2
def initialize(entry)
-
super(entry)
-
dirname = if zipfile.is_a?(::String)
-
::File.dirname(zipfile)
-
else
-
'.'
-
end
-
@temp_file = Tempfile.new(::File.basename(name), dirname)
-
@temp_file.binmode
-
end
-
-
2
def get_output_stream
-
if block_given?
-
begin
-
yield(@temp_file)
-
ensure
-
@temp_file.close
-
end
-
else
-
@temp_file
-
end
-
end
-
-
2
def get_input_stream
-
unless @temp_file.closed?
-
raise StandardError, "cannot open entry for reading while its open for writing - #{name}"
-
end
-
@temp_file.open # reopens tempfile from top
-
@temp_file.binmode
-
if block_given?
-
begin
-
yield(@temp_file)
-
ensure
-
@temp_file.close
-
end
-
else
-
@temp_file
-
end
-
end
-
-
2
def write_to_zip_output_stream(aZipOutputStream)
-
aZipOutputStream.put_next_entry(self)
-
get_input_stream { |is| ::Zip::IOExtras.copy_stream(aZipOutputStream, is) }
-
end
-
-
2
def clean_up
-
@temp_file.unlink
-
end
-
end
-
end
-
-
# Copyright (C) 2002, 2003 Thomas Sondergaard
-
# rubyzip is free software; you can redistribute it and/or
-
# modify it under the terms of the ruby license.
-
2
dir = File.dirname(__FILE__)
-
2
$LOAD_PATH.unshift dir unless $LOAD_PATH.include?(dir)
-
-
# This is necessary to set so that the Haml code that tries to load Sass
-
# knows that Sass is indeed loading,
-
# even if there's some crazy autoload stuff going on.
-
2
SASS_BEGUN_TO_LOAD = true unless defined?(SASS_BEGUN_TO_LOAD)
-
-
2
require 'sass/version'
-
-
# The module that contains everything Sass-related:
-
#
-
# * {Sass::Engine} is the class used to render Sass/SCSS within Ruby code.
-
# * {Sass::Plugin} is interfaces with web frameworks (Rails and Merb in particular).
-
# * {Sass::SyntaxError} is raised when Sass encounters an error.
-
# * {Sass::CSS} handles conversion of CSS to Sass.
-
#
-
# Also see the {file:SASS_REFERENCE.md full Sass reference}.
-
2
module Sass
-
# The global load paths for Sass files. This is meant for plugins and
-
# libraries to register the paths to their Sass stylesheets to that they may
-
# be `@imported`. This load path is used by every instance of [Sass::Engine].
-
# They are lower-precedence than any load paths passed in via the
-
# {file:SASS_REFERENCE.md#load_paths-option `:load_paths` option}.
-
#
-
# If the `SASS_PATH` environment variable is set,
-
# the initial value of `load_paths` will be initialized based on that.
-
# The variable should be a colon-separated list of path names
-
# (semicolon-separated on Windows).
-
#
-
# Note that files on the global load path are never compiled to CSS
-
# themselves, even if they aren't partials. They exist only to be imported.
-
#
-
# @example
-
# Sass.load_paths << File.dirname(__FILE__ + '/sass')
-
# @return [Array<String, Pathname, Sass::Importers::Base>]
-
2
def self.load_paths
-
@load_paths ||= ENV['SASS_PATH'] ?
-
3
ENV['SASS_PATH'].split(Sass::Util.windows? ? ';' : ':') : []
-
end
-
-
# Compile a Sass or SCSS string to CSS.
-
# Defaults to SCSS.
-
#
-
# @param contents [String] The contents of the Sass file.
-
# @param options [{Symbol => Object}] An options hash;
-
# see {file:SASS_REFERENCE.md#sass_options the Sass options documentation}
-
# @raise [Sass::SyntaxError] if there's an error in the document
-
# @raise [Encoding::UndefinedConversionError] if the source encoding
-
# cannot be converted to UTF-8
-
# @raise [ArgumentError] if the document uses an unknown encoding with `@charset`
-
2
def self.compile(contents, options = {})
-
options[:syntax] ||= :scss
-
Engine.new(contents, options).to_css
-
end
-
-
# Compile a file on disk to CSS.
-
#
-
# @param filename [String] The path to the Sass, SCSS, or CSS file on disk.
-
# @param options [{Symbol => Object}] An options hash;
-
# see {file:SASS_REFERENCE.md#sass_options the Sass options documentation}
-
# @raise [Sass::SyntaxError] if there's an error in the document
-
# @raise [Encoding::UndefinedConversionError] if the source encoding
-
# cannot be converted to UTF-8
-
# @raise [ArgumentError] if the document uses an unknown encoding with `@charset`
-
#
-
# @overload compile_file(filename, options = {})
-
# Return the compiled CSS rather than writing it to a file.
-
#
-
# @return [String] The compiled CSS.
-
#
-
# @overload compile_file(filename, css_filename, options = {})
-
# Write the compiled CSS to a file.
-
#
-
# @param css_filename [String] The location to which to write the compiled CSS.
-
2
def self.compile_file(filename, *args)
-
options = args.last.is_a?(Hash) ? args.pop : {}
-
css_filename = args.shift
-
result = Sass::Engine.for_file(filename, options).render
-
if css_filename
-
options[:css_filename] ||= css_filename
-
open(css_filename,"w") {|css_file| css_file.write(result)}
-
nil
-
else
-
result
-
end
-
end
-
end
-
-
2
require 'sass/logger'
-
2
require 'sass/util'
-
-
2
require 'sass/engine'
-
2
require 'sass/plugin' if defined?(Merb::Plugins)
-
2
require 'sass/railtie'
-
2
require 'stringio'
-
-
2
module Sass
-
# Sass cache stores are in charge of storing cached information,
-
# especially parse trees for Sass documents.
-
#
-
# User-created importers must inherit from {CacheStores::Base}.
-
2
module CacheStores
-
end
-
end
-
-
2
require 'sass/cache_stores/base'
-
2
require 'sass/cache_stores/filesystem'
-
2
require 'sass/cache_stores/memory'
-
2
require 'sass/cache_stores/chain'
-
2
module Sass
-
2
module CacheStores
-
# An abstract base class for backends for the Sass cache.
-
# Any key-value store can act as such a backend;
-
# it just needs to implement the
-
# \{#_store} and \{#_retrieve} methods.
-
#
-
# To use a cache store with Sass,
-
# use the {file:SASS_REFERENCE.md#cache_store-option `:cache_store` option}.
-
#
-
# @abstract
-
2
class Base
-
# Store cached contents for later retrieval
-
# Must be implemented by all CacheStore subclasses
-
#
-
# Note: cache contents contain binary data.
-
#
-
# @param key [String] The key to store the contents under
-
# @param version [String] The current sass version.
-
# Cached contents must not be retrieved across different versions of sass.
-
# @param sha [String] The sha of the sass source.
-
# Cached contents must not be retrieved if the sha has changed.
-
# @param contents [String] The contents to store.
-
2
def _store(key, version, sha, contents)
-
raise "#{self.class} must implement #_store."
-
end
-
-
# Retrieved cached contents.
-
# Must be implemented by all subclasses.
-
#
-
# Note: if the key exists but the sha or version have changed,
-
# then the key may be deleted by the cache store, if it wants to do so.
-
#
-
# @param key [String] The key to retrieve
-
# @param version [String] The current sass version.
-
# Cached contents must not be retrieved across different versions of sass.
-
# @param sha [String] The sha of the sass source.
-
# Cached contents must not be retrieved if the sha has changed.
-
# @return [String] The contents that were previously stored.
-
# @return [NilClass] when the cache key is not found or the version or sha have changed.
-
2
def _retrieve(key, version, sha)
-
raise "#{self.class} must implement #_retrieve."
-
end
-
-
# Store a {Sass::Tree::RootNode}.
-
#
-
# @param key [String] The key to store it under.
-
# @param sha [String] The checksum for the contents that are being stored.
-
# @param obj [Object] The object to cache.
-
2
def store(key, sha, root)
-
_store(key, Sass::VERSION, sha, Marshal.dump(root))
-
rescue TypeError, LoadError => e
-
Sass::Util.sass_warn "Warning. Error encountered while saving cache #{path_to(key)}: #{e}"
-
nil
-
end
-
-
# Retrieve a {Sass::Tree::RootNode}.
-
#
-
# @param key [String] The key the root element was stored under.
-
# @param sha [String] The checksum of the root element's content.
-
# @return [Object] The cached object.
-
2
def retrieve(key, sha)
-
contents = _retrieve(key, Sass::VERSION, sha)
-
Marshal.load(contents) if contents
-
rescue EOFError, TypeError, ArgumentError, LoadError => e
-
Sass::Util.sass_warn "Warning. Error encountered while reading cache #{path_to(key)}: #{e}"
-
nil
-
end
-
-
# Return the key for the sass file.
-
#
-
# The `(sass_dirname, sass_basename)` pair
-
# should uniquely identify the Sass document,
-
# but otherwise there are no restrictions on their content.
-
#
-
# @param sass_dirname [String]
-
# The fully-expanded location of the Sass file.
-
# This corresponds to the directory name on a filesystem.
-
# @param sass_basename [String] The name of the Sass file that is being referenced.
-
# This corresponds to the basename on a filesystem.
-
2
def key(sass_dirname, sass_basename)
-
dir = Digest::SHA1.hexdigest(sass_dirname)
-
filename = "#{sass_basename}c"
-
"#{dir}/#{filename}"
-
end
-
end
-
end
-
end
-
2
module Sass
-
2
module CacheStores
-
# A meta-cache that chains multiple caches together.
-
# Specifically:
-
#
-
# * All `#store`s are passed to all caches.
-
# * `#retrieve`s are passed to each cache until one has a hit.
-
# * When one cache has a hit, the value is `#store`d in all earlier caches.
-
2
class Chain < Base
-
# Create a new cache chaining the given caches.
-
#
-
# @param caches [Array<Sass::CacheStores::Base>] The caches to chain.
-
2
def initialize(*caches)
-
1
@caches = caches
-
end
-
-
# @see Base#store
-
2
def store(key, sha, obj)
-
@caches.each {|c| c.store(key, sha, obj)}
-
end
-
-
# @see Base#retrieve
-
2
def retrieve(key, sha)
-
@caches.each_with_index do |c, i|
-
next unless obj = c.retrieve(key, sha)
-
@caches[0...i].each {|prev| prev.store(key, sha, obj)}
-
return obj
-
end
-
nil
-
end
-
end
-
end
-
end
-
2
require 'fileutils'
-
-
2
module Sass
-
2
module CacheStores
-
# A backend for the Sass cache using the filesystem.
-
2
class Filesystem < Base
-
# The directory where the cached files will be stored.
-
#
-
# @return [String]
-
2
attr_accessor :cache_location
-
-
# @param cache_location [String] see \{#cache\_location}
-
2
def initialize(cache_location)
-
1
@cache_location = cache_location
-
end
-
-
# @see Base#\_retrieve
-
2
def _retrieve(key, version, sha)
-
return unless File.readable?(path_to(key))
-
File.open(path_to(key), "rb") do |f|
-
if f.readline("\n").strip == version && f.readline("\n").strip == sha
-
return f.read
-
end
-
end
-
begin
-
File.unlink path_to(key)
-
rescue Errno::ENOENT
-
# Already deleted. Race condition?
-
end
-
nil
-
rescue EOFError, TypeError, ArgumentError => e
-
Sass::Util.sass_warn "Warning. Error encountered while reading cache #{path_to(key)}: #{e}"
-
end
-
-
# @see Base#\_store
-
2
def _store(key, version, sha, contents)
-
# return unless File.writable?(File.dirname(@cache_location))
-
# return if File.exists?(@cache_location) && !File.writable?(@cache_location)
-
compiled_filename = path_to(key)
-
# return if File.exists?(File.dirname(compiled_filename)) && !File.writable?(File.dirname(compiled_filename))
-
# return if File.exists?(compiled_filename) && !File.writable?(compiled_filename)
-
FileUtils.mkdir_p(File.dirname(compiled_filename))
-
Sass::Util.atomic_create_and_write_file(compiled_filename, 0600) do |f|
-
f.puts(version)
-
f.puts(sha)
-
f.write(contents)
-
end
-
rescue Errno::EACCES
-
#pass
-
end
-
-
2
private
-
-
# Returns the path to a file for the given key.
-
#
-
# @param key [String]
-
# @return [String] The path to the cache file.
-
2
def path_to(key)
-
key = key.gsub(/[<>:\\|?*%]/) {|c| "%%%03d" % Sass::Util.ord(c)}
-
File.join(cache_location, key)
-
end
-
end
-
end
-
end
-
2
module Sass
-
2
module CacheStores
-
# A backend for the Sass cache using in-process memory.
-
2
class Memory < Base
-
# Since the {Memory} store is stored in the Sass tree's options hash,
-
# when the options get serialized as part of serializing the tree,
-
# you get crazy exponential growth in the size of the cached objects
-
# unless you don't dump the cache.
-
#
-
# @private
-
2
def _dump(depth)
-
""
-
end
-
-
# If we deserialize this class, just make a new empty one.
-
#
-
# @private
-
2
def self._load(repr)
-
Memory.new
-
end
-
-
# Create a new, empty cache store.
-
2
def initialize
-
1
@contents = {}
-
end
-
-
# @see Base#retrieve
-
2
def retrieve(key, sha)
-
if @contents.has_key?(key)
-
return unless @contents[key][:sha] == sha
-
obj = @contents[key][:obj]
-
obj.respond_to?(:deep_copy) ? obj.deep_copy : obj.dup
-
end
-
end
-
-
# @see Base#store
-
2
def store(key, sha, obj)
-
@contents[key] = {:sha => sha, :obj => obj}
-
end
-
-
# Destructively clear the cache.
-
2
def reset!
-
@contents = {}
-
end
-
end
-
end
-
end
-
2
require 'set'
-
2
require 'digest/sha1'
-
2
require 'sass/cache_stores'
-
2
require 'sass/tree/node'
-
2
require 'sass/tree/root_node'
-
2
require 'sass/tree/rule_node'
-
2
require 'sass/tree/comment_node'
-
2
require 'sass/tree/prop_node'
-
2
require 'sass/tree/directive_node'
-
2
require 'sass/tree/media_node'
-
2
require 'sass/tree/supports_node'
-
2
require 'sass/tree/css_import_node'
-
2
require 'sass/tree/variable_node'
-
2
require 'sass/tree/mixin_def_node'
-
2
require 'sass/tree/mixin_node'
-
2
require 'sass/tree/trace_node'
-
2
require 'sass/tree/content_node'
-
2
require 'sass/tree/function_node'
-
2
require 'sass/tree/return_node'
-
2
require 'sass/tree/extend_node'
-
2
require 'sass/tree/if_node'
-
2
require 'sass/tree/while_node'
-
2
require 'sass/tree/for_node'
-
2
require 'sass/tree/each_node'
-
2
require 'sass/tree/debug_node'
-
2
require 'sass/tree/warn_node'
-
2
require 'sass/tree/import_node'
-
2
require 'sass/tree/charset_node'
-
2
require 'sass/tree/visitors/base'
-
2
require 'sass/tree/visitors/perform'
-
2
require 'sass/tree/visitors/cssize'
-
2
require 'sass/tree/visitors/extend'
-
2
require 'sass/tree/visitors/convert'
-
2
require 'sass/tree/visitors/to_css'
-
2
require 'sass/tree/visitors/deep_copy'
-
2
require 'sass/tree/visitors/set_options'
-
2
require 'sass/tree/visitors/check_nesting'
-
2
require 'sass/selector'
-
2
require 'sass/environment'
-
2
require 'sass/script'
-
2
require 'sass/scss'
-
2
require 'sass/error'
-
2
require 'sass/importers'
-
2
require 'sass/shared'
-
2
require 'sass/media'
-
2
require 'sass/supports'
-
-
2
module Sass
-
-
# A Sass mixin or function.
-
#
-
# `name`: `String`
-
# : The name of the mixin/function.
-
#
-
# `args`: `Array<(Script::Node, Script::Node)>`
-
# : The arguments for the mixin/function.
-
# Each element is a tuple containing the variable node of the argument
-
# and the parse tree for the default value of the argument.
-
#
-
# `splat`: `Script::Node?`
-
# : The variable node of the splat argument for this callable, or null.
-
#
-
# `environment`: {Sass::Environment}
-
# : The environment in which the mixin/function was defined.
-
# This is captured so that the mixin/function can have access
-
# to local variables defined in its scope.
-
#
-
# `tree`: `Array<Tree::Node>`
-
# : The parse tree for the mixin/function.
-
#
-
# `has_content`: `Boolean`
-
# : Whether the callable accepts a content block.
-
#
-
# `type`: `String`
-
# : The user-friendly name of the type of the callable.
-
2
Callable = Struct.new(:name, :args, :splat, :environment, :tree, :has_content, :type)
-
-
# This class handles the parsing and compilation of the Sass template.
-
# Example usage:
-
#
-
# template = File.load('stylesheets/sassy.sass')
-
# sass_engine = Sass::Engine.new(template)
-
# output = sass_engine.render
-
# puts output
-
2
class Engine
-
2
include Sass::Util
-
-
# A line of Sass code.
-
#
-
# `text`: `String`
-
# : The text in the line, without any whitespace at the beginning or end.
-
#
-
# `tabs`: `Fixnum`
-
# : The level of indentation of the line.
-
#
-
# `index`: `Fixnum`
-
# : The line number in the original document.
-
#
-
# `offset`: `Fixnum`
-
# : The number of bytes in on the line that the text begins.
-
# This ends up being the number of bytes of leading whitespace.
-
#
-
# `filename`: `String`
-
# : The name of the file in which this line appeared.
-
#
-
# `children`: `Array<Line>`
-
# : The lines nested below this one.
-
#
-
# `comment_tab_str`: `String?`
-
# : The prefix indentation for this comment, if it is a comment.
-
2
class Line < Struct.new(:text, :tabs, :index, :offset, :filename, :children, :comment_tab_str)
-
2
def comment?
-
text[0] == COMMENT_CHAR && (text[1] == SASS_COMMENT_CHAR || text[1] == CSS_COMMENT_CHAR)
-
end
-
end
-
-
# The character that begins a CSS property.
-
2
PROPERTY_CHAR = ?:
-
-
# The character that designates the beginning of a comment,
-
# either Sass or CSS.
-
2
COMMENT_CHAR = ?/
-
-
# The character that follows the general COMMENT_CHAR and designates a Sass comment,
-
# which is not output as a CSS comment.
-
2
SASS_COMMENT_CHAR = ?/
-
-
# The character that indicates that a comment allows interpolation
-
# and should be preserved even in `:compressed` mode.
-
2
SASS_LOUD_COMMENT_CHAR = ?!
-
-
# The character that follows the general COMMENT_CHAR and designates a CSS comment,
-
# which is embedded in the CSS document.
-
2
CSS_COMMENT_CHAR = ?*
-
-
# The character used to denote a compiler directive.
-
2
DIRECTIVE_CHAR = ?@
-
-
# Designates a non-parsed rule.
-
2
ESCAPE_CHAR = ?\\
-
-
# Designates block as mixin definition rather than CSS rules to output
-
2
MIXIN_DEFINITION_CHAR = ?=
-
-
# Includes named mixin declared using MIXIN_DEFINITION_CHAR
-
2
MIXIN_INCLUDE_CHAR = ?+
-
-
# The regex that matches and extracts data from
-
# properties of the form `:name prop`.
-
2
PROPERTY_OLD = /^:([^\s=:"]+)\s*(?:\s+|$)(.*)/
-
-
# The default options for Sass::Engine.
-
# @api public
-
2
DEFAULT_OPTIONS = {
-
:style => :nested,
-
:load_paths => ['.'],
-
:cache => true,
-
:cache_location => './.sass-cache',
-
:syntax => :sass,
-
:filesystem_importer => Sass::Importers::Filesystem
-
}.freeze
-
-
# Converts a Sass options hash into a standard form, filling in
-
# default values and resolving aliases.
-
#
-
# @param options [{Symbol => Object}] The options hash;
-
# see {file:SASS_REFERENCE.md#sass_options the Sass options documentation}
-
# @return [{Symbol => Object}] The normalized options hash.
-
# @private
-
2
def self.normalize_options(options)
-
5
options = DEFAULT_OPTIONS.merge(options.reject {|k, v| v.nil?})
-
-
# If the `:filename` option is passed in without an importer,
-
# assume it's using the default filesystem importer.
-
1
options[:importer] ||= options[:filesystem_importer].new(".") if options[:filename]
-
-
# Tracks the original filename of the top-level Sass file
-
1
options[:original_filename] ||= options[:filename]
-
-
1
options[:cache_store] ||= Sass::CacheStores::Chain.new(
-
Sass::CacheStores::Memory.new, Sass::CacheStores::Filesystem.new(options[:cache_location]))
-
# Support both, because the docs said one and the other actually worked
-
# for quite a long time.
-
1
options[:line_comments] ||= options[:line_numbers]
-
-
1
options[:load_paths] = (options[:load_paths] + Sass.load_paths).map do |p|
-
2
next p unless p.is_a?(String) || (defined?(Pathname) && p.is_a?(Pathname))
-
2
options[:filesystem_importer].new(p.to_s)
-
end
-
-
# Backwards compatibility
-
1
options[:property_syntax] ||= options[:attribute_syntax]
-
1
case options[:property_syntax]
-
when :alternate; options[:property_syntax] = :new
-
when :normal; options[:property_syntax] = :old
-
end
-
-
1
options
-
end
-
-
# Returns the {Sass::Engine} for the given file.
-
# This is preferable to Sass::Engine.new when reading from a file
-
# because it properly sets up the Engine's metadata,
-
# enables parse-tree caching,
-
# and infers the syntax from the filename.
-
#
-
# @param filename [String] The path to the Sass or SCSS file
-
# @param options [{Symbol => Object}] The options hash;
-
# See {file:SASS_REFERENCE.md#sass_options the Sass options documentation}.
-
# @return [Sass::Engine] The Engine for the given Sass or SCSS file.
-
# @raise [Sass::SyntaxError] if there's an error in the document.
-
2
def self.for_file(filename, options)
-
had_syntax = options[:syntax]
-
-
if had_syntax
-
# Use what was explicitly specificed
-
elsif filename =~ /\.scss$/
-
options.merge!(:syntax => :scss)
-
elsif filename =~ /\.sass$/
-
options.merge!(:syntax => :sass)
-
end
-
-
Sass::Engine.new(File.read(filename), options.merge(:filename => filename))
-
end
-
-
# The options for the Sass engine.
-
# See {file:SASS_REFERENCE.md#sass_options the Sass options documentation}.
-
#
-
# @return [{Symbol => Object}]
-
2
attr_reader :options
-
-
# Creates a new Engine. Note that Engine should only be used directly
-
# when compiling in-memory Sass code.
-
# If you're compiling a single Sass file from the filesystem,
-
# use \{Sass::Engine.for\_file}.
-
# If you're compiling multiple files from the filesystem,
-
# use {Sass::Plugin}.
-
#
-
# @param template [String] The Sass template.
-
# This template can be encoded using any encoding
-
# that can be converted to Unicode.
-
# If the template contains an `@charset` declaration,
-
# that overrides the Ruby encoding
-
# (see {file:SASS_REFERENCE.md#encodings the encoding documentation})
-
# @param options [{Symbol => Object}] An options hash.
-
# See {file:SASS_REFERENCE.md#sass_options the Sass options documentation}.
-
# @see {Sass::Engine.for_file}
-
# @see {Sass::Plugin}
-
2
def initialize(template, options={})
-
1
@options = self.class.normalize_options(options)
-
1
@template = template
-
end
-
-
# Render the template to CSS.
-
#
-
# @return [String] The CSS
-
# @raise [Sass::SyntaxError] if there's an error in the document
-
# @raise [Encoding::UndefinedConversionError] if the source encoding
-
# cannot be converted to UTF-8
-
# @raise [ArgumentError] if the document uses an unknown encoding with `@charset`
-
2
def render
-
1
return _render unless @options[:quiet]
-
Sass::Util.silence_sass_warnings {_render}
-
end
-
2
alias_method :to_css, :render
-
-
# Parses the document into its parse tree. Memoized.
-
#
-
# @return [Sass::Tree::Node] The root of the parse tree.
-
# @raise [Sass::SyntaxError] if there's an error in the document
-
2
def to_tree
-
@tree ||= @options[:quiet] ?
-
Sass::Util.silence_sass_warnings {_to_tree} :
-
_to_tree
-
end
-
-
# Returns the original encoding of the document,
-
# or `nil` under Ruby 1.8.
-
#
-
# @return [Encoding, nil]
-
# @raise [Encoding::UndefinedConversionError] if the source encoding
-
# cannot be converted to UTF-8
-
# @raise [ArgumentError] if the document uses an unknown encoding with `@charset`
-
2
def source_encoding
-
4
check_encoding!
-
4
@original_encoding
-
end
-
-
# Gets a set of all the documents
-
# that are (transitive) dependencies of this document,
-
# not including the document itself.
-
#
-
# @return [[Sass::Engine]] The dependency documents.
-
2
def dependencies
-
_dependencies(Set.new, engines = Set.new)
-
Sass::Util.array_minus(engines, [self])
-
end
-
-
# Helper for \{#dependencies}.
-
#
-
# @private
-
2
def _dependencies(seen, engines)
-
return if seen.include?(key = [@options[:filename], @options[:importer]])
-
seen << key
-
engines << self
-
to_tree.grep(Tree::ImportNode) do |n|
-
next if n.css_import?
-
n.imported_file._dependencies(seen, engines)
-
end
-
end
-
-
2
private
-
-
2
def _render
-
1
rendered = _to_tree.render
-
1
return rendered if ruby1_8?
-
1
begin
-
# Try to convert the result to the original encoding,
-
# but if that doesn't work fall back on UTF-8
-
1
rendered = rendered.encode(source_encoding)
-
rescue EncodingError
-
end
-
1
rendered.gsub(Regexp.new('\A@charset "(.*?)"'.encode(source_encoding)),
-
"@charset \"#{source_encoding.name}\"".encode(source_encoding))
-
end
-
-
2
def _to_tree
-
if (@options[:cache] || @options[:read_cache]) &&
-
1
@options[:filename] && @options[:importer]
-
key = sassc_key
-
sha = Digest::SHA1.hexdigest(@template)
-
-
if root = @options[:cache_store].retrieve(key, sha)
-
root.options = @options
-
return root
-
end
-
end
-
-
1
check_encoding!
-
-
1
if @options[:syntax] == :scss
-
1
root = Sass::SCSS::Parser.new(@template, @options[:filename]).parse
-
else
-
root = Tree::RootNode.new(@template)
-
append_children(root, tree(tabulate(@template)).first, true)
-
end
-
-
1
root.options = @options
-
1
if @options[:cache] && key && sha
-
begin
-
old_options = root.options
-
root.options = {}
-
@options[:cache_store].store(key, sha, root)
-
ensure
-
root.options = old_options
-
end
-
end
-
1
root
-
rescue SyntaxError => e
-
e.modify_backtrace(:filename => @options[:filename], :line => @line)
-
e.sass_template = @template
-
raise e
-
end
-
-
2
def sassc_key
-
@options[:cache_store].key(*@options[:importer].key(@options[:filename], @options))
-
end
-
-
2
def check_encoding!
-
5
return if @checked_encoding
-
1
@checked_encoding = true
-
1
@template, @original_encoding = check_sass_encoding(@template) do |msg, line|
-
raise Sass::SyntaxError.new(msg, :line => line)
-
end
-
end
-
-
2
def tabulate(string)
-
tab_str = nil
-
comment_tab_str = nil
-
first = true
-
lines = []
-
string.gsub(/\r\n|\r|\n/, "\n").scan(/^[^\n]*?$/).each_with_index do |line, index|
-
index += (@options[:line] || 1)
-
if line.strip.empty?
-
lines.last.text << "\n" if lines.last && lines.last.comment?
-
next
-
end
-
-
line_tab_str = line[/^\s*/]
-
unless line_tab_str.empty?
-
if tab_str.nil?
-
comment_tab_str ||= line_tab_str
-
next if try_comment(line, lines.last, "", comment_tab_str, index)
-
comment_tab_str = nil
-
end
-
-
tab_str ||= line_tab_str
-
-
raise SyntaxError.new("Indenting at the beginning of the document is illegal.",
-
:line => index) if first
-
-
raise SyntaxError.new("Indentation can't use both tabs and spaces.",
-
:line => index) if tab_str.include?(?\s) && tab_str.include?(?\t)
-
end
-
first &&= !tab_str.nil?
-
if tab_str.nil?
-
lines << Line.new(line.strip, 0, index, 0, @options[:filename], [])
-
next
-
end
-
-
comment_tab_str ||= line_tab_str
-
if try_comment(line, lines.last, tab_str * lines.last.tabs, comment_tab_str, index)
-
next
-
else
-
comment_tab_str = nil
-
end
-
-
line_tabs = line_tab_str.scan(tab_str).size
-
if tab_str * line_tabs != line_tab_str
-
message = <<END.strip.gsub("\n", ' ')
-
Inconsistent indentation: #{Sass::Shared.human_indentation line_tab_str, true} used for indentation,
-
but the rest of the document was indented using #{Sass::Shared.human_indentation tab_str}.
-
END
-
raise SyntaxError.new(message, :line => index)
-
end
-
-
lines << Line.new(line.strip, line_tabs, index, tab_str.size, @options[:filename], [])
-
end
-
lines
-
end
-
-
2
def try_comment(line, last, tab_str, comment_tab_str, index)
-
return unless last && last.comment?
-
# Nested comment stuff must be at least one whitespace char deeper
-
# than the normal indentation
-
return unless line =~ /^#{tab_str}\s/
-
unless line =~ /^(?:#{comment_tab_str})(.*)$/
-
raise SyntaxError.new(<<MSG.strip.gsub("\n", " "), :line => index)
-
Inconsistent indentation:
-
previous line was indented by #{Sass::Shared.human_indentation comment_tab_str},
-
but this line was indented by #{Sass::Shared.human_indentation line[/^\s*/]}.
-
MSG
-
end
-
-
last.comment_tab_str ||= comment_tab_str
-
last.text << "\n" << line
-
true
-
end
-
-
2
def tree(arr, i = 0)
-
return [], i if arr[i].nil?
-
-
base = arr[i].tabs
-
nodes = []
-
while (line = arr[i]) && line.tabs >= base
-
if line.tabs > base
-
raise SyntaxError.new("The line was indented #{line.tabs - base} levels deeper than the previous line.",
-
:line => line.index) if line.tabs > base + 1
-
-
nodes.last.children, i = tree(arr, i)
-
else
-
nodes << line
-
i += 1
-
end
-
end
-
return nodes, i
-
end
-
-
2
def build_tree(parent, line, root = false)
-
@line = line.index
-
node_or_nodes = parse_line(parent, line, root)
-
-
Array(node_or_nodes).each do |node|
-
# Node is a symbol if it's non-outputting, like a variable assignment
-
next unless node.is_a? Tree::Node
-
-
node.line = line.index
-
node.filename = line.filename
-
-
append_children(node, line.children, false)
-
end
-
-
node_or_nodes
-
end
-
-
2
def append_children(parent, children, root)
-
continued_rule = nil
-
continued_comment = nil
-
children.each do |line|
-
child = build_tree(parent, line, root)
-
-
if child.is_a?(Tree::RuleNode)
-
if child.continued? && child.children.empty?
-
if continued_rule
-
continued_rule.add_rules child
-
else
-
continued_rule = child
-
end
-
next
-
elsif continued_rule
-
continued_rule.add_rules child
-
continued_rule.children = child.children
-
continued_rule, child = nil, continued_rule
-
end
-
elsif continued_rule
-
continued_rule = nil
-
end
-
-
if child.is_a?(Tree::CommentNode) && child.type == :silent
-
if continued_comment &&
-
child.line == continued_comment.line +
-
continued_comment.lines + 1
-
continued_comment.value += ["\n"] + child.value
-
next
-
end
-
-
continued_comment = child
-
end
-
-
check_for_no_children(child)
-
validate_and_append_child(parent, child, line, root)
-
end
-
-
parent
-
end
-
-
2
def validate_and_append_child(parent, child, line, root)
-
case child
-
when Array
-
child.each {|c| validate_and_append_child(parent, c, line, root)}
-
when Tree::Node
-
parent << child
-
end
-
end
-
-
2
def check_for_no_children(node)
-
return unless node.is_a?(Tree::RuleNode) && node.children.empty?
-
Sass::Util.sass_warn(<<WARNING.strip)
-
WARNING on line #{node.line}#{" of #{node.filename}" if node.filename}:
-
This selector doesn't have any properties and will not be rendered.
-
WARNING
-
end
-
-
2
def parse_line(parent, line, root)
-
case line.text[0]
-
when PROPERTY_CHAR
-
if line.text[1] == PROPERTY_CHAR ||
-
(@options[:property_syntax] == :new &&
-
line.text =~ PROPERTY_OLD && $2.empty?)
-
# Support CSS3-style pseudo-elements,
-
# which begin with ::,
-
# as well as pseudo-classes
-
# if we're using the new property syntax
-
Tree::RuleNode.new(parse_interp(line.text))
-
else
-
name, value = line.text.scan(PROPERTY_OLD)[0]
-
raise SyntaxError.new("Invalid property: \"#{line.text}\".",
-
:line => @line) if name.nil? || value.nil?
-
parse_property(name, parse_interp(name), value, :old, line)
-
end
-
when ?$
-
parse_variable(line)
-
when COMMENT_CHAR
-
parse_comment(line)
-
when DIRECTIVE_CHAR
-
parse_directive(parent, line, root)
-
when ESCAPE_CHAR
-
Tree::RuleNode.new(parse_interp(line.text[1..-1]))
-
when MIXIN_DEFINITION_CHAR
-
parse_mixin_definition(line)
-
when MIXIN_INCLUDE_CHAR
-
if line.text[1].nil? || line.text[1] == ?\s
-
Tree::RuleNode.new(parse_interp(line.text))
-
else
-
parse_mixin_include(line, root)
-
end
-
else
-
parse_property_or_rule(line)
-
end
-
end
-
-
2
def parse_property_or_rule(line)
-
scanner = Sass::Util::MultibyteStringScanner.new(line.text)
-
hack_char = scanner.scan(/[:\*\.]|\#(?!\{)/)
-
parser = Sass::SCSS::Parser.new(scanner, @options[:filename], @line)
-
-
unless res = parser.parse_interp_ident
-
return Tree::RuleNode.new(parse_interp(line.text))
-
end
-
res.unshift(hack_char) if hack_char
-
if comment = scanner.scan(Sass::SCSS::RX::COMMENT)
-
res << comment
-
end
-
-
name = line.text[0...scanner.pos]
-
if scanner.scan(/\s*:(?:\s|$)/)
-
parse_property(name, res, scanner.rest, :new, line)
-
else
-
res.pop if comment
-
Tree::RuleNode.new(res + parse_interp(scanner.rest))
-
end
-
end
-
-
2
def parse_property(name, parsed_name, value, prop, line)
-
if value.strip.empty?
-
expr = Sass::Script::String.new("")
-
else
-
expr = parse_script(value, :offset => line.offset + line.text.index(value))
-
end
-
node = Tree::PropNode.new(parse_interp(name), expr, prop)
-
if value.strip.empty? && line.children.empty?
-
raise SyntaxError.new(
-
"Invalid property: \"#{node.declaration}\" (no value)." +
-
node.pseudo_class_selector_message)
-
end
-
-
node
-
end
-
-
2
def parse_variable(line)
-
name, value, default = line.text.scan(Script::MATCH)[0]
-
raise SyntaxError.new("Illegal nesting: Nothing may be nested beneath variable declarations.",
-
:line => @line + 1) unless line.children.empty?
-
raise SyntaxError.new("Invalid variable: \"#{line.text}\".",
-
:line => @line) unless name && value
-
-
expr = parse_script(value, :offset => line.offset + line.text.index(value))
-
-
Tree::VariableNode.new(name, expr, default)
-
end
-
-
2
def parse_comment(line)
-
if line.text[1] == CSS_COMMENT_CHAR || line.text[1] == SASS_COMMENT_CHAR
-
silent = line.text[1] == SASS_COMMENT_CHAR
-
loud = !silent && line.text[2] == SASS_LOUD_COMMENT_CHAR
-
if silent
-
value = [line.text]
-
else
-
value = self.class.parse_interp(line.text, line.index, line.offset, :filename => @filename)
-
end
-
value = with_extracted_values(value) do |str|
-
str = str.gsub(/^#{line.comment_tab_str}/m, '')[2..-1] # get rid of // or /*
-
format_comment_text(str, silent)
-
end
-
type = if silent then :silent elsif loud then :loud else :normal end
-
Tree::CommentNode.new(value, type)
-
else
-
Tree::RuleNode.new(parse_interp(line.text))
-
end
-
end
-
-
2
def parse_directive(parent, line, root)
-
directive, whitespace, value = line.text[1..-1].split(/(\s+)/, 2)
-
offset = directive.size + whitespace.size + 1 if whitespace
-
-
# If value begins with url( or ",
-
# it's a CSS @import rule and we don't want to touch it.
-
case directive
-
when 'import'
-
parse_import(line, value, offset)
-
when 'mixin'
-
parse_mixin_definition(line)
-
when 'content'
-
parse_content_directive(line)
-
when 'include'
-
parse_mixin_include(line, root)
-
when 'function'
-
parse_function(line, root)
-
when 'for'
-
parse_for(line, root, value)
-
when 'each'
-
parse_each(line, root, value)
-
when 'else'
-
parse_else(parent, line, value)
-
when 'while'
-
raise SyntaxError.new("Invalid while directive '@while': expected expression.") unless value
-
Tree::WhileNode.new(parse_script(value, :offset => offset))
-
when 'if'
-
raise SyntaxError.new("Invalid if directive '@if': expected expression.") unless value
-
Tree::IfNode.new(parse_script(value, :offset => offset))
-
when 'debug'
-
raise SyntaxError.new("Invalid debug directive '@debug': expected expression.") unless value
-
raise SyntaxError.new("Illegal nesting: Nothing may be nested beneath debug directives.",
-
:line => @line + 1) unless line.children.empty?
-
offset = line.offset + line.text.index(value).to_i
-
Tree::DebugNode.new(parse_script(value, :offset => offset))
-
when 'extend'
-
raise SyntaxError.new("Invalid extend directive '@extend': expected expression.") unless value
-
raise SyntaxError.new("Illegal nesting: Nothing may be nested beneath extend directives.",
-
:line => @line + 1) unless line.children.empty?
-
optional = !!value.gsub!(/\s+#{Sass::SCSS::RX::OPTIONAL}$/, '')
-
offset = line.offset + line.text.index(value).to_i
-
Tree::ExtendNode.new(parse_interp(value, offset), optional)
-
when 'warn'
-
raise SyntaxError.new("Invalid warn directive '@warn': expected expression.") unless value
-
raise SyntaxError.new("Illegal nesting: Nothing may be nested beneath warn directives.",
-
:line => @line + 1) unless line.children.empty?
-
offset = line.offset + line.text.index(value).to_i
-
Tree::WarnNode.new(parse_script(value, :offset => offset))
-
when 'return'
-
raise SyntaxError.new("Invalid @return: expected expression.") unless value
-
raise SyntaxError.new("Illegal nesting: Nothing may be nested beneath return directives.",
-
:line => @line + 1) unless line.children.empty?
-
offset = line.offset + line.text.index(value).to_i
-
Tree::ReturnNode.new(parse_script(value, :offset => offset))
-
when 'charset'
-
name = value && value[/\A(["'])(.*)\1\Z/, 2] #"
-
raise SyntaxError.new("Invalid charset directive '@charset': expected string.") unless name
-
raise SyntaxError.new("Illegal nesting: Nothing may be nested beneath charset directives.",
-
:line => @line + 1) unless line.children.empty?
-
Tree::CharsetNode.new(name)
-
when 'media'
-
parser = Sass::SCSS::Parser.new(value, @options[:filename], @line)
-
Tree::MediaNode.new(parser.parse_media_query_list.to_a)
-
when nil
-
raise SyntaxError.new("Invalid directive: '@'.")
-
else
-
unprefixed_directive = directive.gsub(/^-[a-z0-9]+-/i, '')
-
if unprefixed_directive == 'supports'
-
parser = Sass::SCSS::Parser.new(value, @options[:filename], @line)
-
return Tree::SupportsNode.new(directive, parser.parse_supports_condition)
-
end
-
-
Tree::DirectiveNode.new(
-
value.nil? ? ["@#{directive}"] : ["@#{directive} "] + parse_interp(value, offset))
-
end
-
end
-
-
2
def parse_for(line, root, text)
-
var, from_expr, to_name, to_expr = text.scan(/^([^\s]+)\s+from\s+(.+)\s+(to|through)\s+(.+)$/).first
-
-
if var.nil? # scan failed, try to figure out why for error message
-
if text !~ /^[^\s]+/
-
expected = "variable name"
-
elsif text !~ /^[^\s]+\s+from\s+.+/
-
expected = "'from <expr>'"
-
else
-
expected = "'to <expr>' or 'through <expr>'"
-
end
-
raise SyntaxError.new("Invalid for directive '@for #{text}': expected #{expected}.")
-
end
-
raise SyntaxError.new("Invalid variable \"#{var}\".") unless var =~ Script::VALIDATE
-
-
var = var[1..-1]
-
parsed_from = parse_script(from_expr, :offset => line.offset + line.text.index(from_expr))
-
parsed_to = parse_script(to_expr, :offset => line.offset + line.text.index(to_expr))
-
Tree::ForNode.new(var, parsed_from, parsed_to, to_name == 'to')
-
end
-
-
2
def parse_each(line, root, text)
-
var, list_expr = text.scan(/^([^\s]+)\s+in\s+(.+)$/).first
-
-
if var.nil? # scan failed, try to figure out why for error message
-
if text !~ /^[^\s]+/
-
expected = "variable name"
-
elsif text !~ /^[^\s]+\s+from\s+.+/
-
expected = "'in <expr>'"
-
end
-
raise SyntaxError.new("Invalid for directive '@each #{text}': expected #{expected}.")
-
end
-
raise SyntaxError.new("Invalid variable \"#{var}\".") unless var =~ Script::VALIDATE
-
-
var = var[1..-1]
-
parsed_list = parse_script(list_expr, :offset => line.offset + line.text.index(list_expr))
-
Tree::EachNode.new(var, parsed_list)
-
end
-
-
2
def parse_else(parent, line, text)
-
previous = parent.children.last
-
raise SyntaxError.new("@else must come after @if.") unless previous.is_a?(Tree::IfNode)
-
-
if text
-
if text !~ /^if\s+(.+)/
-
raise SyntaxError.new("Invalid else directive '@else #{text}': expected 'if <expr>'.")
-
end
-
expr = parse_script($1, :offset => line.offset + line.text.index($1))
-
end
-
-
node = Tree::IfNode.new(expr)
-
append_children(node, line.children, false)
-
previous.add_else node
-
nil
-
end
-
-
2
def parse_import(line, value, offset)
-
raise SyntaxError.new("Illegal nesting: Nothing may be nested beneath import directives.",
-
:line => @line + 1) unless line.children.empty?
-
-
scanner = Sass::Util::MultibyteStringScanner.new(value)
-
values = []
-
-
loop do
-
unless node = parse_import_arg(scanner, offset + scanner.pos)
-
raise SyntaxError.new("Invalid @import: expected file to import, was #{scanner.rest.inspect}",
-
:line => @line)
-
end
-
values << node
-
break unless scanner.scan(/,\s*/)
-
end
-
-
if scanner.scan(/;/)
-
raise SyntaxError.new("Invalid @import: expected end of line, was \";\".",
-
:line => @line)
-
end
-
-
return values
-
end
-
-
2
def parse_import_arg(scanner, offset)
-
return if scanner.eos?
-
-
if scanner.match?(/url\(/i)
-
script_parser = Sass::Script::Parser.new(scanner, @line, offset, @options)
-
str = script_parser.parse_string
-
media_parser = Sass::SCSS::Parser.new(scanner, @options[:filename], @line)
-
media = media_parser.parse_media_query_list
-
return Tree::CssImportNode.new(str, media.to_a)
-
end
-
-
unless str = scanner.scan(Sass::SCSS::RX::STRING)
-
return Tree::ImportNode.new(scanner.scan(/[^,;]+/))
-
end
-
-
val = scanner[1] || scanner[2]
-
scanner.scan(/\s*/)
-
if !scanner.match?(/[,;]|$/)
-
media_parser = Sass::SCSS::Parser.new(scanner, @options[:filename], @line)
-
media = media_parser.parse_media_query_list
-
Tree::CssImportNode.new(str || uri, media.to_a)
-
elsif val =~ /^(https?:)?\/\//
-
Tree::CssImportNode.new("url(#{val})")
-
else
-
Tree::ImportNode.new(val)
-
end
-
end
-
-
2
MIXIN_DEF_RE = /^(?:=|@mixin)\s*(#{Sass::SCSS::RX::IDENT})(.*)$/
-
2
def parse_mixin_definition(line)
-
name, arg_string = line.text.scan(MIXIN_DEF_RE).first
-
raise SyntaxError.new("Invalid mixin \"#{line.text[1..-1]}\".") if name.nil?
-
-
offset = line.offset + line.text.size - arg_string.size
-
args, splat = Script::Parser.new(arg_string.strip, @line, offset, @options).
-
parse_mixin_definition_arglist
-
Tree::MixinDefNode.new(name, args, splat)
-
end
-
-
2
CONTENT_RE = /^@content\s*(.+)?$/
-
2
def parse_content_directive(line)
-
trailing = line.text.scan(CONTENT_RE).first.first
-
raise SyntaxError.new("Invalid content directive. Trailing characters found: \"#{trailing}\".") unless trailing.nil?
-
raise SyntaxError.new("Illegal nesting: Nothing may be nested beneath @content directives.",
-
:line => line.index + 1) unless line.children.empty?
-
Tree::ContentNode.new
-
end
-
-
2
MIXIN_INCLUDE_RE = /^(?:\+|@include)\s*(#{Sass::SCSS::RX::IDENT})(.*)$/
-
2
def parse_mixin_include(line, root)
-
name, arg_string = line.text.scan(MIXIN_INCLUDE_RE).first
-
raise SyntaxError.new("Invalid mixin include \"#{line.text}\".") if name.nil?
-
-
offset = line.offset + line.text.size - arg_string.size
-
args, keywords, splat = Script::Parser.new(arg_string.strip, @line, offset, @options).
-
parse_mixin_include_arglist
-
Tree::MixinNode.new(name, args, keywords, splat)
-
end
-
-
2
FUNCTION_RE = /^@function\s*(#{Sass::SCSS::RX::IDENT})(.*)$/
-
2
def parse_function(line, root)
-
name, arg_string = line.text.scan(FUNCTION_RE).first
-
raise SyntaxError.new("Invalid function definition \"#{line.text}\".") if name.nil?
-
-
offset = line.offset + line.text.size - arg_string.size
-
args, splat = Script::Parser.new(arg_string.strip, @line, offset, @options).
-
parse_function_definition_arglist
-
Tree::FunctionNode.new(name, args, splat)
-
end
-
-
2
def parse_script(script, options = {})
-
line = options[:line] || @line
-
offset = options[:offset] || 0
-
Script.parse(script, line, offset, @options)
-
end
-
-
2
def format_comment_text(text, silent)
-
content = text.split("\n")
-
-
if content.first && content.first.strip.empty?
-
removed_first = true
-
content.shift
-
end
-
-
return silent ? "//" : "/* */" if content.empty?
-
content.last.gsub!(%r{ ?\*/ *$}, '')
-
content.map! {|l| l.gsub!(/^\*( ?)/, '\1') || (l.empty? ? "" : " ") + l}
-
content.first.gsub!(/^ /, '') unless removed_first
-
if silent
-
"//" + content.join("\n//")
-
else
-
# The #gsub fixes the case of a trailing */
-
"/*" + content.join("\n *").gsub(/ \*\Z/, '') + " */"
-
end
-
end
-
-
2
def parse_interp(text, offset = 0)
-
self.class.parse_interp(text, @line, offset, :filename => @filename)
-
end
-
-
# It's important that this have strings (at least)
-
# at the beginning, the end, and between each Script::Node.
-
#
-
# @private
-
2
def self.parse_interp(text, line, offset, options)
-
1758
res = []
-
1758
rest = Sass::Shared.handle_interpolation text do |scan|
-
escapes = scan[2].size
-
res << scan.matched[0...-2 - escapes]
-
if escapes % 2 == 1
-
res << "\\" * (escapes - 1) << '#{'
-
else
-
res << "\\" * [0, escapes - 1].max
-
res << Script::Parser.new(
-
scan, line, offset + scan.pos - scan.matched_size, options).
-
parse_interpolated
-
end
-
end
-
1758
res << rest
-
end
-
end
-
end
-
2
require 'set'
-
-
2
module Sass
-
# The lexical environment for SassScript.
-
# This keeps track of variable, mixin, and function definitions.
-
#
-
# A new environment is created for each level of Sass nesting.
-
# This allows variables to be lexically scoped.
-
# The new environment refers to the environment in the upper scope,
-
# so it has access to variables defined in enclosing scopes,
-
# but new variables are defined locally.
-
#
-
# Environment also keeps track of the {Engine} options
-
# so that they can be made available to {Sass::Script::Functions}.
-
2
class Environment
-
# The enclosing environment,
-
# or nil if this is the global environment.
-
#
-
# @return [Environment]
-
2
attr_reader :parent
-
2
attr_reader :options
-
2
attr_writer :caller
-
2
attr_writer :content
-
-
# @param options [{Symbol => Object}] The options hash. See
-
# {file:SASS_REFERENCE.md#sass_options the Sass options documentation}.
-
# @param parent [Environment] See \{#parent}
-
2
def initialize(parent = nil, options = nil)
-
19827
@parent = parent
-
19827
@options = options || (parent && parent.options) || {}
-
end
-
-
# The environment of the caller of this environment's mixin or function.
-
# @return {Environment?}
-
2
def caller
-
@caller || (@parent && @parent.caller)
-
end
-
-
# The content passed to this environmnet. This is naturally only set
-
# for mixin body environments with content passed in.
-
# @return {Environment?}
-
2
def content
-
@content || (@parent && @parent.content)
-
end
-
-
2
private
-
-
2
class << self
-
2
private
-
2
UNDERSCORE, DASH = '_', '-'
-
-
# Note: when updating this,
-
# update sass/yard/inherited_hash.rb as well.
-
2
def inherited_hash(name)
-
6
class_eval <<RUBY, __FILE__, __LINE__ + 1
-
def #{name}(name)
-
_#{name}(name.tr(UNDERSCORE, DASH))
-
end
-
-
def _#{name}(name)
-
(@#{name}s && @#{name}s[name]) || @parent && @parent._#{name}(name)
-
end
-
protected :_#{name}
-
-
def set_#{name}(name, value)
-
name = name.tr(UNDERSCORE, DASH)
-
@#{name}s[name] = value unless try_set_#{name}(name, value)
-
end
-
-
def try_set_#{name}(name, value)
-
@#{name}s ||= {}
-
if @#{name}s.include?(name)
-
@#{name}s[name] = value
-
true
-
elsif @parent
-
@parent.try_set_#{name}(name, value)
-
else
-
false
-
end
-
end
-
protected :try_set_#{name}
-
-
def set_local_#{name}(name, value)
-
@#{name}s ||= {}
-
@#{name}s[name.tr(UNDERSCORE, DASH)] = value
-
end
-
RUBY
-
end
-
end
-
-
# variable
-
# Script::Literal
-
2
inherited_hash :var
-
# mixin
-
# Sass::Callable
-
2
inherited_hash :mixin
-
# function
-
# Sass::Callable
-
2
inherited_hash :function
-
end
-
end
-
2
module Sass
-
# An exception class that keeps track of
-
# the line of the Sass template it was raised on
-
# and the Sass file that was being parsed (if applicable).
-
#
-
# All Sass errors are raised as {Sass::SyntaxError}s.
-
#
-
# When dealing with SyntaxErrors,
-
# it's important to provide filename and line number information.
-
# This will be used in various error reports to users, including backtraces;
-
# see \{#sass\_backtrace} for details.
-
#
-
# Some of this information is usually provided as part of the constructor.
-
# New backtrace entries can be added with \{#add\_backtrace},
-
# which is called when an exception is raised between files (e.g. with `@import`).
-
#
-
# Often, a chunk of code will all have similar backtrace information -
-
# the same filename or even line.
-
# It may also be useful to have a default line number set.
-
# In those situations, the default values can be used
-
# by omitting the information on the original exception,
-
# and then calling \{#modify\_backtrace} in a wrapper `rescue`.
-
# When doing this, be sure that all exceptions ultimately end up
-
# with the information filled in.
-
2
class SyntaxError < StandardError
-
# The backtrace of the error within Sass files.
-
# This is an array of hashes containing information for a single entry.
-
# The hashes have the following keys:
-
#
-
# `:filename`
-
# : The name of the file in which the exception was raised,
-
# or `nil` if no filename is available.
-
#
-
# `:mixin`
-
# : The name of the mixin in which the exception was raised,
-
# or `nil` if it wasn't raised in a mixin.
-
#
-
# `:line`
-
# : The line of the file on which the error occurred. Never nil.
-
#
-
# This information is also included in standard backtrace format
-
# in the output of \{#backtrace}.
-
#
-
# @return [Aray<{Symbol => Object>}]
-
2
attr_accessor :sass_backtrace
-
-
# The text of the template where this error was raised.
-
#
-
# @return [String]
-
2
attr_accessor :sass_template
-
-
# @param msg [String] The error message
-
# @param attrs [{Symbol => Object}] The information in the backtrace entry.
-
# See \{#sass\_backtrace}
-
2
def initialize(msg, attrs = {})
-
110
@message = msg
-
110
@sass_backtrace = []
-
110
add_backtrace(attrs)
-
end
-
-
# The name of the file in which the exception was raised.
-
# This could be `nil` if no filename is available.
-
#
-
# @return [String, nil]
-
2
def sass_filename
-
sass_backtrace.first[:filename]
-
end
-
-
# The name of the mixin in which the error occurred.
-
# This could be `nil` if the error occurred outside a mixin.
-
#
-
# @return [Fixnum]
-
2
def sass_mixin
-
sass_backtrace.first[:mixin]
-
end
-
-
# The line of the Sass template on which the error occurred.
-
#
-
# @return [Fixnum]
-
2
def sass_line
-
sass_backtrace.first[:line]
-
end
-
-
# Adds an entry to the exception's Sass backtrace.
-
#
-
# @param attrs [{Symbol => Object}] The information in the backtrace entry.
-
# See \{#sass\_backtrace}
-
2
def add_backtrace(attrs)
-
220
sass_backtrace << attrs.reject {|k, v| v.nil?}
-
end
-
-
# Modify the top Sass backtrace entries
-
# (that is, the most deeply nested ones)
-
# to have the given attributes.
-
#
-
# Specifically, this goes through the backtrace entries
-
# from most deeply nested to least,
-
# setting the given attributes for each entry.
-
# If an entry already has one of the given attributes set,
-
# the pre-existing attribute takes precedence
-
# and is not used for less deeply-nested entries
-
# (even if they don't have that attribute set).
-
#
-
# @param attrs [{Symbol => Object}] The information to add to the backtrace entry.
-
# See \{#sass\_backtrace}
-
2
def modify_backtrace(attrs)
-
attrs = attrs.reject {|k, v| v.nil?}
-
# Move backwards through the backtrace
-
(0...sass_backtrace.size).to_a.reverse.each do |i|
-
entry = sass_backtrace[i]
-
sass_backtrace[i] = attrs.merge(entry)
-
attrs.reject! {|k, v| entry.include?(k)}
-
break if attrs.empty?
-
end
-
end
-
-
# @return [String] The error message
-
2
def to_s
-
@message
-
end
-
-
# Returns the standard exception backtrace,
-
# including the Sass backtrace.
-
#
-
# @return [Array<String>]
-
2
def backtrace
-
110
return nil if super.nil?
-
return super if sass_backtrace.all? {|h| h.empty?}
-
sass_backtrace.map do |h|
-
"#{h[:filename] || "(sass)"}:#{h[:line]}" +
-
(h[:mixin] ? ":in `#{h[:mixin]}'" : "")
-
end + super
-
end
-
-
# Returns a string representation of the Sass backtrace.
-
#
-
# @param default_filename [String] The filename to use for unknown files
-
# @see #sass_backtrace
-
# @return [String]
-
2
def sass_backtrace_str(default_filename = "an unknown file")
-
lines = self.message.split("\n")
-
msg = lines[0] + lines[1..-1].
-
map {|l| "\n" + (" " * "Syntax error: ".size) + l}.join
-
"Syntax error: #{msg}" +
-
Sass::Util.enum_with_index(sass_backtrace).map do |entry, i|
-
"\n #{i == 0 ? "on" : "from"} line #{entry[:line]}" +
-
" of #{entry[:filename] || default_filename}" +
-
(entry[:mixin] ? ", in `#{entry[:mixin]}'" : "")
-
end.join
-
end
-
-
2
class << self
-
# Returns an error report for an exception in CSS format.
-
#
-
# @param e [Exception]
-
# @param options [{Symbol => Object}] The options passed to {Sass::Engine#initialize}
-
# @return [String] The error report
-
# @raise [Exception] `e`, if the
-
# {file:SASS_REFERENCE.md#full_exception-option `:full_exception`} option
-
# is set to false.
-
2
def exception_to_css(e, options)
-
raise e unless options[:full_exception]
-
-
header = header_string(e, options)
-
-
<<END
-
/*
-
#{header.gsub("*/", "*\\/")}
-
-
Backtrace:\n#{e.backtrace.join("\n").gsub("*/", "*\\/")}
-
*/
-
body:before {
-
white-space: pre;
-
font-family: monospace;
-
content: "#{header.gsub('"', '\"').gsub("\n", '\\A ')}"; }
-
END
-
end
-
-
2
private
-
-
2
def header_string(e, options)
-
unless e.is_a?(Sass::SyntaxError) && e.sass_line && e.sass_template
-
return "#{e.class}: #{e.message}"
-
end
-
-
line_offset = options[:line] || 1
-
line_num = e.sass_line + 1 - line_offset
-
min = [line_num - 6, 0].max
-
section = e.sass_template.rstrip.split("\n")[min ... line_num + 5]
-
return e.sass_backtrace_str if section.nil? || section.empty?
-
-
e.sass_backtrace_str + "\n\n" + Sass::Util.enum_with_index(section).
-
map {|line, i| "#{line_offset + min + i}: #{line}"}.join("\n")
-
end
-
end
-
end
-
-
# The class for Sass errors that are raised due to invalid unit conversions
-
# in SassScript.
-
2
class UnitConversionError < SyntaxError; end
-
end
-
2
module Sass
-
# Sass importers are in charge of taking paths passed to `@import`
-
# and finding the appropriate Sass code for those paths.
-
# By default, this code is always loaded from the filesystem,
-
# but importers could be added to load from a database or over HTTP.
-
#
-
# Each importer is in charge of a single load path
-
# (or whatever the corresponding notion is for the backend).
-
# Importers can be placed in the {file:SASS_REFERENCE.md#load_paths-option `:load_paths` array}
-
# alongside normal filesystem paths.
-
#
-
# When resolving an `@import`, Sass will go through the load paths
-
# looking for an importer that successfully imports the path.
-
# Once one is found, the imported file is used.
-
#
-
# User-created importers must inherit from {Importers::Base}.
-
2
module Importers
-
end
-
end
-
-
2
require 'sass/importers/base'
-
2
require 'sass/importers/filesystem'
-
2
module Sass
-
2
module Importers
-
# The abstract base class for Sass importers.
-
# All importers should inherit from this.
-
#
-
# At the most basic level, an importer is given a string
-
# and must return a {Sass::Engine} containing some Sass code.
-
# This string can be interpreted however the importer wants;
-
# however, subclasses are encouraged to use the URI format
-
# for pathnames.
-
#
-
# Importers that have some notion of "relative imports"
-
# should take a single load path in their constructor,
-
# and interpret paths as relative to that.
-
# They should also implement the \{#find\_relative} method.
-
#
-
# Importers should be serializable via `Marshal.dump`.
-
# In addition to the standard `_dump` and `_load` methods,
-
# importers can define `_before_dump`, `_after_dump`, `_around_dump`,
-
# and `_after_load` methods as per {Sass::Util#dump} and {Sass::Util#load}.
-
#
-
# @abstract
-
2
class Base
-
-
# Find a Sass file relative to another file.
-
# Importers without a notion of "relative paths"
-
# should just return nil here.
-
#
-
# If the importer does have a notion of "relative paths",
-
# it should ignore its load path during this method.
-
#
-
# See \{#find} for important information on how this method should behave.
-
#
-
# The `:filename` option passed to the returned {Sass::Engine}
-
# should be of a format that could be passed to \{#find}.
-
#
-
# @param uri [String] The URI to import. This is not necessarily relative,
-
# but this method should only return true if it is.
-
# @param base [String] The base filename. If `uri` is relative,
-
# it should be interpreted as relative to `base`.
-
# `base` is guaranteed to be in a format importable by this importer.
-
# @param options [{Symbol => Object}] Options for the Sass file
-
# containing the `@import` that's currently being resolved.
-
# @return [Sass::Engine, nil] An Engine containing the imported file,
-
# or nil if it couldn't be found or was in the wrong format.
-
2
def find_relative(uri, base, options)
-
Sass::Util.abstract(self)
-
end
-
-
# Find a Sass file, if it exists.
-
#
-
# This is the primary entry point of the Importer.
-
# It corresponds directly to an `@import` statement in Sass.
-
# It should do three basic things:
-
#
-
# * Determine if the URI is in this importer's format.
-
# If not, return nil.
-
# * Determine if the file indicated by the URI actually exists and is readable.
-
# If not, return nil.
-
# * Read the file and place the contents in a {Sass::Engine}.
-
# Return that engine.
-
#
-
# If this importer's format allows for file extensions,
-
# it should treat them the same way as the default {Filesystem} importer.
-
# If the URI explicitly has a `.sass` or `.scss` filename,
-
# the importer should look for that exact file
-
# and import it as the syntax indicated.
-
# If it doesn't exist, the importer should return nil.
-
#
-
# If the URI doesn't have either of these extensions,
-
# the importer should look for files with the extensions.
-
# If no such files exist, it should return nil.
-
#
-
# The {Sass::Engine} to be returned should be passed `options`,
-
# with a few modifications. `:syntax` should be set appropriately,
-
# `:filename` should be set to `uri`,
-
# and `:importer` should be set to this importer.
-
#
-
# @param uri [String] The URI to import.
-
# @param options [{Symbol => Object}] Options for the Sass file
-
# containing the `@import` that's currently being resolved.
-
# This is safe for subclasses to modify destructively.
-
# Callers should only pass in a value they don't mind being destructively modified.
-
# @return [Sass::Engine, nil] An Engine containing the imported file,
-
# or nil if it couldn't be found or was in the wrong format.
-
2
def find(uri, options)
-
Sass::Util.abstract(self)
-
end
-
-
# Returns the time the given Sass file was last modified.
-
#
-
# If the given file has been deleted or the time can't be accessed
-
# for some other reason, this should return nil.
-
#
-
# @param uri [String] The URI of the file to check.
-
# Comes from a `:filename` option set on an engine returned by this importer.
-
# @param options [{Symbol => Objet}] Options for the Sass file
-
# containing the `@import` currently being checked.
-
# @return [Time, nil]
-
2
def mtime(uri, options)
-
Sass::Util.abstract(self)
-
end
-
-
# Get the cache key pair for the given Sass URI.
-
# The URI need not be checked for validity.
-
#
-
# The only strict requirement is that the returned pair of strings
-
# uniquely identify the file at the given URI.
-
# However, the first component generally corresponds roughly to the directory,
-
# and the second to the basename, of the URI.
-
#
-
# Note that keys must be unique *across importers*.
-
# Thus it's probably a good idea to include the importer name
-
# at the beginning of the first component.
-
#
-
# @param uri [String] A URI known to be valid for this importer.
-
# @param options [{Symbol => Object}] Options for the Sass file
-
# containing the `@import` currently being checked.
-
# @return [(String, String)] The key pair which uniquely identifies
-
# the file at the given URI.
-
2
def key(uri, options)
-
Sass::Util.abstract(self)
-
end
-
-
# A string representation of the importer.
-
# Should be overridden by subclasses.
-
#
-
# This is used to help debugging,
-
# and should usually just show the load path encapsulated by this importer.
-
#
-
# @return [String]
-
2
def to_s
-
Sass::Util.abstract(self)
-
end
-
end
-
end
-
end
-
-
-
2
require 'pathname'
-
2
require 'set'
-
-
2
module Sass
-
2
module Importers
-
# The default importer, used for any strings found in the load path.
-
# Simply loads Sass files from the filesystem using the default logic.
-
2
class Filesystem < Base
-
-
2
attr_accessor :root
-
-
# Creates a new filesystem importer that imports files relative to a given path.
-
#
-
# @param root [String] The root path.
-
# This importer will import files relative to this path.
-
2
def initialize(root)
-
2
@root = File.expand_path(root)
-
2
@same_name_warnings = Set.new
-
end
-
-
# @see Base#find_relative
-
2
def find_relative(name, base, options)
-
_find(File.dirname(base), name, options)
-
end
-
-
# @see Base#find
-
2
def find(name, options)
-
_find(@root, name, options)
-
end
-
-
# @see Base#mtime
-
2
def mtime(name, options)
-
file, _ = Sass::Util.destructure(find_real_file(@root, name, options))
-
File.mtime(file) if file
-
rescue Errno::ENOENT
-
nil
-
end
-
-
# @see Base#key
-
2
def key(name, options)
-
[self.class.name + ":" + File.dirname(File.expand_path(name)),
-
File.basename(name)]
-
end
-
-
# @see Base#to_s
-
2
def to_s
-
@root
-
end
-
-
2
def hash
-
@root.hash
-
end
-
-
2
def eql?(other)
-
root.eql?(other.root)
-
end
-
-
2
protected
-
-
# If a full uri is passed, this removes the root from it
-
# otherwise returns the name unchanged
-
2
def remove_root(name)
-
if name.index(@root + "/") == 0
-
name[(@root.length + 1)..-1]
-
else
-
name
-
end
-
end
-
-
# A hash from file extensions to the syntaxes for those extensions.
-
# The syntaxes must be `:sass` or `:scss`.
-
#
-
# This can be overridden by subclasses that want normal filesystem importing
-
# with unusual extensions.
-
#
-
# @return [{String => Symbol}]
-
2
def extensions
-
{'sass' => :sass, 'scss' => :scss}
-
end
-
-
# Given an `@import`ed path, returns an array of possible
-
# on-disk filenames and their corresponding syntaxes for that path.
-
#
-
# @param name [String] The filename.
-
# @return [Array(String, Symbol)] An array of pairs.
-
# The first element of each pair is a filename to look for;
-
# the second element is the syntax that file would be in (`:sass` or `:scss`).
-
2
def possible_files(name)
-
name = escape_glob_characters(name)
-
dirname, basename, extname = split(name)
-
sorted_exts = extensions.sort
-
syntax = extensions[extname]
-
-
if syntax
-
ret = [["#{dirname}/{_,}#{basename}.#{extensions.invert[syntax]}", syntax]]
-
else
-
ret = sorted_exts.map {|ext, syn| ["#{dirname}/{_,}#{basename}.#{ext}", syn]}
-
end
-
-
# JRuby chokes when trying to import files from JARs when the path starts with './'.
-
ret.map {|f, s| [f.sub(%r{^\./}, ''), s]}
-
end
-
-
2
def escape_glob_characters(name)
-
name.gsub(/[\*\[\]\{\}\?]/) do |char|
-
"\\#{char}"
-
end
-
end
-
-
2
REDUNDANT_DIRECTORY = %r{#{Regexp.escape(File::SEPARATOR)}\.#{Regexp.escape(File::SEPARATOR)}}
-
# Given a base directory and an `@import`ed name,
-
# finds an existant file that matches the name.
-
#
-
# @param dir [String] The directory relative to which to search.
-
# @param name [String] The filename to search for.
-
# @return [(String, Symbol)] A filename-syntax pair.
-
2
def find_real_file(dir, name, options)
-
# on windows 'dir' can be in native File::ALT_SEPARATOR form
-
dir = dir.gsub(File::ALT_SEPARATOR, File::SEPARATOR) unless File::ALT_SEPARATOR.nil?
-
-
found = possible_files(remove_root(name)).map do |f, s|
-
path = (dir == "." || Pathname.new(f).absolute?) ? f : "#{escape_glob_characters(dir)}/#{f}"
-
Dir[path].map do |full_path|
-
full_path.gsub!(REDUNDANT_DIRECTORY, File::SEPARATOR)
-
[Pathname.new(full_path).cleanpath.to_s, s]
-
end
-
end
-
found = Sass::Util.flatten(found, 1)
-
return if found.empty?
-
-
if found.size > 1 && !@same_name_warnings.include?(found.first.first)
-
found.each {|(f, _)| @same_name_warnings << f}
-
relative_to = Pathname.new(dir)
-
if options[:_line]
-
# If _line exists, we're here due to an actual import in an
-
# import_node and we want to print a warning for a user writing an
-
# ambiguous import.
-
candidates = found.map {|(f, _)| " " + Pathname.new(f).relative_path_from(relative_to).to_s}.join("\n")
-
Sass::Util.sass_warn <<WARNING
-
WARNING: On line #{options[:_line]}#{" of #{options[:filename]}" if options[:filename]}:
-
It's not clear which file to import for '@import "#{name}"'.
-
Candidates:
-
#{candidates}
-
For now I'll choose #{File.basename found.first.first}.
-
This will be an error in future versions of Sass.
-
WARNING
-
else
-
# Otherwise, we're here via StalenessChecker, and we want to print a
-
# warning for a user running `sass --watch` with two ambiguous files.
-
candidates = found.map {|(f, _)| " " + File.basename(f)}.join("\n")
-
Sass::Util.sass_warn <<WARNING
-
WARNING: In #{File.dirname(name)}:
-
There are multiple files that match the name "#{File.basename(name)}":
-
#{candidates}
-
WARNING
-
end
-
end
-
found.first
-
end
-
-
# Splits a filename into three parts, a directory part, a basename, and an extension
-
# Only the known extensions returned from the extensions method will be recognized as such.
-
2
def split(name)
-
extension = nil
-
dirname, basename = File.dirname(name), File.basename(name)
-
if basename =~ /^(.*)\.(#{extensions.keys.map{|e| Regexp.escape(e)}.join('|')})$/
-
basename = $1
-
extension = $2
-
end
-
[dirname, basename, extension]
-
end
-
-
2
private
-
-
2
def _find(dir, name, options)
-
full_filename, syntax = Sass::Util.destructure(find_real_file(dir, name, options))
-
return unless full_filename && File.readable?(full_filename)
-
-
options[:syntax] = syntax
-
options[:filename] = full_filename
-
options[:importer] = self
-
Sass::Engine.new(File.read(full_filename), options)
-
end
-
end
-
end
-
end
-
2
module Sass::Logger
-
-
end
-
-
2
require "sass/logger/log_level"
-
2
require "sass/logger/base"
-
-
2
module Sass
-
-
2
class << self
-
2
attr_accessor :logger
-
end
-
-
2
self.logger = Sass::Logger::Base.new
-
end
-
2
require 'sass/logger/log_level'
-
-
2
class Sass::Logger::Base
-
-
2
include Sass::Logger::LogLevel
-
-
2
attr_accessor :log_level
-
2
attr_accessor :disabled
-
-
2
log_level :trace
-
2
log_level :debug
-
2
log_level :info
-
2
log_level :warn
-
2
log_level :error
-
-
2
def initialize(log_level = :debug)
-
4
self.log_level = log_level
-
end
-
-
2
def logging_level?(level)
-
!disabled && self.class.log_level?(level, log_level)
-
end
-
-
2
def log(level, message)
-
self._log(level, message) if logging_level?(level)
-
end
-
-
2
def _log(level, message)
-
Kernel::warn(message)
-
end
-
-
end
-
2
module Sass
-
2
module Logger
-
2
module LogLevel
-
-
2
def self.included(base)
-
2
base.extend(ClassMethods)
-
end
-
-
2
module ClassMethods
-
2
def inherited(subclass)
-
2
subclass.log_levels = subclass.superclass.log_levels.dup
-
end
-
-
2
def log_levels
-
22
@log_levels ||= {}
-
end
-
-
2
def log_levels=(levels)
-
2
@log_levels = levels
-
end
-
-
2
def log_level?(level, min_level)
-
log_levels[level] >= log_levels[min_level]
-
end
-
-
2
def log_level(name, options = {})
-
10
if options[:prepend]
-
level = log_levels.values.min
-
level = level.nil? ? 0 : level - 1
-
else
-
10
level = log_levels.values.max
-
10
level = level.nil? ? 0 : level + 1
-
end
-
10
log_levels.update(name => level)
-
10
define_logger(name)
-
end
-
-
2
def define_logger(name, options = {})
-
10
class_eval <<-RUBY, __FILE__, __LINE__ + 1
-
def #{name}(message)
-
#{options.fetch(:to, :log)}(#{name.inspect}, message)
-
end
-
RUBY
-
end
-
end
-
-
end
-
end
-
end
-
# A namespace for the `@media` query parse tree.
-
2
module Sass::Media
-
# A comma-separated list of queries.
-
#
-
# media_query [ ',' S* media_query ]*
-
2
class QueryList
-
# The queries contained in this list.
-
#
-
# @return [Array<Query>]
-
2
attr_accessor :queries
-
-
# @param queries [Array<Query>] See \{#queries}
-
2
def initialize(queries)
-
422
@queries = queries
-
end
-
-
# Merges this query list with another. The returned query list
-
# queries for the intersection between the two inputs.
-
#
-
# Both query lists should be resolved.
-
#
-
# @param other [QueryList]
-
# @return [QueryList?] The merged list, or nil if there is no intersection.
-
2
def merge(other)
-
new_queries = queries.map {|q1| other.queries.map {|q2| q1.merge(q2)}}.flatten.compact
-
return if new_queries.empty?
-
QueryList.new(new_queries)
-
end
-
-
# Returns the CSS for the media query list.
-
#
-
# @return [String]
-
2
def to_css
-
425
queries.map {|q| q.to_css}.join(', ')
-
end
-
-
# Returns the Sass/SCSS code for the media query list.
-
#
-
# @param options [{Symbol => Object}] An options hash (see {Sass::CSS#initialize}).
-
# @return [String]
-
2
def to_src(options)
-
queries.map {|q| q.to_src(options)}.join(', ')
-
end
-
-
# Returns a representation of the query as an array of strings and
-
# potentially {Sass::Script::Node}s (if there's interpolation in it). When
-
# the interpolation is resolved and the strings are joined together, this
-
# will be the string representation of this query.
-
#
-
# @return [Array<String, Sass::Script::Node>]
-
2
def to_a
-
425
Sass::Util.intersperse(queries.map {|q| q.to_a}, ', ').flatten
-
end
-
-
# Returns a deep copy of this query list and all its children.
-
#
-
# @return [QueryList]
-
2
def deep_copy
-
QueryList.new(queries.map {|q| q.deep_copy})
-
end
-
end
-
-
# A single media query.
-
#
-
# [ [ONLY | NOT]? S* media_type S* | expression ] [ AND S* expression ]*
-
2
class Query
-
# The modifier for the query.
-
#
-
# When parsed as Sass code, this contains strings and SassScript nodes. When
-
# parsed as CSS, it contains a single string (accessible via
-
# \{#resolved_modifier}).
-
#
-
# @return [Array<String, Sass::Script::Node>]
-
2
attr_accessor :modifier
-
-
# The type of the query (e.g. `"screen"` or `"print"`).
-
#
-
# When parsed as Sass code, this contains strings and SassScript nodes. When
-
# parsed as CSS, it contains a single string (accessible via
-
# \{#resolved_type}).
-
#
-
# @return [Array<String, Sass::Script::Node>]
-
2
attr_accessor :type
-
-
# The trailing expressions in the query.
-
#
-
# When parsed as Sass code, each expression contains strings and SassScript
-
# nodes. When parsed as CSS, each one contains a single string.
-
#
-
# @return [Array<Array<String, Sass::Script::Node>>]
-
2
attr_accessor :expressions
-
-
# @param modifier [Array<String, Sass::Script::Node>] See \{#modifier}
-
# @param type [Array<String, Sass::Script::Node>] See \{#type}
-
# @param expressions [Array<Array<String, Sass::Script::Node>>] See \{#expressions}
-
2
def initialize(modifier, type, expressions)
-
428
@modifier = modifier
-
428
@type = type
-
428
@expressions = expressions
-
end
-
-
# See \{#modifier}.
-
# @return [String]
-
2
def resolved_modifier
-
# modifier should contain only a single string
-
428
modifier.first || ''
-
end
-
-
# See \{#type}.
-
# @return [String]
-
2
def resolved_type
-
# type should contain only a single string
-
428
type.first || ''
-
end
-
-
# Merges this query with another. The returned query queries for
-
# the intersection between the two inputs.
-
#
-
# Both queries should be resolved.
-
#
-
# @param other [Query]
-
# @return [Query?] The merged query, or nil if there is no intersection.
-
2
def merge(other)
-
m1, t1 = resolved_modifier.downcase, resolved_type.downcase
-
m2, t2 = other.resolved_modifier.downcase, other.resolved_type.downcase
-
t1 = t2 if t1.empty?
-
t2 = t1 if t2.empty?
-
if ((m1 == 'not') ^ (m2 == 'not'))
-
return if t1 == t2
-
type = m1 == 'not' ? t2 : t1
-
mod = m1 == 'not' ? m2 : m1
-
elsif m1 == 'not' && m2 == 'not'
-
# CSS has no way of representing "neither screen nor print"
-
return unless t1 == t2
-
type = t1
-
mod = 'not'
-
elsif t1 != t2
-
return
-
else # t1 == t2, neither m1 nor m2 are "not"
-
type = t1
-
mod = m1.empty? ? m2 : m1
-
end
-
return Query.new([mod], [type], other.expressions + expressions)
-
end
-
-
# Returns the CSS for the media query.
-
#
-
# @return [String]
-
2
def to_css
-
214
css = ''
-
214
css << resolved_modifier
-
214
css << ' ' unless resolved_modifier.empty?
-
214
css << resolved_type
-
214
css << ' and ' unless resolved_type.empty? || expressions.empty?
-
css << expressions.map do |e|
-
# It's possible for there to be script nodes in Expressions even when
-
# we're converting to CSS in the case where we parsed the document as
-
# CSS originally (as in css_test.rb).
-
1366
e.map {|c| c.is_a?(Sass::Script::Node) ? c.to_sass : c.to_s}.join
-
214
end.join(' and ')
-
214
css
-
end
-
-
# Returns the Sass/SCSS code for the media query.
-
#
-
# @param options [{Symbol => Object}] An options hash (see {Sass::CSS#initialize}).
-
# @return [String]
-
2
def to_src(options)
-
src = ''
-
src << Sass::Media._interp_to_src(modifier, options)
-
src << ' ' unless modifier.empty?
-
src << Sass::Media._interp_to_src(type, options)
-
src << ' and ' unless type.empty? || expressions.empty?
-
src << expressions.map do |e|
-
Sass::Media._interp_to_src(e, options)
-
end.join(' and ')
-
src
-
end
-
-
# @see \{MediaQuery#to\_a}
-
2
def to_a
-
214
res = []
-
214
res += modifier
-
214
res << ' ' unless modifier.empty?
-
214
res += type
-
214
res << ' and ' unless type.empty? || expressions.empty?
-
214
res += Sass::Util.intersperse(expressions, ' and ').flatten
-
214
res
-
end
-
-
# Returns a deep copy of this query and all its children.
-
#
-
# @return [Query]
-
2
def deep_copy
-
Query.new(
-
modifier.map {|c| c.is_a?(Sass::Script::Node) ? c.deep_copy : c},
-
type.map {|c| c.is_a?(Sass::Script::Node) ? c.deep_copy : c},
-
expressions.map {|e| e.map {|c| c.is_a?(Sass::Script::Node) ? c.deep_copy : c}})
-
end
-
end
-
-
# Converts an interpolation array to source.
-
#
-
# @param [Array<String, Sass::Script::Node>] The interpolation array to convert.
-
# @param options [{Symbol => Object}] An options hash (see {Sass::CSS#initialize}).
-
# @return [String]
-
2
def self._interp_to_src(interp, options)
-
interp.map do |r|
-
next r if r.is_a?(String)
-
"\#{#{r.to_sass(options)}}"
-
end.join
-
end
-
end
-
# Rails 3.0.0.beta.2+, < 3.1
-
2
if defined?(ActiveSupport) && Sass::Util.has?(:public_method, ActiveSupport, :on_load) &&
-
!Sass::Util.ap_geq?('3.1.0.beta')
-
require 'sass/plugin/configuration'
-
ActiveSupport.on_load(:before_configuration) do
-
require 'sass'
-
require 'sass/plugin'
-
require 'sass/plugin/rails'
-
end
-
end
-
2
module Sass
-
# The root directory of the Sass source tree.
-
# This may be overridden by the package manager
-
# if the lib directory is separated from the main source tree.
-
# @api public
-
2
ROOT_DIR = File.expand_path(File.join(__FILE__, "../../.."))
-
end
-
2
require 'sass/script/node'
-
2
require 'sass/script/variable'
-
2
require 'sass/script/funcall'
-
2
require 'sass/script/operation'
-
2
require 'sass/script/literal'
-
2
require 'sass/script/parser'
-
-
2
module Sass
-
# SassScript is code that's embedded in Sass documents
-
# to allow for property values to be computed from variables.
-
#
-
# This module contains code that handles the parsing and evaluation of SassScript.
-
2
module Script
-
# The regular expression used to parse variables.
-
2
MATCH = /^\$(#{Sass::SCSS::RX::IDENT})\s*:\s*(.+?)(!(?i:default))?$/
-
-
# The regular expression used to validate variables without matching.
-
2
VALIDATE = /^\$#{Sass::SCSS::RX::IDENT}$/
-
-
# Parses a string of SassScript
-
#
-
# @param value [String] The SassScript
-
# @param line [Fixnum] The number of the line on which the SassScript appeared.
-
# Used for error reporting
-
# @param offset [Fixnum] The number of characters in on `line` that the SassScript started.
-
# Used for error reporting
-
# @param options [{Symbol => Object}] An options hash;
-
# see {file:SASS_REFERENCE.md#sass_options the Sass options documentation}
-
# @return [Script::Node] The root node of the parse tree
-
2
def self.parse(value, line, offset, options = {})
-
Parser.parse(value, line, offset, options)
-
rescue Sass::SyntaxError => e
-
e.message << ": #{value.inspect}." if e.message == "SassScript error"
-
e.modify_backtrace(:line => line, :filename => options[:filename])
-
raise e
-
end
-
-
end
-
end
-
2
module Sass::Script
-
# A SassScript object representing a variable argument list. This works just
-
# like a normal list, but can also contain keyword arguments.
-
#
-
# The keyword arguments attached to this list are unused except when this is
-
# passed as a glob argument to a function or mixin.
-
2
class ArgList < List
-
# Whether \{#keywords} has been accessed. If so, we assume that all keywords
-
# were valid for the function that created this ArgList.
-
#
-
# @return [Boolean]
-
2
attr_accessor :keywords_accessed
-
-
# Creates a new argument list.
-
#
-
# @param value [Array<Literal>] See \{List#value}.
-
# @param keywords [Hash<String, Literal>] See \{#keywords}
-
# @param separator [String] See \{List#separator}.
-
2
def initialize(value, keywords, separator)
-
super(value, separator)
-
@keywords = keywords
-
end
-
-
# The keyword arguments attached to this list.
-
#
-
# @return [Hash<String, Literal>]
-
2
def keywords
-
@keywords_accessed = true
-
@keywords
-
end
-
-
# @see Node#children
-
2
def children
-
super + @keywords.values
-
end
-
-
# @see Node#deep_copy
-
2
def deep_copy
-
node = super
-
node.instance_variable_set('@keywords',
-
Sass::Util.map_hash(@keywords) {|k, v| [k, v.deep_copy]})
-
node
-
end
-
-
2
protected
-
-
# @see Node#_perform
-
2
def _perform(environment)
-
self
-
end
-
end
-
end
-
2
require 'sass/script/literal'
-
-
2
module Sass::Script
-
# A SassScript object representing a boolean (true or false) value.
-
2
class Bool < Literal
-
# The Ruby value of the boolean.
-
#
-
# @return [Boolean]
-
2
attr_reader :value
-
2
alias_method :to_bool, :value
-
-
# @return [String] "true" or "false"
-
2
def to_s(opts = {})
-
@value.to_s
-
end
-
2
alias_method :to_sass, :to_s
-
end
-
end
-
2
require 'sass/script/literal'
-
-
2
module Sass::Script
-
# A SassScript object representing a CSS color.
-
#
-
# A color may be represented internally as RGBA, HSLA, or both.
-
# It's originally represented as whatever its input is;
-
# if it's created with RGB values, it's represented as RGBA,
-
# and if it's created with HSL values, it's represented as HSLA.
-
# Once a property is accessed that requires the other representation --
-
# for example, \{#red} for an HSL color --
-
# that component is calculated and cached.
-
#
-
# The alpha channel of a color is independent of its RGB or HSL representation.
-
# It's always stored, as 1 if nothing else is specified.
-
# If only the alpha channel is modified using \{#with},
-
# the cached RGB and HSL values are retained.
-
2
class Color < Literal
-
4
class << self; include Sass::Util; end
-
-
# A hash from color names to `[red, green, blue]` value arrays.
-
2
COLOR_NAMES = map_vals({
-
'aliceblue' => 0xf0f8ff,
-
'antiquewhite' => 0xfaebd7,
-
'aqua' => 0x00ffff,
-
'aquamarine' => 0x7fffd4,
-
'azure' => 0xf0ffff,
-
'beige' => 0xf5f5dc,
-
'bisque' => 0xffe4c4,
-
'black' => 0x000000,
-
'blanchedalmond' => 0xffebcd,
-
'blue' => 0x0000ff,
-
'blueviolet' => 0x8a2be2,
-
'brown' => 0xa52a2a,
-
'burlywood' => 0xdeb887,
-
'cadetblue' => 0x5f9ea0,
-
'chartreuse' => 0x7fff00,
-
'chocolate' => 0xd2691e,
-
'coral' => 0xff7f50,
-
'cornflowerblue' => 0x6495ed,
-
'cornsilk' => 0xfff8dc,
-
'crimson' => 0xdc143c,
-
'cyan' => 0x00ffff,
-
'darkblue' => 0x00008b,
-
'darkcyan' => 0x008b8b,
-
'darkgoldenrod' => 0xb8860b,
-
'darkgray' => 0xa9a9a9,
-
'darkgrey' => 0xa9a9a9,
-
'darkgreen' => 0x006400,
-
'darkkhaki' => 0xbdb76b,
-
'darkmagenta' => 0x8b008b,
-
'darkolivegreen' => 0x556b2f,
-
'darkorange' => 0xff8c00,
-
'darkorchid' => 0x9932cc,
-
'darkred' => 0x8b0000,
-
'darksalmon' => 0xe9967a,
-
'darkseagreen' => 0x8fbc8f,
-
'darkslateblue' => 0x483d8b,
-
'darkslategray' => 0x2f4f4f,
-
'darkslategrey' => 0x2f4f4f,
-
'darkturquoise' => 0x00ced1,
-
'darkviolet' => 0x9400d3,
-
'deeppink' => 0xff1493,
-
'deepskyblue' => 0x00bfff,
-
'dimgray' => 0x696969,
-
'dimgrey' => 0x696969,
-
'dodgerblue' => 0x1e90ff,
-
'firebrick' => 0xb22222,
-
'floralwhite' => 0xfffaf0,
-
'forestgreen' => 0x228b22,
-
'fuchsia' => 0xff00ff,
-
'gainsboro' => 0xdcdcdc,
-
'ghostwhite' => 0xf8f8ff,
-
'gold' => 0xffd700,
-
'goldenrod' => 0xdaa520,
-
'gray' => 0x808080,
-
'green' => 0x008000,
-
'greenyellow' => 0xadff2f,
-
'honeydew' => 0xf0fff0,
-
'hotpink' => 0xff69b4,
-
'indianred' => 0xcd5c5c,
-
'indigo' => 0x4b0082,
-
'ivory' => 0xfffff0,
-
'khaki' => 0xf0e68c,
-
'lavender' => 0xe6e6fa,
-
'lavenderblush' => 0xfff0f5,
-
'lawngreen' => 0x7cfc00,
-
'lemonchiffon' => 0xfffacd,
-
'lightblue' => 0xadd8e6,
-
'lightcoral' => 0xf08080,
-
'lightcyan' => 0xe0ffff,
-
'lightgoldenrodyellow' => 0xfafad2,
-
'lightgreen' => 0x90ee90,
-
'lightgray' => 0xd3d3d3,
-
'lightgrey' => 0xd3d3d3,
-
'lightpink' => 0xffb6c1,
-
'lightsalmon' => 0xffa07a,
-
'lightseagreen' => 0x20b2aa,
-
'lightskyblue' => 0x87cefa,
-
'lightslategray' => 0x778899,
-
'lightslategrey' => 0x778899,
-
'lightsteelblue' => 0xb0c4de,
-
'lightyellow' => 0xffffe0,
-
'lime' => 0x00ff00,
-
'limegreen' => 0x32cd32,
-
'linen' => 0xfaf0e6,
-
'magenta' => 0xff00ff,
-
'maroon' => 0x800000,
-
'mediumaquamarine' => 0x66cdaa,
-
'mediumblue' => 0x0000cd,
-
'mediumorchid' => 0xba55d3,
-
'mediumpurple' => 0x9370db,
-
'mediumseagreen' => 0x3cb371,
-
'mediumslateblue' => 0x7b68ee,
-
'mediumspringgreen' => 0x00fa9a,
-
'mediumturquoise' => 0x48d1cc,
-
'mediumvioletred' => 0xc71585,
-
'midnightblue' => 0x191970,
-
'mintcream' => 0xf5fffa,
-
'mistyrose' => 0xffe4e1,
-
'moccasin' => 0xffe4b5,
-
'navajowhite' => 0xffdead,
-
'navy' => 0x000080,
-
'oldlace' => 0xfdf5e6,
-
'olive' => 0x808000,
-
'olivedrab' => 0x6b8e23,
-
'orange' => 0xffa500,
-
'orangered' => 0xff4500,
-
'orchid' => 0xda70d6,
-
'palegoldenrod' => 0xeee8aa,
-
'palegreen' => 0x98fb98,
-
'paleturquoise' => 0xafeeee,
-
'palevioletred' => 0xdb7093,
-
'papayawhip' => 0xffefd5,
-
'peachpuff' => 0xffdab9,
-
'peru' => 0xcd853f,
-
'pink' => 0xffc0cb,
-
'plum' => 0xdda0dd,
-
'powderblue' => 0xb0e0e6,
-
'purple' => 0x800080,
-
'red' => 0xff0000,
-
'rosybrown' => 0xbc8f8f,
-
'royalblue' => 0x4169e1,
-
'saddlebrown' => 0x8b4513,
-
'salmon' => 0xfa8072,
-
'sandybrown' => 0xf4a460,
-
'seagreen' => 0x2e8b57,
-
'seashell' => 0xfff5ee,
-
'sienna' => 0xa0522d,
-
'silver' => 0xc0c0c0,
-
'skyblue' => 0x87ceeb,
-
'slateblue' => 0x6a5acd,
-
'slategray' => 0x708090,
-
'slategrey' => 0x708090,
-
'snow' => 0xfffafa,
-
'springgreen' => 0x00ff7f,
-
'steelblue' => 0x4682b4,
-
'tan' => 0xd2b48c,
-
'teal' => 0x008080,
-
'thistle' => 0xd8bfd8,
-
'tomato' => 0xff6347,
-
'turquoise' => 0x40e0d0,
-
'violet' => 0xee82ee,
-
'wheat' => 0xf5deb3,
-
'white' => 0xffffff,
-
'whitesmoke' => 0xf5f5f5,
-
'yellow' => 0xffff00,
-
'yellowgreen' => 0x9acd32
-
1168
}) {|color| (0..2).map {|n| color >> (n << 3) & 0xff}.reverse}
-
-
# A hash from `[red, green, blue]` value arrays to color names.
-
294
COLOR_NAMES_REVERSE = map_hash(hash_to_a(COLOR_NAMES)) {|k, v| [v, k]}
-
-
# Constructs an RGB or HSL color object,
-
# optionally with an alpha channel.
-
#
-
# The RGB values must be between 0 and 255.
-
# The saturation and lightness values must be between 0 and 100.
-
# The alpha value must be between 0 and 1.
-
#
-
# @raise [Sass::SyntaxError] if any color value isn't in the specified range
-
#
-
# @overload initialize(attrs)
-
# The attributes are specified as a hash.
-
# This hash must contain either `:hue`, `:saturation`, and `:value` keys,
-
# or `:red`, `:green`, and `:blue` keys.
-
# It cannot contain both HSL and RGB keys.
-
# It may also optionally contain an `:alpha` key.
-
#
-
# @param attrs [{Symbol => Numeric}] A hash of color attributes to values
-
# @raise [ArgumentError] if not enough attributes are specified,
-
# or both RGB and HSL attributes are specified
-
#
-
# @overload initialize(rgba)
-
# The attributes are specified as an array.
-
# This overload only supports RGB or RGBA colors.
-
#
-
# @param rgba [Array<Numeric>] A three- or four-element array
-
# of the red, green, blue, and optionally alpha values (respectively)
-
# of the color
-
# @raise [ArgumentError] if not enough attributes are specified
-
2
def initialize(attrs, allow_both_rgb_and_hsl = false)
-
950
super(nil)
-
-
950
if attrs.is_a?(Array)
-
492
unless (3..4).include?(attrs.size)
-
raise ArgumentError.new("Color.new(array) expects a three- or four-element array")
-
end
-
-
1968
red, green, blue = attrs[0...3].map {|c| c.to_i}
-
492
@attrs = {:red => red, :green => green, :blue => blue}
-
492
@attrs[:alpha] = attrs[3] ? attrs[3].to_f : 1
-
else
-
2290
attrs = attrs.reject {|k, v| v.nil?}
-
458
hsl = [:hue, :saturation, :lightness] & attrs.keys
-
458
rgb = [:red, :green, :blue] & attrs.keys
-
458
if !allow_both_rgb_and_hsl && !hsl.empty? && !rgb.empty?
-
raise ArgumentError.new("Color.new(hash) may not have both HSL and RGB keys specified")
-
elsif hsl.empty? && rgb.empty?
-
raise ArgumentError.new("Color.new(hash) must have either HSL or RGB keys specified")
-
elsif !hsl.empty? && hsl.size != 3
-
raise ArgumentError.new("Color.new(hash) must have all three HSL values specified")
-
elsif !rgb.empty? && rgb.size != 3
-
raise ArgumentError.new("Color.new(hash) must have all three RGB values specified")
-
end
-
-
458
@attrs = attrs
-
458
@attrs[:hue] %= 360 if @attrs[:hue]
-
458
@attrs[:alpha] ||= 1
-
end
-
-
950
[:red, :green, :blue].each do |k|
-
2850
next if @attrs[k].nil?
-
2850
@attrs[k] = @attrs[k].to_i
-
2850
Sass::Util.check_range("#{k.to_s.capitalize} value", 0..255, @attrs[k])
-
end
-
-
950
[:saturation, :lightness].each do |k|
-
1900
next if @attrs[k].nil?
-
value = Number.new(@attrs[k], ['%']) # Get correct unit for error messages
-
@attrs[k] = Sass::Util.check_range("#{k.to_s.capitalize}", 0..100, value, '%')
-
end
-
-
950
@attrs[:alpha] = Sass::Util.check_range("Alpha channel", 0..1, @attrs[:alpha])
-
end
-
-
# The red component of the color.
-
#
-
# @return [Fixnum]
-
2
def red
-
552
hsl_to_rgb!
-
552
@attrs[:red]
-
end
-
-
# The green component of the color.
-
#
-
# @return [Fixnum]
-
2
def green
-
552
hsl_to_rgb!
-
552
@attrs[:green]
-
end
-
-
# The blue component of the color.
-
#
-
# @return [Fixnum]
-
2
def blue
-
552
hsl_to_rgb!
-
552
@attrs[:blue]
-
end
-
-
# The hue component of the color.
-
#
-
# @return [Numeric]
-
2
def hue
-
rgb_to_hsl!
-
@attrs[:hue]
-
end
-
-
# The saturation component of the color.
-
#
-
# @return [Numeric]
-
2
def saturation
-
rgb_to_hsl!
-
@attrs[:saturation]
-
end
-
-
# The lightness component of the color.
-
#
-
# @return [Numeric]
-
2
def lightness
-
rgb_to_hsl!
-
@attrs[:lightness]
-
end
-
-
# The alpha channel (opacity) of the color.
-
# This is 1 unless otherwise defined.
-
#
-
# @return [Fixnum]
-
2
def alpha
-
924
@attrs[:alpha]
-
end
-
-
# Returns whether this color object is translucent;
-
# that is, whether the alpha channel is non-1.
-
#
-
# @return [Boolean]
-
2
def alpha?
-
492
alpha < 1
-
end
-
-
# Returns the red, green, and blue components of the color.
-
#
-
# @return [Array<Fixnum>] A frozen three-element array of the red, green, and blue
-
# values (respectively) of the color
-
2
def rgb
-
552
[red, green, blue].freeze
-
end
-
-
# Returns the hue, saturation, and lightness components of the color.
-
#
-
# @return [Array<Fixnum>] A frozen three-element array of the
-
# hue, saturation, and lightness values (respectively) of the color
-
2
def hsl
-
[hue, saturation, lightness].freeze
-
end
-
-
# The SassScript `==` operation.
-
# **Note that this returns a {Sass::Script::Bool} object,
-
# not a Ruby boolean**.
-
#
-
# @param other [Literal] The right-hand side of the operator
-
# @return [Bool] True if this literal is the same as the other,
-
# false otherwise
-
2
def eq(other)
-
Sass::Script::Bool.new(
-
other.is_a?(Color) && rgb == other.rgb && alpha == other.alpha)
-
end
-
-
# Returns a copy of this color with one or more channels changed.
-
# RGB or HSL colors may be changed, but not both at once.
-
#
-
# For example:
-
#
-
# Color.new([10, 20, 30]).with(:blue => 40)
-
# #=> rgb(10, 40, 30)
-
# Color.new([126, 126, 126]).with(:red => 0, :green => 255)
-
# #=> rgb(0, 255, 126)
-
# Color.new([255, 0, 127]).with(:saturation => 60)
-
# #=> rgb(204, 51, 127)
-
# Color.new([1, 2, 3]).with(:alpha => 0.4)
-
# #=> rgba(1, 2, 3, 0.4)
-
#
-
# @param attrs [{Symbol => Numeric}]
-
# A map of channel names (`:red`, `:green`, `:blue`,
-
# `:hue`, `:saturation`, `:lightness`, or `:alpha`) to values
-
# @return [Color] The new Color object
-
# @raise [ArgumentError] if both RGB and HSL keys are specified
-
2
def with(attrs)
-
916
attrs = attrs.reject {|k, v| v.nil?}
-
458
hsl = !([:hue, :saturation, :lightness] & attrs.keys).empty?
-
458
rgb = !([:red, :green, :blue] & attrs.keys).empty?
-
458
if hsl && rgb
-
raise ArgumentError.new("Cannot specify HSL and RGB values for a color at the same time")
-
end
-
-
458
if hsl
-
[:hue, :saturation, :lightness].each {|k| attrs[k] ||= send(k)}
-
elsif rgb
-
[:red, :green, :blue].each {|k| attrs[k] ||= send(k)}
-
else
-
# If we're just changing the alpha channel,
-
# keep all the HSL/RGB stuff we've calculated
-
458
attrs = @attrs.merge(attrs)
-
end
-
458
attrs[:alpha] ||= alpha
-
-
458
Color.new(attrs, :allow_both_rgb_and_hsl)
-
end
-
-
# The SassScript `+` operation.
-
# Its functionality depends on the type of its argument:
-
#
-
# {Number}
-
# : Adds the number to each of the RGB color channels.
-
#
-
# {Color}
-
# : Adds each of the RGB color channels together.
-
#
-
# {Literal}
-
# : See {Literal#plus}.
-
#
-
# @param other [Literal] The right-hand side of the operator
-
# @return [Color] The resulting color
-
# @raise [Sass::SyntaxError] if `other` is a number with units
-
2
def plus(other)
-
if other.is_a?(Sass::Script::Number) || other.is_a?(Sass::Script::Color)
-
piecewise(other, :+)
-
else
-
super
-
end
-
end
-
-
# The SassScript `-` operation.
-
# Its functionality depends on the type of its argument:
-
#
-
# {Number}
-
# : Subtracts the number from each of the RGB color channels.
-
#
-
# {Color}
-
# : Subtracts each of the other color's RGB color channels from this color's.
-
#
-
# {Literal}
-
# : See {Literal#minus}.
-
#
-
# @param other [Literal] The right-hand side of the operator
-
# @return [Color] The resulting color
-
# @raise [Sass::SyntaxError] if `other` is a number with units
-
2
def minus(other)
-
if other.is_a?(Sass::Script::Number) || other.is_a?(Sass::Script::Color)
-
piecewise(other, :-)
-
else
-
super
-
end
-
end
-
-
# The SassScript `*` operation.
-
# Its functionality depends on the type of its argument:
-
#
-
# {Number}
-
# : Multiplies the number by each of the RGB color channels.
-
#
-
# {Color}
-
# : Multiplies each of the RGB color channels together.
-
#
-
# @param other [Number, Color] The right-hand side of the operator
-
# @return [Color] The resulting color
-
# @raise [Sass::SyntaxError] if `other` is a number with units
-
2
def times(other)
-
if other.is_a?(Sass::Script::Number) || other.is_a?(Sass::Script::Color)
-
piecewise(other, :*)
-
else
-
raise NoMethodError.new(nil, :times)
-
end
-
end
-
-
# The SassScript `/` operation.
-
# Its functionality depends on the type of its argument:
-
#
-
# {Number}
-
# : Divides each of the RGB color channels by the number.
-
#
-
# {Color}
-
# : Divides each of this color's RGB color channels by the other color's.
-
#
-
# {Literal}
-
# : See {Literal#div}.
-
#
-
# @param other [Literal] The right-hand side of the operator
-
# @return [Color] The resulting color
-
# @raise [Sass::SyntaxError] if `other` is a number with units
-
2
def div(other)
-
if other.is_a?(Sass::Script::Number) || other.is_a?(Sass::Script::Color)
-
piecewise(other, :/)
-
else
-
super
-
end
-
end
-
-
# The SassScript `%` operation.
-
# Its functionality depends on the type of its argument:
-
#
-
# {Number}
-
# : Takes each of the RGB color channels module the number.
-
#
-
# {Color}
-
# : Takes each of this color's RGB color channels modulo the other color's.
-
#
-
# @param other [Number, Color] The right-hand side of the operator
-
# @return [Color] The resulting color
-
# @raise [Sass::SyntaxError] if `other` is a number with units
-
2
def mod(other)
-
if other.is_a?(Sass::Script::Number) || other.is_a?(Sass::Script::Color)
-
piecewise(other, :%)
-
else
-
raise NoMethodError.new(nil, :mod)
-
end
-
end
-
-
# Returns a string representation of the color.
-
# This is usually the color's hex value,
-
# but if the color has a name that's used instead.
-
#
-
# @return [String] The string representation
-
2
def to_s(opts = {})
-
492
return rgba_str if alpha?
-
60
return smallest if options[:style] == :compressed
-
return COLOR_NAMES_REVERSE[rgb] if COLOR_NAMES_REVERSE[rgb]
-
hex_str
-
end
-
2
alias_method :to_sass, :to_s
-
-
# Returns a string representation of the color.
-
#
-
# @return [String] The hex value
-
2
def inspect
-
alpha? ? rgba_str : hex_str
-
end
-
-
2
private
-
-
2
def smallest
-
60
small_hex_str = hex_str.gsub(/^#(.)\1(.)\2(.)\3$/, '#\1\2\3')
-
60
return small_hex_str unless (color = COLOR_NAMES_REVERSE[rgb]) &&
-
60
color.size <= small_hex_str.size
-
return color
-
end
-
-
2
def rgba_str
-
432
split = options[:style] == :compressed ? ',' : ', '
-
432
"rgba(#{rgb.join(split)}#{split}#{Number.round(alpha)})"
-
end
-
-
2
def hex_str
-
240
red, green, blue = rgb.map { |num| num.to_s(16).rjust(2, '0') }
-
60
"##{red}#{green}#{blue}"
-
end
-
-
2
def piecewise(other, operation)
-
other_num = other.is_a? Number
-
if other_num && !other.unitless?
-
raise Sass::SyntaxError.new("Cannot add a number with units (#{other}) to a color (#{self}).")
-
end
-
-
result = []
-
for i in (0...3)
-
res = rgb[i].send(operation, other_num ? other.value : other.rgb[i])
-
result[i] = [ [res, 255].min, 0 ].max
-
end
-
-
if !other_num && other.alpha != alpha
-
raise Sass::SyntaxError.new("Alpha channels must be equal: #{self} #{operation} #{other}")
-
end
-
-
with(:red => result[0], :green => result[1], :blue => result[2])
-
end
-
-
2
def hsl_to_rgb!
-
1656
return if @attrs[:red] && @attrs[:blue] && @attrs[:green]
-
-
h = @attrs[:hue] / 360.0
-
s = @attrs[:saturation] / 100.0
-
l = @attrs[:lightness] / 100.0
-
-
# Algorithm from the CSS3 spec: http://www.w3.org/TR/css3-color/#hsl-color.
-
m2 = l <= 0.5 ? l * (s + 1) : l + s - l * s
-
m1 = l * 2 - m2
-
@attrs[:red], @attrs[:green], @attrs[:blue] = [
-
hue_to_rgb(m1, m2, h + 1.0/3),
-
hue_to_rgb(m1, m2, h),
-
hue_to_rgb(m1, m2, h - 1.0/3)
-
].map {|c| (c * 0xff).round}
-
end
-
-
2
def hue_to_rgb(m1, m2, h)
-
h += 1 if h < 0
-
h -= 1 if h > 1
-
return m1 + (m2 - m1) * h * 6 if h * 6 < 1
-
return m2 if h * 2 < 1
-
return m1 + (m2 - m1) * (2.0/3 - h) * 6 if h * 3 < 2
-
return m1
-
end
-
-
2
def rgb_to_hsl!
-
return if @attrs[:hue] && @attrs[:saturation] && @attrs[:lightness]
-
r, g, b = [:red, :green, :blue].map {|k| @attrs[k] / 255.0}
-
-
# Algorithm from http://en.wikipedia.org/wiki/HSL_and_HSV#Conversion_from_RGB_to_HSL_or_HSV
-
max = [r, g, b].max
-
min = [r, g, b].min
-
d = max - min
-
-
h =
-
case max
-
when min; 0
-
when r; 60 * (g-b)/d
-
when g; 60 * (b-r)/d + 120
-
when b; 60 * (r-g)/d + 240
-
end
-
-
l = (max + min)/2.0
-
-
s =
-
if max == min
-
0
-
elsif l < 0.5
-
d/(2*l)
-
else
-
d/(2 - 2*l)
-
end
-
-
@attrs[:hue] = h % 360
-
@attrs[:saturation] = s * 100
-
@attrs[:lightness] = l * 100
-
end
-
end
-
end
-
2
module Sass
-
2
module Script
-
# This is a subclass of {Lexer} for use in parsing plain CSS properties.
-
#
-
# @see Sass::SCSS::CssParser
-
2
class CssLexer < Lexer
-
2
private
-
-
2
def token
-
908
important || super
-
end
-
-
2
def string(re, *args)
-
2503
if re == :uri
-
687
return unless uri = scan(URI)
-
return [:string, Script::String.new(uri)]
-
end
-
-
1816
return unless scan(STRING)
-
[:string, Script::String.new((@scanner[1] || @scanner[2]).gsub(/\\(['"])/, '\1'), :string)]
-
end
-
-
2
def important
-
908
return unless s = scan(IMPORTANT)
-
[:raw, s]
-
end
-
end
-
end
-
end
-
2
require 'sass/script'
-
2
require 'sass/script/css_lexer'
-
-
2
module Sass
-
2
module Script
-
# This is a subclass of {Parser} for use in parsing plain CSS properties.
-
#
-
# @see Sass::SCSS::CssParser
-
2
class CssParser < Parser
-
2
private
-
-
# @private
-
456
def lexer_class; CssLexer; end
-
-
# We need a production that only does /,
-
# since * and % aren't allowed in plain CSS
-
2
production :div, :unary_plus, :div
-
-
2
def string
-
675
return number unless tok = try_tok(:string)
-
return tok.value unless @lexer.peek && @lexer.peek.type == :begin_interpolation
-
end
-
-
# Short-circuit all the SassScript-only productions
-
2
alias_method :interpolation, :space
-
2
alias_method :or_expr, :div
-
2
alias_method :unary_div, :ident
-
2
alias_method :paren, :string
-
end
-
end
-
end
-
2
require 'sass/script/functions'
-
-
2
module Sass
-
2
module Script
-
# A SassScript parse node representing a function call.
-
#
-
# A function call either calls one of the functions in {Script::Functions},
-
# or if no function with the given name exists
-
# it returns a string representation of the function call.
-
2
class Funcall < Node
-
# The name of the function.
-
#
-
# @return [String]
-
2
attr_reader :name
-
-
# The arguments to the function.
-
#
-
# @return [Array<Script::Node>]
-
2
attr_reader :args
-
-
# The keyword arguments to the function.
-
#
-
# @return [{String => Script::Node}]
-
2
attr_reader :keywords
-
-
# The splat argument for this function, if one exists.
-
#
-
# @return [Script::Node?]
-
2
attr_accessor :splat
-
-
# @param name [String] See \{#name}
-
# @param args [Array<Script::Node>] See \{#args}
-
# @param splat [Script::Node] See \{#splat}
-
# @param keywords [{String => Script::Node}] See \{#keywords}
-
2
def initialize(name, args, keywords, splat)
-
1773
@name = name
-
1773
@args = args
-
1773
@keywords = keywords
-
1773
@splat = splat
-
1773
super()
-
end
-
-
# @return [String] A string representation of the function call
-
2
def inspect
-
args = @args.map {|a| a.inspect}.join(', ')
-
keywords = Sass::Util.hash_to_a(@keywords).
-
map {|k, v| "$#{k}: #{v.inspect}"}.join(', ')
-
if self.splat
-
splat = (args.empty? && keywords.empty?) ? "" : ", "
-
splat = "#{splat}#{self.splat.inspect}..."
-
end
-
"#{name}(#{args}#{', ' unless args.empty? || keywords.empty?}#{keywords}#{splat})"
-
end
-
-
# @see Node#to_sass
-
2
def to_sass(opts = {})
-
arg_to_sass = lambda do |arg|
-
sass = arg.to_sass(opts)
-
sass = "(#{sass})" if arg.is_a?(Sass::Script::List) && arg.separator == :comma
-
sass
-
end
-
-
args = @args.map(&arg_to_sass).join(', ')
-
keywords = Sass::Util.hash_to_a(@keywords).
-
map {|k, v| "$#{dasherize(k, opts)}: #{arg_to_sass[v]}"}.join(', ')
-
if self.splat
-
splat = (args.empty? && keywords.empty?) ? "" : ", "
-
splat = "#{splat}#{arg_to_sass[self.splat]}..."
-
end
-
"#{dasherize(name, opts)}(#{args}#{', ' unless args.empty? || keywords.empty?}#{keywords}#{splat})"
-
end
-
-
# Returns the arguments to the function.
-
#
-
# @return [Array<Node>]
-
# @see Node#children
-
2
def children
-
3546
res = @args + @keywords.values
-
3546
res << @splat if @splat
-
3546
res
-
end
-
-
# @see Node#deep_copy
-
2
def deep_copy
-
node = dup
-
node.instance_variable_set('@args', args.map {|a| a.deep_copy})
-
node.instance_variable_set('@keywords', Hash[keywords.map {|k, v| [k, v.deep_copy]}])
-
node
-
end
-
-
2
protected
-
-
# Evaluates the function call.
-
#
-
# @param environment [Sass::Environment] The environment in which to evaluate the SassScript
-
# @return [Literal] The SassScript object that is the value of the function call
-
# @raise [Sass::SyntaxError] if the function call raises an ArgumentError
-
2
def _perform(environment)
-
7222
args = @args.map {|a| a.perform(environment)}
-
1773
splat = @splat.perform(environment) if @splat
-
1773
if fn = environment.function(@name)
-
keywords = Sass::Util.map_hash(@keywords) {|k, v| [k, v.perform(environment)]}
-
return without_original(perform_sass_fn(fn, args, keywords, splat))
-
end
-
-
1773
ruby_name = @name.tr('-', '_')
-
1773
args = construct_ruby_args(ruby_name, args, splat, environment)
-
-
1773
unless Functions.callable?(ruby_name)
-
1278
without_original(opts(to_literal(args)))
-
else
-
495
without_original(opts(Functions::EvaluationContext.new(environment.options).
-
send(ruby_name, *args)))
-
end
-
rescue ArgumentError => e
-
message = e.message
-
-
# If this is a legitimate Ruby-raised argument error, re-raise it.
-
# Otherwise, it's an error in the user's stylesheet, so wrap it.
-
if Sass::Util.rbx?
-
# Rubinius has a different error report string than vanilla Ruby. It
-
# also doesn't put the actual method for which the argument error was
-
# thrown in the backtrace, nor does it include `send`, so we look for
-
# `_perform`.
-
if e.message =~ /^method '([^']+)': given (\d+), expected (\d+)/
-
error_name, given, expected = $1, $2, $3
-
raise e if error_name != ruby_name || e.backtrace[0] !~ /:in `_perform'$/
-
message = "wrong number of arguments (#{given} for #{expected})"
-
end
-
elsif Sass::Util.jruby?
-
if Sass::Util.jruby1_6?
-
should_maybe_raise = e.message =~ /^wrong number of arguments \((\d+) for (\d+)\)/ &&
-
# The one case where JRuby does include the Ruby name of the function
-
# is manually-thrown ArgumentErrors, which are indistinguishable from
-
# legitimate ArgumentErrors. We treat both of these as
-
# Sass::SyntaxErrors even though it can hide Ruby errors.
-
e.backtrace[0] !~ /:in `(block in )?#{ruby_name}'$/
-
else
-
should_maybe_raise = e.message =~ /^wrong number of arguments calling `[^`]+` \((\d+) for (\d+)\)/
-
given, expected = $1, $2
-
end
-
-
if should_maybe_raise
-
# JRuby 1.7 includes __send__ before send and _perform.
-
trace = e.backtrace.dup
-
raise e if !Sass::Util.jruby1_6? && trace.shift !~ /:in `__send__'$/
-
-
# JRuby (as of 1.7.2) doesn't put the actual method
-
# for which the argument error was thrown in the backtrace, so we
-
# detect whether our send threw an argument error.
-
if !(trace[0] =~ /:in `send'$/ && trace[1] =~ /:in `_perform'$/)
-
raise e
-
elsif !Sass::Util.jruby1_6?
-
# JRuby 1.7 doesn't use standard formatting for its ArgumentErrors.
-
message = "wrong number of arguments (#{given} for #{expected})"
-
end
-
end
-
elsif e.message =~ /^wrong number of arguments \(\d+ for \d+\)/ &&
-
e.backtrace[0] !~ /:in `(block in )?#{ruby_name}'$/
-
raise e
-
end
-
raise Sass::SyntaxError.new("#{message} for `#{name}'")
-
end
-
-
# This method is factored out from `_perform` so that compass can override
-
# it with a cross-browser implementation for functions that require vendor prefixes
-
# in the generated css.
-
2
def to_literal(args)
-
1278
Script::String.new("#{name}(#{args.join(', ')})")
-
end
-
-
2
private
-
-
2
def without_original(value)
-
1773
return value unless value.is_a?(Number)
-
value = value.dup
-
value.original = nil
-
return value
-
end
-
-
2
def construct_ruby_args(name, args, splat, environment)
-
1773
args += splat.to_a if splat
-
-
# If variable arguments were passed, there won't be any explicit keywords.
-
1773
if splat.is_a?(Sass::Script::ArgList)
-
kwargs_size = splat.keywords.size
-
splat.keywords_accessed = false
-
else
-
1773
kwargs_size = @keywords.size
-
end
-
-
1773
unless signature = Functions.signature(name.to_sym, args.size, kwargs_size)
-
1278
return args if @keywords.empty?
-
raise Sass::SyntaxError.new("Function #{name} doesn't support keyword arguments")
-
end
-
495
keywords = splat.is_a?(Sass::Script::ArgList) ? splat.keywords :
-
Sass::Util.map_hash(@keywords) {|k, v| [k, v.perform(environment)]}
-
-
# If the user passes more non-keyword args than the function expects,
-
# but it does expect keyword args, Ruby's arg handling won't raise an error.
-
# Since we don't want to make functions think about this,
-
# we'll handle it for them here.
-
495
if signature.var_kwargs && !signature.var_args && args.size > signature.args.size
-
raise Sass::SyntaxError.new(
-
"#{args[signature.args.size].inspect} is not a keyword argument for `#{name}'")
-
elsif keywords.empty?
-
495
return args
-
end
-
-
args = args + signature.args[args.size..-1].map do |argname|
-
if keywords.has_key?(argname)
-
keywords.delete(argname)
-
else
-
raise Sass::SyntaxError.new("Function #{name} requires an argument named $#{argname}")
-
end
-
end
-
-
if keywords.size > 0
-
if signature.var_kwargs
-
args << keywords
-
else
-
argname = keywords.keys.sort.first
-
if signature.args.include?(argname)
-
raise Sass::SyntaxError.new("Function #{name} was passed argument $#{argname} both by position and by name")
-
else
-
raise Sass::SyntaxError.new("Function #{name} doesn't have an argument named $#{argname}")
-
end
-
end
-
end
-
-
args
-
end
-
-
2
def perform_sass_fn(function, args, keywords, splat)
-
Sass::Tree::Visitors::Perform.perform_arguments(function, args, keywords, splat) do |env|
-
val = catch :_sass_return do
-
function.tree.each {|c| Sass::Tree::Visitors::Perform.visit(c, env)}
-
raise Sass::SyntaxError.new("Function #{@name} finished without @return")
-
end
-
val
-
end
-
end
-
end
-
end
-
end
-
2
module Sass::Script
-
# Methods in this module are accessible from the SassScript context.
-
# For example, you can write
-
#
-
# $color: hsl(120deg, 100%, 50%)
-
#
-
# and it will call {Sass::Script::Functions#hsl}.
-
#
-
# The following functions are provided:
-
#
-
# *Note: These functions are described in more detail below.*
-
#
-
# ## RGB Functions
-
#
-
# \{#rgb rgb($red, $green, $blue)}
-
# : Creates a {Color} from red, green, and blue values.
-
#
-
# \{#rgba rgba($red, $green, $blue, $alpha)}
-
# : Creates a {Color} from red, green, blue, and alpha values.
-
#
-
# \{#red red($color)}
-
# : Gets the red component of a color.
-
#
-
# \{#green green($color)}
-
# : Gets the green component of a color.
-
#
-
# \{#blue blue($color)}
-
# : Gets the blue component of a color.
-
#
-
# \{#mix mix($color-1, $color-2, \[$weight\])}
-
# : Mixes two colors together.
-
#
-
# ## HSL Functions
-
#
-
# \{#hsl hsl($hue, $saturation, $lightness)}
-
# : Creates a {Color} from hue, saturation, and lightness values.
-
#
-
# \{#hsla hsla($hue, $saturation, $lightness, $alpha)}
-
# : Creates a {Color} from hue, saturation, lightness, and alpha
-
# values.
-
#
-
# \{#hue hue($color)}
-
# : Gets the hue component of a color.
-
#
-
# \{#saturation saturation($color)}
-
# : Gets the saturation component of a color.
-
#
-
# \{#lightness lightness($color)}
-
# : Gets the lightness component of a color.
-
#
-
# \{#adjust_hue adjust-hue($color, $degrees)}
-
# : Changes the hue of a color.
-
#
-
# \{#lighten lighten($color, $amount)}
-
# : Makes a color lighter.
-
#
-
# \{#darken darken($color, $amount)}
-
# : Makes a color darker.
-
#
-
# \{#saturate saturate($color, $amount)}
-
# : Makes a color more saturated.
-
#
-
# \{#desaturate desaturate($color, $amount)}
-
# : Makes a color less saturated.
-
#
-
# \{#grayscale grayscale($color)}
-
# : Converts a color to grayscale.
-
#
-
# \{#complement complement($color)}
-
# : Returns the complement of a color.
-
#
-
# \{#invert invert($color)}
-
# : Returns the inverse of a color.
-
#
-
# ## Opacity Functions
-
#
-
# \{#alpha alpha($color)} / \{#opacity opacity($color)}
-
# : Gets the alpha component (opacity) of a color.
-
#
-
# \{#rgba rgba($color, $alpha)}
-
# : Changes the alpha component for a color.
-
#
-
# \{#opacify opacify($color, $amount)} / \{#fade_in fade-in($color, $amount)}
-
# : Makes a color more opaque.
-
#
-
# \{#transparentize transparentize($color, $amount)} / \{#fade_out fade-out($color, $amount)}
-
# : Makes a color more transparent.
-
#
-
# ## Other Color Functions
-
#
-
# \{#adjust_color adjust-color($color, \[$red\], \[$green\], \[$blue\], \[$hue\], \[$saturation\], \[$lightness\], \[$alpha\])}
-
# : Increases or decreases one or more components of a color.
-
#
-
# \{#scale_color scale-color($color, \[$red\], \[$green\], \[$blue\], \[$saturation\], \[$lightness\], \[$alpha\])}
-
# : Fluidly scales one or more properties of a color.
-
#
-
# \{#change_color change-color($color, \[$red\], \[$green\], \[$blue\], \[$hue\], \[$saturation\], \[$lightness\], \[$alpha\])}
-
# : Changes one or more properties of a color.
-
#
-
# \{#ie_hex_str ie-hex-str($color)}
-
# : Converts a color into the format understood by IE filters.
-
#
-
# ## String Functions
-
#
-
# \{#unquote unquote($string)}
-
# : Removes quotes from a string.
-
#
-
# \{#quote quote($string)}
-
# : Adds quotes to a string.
-
#
-
# ## Number Functions
-
#
-
# \{#percentage percentage($value)}
-
# : Converts a unitless number to a percentage.
-
#
-
# \{#round round($value)}
-
# : Rounds a number to the nearest whole number.
-
#
-
# \{#ceil ceil($value)}
-
# : Rounds a number up to the next whole number.
-
#
-
# \{#floor floor($value)}
-
# : Rounds a number down to the previous whole number.
-
#
-
# \{#abs abs($value)}
-
# : Returns the absolute value of a number.
-
#
-
# \{#min min($numbers...)\}
-
# : Finds the minimum of several numbers.
-
#
-
# \{#max max($numbers...)\}
-
# : Finds the maximum of several numbers.
-
#
-
# ## List Functions {#list-functions}
-
#
-
# \{#length length($list)}
-
# : Returns the length of a list.
-
#
-
# \{#nth nth($list, $n)}
-
# : Returns a specific item in a list.
-
#
-
# \{#join join($list1, $list2, \[$separator\])}
-
# : Joins together two lists into one.
-
#
-
# \{#append append($list1, $val, \[$separator\])}
-
# : Appends a single value onto the end of a list.
-
#
-
# \{#zip zip($lists...)}
-
# : Combines several lists into a single multidimensional list.
-
#
-
# \{#index index($list, $value)}
-
# : Returns the position of a value within a list.
-
#
-
# ## Introspection Functions
-
#
-
# \{#type_of type-of($value)}
-
# : Returns the type of a value.
-
#
-
# \{#unit unit($number)}
-
# : Returns the unit(s) associated with a number.
-
#
-
# \{#unitless unitless($number)}
-
# : Returns whether a number has units.
-
#
-
# \{#comparable comparable($number-1, $number-2)}
-
# : Returns whether two numbers can be added, subtracted, or compared.
-
#
-
# ## Miscellaneous Functions
-
#
-
# \{#if if($condition, $if-true, $if-false)}
-
# : Returns one of two values, depending on whether or not `$condition` is
-
# true.
-
#
-
# ## Adding Custom Functions
-
#
-
# New Sass functions can be added by adding Ruby methods to this module.
-
# For example:
-
#
-
# module Sass::Script::Functions
-
# def reverse(string)
-
# assert_type string, :String
-
# Sass::Script::String.new(string.value.reverse)
-
# end
-
# declare :reverse, :args => [:string]
-
# end
-
#
-
# Calling {declare} tells Sass the argument names for your function.
-
# If omitted, the function will still work, but will not be able to accept keyword arguments.
-
# {declare} can also allow your function to take arbitrary keyword arguments.
-
#
-
# There are a few things to keep in mind when modifying this module.
-
# First of all, the arguments passed are {Sass::Script::Literal} objects.
-
# Literal objects are also expected to be returned.
-
# This means that Ruby values must be unwrapped and wrapped.
-
#
-
# Most Literal objects support the {Sass::Script::Literal#value value} accessor
-
# for getting their Ruby values.
-
# Color objects, though, must be accessed using {Sass::Script::Color#rgb rgb},
-
# {Sass::Script::Color#red red}, {Sass::Script::Color#blue green}, or {Sass::Script::Color#blue blue}.
-
#
-
# Second, making Ruby functions accessible from Sass introduces the temptation
-
# to do things like database access within stylesheets.
-
# This is generally a bad idea;
-
# since Sass files are by default only compiled once,
-
# dynamic code is not a great fit.
-
#
-
# If you really, really need to compile Sass on each request,
-
# first make sure you have adequate caching set up.
-
# Then you can use {Sass::Engine} to render the code,
-
# using the {file:SASS_REFERENCE.md#custom-option `options` parameter}
-
# to pass in data that {EvaluationContext#options can be accessed}
-
# from your Sass functions.
-
#
-
# Within one of the functions in this module,
-
# methods of {EvaluationContext} can be used.
-
#
-
# ### Caveats
-
#
-
# When creating new {Literal} objects within functions,
-
# be aware that it's not safe to call {Literal#to_s #to_s}
-
# (or other methods that use the string representation)
-
# on those objects without first setting {Node#options= the #options attribute}.
-
2
module Functions
-
2
@signatures = {}
-
-
# A class representing a Sass function signature.
-
#
-
# @attr args [Array<Symbol>] The names of the arguments to the function.
-
# @attr var_args [Boolean] Whether the function takes a variable number of arguments.
-
# @attr var_kwargs [Boolean] Whether the function takes an arbitrary set of keyword arguments.
-
2
Signature = Struct.new(:args, :var_args, :var_kwargs)
-
-
# Declare a Sass signature for a Ruby-defined function.
-
# This includes the names of the arguments,
-
# whether the function takes a variable number of arguments,
-
# and whether the function takes an arbitrary set of keyword arguments.
-
#
-
# It's not necessary to declare a signature for a function.
-
# However, without a signature it won't support keyword arguments.
-
#
-
# A single function can have multiple signatures declared
-
# as long as each one takes a different number of arguments.
-
# It's also possible to declare multiple signatures
-
# that all take the same number of arguments,
-
# but none of them but the first will be used
-
# unless the user uses keyword arguments.
-
#
-
# @example
-
# declare :rgba, [:hex, :alpha]
-
# declare :rgba, [:red, :green, :blue, :alpha]
-
# declare :accepts_anything, [], :var_args => true, :var_kwargs => true
-
# declare :some_func, [:foo, :bar, :baz], :var_kwargs => true
-
#
-
# @param method_name [Symbol] The name of the method
-
# whose signature is being declared.
-
# @param args [Array<Symbol>] The names of the arguments for the function signature.
-
# @option options :var_args [Boolean] (false)
-
# Whether the function accepts a variable number of (unnamed) arguments
-
# in addition to the named arguments.
-
# @option options :var_kwargs [Boolean] (false)
-
# Whether the function accepts other keyword arguments
-
# in addition to those in `:args`.
-
# If this is true, the Ruby function will be passed a hash from strings
-
# to {Sass::Script::Literal}s as the last argument.
-
# In addition, if this is true and `:var_args` is not,
-
# Sass will ensure that the last argument passed is a hash.
-
2
def self.declare(method_name, args, options = {})
-
112
@signatures[method_name] ||= []
-
@signatures[method_name] << Signature.new(
-
170
args.map {|s| s.to_s},
-
options[:var_args],
-
112
options[:var_kwargs])
-
end
-
-
# Determine the correct signature for the number of arguments
-
# passed in for a given function.
-
# If no signatures match, the first signature is returned for error messaging.
-
#
-
# @param method_name [Symbol] The name of the Ruby function to be called.
-
# @param arg_arity [Number] The number of unnamed arguments the function was passed.
-
# @param kwarg_arity [Number] The number of keyword arguments the function was passed.
-
#
-
# @return [{Symbol => Object}, nil]
-
# The signature options for the matching signature,
-
# or nil if no signatures are declared for this function. See {declare}.
-
2
def self.signature(method_name, arg_arity, kwarg_arity)
-
1773
return unless @signatures[method_name]
-
495
@signatures[method_name].each do |signature|
-
495
return signature if signature.args.size == arg_arity + kwarg_arity
-
next unless signature.args.size < arg_arity + kwarg_arity
-
-
# We have enough args.
-
# Now we need to figure out which args are varargs
-
# and if the signature allows them.
-
t_arg_arity, t_kwarg_arity = arg_arity, kwarg_arity
-
if signature.args.size > t_arg_arity
-
# we transfer some kwargs arity to args arity
-
# if it does not have enough args -- assuming the names will work out.
-
t_kwarg_arity -= (signature.args.size - t_arg_arity)
-
t_arg_arity = signature.args.size
-
end
-
-
if ( t_arg_arity == signature.args.size || t_arg_arity > signature.args.size && signature.var_args ) &&
-
(t_kwarg_arity == 0 || t_kwarg_arity > 0 && signature.var_kwargs)
-
return signature
-
end
-
end
-
@signatures[method_name].first
-
end
-
-
# The context in which methods in {Script::Functions} are evaluated.
-
# That means that all instance methods of {EvaluationContext}
-
# are available to use in functions.
-
2
class EvaluationContext
-
2
include Functions
-
-
# The options hash for the {Sass::Engine} that is processing the function call
-
#
-
# @return [{Symbol => Object}]
-
2
attr_reader :options
-
-
# @param options [{Symbol => Object}] See \{#options}
-
2
def initialize(options)
-
495
@options = options
-
end
-
-
# Asserts that the type of a given SassScript value
-
# is the expected type (designated by a symbol).
-
#
-
# Valid types are `:Bool`, `:Color`, `:Number`, and `:String`.
-
# Note that `:String` will match both double-quoted strings
-
# and unquoted identifiers.
-
#
-
# @example
-
# assert_type value, :String
-
# assert_type value, :Number
-
# @param value [Sass::Script::Literal] A SassScript value
-
# @param type [Symbol] The name of the type the value is expected to be
-
# @param name [String, Symbol, nil] The name of the argument.
-
2
def assert_type(value, type, name = nil)
-
2302
return if value.is_a?(Sass::Script.const_get(type))
-
err = "#{value.inspect} is not a #{type.to_s.downcase}"
-
err = "$#{name.to_s.gsub('_', '-')}: " + err if name
-
raise ArgumentError.new(err)
-
end
-
end
-
-
2
class << self
-
# Returns whether user function with a given name exists.
-
#
-
# @param function_name [String]
-
# @return [Boolean]
-
2
alias_method :callable?, :public_method_defined?
-
-
2
private
-
2
def include(*args)
-
r = super
-
# We have to re-include ourselves into EvaluationContext to work around
-
# an icky Ruby restriction.
-
EvaluationContext.send :include, self
-
r
-
end
-
end
-
-
# Creates a {Color} object from red, green, and blue values.
-
#
-
# @see #rgba
-
# @overload rgb($red, $green, $blue)
-
# @param $red [Number] The amount of red in the color. Must be between 0 and
-
# 255 inclusive, or between `0%` and `100%` inclusive
-
# @param $green [Number] The amount of green in the color. Must be between 0
-
# and 255 inclusive, or between `0%` and `100%` inclusive
-
# @param $blue [Number] The amount of blue in the color. Must be between 0
-
# and 255 inclusive, or between `0%` and `100%` inclusive
-
# @return [Color]
-
# @raise [ArgumentError] if any parameter is the wrong type or out of bounds
-
2
def rgb(red, green, blue)
-
462
assert_type red, :Number, :red
-
462
assert_type green, :Number, :green
-
462
assert_type blue, :Number, :blue
-
-
462
Color.new([[red, :red], [green, :green], [blue, :blue]].map do |(c, name)|
-
1386
v = c.value
-
1386
if c.numerator_units == ["%"] && c.denominator_units.empty?
-
v = Sass::Util.check_range("$#{name}: Color value", 0..100, c, '%')
-
v * 255 / 100.0
-
else
-
1386
Sass::Util.check_range("$#{name}: Color value", 0..255, c)
-
end
-
end)
-
end
-
2
declare :rgb, [:red, :green, :blue]
-
-
# Creates a {Color} from red, green, blue, and alpha values.
-
# @see #rgb
-
#
-
# @overload rgba($red, $green, $blue, $alpha)
-
# @param $red [Number] The amount of red in the color. Must be between 0
-
# and 255 inclusive
-
# @param $green [Number] The amount of green in the color. Must be between
-
# 0 and 255 inclusive
-
# @param $blue [Number] The amount of blue in the color. Must be between 0
-
# and 255 inclusive
-
# @param $alpha [Number] The opacity of the color. Must be between 0 and 1
-
# inclusive
-
# @return [Color]
-
# @raise [ArgumentError] if any parameter is the wrong type or out of
-
# bounds
-
#
-
# @overload rgba($color, $alpha)
-
# Sets the opacity of an existing color.
-
#
-
# @example
-
# rgba(#102030, 0.5) => rgba(16, 32, 48, 0.5)
-
# rgba(blue, 0.2) => rgba(0, 0, 255, 0.2)
-
#
-
# @param $color [Color] The color whose opacity will be changed.
-
# @param $alpha [Number] The new opacity of the color. Must be between 0
-
# and 1 inclusive
-
# @return [Color]
-
# @raise [ArgumentError] if `$alpha` is out of bounds or either parameter
-
# is the wrong type
-
2
def rgba(*args)
-
916
case args.size
-
when 2
-
458
color, alpha = args
-
-
458
assert_type color, :Color, :color
-
458
assert_type alpha, :Number, :alpha
-
-
458
Sass::Util.check_range('Alpha channel', 0..1, alpha)
-
458
color.with(:alpha => alpha.value)
-
when 4
-
458
red, green, blue, alpha = args
-
458
rgba(rgb(red, green, blue), alpha)
-
else
-
raise ArgumentError.new("wrong number of arguments (#{args.size} for 4)")
-
end
-
end
-
2
declare :rgba, [:red, :green, :blue, :alpha]
-
2
declare :rgba, [:color, :alpha]
-
-
# Creates a {Color} from hue, saturation, and lightness values. Uses the
-
# algorithm from the [CSS3 spec][].
-
#
-
# [CSS3 spec]: http://www.w3.org/TR/css3-color/#hsl-color
-
#
-
# @see #hsla
-
# @overload hsl($hue, $saturation, $lightness)
-
# @param $hue [Number] The hue of the color. Should be between 0 and 360
-
# degrees, inclusive
-
# @param $saturation [Number] The saturation of the color. Must be between
-
# `0%` and `100%`, inclusive
-
# @param $lightness [Number] The lightness of the color. Must be between
-
# `0%` and `100%`, inclusive
-
# @return [Color]
-
# @raise [ArgumentError] if `$saturation` or `$lightness` are out of bounds
-
# or any parameter is the wrong type
-
2
def hsl(hue, saturation, lightness)
-
hsla(hue, saturation, lightness, Number.new(1))
-
end
-
2
declare :hsl, [:hue, :saturation, :lightness]
-
-
# Creates a {Color} from hue, saturation, lightness, and alpha
-
# values. Uses the algorithm from the [CSS3 spec][].
-
#
-
# [CSS3 spec]: http://www.w3.org/TR/css3-color/#hsl-color
-
#
-
# @see #hsl
-
# @overload hsla($hue, $saturation, $lightness, $alpha)
-
# @param $hue [Number] The hue of the color. Should be between 0 and 360
-
# degrees, inclusive
-
# @param $saturation [Number] The saturation of the color. Must be between
-
# `0%` and `100%`, inclusive
-
# @param $lightness [Number] The lightness of the color. Must be between
-
# `0%` and `100%`, inclusive
-
# @param $alpha [Number] The opacity of the color. Must be between 0 and 1,
-
# inclusive
-
# @return [Color]
-
# @raise [ArgumentError] if `$saturation`, `$lightness`, or `$alpha` are out
-
# of bounds or any parameter is the wrong type
-
2
def hsla(hue, saturation, lightness, alpha)
-
assert_type hue, :Number, :hue
-
assert_type saturation, :Number, :saturation
-
assert_type lightness, :Number, :lightness
-
assert_type alpha, :Number, :alpha
-
-
Sass::Util.check_range('Alpha channel', 0..1, alpha)
-
-
h = hue.value
-
s = Sass::Util.check_range('Saturation', 0..100, saturation, '%')
-
l = Sass::Util.check_range('Lightness', 0..100, lightness, '%')
-
-
Color.new(:hue => h, :saturation => s, :lightness => l, :alpha => alpha.value)
-
end
-
2
declare :hsla, [:hue, :saturation, :lightness, :alpha]
-
-
# Gets the red component of a color. Calculated from HSL where necessary via
-
# [this algorithm][hsl-to-rgb].
-
#
-
# [hsl-to-rgb]: http://www.w3.org/TR/css3-color/#hsl-color
-
#
-
# @overload red($color)
-
# @param $color [Color]
-
# @return [Number] The red component, between 0 and 255 inclusive
-
# @raise [ArgumentError] if `$color` isn't a color
-
2
def red(color)
-
assert_type color, :Color, :color
-
Sass::Script::Number.new(color.red)
-
end
-
2
declare :red, [:color]
-
-
# Gets the green component of a color. Calculated from HSL where necessary
-
# via [this algorithm][hsl-to-rgb].
-
#
-
# [hsl-to-rgb]: http://www.w3.org/TR/css3-color/#hsl-color
-
#
-
# @overload green($color)
-
# @param $color [Color]
-
# @return [Number] The green component, between 0 and 255 inclusive
-
# @raise [ArgumentError] if `$color` isn't a color
-
2
def green(color)
-
assert_type color, :Color, :color
-
Sass::Script::Number.new(color.green)
-
end
-
2
declare :green, [:color]
-
-
# Gets the blue component of a color. Calculated from HSL where necessary
-
# via [this algorithm][hsl-to-rgb].
-
#
-
# [hsl-to-rgb]: http://www.w3.org/TR/css3-color/#hsl-color
-
#
-
# @overload blue($color)
-
# @param $color [Color]
-
# @return [Number] The blue component, between 0 and 255 inclusive
-
# @raise [ArgumentError] if `$color` isn't a color
-
2
def blue(color)
-
assert_type color, :Color, :color
-
Sass::Script::Number.new(color.blue)
-
end
-
2
declare :blue, [:color]
-
-
# Returns the hue component of a color. See [the CSS3 HSL
-
# specification][hsl]. Calculated from RGB where necessary via [this
-
# algorithm][rgb-to-hsl].
-
#
-
# [hsl]: http://en.wikipedia.org/wiki/HSL_and_HSV#Conversion_from_RGB_to_HSL_or_HSV
-
# [rgb-to-hsl]: http://en.wikipedia.org/wiki/HSL_and_HSV#Conversion_from_RGB_to_HSL_or_HSV
-
#
-
# @overload hue($color)
-
# @param $color [Color]
-
# @return [Number] The hue component, between 0deg and 360deg
-
# @raise [ArgumentError] if `$color` isn't a color
-
2
def hue(color)
-
assert_type color, :Color, :color
-
Sass::Script::Number.new(color.hue, ["deg"])
-
end
-
2
declare :hue, [:color]
-
-
# Returns the saturation component of a color. See [the CSS3 HSL
-
# specification][hsl]. Calculated from RGB where necessary via [this
-
# algorithm][rgb-to-hsl].
-
#
-
# [hsl]: http://en.wikipedia.org/wiki/HSL_and_HSV#Conversion_from_RGB_to_HSL_or_HSV
-
# [rgb-to-hsl]: http://en.wikipedia.org/wiki/HSL_and_HSV#Conversion_from_RGB_to_HSL_or_HSV
-
#
-
# @overload saturation($color)
-
# @param $color [Color]
-
# @return [Number] The saturation component, between 0% and 100%
-
# @raise [ArgumentError] if `$color` isn't a color
-
2
def saturation(color)
-
assert_type color, :Color, :color
-
Sass::Script::Number.new(color.saturation, ["%"])
-
end
-
2
declare :saturation, [:color]
-
-
# Returns the lightness component of a color. See [the CSS3 HSL
-
# specification][hsl]. Calculated from RGB where necessary via [this
-
# algorithm][rgb-to-hsl].
-
#
-
# [hsl]: http://en.wikipedia.org/wiki/HSL_and_HSV#Conversion_from_RGB_to_HSL_or_HSV
-
# [rgb-to-hsl]: http://en.wikipedia.org/wiki/HSL_and_HSV#Conversion_from_RGB_to_HSL_or_HSV
-
#
-
# @overload lightness($color)
-
# @param $color [Color]
-
# @return [Number] The lightness component, between 0% and 100%
-
# @raise [ArgumentError] if `$color` isn't a color
-
2
def lightness(color)
-
assert_type color, :Color, :color
-
Sass::Script::Number.new(color.lightness, ["%"])
-
end
-
2
declare :lightness, [:color]
-
-
# Returns the alpha component (opacity) of a color. This is 1 unless
-
# otherwise specified.
-
#
-
# This function also supports the proprietary Microsoft `alpha(opacity=20)`
-
# syntax as a special case.
-
#
-
# @overload alpha($color)
-
# @param $color [Color]
-
# @return [Number] The alpha component, between 0 and 1
-
# @raise [ArgumentError] if `$color` isn't a color
-
2
def alpha(*args)
-
33
if args.all? do |a|
-
33
a.is_a?(Sass::Script::String) && a.type == :identifier &&
-
a.value =~ /^[a-zA-Z]+\s*=/
-
end
-
# Support the proprietary MS alpha() function
-
66
return Sass::Script::String.new("alpha(#{args.map {|a| a.to_s}.join(", ")})")
-
end
-
-
raise ArgumentError.new("wrong number of arguments (#{args.size} for 1)") if args.size != 1
-
-
assert_type args.first, :Color, :color
-
Sass::Script::Number.new(args.first.alpha)
-
end
-
2
declare :alpha, [:color]
-
-
# Returns the alpha component (opacity) of a color. This is 1 unless
-
# otherwise specified.
-
#
-
# @overload opacity($color)
-
# @param $color [Color]
-
# @return [Number] The alpha component, between 0 and 1
-
# @raise [ArgumentError] if `$color` isn't a color
-
2
def opacity(color)
-
return Sass::Script::String.new("opacity(#{color})") if color.is_a?(Sass::Script::Number)
-
assert_type color, :Color, :color
-
Sass::Script::Number.new(color.alpha)
-
end
-
2
declare :opacity, [:color]
-
-
# Makes a color more opaque. Takes a color and a number between 0 and 1, and
-
# returns a color with the opacity increased by that amount.
-
#
-
# @see #transparentize
-
# @example
-
# opacify(rgba(0, 0, 0, 0.5), 0.1) => rgba(0, 0, 0, 0.6)
-
# opacify(rgba(0, 0, 17, 0.8), 0.2) => #001
-
# @overload opacify($color, $amount)
-
# @param $color [Color]
-
# @param $amount [Number] The amount to increase the opacity by, between 0
-
# and 1
-
# @return [Color]
-
# @raise [ArgumentError] if `$amount` is out of bounds, or either parameter
-
# is the wrong type
-
2
def opacify(color, amount)
-
_adjust(color, amount, :alpha, 0..1, :+)
-
end
-
2
declare :opacify, [:color, :amount]
-
-
2
alias_method :fade_in, :opacify
-
2
declare :fade_in, [:color, :amount]
-
-
# Makes a color more transparent. Takes a color and a number between 0 and
-
# 1, and returns a color with the opacity decreased by that amount.
-
#
-
# @see #opacify
-
# @example
-
# transparentize(rgba(0, 0, 0, 0.5), 0.1) => rgba(0, 0, 0, 0.4)
-
# transparentize(rgba(0, 0, 0, 0.8), 0.2) => rgba(0, 0, 0, 0.6)
-
# @overload transparentize($color, $amount)
-
# @param $color [Color]
-
# @param $amount [Number] The amount to decrease the opacity by, between 0
-
# and 1
-
# @return [Color]
-
# @raise [ArgumentError] if `$amount` is out of bounds, or either parameter
-
# is the wrong type
-
2
def transparentize(color, amount)
-
_adjust(color, amount, :alpha, 0..1, :-)
-
end
-
2
declare :transparentize, [:color, :amount]
-
-
2
alias_method :fade_out, :transparentize
-
2
declare :fade_out, [:color, :amount]
-
-
# Makes a color lighter. Takes a color and a number between `0%` and `100%`,
-
# and returns a color with the lightness increased by that amount.
-
#
-
# @see #darken
-
# @example
-
# lighten(hsl(0, 0%, 0%), 30%) => hsl(0, 0, 30)
-
# lighten(#800, 20%) => #e00
-
# @overload lighten($color, $amount)
-
# @param $color [Color]
-
# @param $amount [Number] The amount to increase the lightness by, between
-
# `0%` and `100%`
-
# @return [Color]
-
# @raise [ArgumentError] if `$amount` is out of bounds, or either parameter
-
# is the wrong type
-
2
def lighten(color, amount)
-
_adjust(color, amount, :lightness, 0..100, :+, "%")
-
end
-
2
declare :lighten, [:color, :amount]
-
-
# Makes a color darker. Takes a color and a number between 0% and 100%, and
-
# returns a color with the lightness decreased by that amount.
-
#
-
# @see #lighten
-
# @example
-
# darken(hsl(25, 100%, 80%), 30%) => hsl(25, 100%, 50%)
-
# darken(#800, 20%) => #200
-
# @overload darken($color, $amount)
-
# @param $color [Color]
-
# @param $amount [Number] The amount to dencrease the lightness by, between
-
# `0%` and `100%`
-
# @return [Color]
-
# @raise [ArgumentError] if `$amount` is out of bounds, or either parameter
-
# is the wrong type
-
2
def darken(color, amount)
-
_adjust(color, amount, :lightness, 0..100, :-, "%")
-
end
-
2
declare :darken, [:color, :amount]
-
-
# Makes a color more saturated. Takes a color and a number between 0% and
-
# 100%, and returns a color with the saturation increased by that amount.
-
#
-
# @see #desaturate
-
# @example
-
# saturate(hsl(120, 30%, 90%), 20%) => hsl(120, 50%, 90%)
-
# saturate(#855, 20%) => #9e3f3f
-
# @overload saturate($color, $amount)
-
# @param $color [Color]
-
# @param $amount [Number] The amount to increase the saturation by, between
-
# `0%` and `100%`
-
# @return [Color]
-
# @raise [ArgumentError] if `$amount` is out of bounds, or either parameter
-
# is the wrong type
-
2
def saturate(color, amount = nil)
-
# Support the filter effects definition of saturate.
-
# https://dvcs.w3.org/hg/FXTF/raw-file/tip/filters/index.html
-
return Sass::Script::String.new("saturate(#{color})") if amount.nil?
-
_adjust(color, amount, :saturation, 0..100, :+, "%")
-
end
-
2
declare :saturate, [:color, :amount]
-
2
declare :saturate, [:amount]
-
-
# Makes a color less saturated. Takes a color and a number between 0% and
-
# 100%, and returns a color with the saturation decreased by that value.
-
#
-
# @see #saturate
-
# @example
-
# desaturate(hsl(120, 30%, 90%), 20%) => hsl(120, 10%, 90%)
-
# desaturate(#855, 20%) => #726b6b
-
# @overload desaturate($color, $amount)
-
# @param $color [Color]
-
# @param $amount [Number] The amount to decrease the saturation by, between
-
# `0%` and `100%`
-
# @return [Color]
-
# @raise [ArgumentError] if `$amount` is out of bounds, or either parameter
-
# is the wrong type
-
2
def desaturate(color, amount)
-
_adjust(color, amount, :saturation, 0..100, :-, "%")
-
end
-
2
declare :desaturate, [:color, :amount]
-
-
# Changes the hue of a color. Takes a color and a number of degrees (usually
-
# between `-360deg` and `360deg`), and returns a color with the hue rotated
-
# along the color wheel by that amount.
-
#
-
# @example
-
# adjust-hue(hsl(120, 30%, 90%), 60deg) => hsl(180, 30%, 90%)
-
# adjust-hue(hsl(120, 30%, 90%), 060deg) => hsl(60, 30%, 90%)
-
# adjust-hue(#811, 45deg) => #886a11
-
# @overload adjust_hue($color, $degrees)
-
# @param $color [Color]
-
# @param $degrees [Number] The number of degrees to rotate the hue
-
# @return [Color]
-
# @raise [ArgumentError] if either parameter is the wrong type
-
2
def adjust_hue(color, degrees)
-
assert_type color, :Color, :color
-
assert_type degrees, :Number, :degrees
-
color.with(:hue => color.hue + degrees.value)
-
end
-
2
declare :adjust_hue, [:color, :degrees]
-
-
# Converts a color into the format understood by IE filters.
-
#
-
# @example
-
# ie-hex-str(#abc) => #FFAABBCC
-
# ie-hex-str(#3322BB) => #FF3322BB
-
# ie-hex-str(rgba(0, 255, 0, 0.5)) => #8000FF00
-
# @overload ie_hex_str($color)
-
# @param $color [Color]
-
# @return [String] The IE-formatted string representation of the color
-
# @raise [ArgumentError] if `$color` isn't a color
-
2
def ie_hex_str(color)
-
assert_type color, :Color, :color
-
alpha = (color.alpha * 255).round.to_s(16).rjust(2, '0')
-
Sass::Script::String.new("##{alpha}#{color.send(:hex_str)[1..-1]}".upcase)
-
end
-
2
declare :ie_hex_str, [:color]
-
-
# Increases or decreases one or more properties of a color. This can change
-
# the red, green, blue, hue, saturation, value, and alpha properties. The
-
# properties are specified as keyword arguments, and are added to or
-
# subtracted from the color's current value for that property.
-
#
-
# All properties are optional. You can't specify both RGB properties
-
# (`$red`, `$green`, `$blue`) and HSL properties (`$hue`, `$saturation`,
-
# `$value`) at the same time.
-
#
-
# @example
-
# adjust-color(#102030, $blue: 5) => #102035
-
# adjust-color(#102030, $red: -5, $blue: 5) => #0b2035
-
# adjust-color(hsl(25, 100%, 80%), $lightness: -30%, $alpha: -0.4) => hsla(25, 100%, 50%, 0.6)
-
# @overload adjust_color($color, [$red], [$green], [$blue], [$hue], [$saturation], [$lightness], [$alpha])
-
# @param $color [Color]
-
# @param $red [Number] The adjustment to make on the red component, between
-
# -255 and 255 inclusive
-
# @param $green [Number] The adjustment to make on the green component,
-
# between -255 and 255 inclusive
-
# @param $blue [Number] The adjustment to make on the blue component, between
-
# -255 and 255 inclusive
-
# @param $hue [Number] The adjustment to make on the hue component, in
-
# degrees
-
# @param $saturation [Number] The adjustment to make on the saturation
-
# component, between `-100%` and `100%` inclusive
-
# @param $lightness [Number] The adjustment to make on the lightness
-
# component, between `-100%` and `100%` inclusive
-
# @param $alpha [Number] The adjustment to make on the alpha component,
-
# between -1 and 1 inclusive
-
# @return [Color]
-
# @raise [ArgumentError] if any parameter is the wrong type or out-of
-
# bounds, or if RGB properties and HSL properties are adjusted at the
-
# same time
-
2
def adjust_color(color, kwargs)
-
assert_type color, :Color, :color
-
with = Sass::Util.map_hash({
-
"red" => [-255..255, ""],
-
"green" => [-255..255, ""],
-
"blue" => [-255..255, ""],
-
"hue" => nil,
-
"saturation" => [-100..100, "%"],
-
"lightness" => [-100..100, "%"],
-
"alpha" => [-1..1, ""]
-
}) do |name, (range, units)|
-
-
next unless val = kwargs.delete(name)
-
assert_type val, :Number, name
-
Sass::Util.check_range("$#{name}: Amount", range, val, units) if range
-
adjusted = color.send(name) + val.value
-
adjusted = [0, Sass::Util.restrict(adjusted, range)].max if range
-
[name.to_sym, adjusted]
-
end
-
-
unless kwargs.empty?
-
name, val = kwargs.to_a.first
-
raise ArgumentError.new("Unknown argument $#{name} (#{val})")
-
end
-
-
color.with(with)
-
end
-
2
declare :adjust_color, [:color], :var_kwargs => true
-
-
# Fluidly scales one or more properties of a color. Unlike
-
# \{#adjust_color adjust-color}, which changes a color's properties by fixed
-
# amounts, \{#scale_color scale-color} fluidly changes them based on how
-
# high or low they already are. That means that lightening an already-light
-
# color with \{#scale_color scale-color} won't change the lightness much,
-
# but lightening a dark color by the same amount will change it more
-
# dramatically. This has the benefit of making `scale-color($color, ...)`
-
# have a similar effect regardless of what `$color` is.
-
#
-
# For example, the lightness of a color can be anywhere between `0%` and
-
# `100%`. If `scale-color($color, $lightness: 40%)` is called, the resulting
-
# color's lightness will be 40% of the way between its original lightness
-
# and 100. If `scale-color($color, $lightness: -40%)` is called instead, the
-
# lightness will be 40% of the way between the original and 0.
-
#
-
# This can change the red, green, blue, saturation, value, and alpha
-
# properties. The properties are specified as keyword arguments. All
-
# arguments should be percentages between `0%` and `100%`.
-
#
-
# All properties are optional. You can't specify both RGB properties
-
# (`$red`, `$green`, `$blue`) and HSL properties (`$saturation`, `$value`)
-
# at the same time.
-
#
-
# @example
-
# scale-color(hsl(120, 70%, 80%), $lightness: 50%) => hsl(120, 70%, 90%)
-
# scale-color(rgb(200, 150%, 170%), $green: -40%, $blue: 70%) => rgb(200, 90, 229)
-
# scale-color(hsl(200, 70%, 80%), $saturation: -90%, $alpha: -30%) => hsla(200, 7%, 80%, 0.7)
-
# @overload scale_color($color, [$red], [$green], [$blue], [$saturation], [$lightness], [$alpha])
-
# @param $color [Color]
-
# @param $red [Number]
-
# @param $green [Number]
-
# @param $blue [Number]
-
# @param $saturation [Number]
-
# @param $lightness [Number]
-
# @param $alpha [Number]
-
# @return [Color]
-
# @raise [ArgumentError] if any parameter is the wrong type or out-of
-
# bounds, or if RGB properties and HSL properties are adjusted at the
-
# same time
-
2
def scale_color(color, kwargs)
-
assert_type color, :Color, :color
-
with = Sass::Util.map_hash({
-
"red" => 255,
-
"green" => 255,
-
"blue" => 255,
-
"saturation" => 100,
-
"lightness" => 100,
-
"alpha" => 1
-
}) do |name, max|
-
-
next unless val = kwargs.delete(name)
-
assert_type val, :Number, name
-
if !(val.numerator_units == ['%'] && val.denominator_units.empty?)
-
raise ArgumentError.new("$#{name}: Amount #{val} must be a % (e.g. #{val.value}%)")
-
else
-
Sass::Util.check_range("$#{name}: Amount", -100..100, val, '%')
-
end
-
-
current = color.send(name)
-
scale = val.value/100.0
-
diff = scale > 0 ? max - current : current
-
[name.to_sym, current + diff*scale]
-
end
-
-
unless kwargs.empty?
-
name, val = kwargs.to_a.first
-
raise ArgumentError.new("Unknown argument $#{name} (#{val})")
-
end
-
-
color.with(with)
-
end
-
2
declare :scale_color, [:color], :var_kwargs => true
-
-
# Changes one or more properties of a color. This can change the red, green,
-
# blue, hue, saturation, value, and alpha properties. The properties are
-
# specified as keyword arguments, and replace the color's current value for
-
# that property.
-
#
-
# All properties are optional. You can't specify both RGB properties
-
# (`$red`, `$green`, `$blue`) and HSL properties (`$hue`, `$saturation`,
-
# `$value`) at the same time.
-
#
-
# @example
-
# change-color(#102030, $blue: 5) => #102005
-
# change-color(#102030, $red: 120, $blue: 5) => #782005
-
# change-color(hsl(25, 100%, 80%), $lightness: 40%, $alpha: 0.8) => hsla(25, 100%, 40%, 0.8)
-
# @overload change_color($color, [$red], [$green], [$blue], [$hue], [$saturation], [$lightness], [$alpha])
-
# @param $color [Color]
-
# @param $red [Number] The new red component for the color, within 0 and 255
-
# inclusive
-
# @param $green [Number] The new green component for the color, within 0 and
-
# 255 inclusive
-
# @param $blue [Number] The new blue component for the color, within 0 and
-
# 255 inclusive
-
# @param $hue [Number] The new hue component for the color, in degrees
-
# @param $saturation [Number] The new saturation component for the color,
-
# between `0%` and `100%` inclusive
-
# @param $lightness [Number] The new lightness component for the color,
-
# within `0%` and `100%` inclusive
-
# @param $alpha [Number] The new alpha component for the color, within 0 and
-
# 1 inclusive
-
# @return [Color]
-
# @raise [ArgumentError] if any parameter is the wrong type or out-of
-
# bounds, or if RGB properties and HSL properties are adjusted at the
-
# same time
-
2
def change_color(color, kwargs)
-
assert_type color, :Color, :color
-
with = Sass::Util.map_hash(%w[red green blue hue saturation lightness alpha]) do |name, max|
-
next unless val = kwargs.delete(name)
-
assert_type val, :Number, name
-
[name.to_sym, val.value]
-
end
-
-
unless kwargs.empty?
-
name, val = kwargs.to_a.first
-
raise ArgumentError.new("Unknown argument $#{name} (#{val})")
-
end
-
-
color.with(with)
-
end
-
2
declare :change_color, [:color], :var_kwargs => true
-
-
# Mixes two colors together. Specifically, takes the average of each of the
-
# RGB components, optionally weighted by the given percentage. The opacity
-
# of the colors is also considered when weighting the components.
-
#
-
# The weight specifies the amount of the first color that should be included
-
# in the returned color. The default, `50%`, means that half the first color
-
# and half the second color should be used. `25%` means that a quarter of
-
# the first color and three quarters of the second color should be used.
-
#
-
# @example
-
# mix(#f00, #00f) => #7f007f
-
# mix(#f00, #00f, 25%) => #3f00bf
-
# mix(rgba(255, 0, 0, 0.5), #00f) => rgba(63, 0, 191, 0.75)
-
# @overload mix($color-1, $color-2, $weight: 50%)
-
# @param $color-1 [Color]
-
# @param $color-2 [Color]
-
# @param $weight [Number] The relative weight of each color. Closer to `0%`
-
# gives more weight to `$color`, closer to `100%` gives more weight to
-
# `$color2`
-
# @return [Color]
-
# @raise [ArgumentError] if `$weight` is out of bounds or any parameter is
-
# the wrong type
-
2
def mix(color_1, color_2, weight = Number.new(50))
-
assert_type color_1, :Color, :color_1
-
assert_type color_2, :Color, :color_2
-
assert_type weight, :Number, :weight
-
-
Sass::Util.check_range("Weight", 0..100, weight, '%')
-
-
# This algorithm factors in both the user-provided weight (w) and the
-
# difference between the alpha values of the two colors (a) to decide how
-
# to perform the weighted average of the two RGB values.
-
#
-
# It works by first normalizing both parameters to be within [-1, 1],
-
# where 1 indicates "only use color_1", -1 indicates "only use color_2", and
-
# all values in between indicated a proportionately weighted average.
-
#
-
# Once we have the normalized variables w and a, we apply the formula
-
# (w + a)/(1 + w*a) to get the combined weight (in [-1, 1]) of color_1.
-
# This formula has two especially nice properties:
-
#
-
# * When either w or a are -1 or 1, the combined weight is also that number
-
# (cases where w * a == -1 are undefined, and handled as a special case).
-
#
-
# * When a is 0, the combined weight is w, and vice versa.
-
#
-
# Finally, the weight of color_1 is renormalized to be within [0, 1]
-
# and the weight of color_2 is given by 1 minus the weight of color_1.
-
p = (weight.value/100.0).to_f
-
w = p*2 - 1
-
a = color_1.alpha - color_2.alpha
-
-
w1 = (((w * a == -1) ? w : (w + a)/(1 + w*a)) + 1)/2.0
-
w2 = 1 - w1
-
-
rgb = color_1.rgb.zip(color_2.rgb).map {|v1, v2| v1*w1 + v2*w2}
-
alpha = color_1.alpha*p + color_2.alpha*(1-p)
-
Color.new(rgb + [alpha])
-
end
-
2
declare :mix, [:color_1, :color_2]
-
2
declare :mix, [:color_1, :color_2, :weight]
-
-
# Converts a color to grayscale. This is identical to `desaturate(color,
-
# 100%)`.
-
#
-
# @see #desaturate
-
# @overload grayscale($color)
-
# @param $color [Color]
-
# @return [Color]
-
# @raise [ArgumentError] if `$color` isn't a color
-
2
def grayscale(color)
-
return Sass::Script::String.new("grayscale(#{color})") if color.is_a?(Sass::Script::Number)
-
desaturate color, Number.new(100)
-
end
-
2
declare :grayscale, [:color]
-
-
# Returns the complement of a color. This is identical to `adjust-hue(color,
-
# 180deg)`.
-
#
-
# @see #adjust_hue #adjust-hue
-
# @overload complement($color)
-
# @param $color [Color]
-
# @return [Color]
-
# @raise [ArgumentError] if `$color` isn't a color
-
2
def complement(color)
-
adjust_hue color, Number.new(180)
-
end
-
2
declare :complement, [:color]
-
-
# Returns the inverse (negative) of a color. The red, green, and blue values
-
# are inverted, while the opacity is left alone.
-
#
-
# @overload invert($color)
-
# @param $color [Color]
-
# @return [Color]
-
# @raise [ArgumentError] if `$color` isn't a color
-
2
def invert(color)
-
return Sass::Script::String.new("invert(#{color})") if color.is_a?(Sass::Script::Number)
-
-
assert_type color, :Color, :color
-
color.with(
-
:red => (255 - color.red),
-
:green => (255 - color.green),
-
:blue => (255 - color.blue))
-
end
-
2
declare :invert, [:color]
-
-
# Removes quotes from a string. If the string is already unquoted, this will
-
# return it unmodified.
-
#
-
# @see #quote
-
# @example
-
# unquote("foo") => foo
-
# unquote(foo) => foo
-
# @overload unquote($string)
-
# @param $string [String]
-
# @return [String]
-
# @raise [ArgumentError] if `$string` isn't a string
-
2
def unquote(string)
-
if string.is_a?(Sass::Script::String)
-
Sass::Script::String.new(string.value, :identifier)
-
else
-
string
-
end
-
end
-
2
declare :unquote, [:string]
-
-
# Add quotes to a string if the string isn't quoted,
-
# or returns the same string if it is.
-
#
-
# @see #unquote
-
# @example
-
# quote("foo") => "foo"
-
# quote(foo) => "foo"
-
# @overload quote($string)
-
# @param $string [String]
-
# @return [String]
-
# @raise [ArgumentError] if `$string` isn't a string
-
2
def quote(string)
-
assert_type string, :String, :string
-
Sass::Script::String.new(string.value, :string)
-
end
-
2
declare :quote, [:string]
-
-
# Returns the type of a value.
-
#
-
# @example
-
# type-of(100px) => number
-
# type-of(asdf) => string
-
# type-of("asdf") => string
-
# type-of(true) => bool
-
# type-of(#fff) => color
-
# type-of(blue) => color
-
# @overload type_of($value)
-
# @param $value [Literal] The value to inspect
-
# @return [String] The unquoted string name of the value's type
-
2
def type_of(value)
-
Sass::Script::String.new(value.class.name.gsub(/Sass::Script::/,'').downcase)
-
end
-
2
declare :type_of, [:value]
-
-
# Returns the unit(s) associated with a number. Complex units are sorted in
-
# alphabetical order by numerator and denominator.
-
#
-
# @example
-
# unit(100) => ""
-
# unit(100px) => "px"
-
# unit(3em) => "em"
-
# unit(10px * 5em) => "em*px"
-
# unit(10px * 5em / 30cm / 1rem) => "em*px/cm*rem"
-
# @overload unit($number)
-
# @param $number [Number]
-
# @return [String] The unit(s) of the number, as a quoted string
-
# @raise [ArgumentError] if `$number` isn't a number
-
2
def unit(number)
-
assert_type number, :Number, :number
-
Sass::Script::String.new(number.unit_str, :string)
-
end
-
2
declare :unit, [:number]
-
-
# Returns whether a number has units.
-
#
-
# @example
-
# unitless(100) => true
-
# unitless(100px) => false
-
# @overload unitless($number)
-
# @param $number [Number]
-
# @return [Bool]
-
# @raise [ArgumentError] if `$number` isn't a number
-
2
def unitless(number)
-
assert_type number, :Number, :number
-
Sass::Script::Bool.new(number.unitless?)
-
end
-
2
declare :unitless, [:number]
-
-
# Returns whether two numbers can added, subtracted, or compared.
-
#
-
# @example
-
# comparable(2px, 1px) => true
-
# comparable(100px, 3em) => false
-
# comparable(10cm, 3mm) => true
-
# @overload comparable($number-1, $number-2)
-
# @param $number-1 [Number]
-
# @param $number-2 [Number]
-
# @return [Bool]
-
# @raise [ArgumentError] if either parameter is the wrong type
-
2
def comparable(number_1, number_2)
-
assert_type number_1, :Number, :number_1
-
assert_type number_2, :Number, :number_2
-
Sass::Script::Bool.new(number_1.comparable_to?(number_2))
-
end
-
2
declare :comparable, [:number_1, :number_2]
-
-
# Converts a unitless number to a percentage.
-
#
-
# @example
-
# percentage(0.2) => 20%
-
# percentage(100px / 50px) => 200%
-
# @overload percentage($value)
-
# @param $value [Number]
-
# @return [Number]
-
# @raise [ArgumentError] if `$value` isn't a unitless number
-
2
def percentage(value)
-
unless value.is_a?(Sass::Script::Number) && value.unitless?
-
raise ArgumentError.new("$value: #{value.inspect} is not a unitless number")
-
end
-
Sass::Script::Number.new(value.value * 100, ['%'])
-
end
-
2
declare :percentage, [:value]
-
-
# Rounds a number to the nearest whole number.
-
#
-
# @example
-
# round(10.4px) => 10px
-
# round(10.6px) => 11px
-
# @overload round($value)
-
# @param $value [Number]
-
# @return [Number]
-
# @raise [ArgumentError] if `$value` isn't a number
-
2
def round(value)
-
numeric_transformation(value) {|n| n.round}
-
end
-
2
declare :round, [:value]
-
-
# Rounds a number up to the next whole number.
-
#
-
# @example
-
# ceil(10.4px) => 11px
-
# ceil(10.6px) => 11px
-
# @overload ceil($value)
-
# @param $value [Number]
-
# @return [Number]
-
# @raise [ArgumentError] if `$value` isn't a number
-
2
def ceil(value)
-
numeric_transformation(value) {|n| n.ceil}
-
end
-
2
declare :ceil, [:value]
-
-
# Rounds a number down to the previous whole number.
-
#
-
# @example
-
# floor(10.4px) => 10px
-
# floor(10.6px) => 10px
-
# @overload floor($value)
-
# @param $value [Number]
-
# @return [Number]
-
# @raise [ArgumentError] if `$value` isn't a number
-
2
def floor(value)
-
numeric_transformation(value) {|n| n.floor}
-
end
-
2
declare :floor, [:value]
-
-
# Returns the absolute value of a number.
-
#
-
# @example
-
# abs(10px) => 10px
-
# abs(-10px) => 10px
-
# @overload abs($value)
-
# @param $value [Number]
-
# @return [Number]
-
# @raise [ArgumentError] if `$value` isn't a number
-
2
def abs(value)
-
numeric_transformation(value) {|n| n.abs}
-
end
-
2
declare :abs, [:value]
-
-
# Finds the minimum of several numbers. This function takes any number of
-
# arguments.
-
#
-
# @example
-
# min(1px, 4px) => 1px
-
# min(5em, 3em, 4em) => 3em
-
# @overload min($numbers...)
-
# @param $numbers [[Number]]
-
# @return [Number]
-
# @raise [ArgumentError] if any argument isn't a number, or if not all of
-
# the arguments have comparable units
-
2
def min(*numbers)
-
numbers.each {|n| assert_type n, :Number}
-
numbers.inject {|min, num| min.lt(num).to_bool ? min : num}
-
end
-
2
declare :min, [], :var_args => :true
-
-
# Finds the maximum of several numbers. This function takes any number of
-
# arguments.
-
#
-
# @example
-
# max(1px, 4px) => 4px
-
# max(5em, 3em, 4em) => 5em
-
# @overload max($numbers...)
-
# @param $numbers [[Number]]
-
# @return [Number]
-
# @raise [ArgumentError] if any argument isn't a number, or if not all of
-
# the arguments have comparable units
-
2
def max(*values)
-
values.each {|v| assert_type v, :Number}
-
values.inject {|max, val| max.gt(val).to_bool ? max : val}
-
end
-
2
declare :max, [], :var_args => :true
-
-
# Return the length of a list.
-
#
-
# @example
-
# length(10px) => 1
-
# length(10px 20px 30px) => 3
-
# @overload length($list)
-
# @param $list [Literal]
-
# @return [Number]
-
2
def length(list)
-
Sass::Script::Number.new(list.to_a.size)
-
end
-
2
declare :length, [:list]
-
-
# Gets the nth item in a list.
-
#
-
# Note that unlike some languages, the first item in a Sass list is number
-
# 1, the second number 2, and so forth.
-
#
-
# @example
-
# nth(10px 20px 30px, 1) => 10px
-
# nth((Helvetica, Arial, sans-serif), 3) => sans-serif
-
# @overload nth($list, $n)
-
# @param $list [Literal]
-
# @param $n [Number] The index of the item to get
-
# @return [Literal]
-
# @raise [ArgumentError] if `$n` isn't an integer between 1 and the length
-
# of `$list`
-
2
def nth(list, n)
-
assert_type n, :Number, :n
-
if !n.int?
-
raise ArgumentError.new("List index #{n} must be an integer")
-
elsif n.to_i < 1
-
raise ArgumentError.new("List index #{n} must be greater than or equal to 1")
-
elsif list.to_a.size == 0
-
raise ArgumentError.new("List index is #{n} but list has no items")
-
elsif n.to_i > (size = list.to_a.size)
-
raise ArgumentError.new("List index is #{n} but list is only #{size} item#{'s' if size != 1} long")
-
end
-
-
list.to_a[n.to_i - 1]
-
end
-
2
declare :nth, [:list, :n]
-
-
# Joins together two lists into one.
-
#
-
# Unless `$separator` is passed, if one list is comma-separated and one is
-
# space-separated, the first parameter's separator is used for the resulting
-
# list. If both lists have fewer than two items, spaces are used for the
-
# resulting list.
-
#
-
# @example
-
# join(10px 20px, 30px 40px) => 10px 20px 30px 40px
-
# join((blue, red), (#abc, #def)) => blue, red, #abc, #def
-
# join(10px, 20px) => 10px 20px
-
# join(10px, 20px, comma) => 10px, 20px
-
# join((blue, red), (#abc, #def), space) => blue red #abc #def
-
# @overload join($list1, $list2, $separator: auto)
-
# @param $list1 [Literal]
-
# @param $list2 [Literal]
-
# @param $separator [String] The list separator to use. If this is `comma`
-
# or `space`, that separator will be used. If this is `auto` (the
-
# default), the separator is determined as explained above.
-
# @return [List]
-
2
def join(list1, list2, separator = Sass::Script::String.new("auto"))
-
assert_type separator, :String, :separator
-
unless %w[auto space comma].include?(separator.value)
-
raise ArgumentError.new("Separator name must be space, comma, or auto")
-
end
-
sep1 = list1.separator if list1.is_a?(Sass::Script::List) && !list1.value.empty?
-
sep2 = list2.separator if list2.is_a?(Sass::Script::List) && !list2.value.empty?
-
Sass::Script::List.new(
-
list1.to_a + list2.to_a,
-
if separator.value == 'auto'
-
sep1 || sep2 || :space
-
else
-
separator.value.to_sym
-
end)
-
end
-
2
declare :join, [:list1, :list2]
-
2
declare :join, [:list1, :list2, :separator]
-
-
# Appends a single value onto the end of a list.
-
#
-
# Unless the `$separator` argument is passed, if the list had only one item,
-
# the resulting list will be space-separated.
-
#
-
# @example
-
# append(10px 20px, 30px) => 10px 20px 30px
-
# append((blue, red), green) => blue, red, green
-
# append(10px 20px, 30px 40px) => 10px 20px (30px 40px)
-
# append(10px, 20px, comma) => 10px, 20px
-
# append((blue, red), green, space) => blue red green
-
# @overload append($list, $val, $separator: auto)
-
# @param $list [Literal]
-
# @param $val [Literal]
-
# @param $separator [String] The list separator to use. If this is `comma`
-
# or `space`, that separator will be used. If this is `auto` (the
-
# default), the separator is determined as explained above.
-
# @return [List]
-
2
def append(list, val, separator = Sass::Script::String.new("auto"))
-
assert_type separator, :String, :separator
-
unless %w[auto space comma].include?(separator.value)
-
raise ArgumentError.new("Separator name must be space, comma, or auto")
-
end
-
sep = list.separator if list.is_a?(Sass::Script::List)
-
Sass::Script::List.new(
-
list.to_a + [val],
-
if separator.value == 'auto'
-
sep || :space
-
else
-
separator.value.to_sym
-
end)
-
end
-
2
declare :append, [:list, :val]
-
2
declare :append, [:list, :val, :separator]
-
-
# Combines several lists into a single multidimensional list. The nth value
-
# of the resulting list is a space separated list of the source lists' nth
-
# values.
-
#
-
# The length of the resulting list is the length of the
-
# shortest list.
-
#
-
# @example
-
# zip(1px 1px 3px, solid dashed solid, red green blue)
-
# => 1px solid red, 1px dashed green, 3px solid blue
-
# @overload zip($lists...)
-
# @param $lists [[Literal]]
-
# @return [List]
-
2
def zip(*lists)
-
length = nil
-
values = []
-
lists.each do |list|
-
array = list.to_a
-
values << array.dup
-
length = length.nil? ? array.length : [length, array.length].min
-
end
-
values.each do |value|
-
value.slice!(length)
-
end
-
new_list_value = values.first.zip(*values[1..-1])
-
List.new(new_list_value.map{|list| List.new(list, :space)}, :comma)
-
end
-
2
declare :zip, [], :var_args => true
-
-
-
# Returns the position of a value within a list. If the value isn't found,
-
# returns false instead.
-
#
-
# Note that unlike some languages, the first item in a Sass list is number
-
# 1, the second number 2, and so forth.
-
#
-
# @example
-
# index(1px solid red, solid) => 2
-
# index(1px solid red, dashed) => false
-
# @overload index($list, $value)
-
# @param $list [Literal]
-
# @param $value [Literal]
-
# @return [Number, Bool] The 1-based index of `$value` in `$list`, or
-
# `false`
-
2
def index(list, value)
-
index = list.to_a.index {|e| e.eq(value).to_bool }
-
if index
-
Number.new(index + 1)
-
else
-
Bool.new(false)
-
end
-
end
-
2
declare :index, [:list, :value]
-
-
# Returns one of two values, depending on whether or not `$condition` is
-
# true. Just like in `@if`, all values other than `false` and `null` are
-
# considered to be true.
-
#
-
# @example
-
# if(true, 1px, 2px) => 1px
-
# if(false, 1px, 2px) => 2px
-
# @overload if($condition, $if-true, $if-false)
-
# @param $condition [Literal] Whether the `$if-true` or `$if-false` will be
-
# returned
-
# @param $if-true [Literal]
-
# @param $if-false [Literal]
-
# @return [Literal] `$if-true` or `$if-false`
-
2
def if(condition, if_true, if_false)
-
if condition.to_bool
-
if_true
-
else
-
if_false
-
end
-
end
-
2
declare :if, [:condition, :if_true, :if_false]
-
-
# This function only exists as a workaround for IE7's [`content: counter`
-
# bug][bug]. It works identically to any other plain-CSS function, except it
-
# avoids adding spaces between the argument commas.
-
#
-
# [bug]: http://jes.st/2013/ie7s-css-breaking-content-counter-bug/
-
#
-
# @example
-
# counter(item, ".") => counter(item,".")
-
# @overload counter($args...)
-
# @return [String]
-
2
def counter(*args)
-
Sass::Script::String.new("counter(#{args.map {|a| a.to_s(options)}.join(',')})")
-
end
-
2
declare :counter, [], :var_args => true
-
-
# This function only exists as a workaround for IE7's [`content: counters`
-
# bug][bug]. It works identically to any other plain-CSS function, except it
-
# avoids adding spaces between the argument commas.
-
#
-
# [bug]: http://jes.st/2013/ie7s-css-breaking-content-counter-bug/
-
#
-
# @example
-
# counters(item, ".") => counters(item,".")
-
# @overload counters($args...)
-
# @return [String]
-
2
def counters(*args)
-
Sass::Script::String.new("counters(#{args.map {|a| a.to_s(options)}.join(',')})")
-
end
-
2
declare :counters, [], :var_args => true
-
-
2
private
-
-
# This method implements the pattern of transforming a numeric value into
-
# another numeric value with the same units.
-
# It yields a number to a block to perform the operation and return a number
-
2
def numeric_transformation(value)
-
assert_type value, :Number, :value
-
Sass::Script::Number.new(yield(value.value), value.numerator_units, value.denominator_units)
-
end
-
-
2
def _adjust(color, amount, attr, range, op, units = "")
-
assert_type color, :Color, :color
-
assert_type amount, :Number, :amount
-
Sass::Util.check_range('Amount', range, amount, units)
-
-
# TODO: is it worth restricting here,
-
# or should we do so in the Color constructor itself,
-
# and allow clipping in rgb() et al?
-
color.with(attr => Sass::Util.restrict(
-
color.send(attr).send(op, amount.value), range))
-
end
-
end
-
end
-
2
module Sass::Script
-
# A SassScript object representing `#{}` interpolation outside a string.
-
#
-
# @see StringInterpolation
-
2
class Interpolation < Node
-
# Interpolation in a property is of the form `before #{mid} after`.
-
#
-
# @param before [Node] The SassScript before the interpolation
-
# @param mid [Node] The SassScript within the interpolation
-
# @param after [Node] The SassScript after the interpolation
-
# @param wb [Boolean] Whether there was whitespace between `before` and `#{`
-
# @param wa [Boolean] Whether there was whitespace between `}` and `after`
-
# @param originally_text [Boolean]
-
# Whether the original format of the interpolation was plain text,
-
# not an interpolation.
-
# This is used when converting back to SassScript.
-
2
def initialize(before, mid, after, wb, wa, originally_text = false)
-
@before = before
-
@mid = mid
-
@after = after
-
@whitespace_before = wb
-
@whitespace_after = wa
-
@originally_text = originally_text
-
end
-
-
# @return [String] A human-readable s-expression representation of the interpolation
-
2
def inspect
-
"(interpolation #{@before.inspect} #{@mid.inspect} #{@after.inspect})"
-
end
-
-
# @see Node#to_sass
-
2
def to_sass(opts = {})
-
res = ""
-
res << @before.to_sass(opts) if @before
-
res << ' ' if @before && @whitespace_before
-
res << '#{' unless @originally_text
-
res << @mid.to_sass(opts)
-
res << '}' unless @originally_text
-
res << ' ' if @after && @whitespace_after
-
res << @after.to_sass(opts) if @after
-
res
-
end
-
-
# Returns the three components of the interpolation, `before`, `mid`, and `after`.
-
#
-
# @return [Array<Node>]
-
# @see #initialize
-
# @see Node#children
-
2
def children
-
[@before, @mid, @after].compact
-
end
-
-
# @see Node#deep_copy
-
2
def deep_copy
-
node = dup
-
node.instance_variable_set('@before', @before.deep_copy) if @before
-
node.instance_variable_set('@mid', @mid.deep_copy)
-
node.instance_variable_set('@after', @after.deep_copy) if @after
-
node
-
end
-
-
2
protected
-
-
# Evaluates the interpolation.
-
#
-
# @param environment [Sass::Environment] The environment in which to evaluate the SassScript
-
# @return [Sass::Script::String] The SassScript string that is the value of the interpolation
-
2
def _perform(environment)
-
res = ""
-
res << @before.perform(environment).to_s if @before
-
res << " " if @before && @whitespace_before
-
val = @mid.perform(environment)
-
res << (val.is_a?(Sass::Script::String) ? val.value : val.to_s)
-
res << " " if @after && @whitespace_after
-
res << @after.perform(environment).to_s if @after
-
opts(Sass::Script::String.new(res))
-
end
-
end
-
end
-
2
require 'sass/scss/rx'
-
-
2
module Sass
-
2
module Script
-
# The lexical analyzer for SassScript.
-
# It takes a raw string and converts it to individual tokens
-
# that are easier to parse.
-
2
class Lexer
-
2
include Sass::SCSS::RX
-
-
# A struct containing information about an individual token.
-
#
-
# `type`: \[`Symbol`\]
-
# : The type of token.
-
#
-
# `value`: \[`Object`\]
-
# : The Ruby object corresponding to the value of the token.
-
#
-
# `line`: \[`Fixnum`\]
-
# : The line of the source file on which the token appears.
-
#
-
# `offset`: \[`Fixnum`\]
-
# : The number of bytes into the line the SassScript token appeared.
-
#
-
# `pos`: \[`Fixnum`\]
-
# : The scanner position at which the SassScript token appeared.
-
2
Token = Struct.new(:type, :value, :line, :offset, :pos)
-
-
# The line number of the lexer's current position.
-
#
-
# @return [Fixnum]
-
2
attr_reader :line
-
-
# The number of bytes into the current line
-
# of the lexer's current position.
-
#
-
# @return [Fixnum]
-
2
attr_reader :offset
-
-
# A hash from operator strings to the corresponding token types.
-
2
OPERATORS = {
-
'+' => :plus,
-
'-' => :minus,
-
'*' => :times,
-
'/' => :div,
-
'%' => :mod,
-
'=' => :single_eq,
-
':' => :colon,
-
'(' => :lparen,
-
')' => :rparen,
-
',' => :comma,
-
'and' => :and,
-
'or' => :or,
-
'not' => :not,
-
'==' => :eq,
-
'!=' => :neq,
-
'>=' => :gte,
-
'<=' => :lte,
-
'>' => :gt,
-
'<' => :lt,
-
'#{' => :begin_interpolation,
-
'}' => :end_interpolation,
-
';' => :semicolon,
-
'{' => :lcurly,
-
'...' => :splat,
-
}
-
-
50
OPERATORS_REVERSE = Sass::Util.map_hash(OPERATORS) {|k, v| [v, k]}
-
-
50
TOKEN_NAMES = Sass::Util.map_hash(OPERATORS_REVERSE) {|k, v| [k, v.inspect]}.merge({
-
:const => "variable (e.g. $foo)",
-
:ident => "identifier (e.g. middle)"
-
})
-
-
# A list of operator strings ordered with longer names first
-
# so that `>` and `<` don't clobber `>=` and `<=`.
-
50
OP_NAMES = OPERATORS.keys.sort_by {|o| -o.size}
-
-
# A sub-list of {OP_NAMES} that only includes operators
-
# with identifier names.
-
50
IDENT_OP_NAMES = OP_NAMES.select {|k, v| k =~ /^\w+/}
-
-
# A hash of regular expressions that are used for tokenizing.
-
2
REGULAR_EXPRESSIONS = {
-
:whitespace => /\s+/,
-
:comment => COMMENT,
-
:single_line_comment => SINGLE_LINE_COMMENT,
-
:variable => /(\$)(#{IDENT})/,
-
:ident => /(#{IDENT})(\()?/,
-
:number => /(-)?(?:(\d*\.\d+)|(\d+))([a-zA-Z%]+)?/,
-
:color => HEXCOLOR,
-
6
:ident_op => %r{(#{Regexp.union(*IDENT_OP_NAMES.map{|s| Regexp.new(Regexp.escape(s) + "(?!#{NMCHAR}|\Z)")})})},
-
:op => %r{(#{Regexp.union(*OP_NAMES)})},
-
}
-
-
2
class << self
-
2
private
-
2
def string_re(open, close)
-
8
/#{open}((?:\\.|\#(?!\{)|[^#{close}\\#])*)(#{close}|#\{)/
-
end
-
end
-
-
# A hash of regular expressions that are used for tokenizing strings.
-
#
-
# The key is a `[Symbol, Boolean]` pair.
-
# The symbol represents which style of quotation to use,
-
# while the boolean represents whether or not the string
-
# is following an interpolated segment.
-
2
STRING_REGULAR_EXPRESSIONS = {
-
:double => {
-
false => string_re('"', '"'),
-
true => string_re('', '"')
-
},
-
:single => {
-
false => string_re("'", "'"),
-
true => string_re('', "'")
-
},
-
:uri => {
-
false => /url\(#{W}(#{URLCHAR}*?)(#{W}\)|#\{)/,
-
true => /(#{URLCHAR}*?)(#{W}\)|#\{)/
-
},
-
# Defined in https://developer.mozilla.org/en/CSS/@-moz-document as a
-
# non-standard version of http://www.w3.org/TR/css3-conditional/
-
:url_prefix => {
-
false => /url-prefix\(#{W}(#{URLCHAR}*?)(#{W}\)|#\{)/,
-
true => /(#{URLCHAR}*?)(#{W}\)|#\{)/
-
},
-
:domain => {
-
false => /domain\(#{W}(#{URLCHAR}*?)(#{W}\)|#\{)/,
-
true => /(#{URLCHAR}*?)(#{W}\)|#\{)/
-
}
-
}
-
-
# @param str [String, StringScanner] The source text to lex
-
# @param line [Fixnum] The line on which the SassScript appears.
-
# Used for error reporting
-
# @param offset [Fixnum] The number of characters in on which the SassScript appears.
-
# Used for error reporting
-
# @param options [{Symbol => Object}] An options hash;
-
# see {file:SASS_REFERENCE.md#sass_options the Sass options documentation}
-
2
def initialize(str, line, offset, options)
-
2344
@scanner = str.is_a?(StringScanner) ? str : Sass::Util::MultibyteStringScanner.new(str)
-
2344
@line = line
-
2344
@offset = offset
-
2344
@options = options
-
2344
@interpolation_stack = []
-
2344
@prev = nil
-
end
-
-
# Moves the lexer forward one token.
-
#
-
# @return [Token] The token that was moved past
-
2
def next
-
14895
@tok ||= read_token
-
14895
@tok, tok = nil, @tok
-
14895
@prev = tok
-
14895
return tok
-
end
-
-
# Returns whether or not there's whitespace before the next token.
-
#
-
# @return [Boolean]
-
2
def whitespace?(tok = @tok)
-
if tok
-
@scanner.string[0...tok.pos] =~ /\s\Z/
-
else
-
@scanner.string[@scanner.pos, 1] =~ /^\s/ ||
-
@scanner.string[@scanner.pos - 1, 1] =~ /\s\Z/
-
end
-
end
-
-
# Returns the next token without moving the lexer forward.
-
#
-
# @return [Token] The next token
-
2
def peek
-
303989
@tok ||= read_token
-
end
-
-
# Rewinds the underlying StringScanner
-
# to before the token returned by \{#peek}.
-
2
def unpeek!
-
2344
@scanner.pos = @tok.pos if @tok
-
end
-
-
# @return [Boolean] Whether or not there's more source text to lex.
-
2
def done?
-
17239
whitespace unless after_interpolation? && @interpolation_stack.last
-
17239
@scanner.eos? && @tok.nil?
-
end
-
-
# @return [Boolean] Whether or not the last token lexed was `:end_interpolation`.
-
2
def after_interpolation?
-
138821
@prev && @prev.type == :end_interpolation
-
end
-
-
# Raise an error to the effect that `name` was expected in the input stream
-
# and wasn't found.
-
#
-
# This calls \{#unpeek!} to rewind the scanner to immediately after
-
# the last returned token.
-
#
-
# @param name [String] The name of the entity that was expected but not found
-
# @raise [Sass::SyntaxError]
-
2
def expected!(name)
-
unpeek!
-
Sass::SCSS::Parser.expected(@scanner, name, @line)
-
end
-
-
# Records all non-comment text the lexer consumes within the block
-
# and returns it as a string.
-
#
-
# @yield A block in which text is recorded
-
# @return [String]
-
2
def str
-
old_pos = @tok ? @tok.pos : @scanner.pos
-
yield
-
new_pos = @tok ? @tok.pos : @scanner.pos
-
@scanner.string[old_pos...new_pos]
-
end
-
-
2
private
-
-
2
def read_token
-
17239
return if done?
-
17239
return unless value = token
-
17239
type, val, size = value
-
17239
size ||= @scanner.matched_size
-
-
17239
val.line = @line if val.is_a?(Script::Node)
-
17239
Token.new(type, val, @line,
-
current_position - size, @scanner.pos - size)
-
end
-
-
2
def whitespace
-
nil while scan(REGULAR_EXPRESSIONS[:whitespace]) ||
-
scan(REGULAR_EXPRESSIONS[:comment]) ||
-
17239
scan(REGULAR_EXPRESSIONS[:single_line_comment])
-
end
-
-
2
def token
-
17239
if after_interpolation? && (interp_type = @interpolation_stack.pop)
-
return string(interp_type, true)
-
end
-
-
17239
variable || string(:double, false) || string(:single, false) || number || color ||
-
string(:uri, false) || raw(UNICODERANGE) || special_fun || special_val || ident_op ||
-
ident || op
-
end
-
-
2
def variable
-
_variable(REGULAR_EXPRESSIONS[:variable])
-
end
-
-
2
def _variable(rx)
-
17155
return unless scan(rx)
-
-
[:const, @scanner[2]]
-
end
-
-
2
def ident
-
10604
return unless scan(REGULAR_EXPRESSIONS[:ident])
-
2724
[@scanner[2] ? :funcall : :ident, @scanner[1]]
-
end
-
-
2
def string(re, open)
-
42429
return unless scan(STRING_REGULAR_EXPRESSIONS[re][open])
-
84
if @scanner[2] == '#{' #'
-
@scanner.pos -= 2 # Don't actually consume the #{
-
@interpolation_stack << re
-
end
-
84
str =
-
if re == :uri
-
26
Script::String.new("#{'url(' unless open}#{@scanner[1]}#{')' unless @scanner[2] == '#{'}")
-
else
-
58
Script::String.new(@scanner[1].gsub(/\\(['"]|\#\{)/, '\1'), :string)
-
end
-
84
[:string, str]
-
end
-
-
2
def number
-
17097
return unless scan(REGULAR_EXPRESSIONS[:number])
-
6417
value = @scanner[2] ? @scanner[2].to_f : @scanner[3].to_i
-
6417
value = -value if @scanner[1]
-
6417
[:number, Script::Number.new(value, Array(@scanner[4]))]
-
end
-
-
2
def color
-
10680
return unless s = scan(REGULAR_EXPRESSIONS[:color])
-
raise Sass::SyntaxError.new(<<MESSAGE.rstrip) unless s.size == 4 || s.size == 7
-
Colors must have either three or six digits: '#{s}'
-
30
MESSAGE
-
30
value = s.scan(/^#(..?)(..?)(..?)$/).first.
-
90
map {|num| num.ljust(2, num).to_i(16)}
-
30
[:color, Script::Color.new(value)]
-
end
-
-
2
def special_fun
-
10624
return unless str1 = scan(/((-[\w-]+-)?(calc|element)|expression|progid:[a-z\.]*)\(/i)
-
20
str2, _ = Sass::Shared.balance(@scanner, ?(, ?), 1)
-
20
c = str2.count("\n")
-
20
old_line = @line
-
20
old_offset = @offset
-
20
@line += c
-
20
@offset = (c == 0 ? @offset + str2.size : str2[/\n(.*)/, 1].size)
-
20
[:special_fun,
-
Sass::Util.merge_adjacent_strings(
-
[str1] + Sass::Engine.parse_interp(str2, old_line, old_offset, @options)),
-
str1.size + str2.size]
-
end
-
-
2
def special_val
-
10604
return unless scan(/!important/i)
-
[:string, Script::String.new("!important")]
-
end
-
-
2
def ident_op
-
10604
return unless op = scan(REGULAR_EXPRESSIONS[:ident_op])
-
[OPERATORS[op]]
-
end
-
-
2
def op
-
7880
return unless op = scan(REGULAR_EXPRESSIONS[:op])
-
7880
@interpolation_stack << nil if op == :begin_interpolation
-
7880
[OPERATORS[op]]
-
end
-
-
2
def raw(rx)
-
10624
return unless val = scan(rx)
-
[:raw, val]
-
end
-
-
2
def scan(re)
-
224756
return unless str = @scanner.scan(re)
-
21322
c = str.count("\n")
-
21322
@line += c
-
21322
@offset = (c == 0 ? @offset + str.size : str[/\n(.*)/, 1].size)
-
21322
str
-
end
-
-
2
def current_position
-
17239
@offset + 1
-
end
-
end
-
end
-
end
-
2
module Sass::Script
-
# A SassScript object representing a CSS list.
-
# This includes both comma-separated lists and space-separated lists.
-
2
class List < Literal
-
# The Ruby array containing the contents of the list.
-
#
-
# @return [Array<Literal>]
-
2
attr_reader :value
-
2
alias_method :children, :value
-
2
alias_method :to_a, :value
-
-
# The operator separating the values of the list.
-
# Either `:comma` or `:space`.
-
#
-
# @return [Symbol]
-
2
attr_reader :separator
-
-
# Creates a new list.
-
#
-
# @param value [Array<Literal>] See \{#value}
-
# @param separator [String] See \{#separator}
-
2
def initialize(value, separator)
-
4175
super(value)
-
4175
@separator = separator
-
end
-
-
# @see Node#deep_copy
-
2
def deep_copy
-
node = dup
-
node.instance_variable_set('@value', value.map {|c| c.deep_copy})
-
node
-
end
-
-
# @see Node#eq
-
2
def eq(other)
-
Sass::Script::Bool.new(
-
other.is_a?(List) && self.value == other.value &&
-
self.separator == other.separator)
-
end
-
-
# @see Node#to_s
-
2
def to_s(opts = {})
-
934
raise Sass::SyntaxError.new("() isn't a valid CSS value.") if value.empty?
-
5860
return value.reject {|e| e.is_a?(Null) || e.is_a?(List) && e.value.empty?}.map {|e| e.to_s(opts)}.join(sep_str)
-
end
-
-
# @see Node#to_sass
-
2
def to_sass(opts = {})
-
return "()" if value.empty?
-
precedence = Sass::Script::Parser.precedence_of(separator)
-
value.reject {|e| e.is_a?(Null)}.map do |v|
-
if v.is_a?(List) && Sass::Script::Parser.precedence_of(v.separator) <= precedence ||
-
separator == :space && v.is_a?(UnaryOperation) && (v.operator == :minus || v.operator == :plus)
-
"(#{v.to_sass(opts)})"
-
else
-
v.to_sass(opts)
-
end
-
end.join(sep_str(nil))
-
end
-
-
# @see Node#inspect
-
2
def inspect
-
"(#{to_sass})"
-
end
-
-
2
protected
-
-
# @see Node#_perform
-
2
def _perform(environment)
-
934
list = Sass::Script::List.new(
-
2463
value.map {|e| e.perform(environment)},
-
separator)
-
934
list.options = self.options
-
934
list
-
end
-
-
2
private
-
-
2
def sep_str(opts = self.options)
-
934
return ' ' if separator == :space
-
37
return ',' if opts && opts[:style] == :compressed
-
return ', '
-
end
-
end
-
end
-
2
module Sass::Script
-
# The abstract superclass for SassScript objects.
-
#
-
# Many of these methods, especially the ones that correspond to SassScript operations,
-
# are designed to be overridden by subclasses which may change the semantics somewhat.
-
# The operations listed here are just the defaults.
-
2
class Literal < Node
-
2
require 'sass/script/string'
-
2
require 'sass/script/number'
-
2
require 'sass/script/color'
-
2
require 'sass/script/bool'
-
2
require 'sass/script/null'
-
2
require 'sass/script/list'
-
2
require 'sass/script/arg_list'
-
-
# Returns the Ruby value of the literal.
-
# The type of this value varies based on the subclass.
-
#
-
# @return [Object]
-
2
attr_reader :value
-
-
# Creates a new literal.
-
#
-
# @param value [Object] The object for \{#value}
-
2
def initialize(value = nil)
-
25414
@value = value
-
25414
super()
-
end
-
-
# Returns an empty array.
-
#
-
# @return [Array<Node>] empty
-
# @see Node#children
-
2
def children
-
30613
[]
-
end
-
-
# @see Node#deep_copy
-
2
def deep_copy
-
dup
-
end
-
-
# Returns the options hash for this node.
-
#
-
# @return [{Symbol => Object}]
-
# @raise [Sass::SyntaxError] if the options hash hasn't been set.
-
# This should only happen when the literal was created
-
# outside of the parser and \{#to\_s} was called on it
-
2
def options
-
2360
opts = super
-
2360
return opts if opts
-
raise Sass::SyntaxError.new(<<MSG)
-
The #options attribute is not set on this #{self.class}.
-
This error is probably occurring because #to_s was called
-
on this literal within a custom Sass function without first
-
setting the #option attribute.
-
MSG
-
end
-
-
# The SassScript `==` operation.
-
# **Note that this returns a {Sass::Script::Bool} object,
-
# not a Ruby boolean**.
-
#
-
# @param other [Literal] The right-hand side of the operator
-
# @return [Bool] True if this literal is the same as the other,
-
# false otherwise
-
2
def eq(other)
-
Sass::Script::Bool.new(self.class == other.class && self.value == other.value)
-
end
-
-
# The SassScript `!=` operation.
-
# **Note that this returns a {Sass::Script::Bool} object,
-
# not a Ruby boolean**.
-
#
-
# @param other [Literal] The right-hand side of the operator
-
# @return [Bool] False if this literal is the same as the other,
-
# true otherwise
-
2
def neq(other)
-
Sass::Script::Bool.new(!eq(other).to_bool)
-
end
-
-
# The SassScript `==` operation.
-
# **Note that this returns a {Sass::Script::Bool} object,
-
# not a Ruby boolean**.
-
#
-
# @param other [Literal] The right-hand side of the operator
-
# @return [Bool] True if this literal is the same as the other,
-
# false otherwise
-
2
def unary_not
-
Sass::Script::Bool.new(!to_bool)
-
end
-
-
# The SassScript `=` operation
-
# (used for proprietary MS syntax like `alpha(opacity=20)`).
-
#
-
# @param other [Literal] The right-hand side of the operator
-
# @return [Script::String] A string containing both literals
-
# separated by `"="`
-
2
def single_eq(other)
-
37
Sass::Script::String.new("#{self.to_s}=#{other.to_s}")
-
end
-
-
# The SassScript `+` operation.
-
#
-
# @param other [Literal] The right-hand side of the operator
-
# @return [Script::String] A string containing both literals
-
# without any separation
-
2
def plus(other)
-
if other.is_a?(Sass::Script::String)
-
return Sass::Script::String.new(self.to_s + other.value, other.type)
-
end
-
Sass::Script::String.new(self.to_s + other.to_s)
-
end
-
-
# The SassScript `-` operation.
-
#
-
# @param other [Literal] The right-hand side of the operator
-
# @return [Script::String] A string containing both literals
-
# separated by `"-"`
-
2
def minus(other)
-
Sass::Script::String.new("#{self.to_s}-#{other.to_s}")
-
end
-
-
# The SassScript `/` operation.
-
#
-
# @param other [Literal] The right-hand side of the operator
-
# @return [Script::String] A string containing both literals
-
# separated by `"/"`
-
2
def div(other)
-
Sass::Script::String.new("#{self.to_s}/#{other.to_s}")
-
end
-
-
# The SassScript unary `+` operation (e.g. `+$a`).
-
#
-
# @param other [Literal] The right-hand side of the operator
-
# @return [Script::String] A string containing the literal
-
# preceded by `"+"`
-
2
def unary_plus
-
Sass::Script::String.new("+#{self.to_s}")
-
end
-
-
# The SassScript unary `-` operation (e.g. `-$a`).
-
#
-
# @param other [Literal] The right-hand side of the operator
-
# @return [Script::String] A string containing the literal
-
# preceded by `"-"`
-
2
def unary_minus
-
Sass::Script::String.new("-#{self.to_s}")
-
end
-
-
# The SassScript unary `/` operation (e.g. `/$a`).
-
#
-
# @param other [Literal] The right-hand side of the operator
-
# @return [Script::String] A string containing the literal
-
# preceded by `"/"`
-
2
def unary_div
-
Sass::Script::String.new("/#{self.to_s}")
-
end
-
-
# @return [String] A readable representation of the literal
-
2
def inspect
-
value.inspect
-
end
-
-
# @return [Boolean] `true` (the Ruby boolean value)
-
2
def to_bool
-
true
-
end
-
-
# Compares this object with another.
-
#
-
# @param other [Object] The object to compare with
-
# @return [Boolean] Whether or not this literal is equivalent to `other`
-
2
def ==(other)
-
eq(other).to_bool
-
end
-
-
# @return [Fixnum] The integer value of this literal
-
# @raise [Sass::SyntaxError] if this literal isn't an integer
-
2
def to_i
-
raise Sass::SyntaxError.new("#{self.inspect} is not an integer.")
-
end
-
-
# @raise [Sass::SyntaxError] if this literal isn't an integer
-
2
def assert_int!; to_i; end
-
-
# Returns the value of this literal as a list.
-
# Single literals are considered the same as single-element lists.
-
#
-
# @return [Array<Literal>] The of this literal as a list
-
2
def to_a
-
[self]
-
end
-
-
# Returns the string representation of this literal
-
# as it would be output to the CSS document.
-
#
-
# @return [String]
-
2
def to_s(opts = {})
-
raise Sass::SyntaxError.new("[BUG] All subclasses of Sass::Literal must implement #to_s.")
-
end
-
2
alias_method :to_sass, :to_s
-
-
# Returns whether or not this object is null.
-
#
-
# @return [Boolean] `false`
-
2
def null?
-
false
-
end
-
-
2
protected
-
-
# Evaluates the literal.
-
#
-
# @param environment [Sass::Environment] The environment in which to evaluate the SassScript
-
# @return [Literal] This literal
-
2
def _perform(environment)
-
18517
self
-
end
-
end
-
end
-
2
module Sass::Script
-
# The abstract superclass for SassScript parse tree nodes.
-
#
-
# Use \{#perform} to evaluate a parse tree.
-
2
class Node
-
# The options hash for this node.
-
#
-
# @return [{Symbol => Object}]
-
2
attr_reader :options
-
-
# The line of the document on which this node appeared.
-
#
-
# @return [Fixnum]
-
2
attr_accessor :line
-
-
# Sets the options hash for this node,
-
# as well as for all child nodes.
-
# See {file:SASS_REFERENCE.md#sass_options the Sass options documentation}.
-
#
-
# @param options [{Symbol => Object}] The options
-
2
def options=(options)
-
37121
@options = options
-
37121
children.each do |c|
-
18758
if c.is_a? Hash
-
c.values.each {|v| v.options = options }
-
else
-
18758
c.options = options
-
end
-
end
-
end
-
-
# Evaluates the node.
-
#
-
# \{#perform} shouldn't be overridden directly;
-
# instead, override \{#\_perform}.
-
#
-
# @param environment [Sass::Environment] The environment in which to evaluate the SassScript
-
# @return [Literal] The SassScript object that is the value of the SassScript
-
2
def perform(environment)
-
21261
_perform(environment)
-
rescue Sass::SyntaxError => e
-
e.modify_backtrace(:line => line)
-
raise e
-
end
-
-
# Returns all child nodes of this node.
-
#
-
# @return [Array<Node>]
-
2
def children
-
Sass::Util.abstract(self)
-
end
-
-
# Returns the text of this SassScript expression.
-
#
-
# @return [String]
-
2
def to_sass(opts = {})
-
Sass::Util.abstract(self)
-
end
-
-
# Returns a deep clone of this node.
-
# The child nodes are cloned, but options are not.
-
#
-
# @return [Node]
-
2
def deep_copy
-
Sass::Util.abstract(self)
-
end
-
-
2
protected
-
-
# Converts underscores to dashes if the :dasherize option is set.
-
2
def dasherize(s, opts)
-
if opts[:dasherize]
-
s.gsub(/_/,'-')
-
else
-
s
-
end
-
end
-
-
# Evaluates this node.
-
# Note that all {Literal} objects created within this method
-
# should have their \{#options} attribute set, probably via \{#opts}.
-
#
-
# @param environment [Sass::Environment] The environment in which to evaluate the SassScript
-
# @return [Literal] The SassScript object that is the value of the SassScript
-
# @see #perform
-
2
def _perform(environment)
-
Sass::Util.abstract(self)
-
end
-
-
# Sets the \{#options} field on the given literal and returns it
-
#
-
# @param literal [Literal]
-
# @return [Literal]
-
2
def opts(literal)
-
1810
literal.options = options
-
1810
literal
-
end
-
end
-
end
-
2
require 'sass/script/literal'
-
-
2
module Sass::Script
-
# A SassScript object representing a null value.
-
2
class Null < Literal
-
# Creates a new null literal.
-
2
def initialize
-
super nil
-
end
-
-
# @return [Boolean] `false` (the Ruby boolean value)
-
2
def to_bool
-
false
-
end
-
-
# @return [Boolean] `true`
-
2
def null?
-
true
-
end
-
-
# @return [String] '' (An empty string)
-
2
def to_s(opts = {})
-
''
-
end
-
-
2
def to_sass(opts = {})
-
'null'
-
end
-
-
# Returns a string representing a null value.
-
#
-
# @return [String]
-
2
def inspect
-
'null'
-
end
-
end
-
end
-
2
require 'sass/script/literal'
-
-
2
module Sass::Script
-
# A SassScript object representing a number.
-
# SassScript numbers can have decimal values,
-
# and can also have units.
-
# For example, `12`, `1px`, and `10.45em`
-
# are all valid values.
-
#
-
# Numbers can also have more complex units, such as `1px*em/in`.
-
# These cannot be inputted directly in Sass code at the moment.
-
2
class Number < Literal
-
# The Ruby value of the number.
-
#
-
# @return [Numeric]
-
2
attr_reader :value
-
-
# A list of units in the numerator of the number.
-
# For example, `1px*em/in*cm` would return `["px", "em"]`
-
# @return [Array<String>]
-
2
attr_reader :numerator_units
-
-
# A list of units in the denominator of the number.
-
# For example, `1px*em/in*cm` would return `["in", "cm"]`
-
# @return [Array<String>]
-
2
attr_reader :denominator_units
-
-
# The original representation of this number.
-
# For example, although the result of `1px/2px` is `0.5`,
-
# the value of `#original` is `"1px/2px"`.
-
#
-
# This is only non-nil when the original value should be used as the CSS value,
-
# as in `font: 1px/2px`.
-
#
-
# @return [Boolean, nil]
-
2
attr_accessor :original
-
-
2
def self.precision
-
2
@precision ||= 5
-
end
-
-
# Sets the number of digits of precision
-
# For example, if this is `3`,
-
# `3.1415926` will be printed as `3.142`.
-
2
def self.precision=(digits)
-
2
@precision = digits.round
-
2
@precision_factor = 10.0**@precision
-
end
-
-
# the precision factor used in numeric output
-
# it is derived from the `precision` method.
-
2
def self.precision_factor
-
3186
@precision_factor ||= 10.0**precision
-
end
-
-
# Handles the deprecation warning for the PRECISION constant
-
# This can be removed in 3.2.
-
2
def self.const_missing(const)
-
if const == :PRECISION
-
Sass::Util.sass_warn("Sass::Script::Number::PRECISION is deprecated and will be removed in a future release. Use Sass::Script::Number.precision_factor instead.")
-
const_set(:PRECISION, self.precision_factor)
-
else
-
super
-
end
-
end
-
-
# Used so we don't allocate two new arrays for each new number.
-
2
NO_UNITS = []
-
-
# @param value [Numeric] The value of the number
-
# @param numerator_units [Array<String>] See \{#numerator\_units}
-
# @param denominator_units [Array<String>] See \{#denominator\_units}
-
2
def initialize(value, numerator_units = NO_UNITS, denominator_units = NO_UNITS)
-
6417
super(value)
-
6417
@numerator_units = numerator_units
-
6417
@denominator_units = denominator_units
-
6417
normalize!
-
end
-
-
# The SassScript `+` operation.
-
# Its functionality depends on the type of its argument:
-
#
-
# {Number}
-
# : Adds the two numbers together, converting units if possible.
-
#
-
# {Color}
-
# : Adds this number to each of the RGB color channels.
-
#
-
# {Literal}
-
# : See {Literal#plus}.
-
#
-
# @param other [Literal] The right-hand side of the operator
-
# @return [Literal] The result of the operation
-
# @raise [Sass::UnitConversionError] if `other` is a number with incompatible units
-
2
def plus(other)
-
if other.is_a? Number
-
operate(other, :+)
-
elsif other.is_a?(Color)
-
other.plus(self)
-
else
-
super
-
end
-
end
-
-
# The SassScript binary `-` operation (e.g. `$a - $b`).
-
# Its functionality depends on the type of its argument:
-
#
-
# {Number}
-
# : Subtracts this number from the other, converting units if possible.
-
#
-
# {Literal}
-
# : See {Literal#minus}.
-
#
-
# @param other [Literal] The right-hand side of the operator
-
# @return [Literal] The result of the operation
-
# @raise [Sass::UnitConversionError] if `other` is a number with incompatible units
-
2
def minus(other)
-
if other.is_a? Number
-
operate(other, :-)
-
else
-
super
-
end
-
end
-
-
# The SassScript unary `+` operation (e.g. `+$a`).
-
#
-
# @return [Number] The value of this number
-
2
def unary_plus
-
self
-
end
-
-
# The SassScript unary `-` operation (e.g. `-$a`).
-
#
-
# @return [Number] The negative value of this number
-
2
def unary_minus
-
Number.new(-value, @numerator_units, @denominator_units)
-
end
-
-
# The SassScript `*` operation.
-
# Its functionality depends on the type of its argument:
-
#
-
# {Number}
-
# : Multiplies the two numbers together, converting units appropriately.
-
#
-
# {Color}
-
# : Multiplies each of the RGB color channels by this number.
-
#
-
# @param other [Number, Color] The right-hand side of the operator
-
# @return [Number, Color] The result of the operation
-
# @raise [NoMethodError] if `other` is an invalid type
-
2
def times(other)
-
if other.is_a? Number
-
operate(other, :*)
-
elsif other.is_a? Color
-
other.times(self)
-
else
-
raise NoMethodError.new(nil, :times)
-
end
-
end
-
-
# The SassScript `/` operation.
-
# Its functionality depends on the type of its argument:
-
#
-
# {Number}
-
# : Divides this number by the other, converting units appropriately.
-
#
-
# {Literal}
-
# : See {Literal#div}.
-
#
-
# @param other [Literal] The right-hand side of the operator
-
# @return [Literal] The result of the operation
-
2
def div(other)
-
if other.is_a? Number
-
res = operate(other, :/)
-
if self.original && other.original
-
res.original = "#{self.original}/#{other.original}"
-
end
-
res
-
else
-
super
-
end
-
end
-
-
# The SassScript `%` operation.
-
#
-
# @param other [Number] The right-hand side of the operator
-
# @return [Number] This number modulo the other
-
# @raise [NoMethodError] if `other` is an invalid type
-
# @raise [Sass::UnitConversionError] if `other` has any units
-
2
def mod(other)
-
if other.is_a?(Number)
-
unless other.unitless?
-
raise Sass::UnitConversionError.new("Cannot modulo by a number with units: #{other.inspect}.")
-
end
-
operate(other, :%)
-
else
-
raise NoMethodError.new(nil, :mod)
-
end
-
end
-
-
# The SassScript `==` operation.
-
#
-
# @param other [Literal] The right-hand side of the operator
-
# @return [Boolean] Whether this number is equal to the other object
-
2
def eq(other)
-
return Sass::Script::Bool.new(false) unless other.is_a?(Sass::Script::Number)
-
this = self
-
begin
-
if unitless?
-
this = this.coerce(other.numerator_units, other.denominator_units)
-
else
-
other = other.coerce(@numerator_units, @denominator_units)
-
end
-
rescue Sass::UnitConversionError
-
return Sass::Script::Bool.new(false)
-
end
-
-
Sass::Script::Bool.new(this.value == other.value)
-
end
-
-
# The SassScript `>` operation.
-
#
-
# @param other [Number] The right-hand side of the operator
-
# @return [Boolean] Whether this number is greater than the other
-
# @raise [NoMethodError] if `other` is an invalid type
-
2
def gt(other)
-
raise NoMethodError.new(nil, :gt) unless other.is_a?(Number)
-
operate(other, :>)
-
end
-
-
# The SassScript `>=` operation.
-
#
-
# @param other [Number] The right-hand side of the operator
-
# @return [Boolean] Whether this number is greater than or equal to the other
-
# @raise [NoMethodError] if `other` is an invalid type
-
2
def gte(other)
-
raise NoMethodError.new(nil, :gte) unless other.is_a?(Number)
-
operate(other, :>=)
-
end
-
-
# The SassScript `<` operation.
-
#
-
# @param other [Number] The right-hand side of the operator
-
# @return [Boolean] Whether this number is less than the other
-
# @raise [NoMethodError] if `other` is an invalid type
-
2
def lt(other)
-
raise NoMethodError.new(nil, :lt) unless other.is_a?(Number)
-
operate(other, :<)
-
end
-
-
# The SassScript `<=` operation.
-
#
-
# @param other [Number] The right-hand side of the operator
-
# @return [Boolean] Whether this number is less than or equal to the other
-
# @raise [NoMethodError] if `other` is an invalid type
-
2
def lte(other)
-
raise NoMethodError.new(nil, :lte) unless other.is_a?(Number)
-
operate(other, :<=)
-
end
-
-
# @return [String] The CSS representation of this number
-
# @raise [Sass::SyntaxError] if this number has units that can't be used in CSS
-
# (e.g. `px*in`)
-
2
def to_s(opts = {})
-
12613
return original if original
-
6417
raise Sass::SyntaxError.new("#{inspect} isn't a valid CSS value.") unless legal_units?
-
6417
inspect
-
end
-
-
# Returns a readable representation of this number.
-
#
-
# This representation is valid CSS (and valid SassScript)
-
# as long as there is only one unit.
-
#
-
# @return [String] The representation
-
2
def inspect(opts = {})
-
6638
value = self.class.round(self.value)
-
6638
unitless? ? value.to_s : "#{value}#{unit_str}"
-
end
-
2
alias_method :to_sass, :inspect
-
-
# @return [Fixnum] The integer value of the number
-
# @raise [Sass::SyntaxError] if the number isn't an integer
-
2
def to_i
-
super unless int?
-
return value
-
end
-
-
# @return [Boolean] Whether or not this number is an integer.
-
2
def int?
-
value % 1 == 0.0
-
end
-
-
# @return [Boolean] Whether or not this number has no units.
-
2
def unitless?
-
13055
@numerator_units.empty? && @denominator_units.empty?
-
end
-
-
# @return [Boolean] Whether or not this number has units that can be represented in CSS
-
# (that is, zero or one \{#numerator\_units}).
-
2
def legal_units?
-
6417
(@numerator_units.empty? || @numerator_units.size == 1) && @denominator_units.empty?
-
end
-
-
# Returns this number converted to other units.
-
# The conversion takes into account the relationship between e.g. mm and cm,
-
# as well as between e.g. in and cm.
-
#
-
# If this number has no units, it will simply return itself
-
# with the given units.
-
#
-
# An incompatible coercion, e.g. between px and cm, will raise an error.
-
#
-
# @param num_units [Array<String>] The numerator units to coerce this number into.
-
# See {\#numerator\_units}
-
# @param den_units [Array<String>] The denominator units to coerce this number into.
-
# See {\#denominator\_units}
-
# @return [Number] The number with the new units
-
# @raise [Sass::UnitConversionError] if the given units are incompatible with the number's
-
# current units
-
2
def coerce(num_units, den_units)
-
Number.new(if unitless?
-
self.value
-
else
-
self.value * coercion_factor(@numerator_units, num_units) /
-
coercion_factor(@denominator_units, den_units)
-
end, num_units, den_units)
-
end
-
-
# @param other [Number] A number to decide if it can be compared with this number.
-
# @return [Boolean] Whether or not this number can be compared with the other.
-
2
def comparable_to?(other)
-
begin
-
operate(other, :+)
-
true
-
rescue Sass::UnitConversionError
-
false
-
end
-
end
-
-
# Returns a human readable representation of the units in this number.
-
# For complex units this takes the form of:
-
# numerator_unit1 * numerator_unit2 / denominator_unit1 * denominator_unit2
-
# @return [String] a string that represents the units in this number
-
2
def unit_str
-
2185
rv = @numerator_units.sort.join("*")
-
2185
if @denominator_units.any?
-
rv << "/"
-
rv << @denominator_units.sort.join("*")
-
end
-
2185
rv
-
end
-
-
2
private
-
-
# @private
-
2
def self.round(num)
-
7070
if num.is_a?(Float) && (num.infinite? || num.nan?)
-
num
-
7070
elsif num % 1 == 0.0
-
5477
num.to_i
-
else
-
1593
((num * self.precision_factor).round / self.precision_factor).to_f
-
end
-
end
-
-
2
OPERATIONS = [:+, :-, :<=, :<, :>, :>=]
-
-
2
def operate(other, operation)
-
this = self
-
if OPERATIONS.include?(operation)
-
if unitless?
-
this = this.coerce(other.numerator_units, other.denominator_units)
-
else
-
other = other.coerce(@numerator_units, @denominator_units)
-
end
-
end
-
# avoid integer division
-
value = (:/ == operation) ? this.value.to_f : this.value
-
result = value.send(operation, other.value)
-
-
if result.is_a?(Numeric)
-
Number.new(result, *compute_units(this, other, operation))
-
else # Boolean op
-
Bool.new(result)
-
end
-
end
-
-
2
def coercion_factor(from_units, to_units)
-
# get a list of unmatched units
-
from_units, to_units = sans_common_units(from_units, to_units)
-
-
if from_units.size != to_units.size || !convertable?(from_units | to_units)
-
raise Sass::UnitConversionError.new("Incompatible units: '#{from_units.join('*')}' and '#{to_units.join('*')}'.")
-
end
-
-
from_units.zip(to_units).inject(1) {|m,p| m * conversion_factor(p[0], p[1]) }
-
end
-
-
2
def compute_units(this, other, operation)
-
case operation
-
when :*
-
[this.numerator_units + other.numerator_units, this.denominator_units + other.denominator_units]
-
when :/
-
[this.numerator_units + other.denominator_units, this.denominator_units + other.numerator_units]
-
else
-
[this.numerator_units, this.denominator_units]
-
end
-
end
-
-
2
def normalize!
-
6417
return if unitless?
-
1966
@numerator_units, @denominator_units = sans_common_units(@numerator_units, @denominator_units)
-
-
1966
@denominator_units.each_with_index do |d, i|
-
if convertable?(d) && (u = @numerator_units.detect(&method(:convertable?)))
-
@value /= conversion_factor(d, u)
-
@denominator_units.delete_at(i)
-
@numerator_units.delete_at(@numerator_units.index(u))
-
end
-
end
-
end
-
-
# A hash of unit names to their index in the conversion table
-
2
CONVERTABLE_UNITS = {"in" => 0, "cm" => 1, "pc" => 2, "mm" => 3, "pt" => 4, "px" => 5 }
-
2
CONVERSION_TABLE = [[ 1, 2.54, 6, 25.4, 72 , 96 ], # in
-
[ nil, 1, 2.36220473, 10, 28.3464567, 37.795275591], # cm
-
[ nil, nil, 1, 4.23333333, 12 , 16 ], # pc
-
[ nil, nil, nil, 1, 2.83464567, 3.7795275591], # mm
-
[ nil, nil, nil, nil, 1 , 1.3333333333], # pt
-
[ nil, nil, nil, nil, nil , 1 ]] # px
-
-
2
def conversion_factor(from_unit, to_unit)
-
res = CONVERSION_TABLE[CONVERTABLE_UNITS[from_unit]][CONVERTABLE_UNITS[to_unit]]
-
return 1.0 / conversion_factor(to_unit, from_unit) if res.nil?
-
res
-
end
-
-
2
def convertable?(units)
-
Array(units).all? {|u| CONVERTABLE_UNITS.include?(u)}
-
end
-
-
2
def sans_common_units(units1, units2)
-
1966
units2 = units2.dup
-
# Can't just use -, because we want px*px to coerce properly to px*mm
-
return units1.map do |u|
-
1966
next u unless j = units2.index(u)
-
units2.delete_at(j)
-
nil
-
1966
end.compact, units2
-
end
-
end
-
end
-
2
require 'set'
-
2
require 'sass/script/string'
-
2
require 'sass/script/number'
-
2
require 'sass/script/color'
-
2
require 'sass/script/functions'
-
2
require 'sass/script/unary_operation'
-
2
require 'sass/script/interpolation'
-
2
require 'sass/script/string_interpolation'
-
-
2
module Sass::Script
-
# A SassScript parse node representing a binary operation,
-
# such as `$a + $b` or `"foo" + 1`.
-
2
class Operation < Node
-
2
attr_reader :operand1
-
2
attr_reader :operand2
-
2
attr_reader :operator
-
-
# @param operand1 [Script::Node] The parse-tree node
-
# for the right-hand side of the operator
-
# @param operand2 [Script::Node] The parse-tree node
-
# for the left-hand side of the operator
-
# @param operator [Symbol] The operator to perform.
-
# This should be one of the binary operator names in {Lexer::OPERATORS}
-
2
def initialize(operand1, operand2, operator)
-
37
@operand1 = operand1
-
37
@operand2 = operand2
-
37
@operator = operator
-
37
super()
-
end
-
-
# @return [String] A human-readable s-expression representation of the operation
-
2
def inspect
-
"(#{@operator.inspect} #{@operand1.inspect} #{@operand2.inspect})"
-
end
-
-
# @see Node#to_sass
-
2
def to_sass(opts = {})
-
o1 = operand_to_sass @operand1, :left, opts
-
o2 = operand_to_sass @operand2, :right, opts
-
sep =
-
case @operator
-
when :comma; ", "
-
when :space; " "
-
else; " #{Lexer::OPERATORS_REVERSE[@operator]} "
-
end
-
"#{o1}#{sep}#{o2}"
-
end
-
-
# Returns the operands for this operation.
-
#
-
# @return [Array<Node>]
-
# @see Node#children
-
2
def children
-
74
[@operand1, @operand2]
-
end
-
-
# @see Node#deep_copy
-
2
def deep_copy
-
node = dup
-
node.instance_variable_set('@operand1', @operand1.deep_copy)
-
node.instance_variable_set('@operand2', @operand2.deep_copy)
-
node
-
end
-
-
2
protected
-
-
# Evaluates the operation.
-
#
-
# @param environment [Sass::Environment] The environment in which to evaluate the SassScript
-
# @return [Literal] The SassScript object that is the value of the operation
-
# @raise [Sass::SyntaxError] if the operation is undefined for the operands
-
2
def _perform(environment)
-
37
literal1 = @operand1.perform(environment)
-
-
# Special-case :and and :or to support short-circuiting.
-
37
if @operator == :and
-
return literal1.to_bool ? @operand2.perform(environment) : literal1
-
elsif @operator == :or
-
return literal1.to_bool ? literal1 : @operand2.perform(environment)
-
end
-
-
37
literal2 = @operand2.perform(environment)
-
-
37
if (literal1.is_a?(Null) || literal2.is_a?(Null)) && @operator != :eq && @operator != :neq
-
raise Sass::SyntaxError.new("Invalid null operation: \"#{literal1.inspect} #{@operator} #{literal2.inspect}\".")
-
end
-
-
37
begin
-
37
opts(literal1.send(@operator, literal2))
-
rescue NoMethodError => e
-
raise e unless e.name.to_s == @operator.to_s
-
raise Sass::SyntaxError.new("Undefined operation: \"#{literal1} #{@operator} #{literal2}\".")
-
end
-
end
-
-
2
private
-
-
2
def operand_to_sass(op, side, opts)
-
return "(#{op.to_sass(opts)})" if op.is_a?(List)
-
return op.to_sass(opts) unless op.is_a?(Operation)
-
-
pred = Sass::Script::Parser.precedence_of(@operator)
-
sub_pred = Sass::Script::Parser.precedence_of(op.operator)
-
assoc = Sass::Script::Parser.associative?(@operator)
-
return "(#{op.to_sass(opts)})" if sub_pred < pred ||
-
(side == :right && sub_pred == pred && !assoc)
-
op.to_sass(opts)
-
end
-
end
-
end
-
2
require 'sass/script/lexer'
-
-
2
module Sass
-
2
module Script
-
# The parser for SassScript.
-
# It parses a string of code into a tree of {Script::Node}s.
-
2
class Parser
-
# The line number of the parser's current position.
-
#
-
# @return [Fixnum]
-
2
def line
-
2344
@lexer.line
-
end
-
-
# @param str [String, StringScanner] The source text to parse
-
# @param line [Fixnum] The line on which the SassScript appears.
-
# Used for error reporting
-
# @param offset [Fixnum] The number of characters in on which the SassScript appears.
-
# Used for error reporting
-
# @param options [{Symbol => Object}] An options hash;
-
# see {file:SASS_REFERENCE.md#sass_options the Sass options documentation}
-
2
def initialize(str, line, offset, options = {})
-
2344
@options = options
-
2344
@lexer = lexer_class.new(str, line, offset, options)
-
end
-
-
# Parses a SassScript expression within an interpolated segment (`#{}`).
-
# This means that it stops when it comes across an unmatched `}`,
-
# which signals the end of an interpolated segment,
-
# it returns rather than throwing an error.
-
#
-
# @return [Script::Node] The root node of the parse tree
-
# @raise [Sass::SyntaxError] if the expression isn't valid SassScript
-
2
def parse_interpolated
-
expr = assert_expr :expr
-
assert_tok :end_interpolation
-
expr.options = @options
-
expr
-
rescue Sass::SyntaxError => e
-
e.modify_backtrace :line => @lexer.line, :filename => @options[:filename]
-
raise e
-
end
-
-
# Parses a SassScript expression.
-
#
-
# @return [Script::Node] The root node of the parse tree
-
# @raise [Sass::SyntaxError] if the expression isn't valid SassScript
-
2
def parse
-
2344
expr = assert_expr :expr
-
2344
assert_done
-
2344
expr.options = @options
-
2344
expr
-
rescue Sass::SyntaxError => e
-
e.modify_backtrace :line => @lexer.line, :filename => @options[:filename]
-
raise e
-
end
-
-
# Parses a SassScript expression,
-
# ending it when it encounters one of the given identifier tokens.
-
#
-
# @param [#include?(String)] A set of strings that delimit the expression.
-
# @return [Script::Node] The root node of the parse tree
-
# @raise [Sass::SyntaxError] if the expression isn't valid SassScript
-
2
def parse_until(tokens)
-
@stop_at = tokens
-
expr = assert_expr :expr
-
assert_done
-
expr.options = @options
-
expr
-
rescue Sass::SyntaxError => e
-
e.modify_backtrace :line => @lexer.line, :filename => @options[:filename]
-
raise e
-
end
-
-
# Parses the argument list for a mixin include.
-
#
-
# @return [(Array<Script::Node>, {String => Script::Node}, Script::Node)]
-
# The root nodes of the positional arguments, keyword arguments, and
-
# splat argument. Keyword arguments are in a hash from names to values.
-
# @raise [Sass::SyntaxError] if the argument list isn't valid SassScript
-
2
def parse_mixin_include_arglist
-
args, keywords = [], {}
-
if try_tok(:lparen)
-
args, keywords, splat = mixin_arglist || [[], {}]
-
assert_tok(:rparen)
-
end
-
assert_done
-
-
args.each {|a| a.options = @options}
-
keywords.each {|k, v| v.options = @options}
-
splat.options = @options if splat
-
return args, keywords, splat
-
rescue Sass::SyntaxError => e
-
e.modify_backtrace :line => @lexer.line, :filename => @options[:filename]
-
raise e
-
end
-
-
# Parses the argument list for a mixin definition.
-
#
-
# @return [(Array<Script::Node>, Script::Node)]
-
# The root nodes of the arguments, and the splat argument.
-
# @raise [Sass::SyntaxError] if the argument list isn't valid SassScript
-
2
def parse_mixin_definition_arglist
-
args, splat = defn_arglist!(false)
-
assert_done
-
-
args.each do |k, v|
-
k.options = @options
-
v.options = @options if v
-
end
-
splat.options = @options if splat
-
return args, splat
-
rescue Sass::SyntaxError => e
-
e.modify_backtrace :line => @lexer.line, :filename => @options[:filename]
-
raise e
-
end
-
-
# Parses the argument list for a function definition.
-
#
-
# @return [(Array<Script::Node>, Script::Node)]
-
# The root nodes of the arguments, and the splat argument.
-
# @raise [Sass::SyntaxError] if the argument list isn't valid SassScript
-
2
def parse_function_definition_arglist
-
args, splat = defn_arglist!(true)
-
assert_done
-
-
args.each do |k, v|
-
k.options = @options
-
v.options = @options if v
-
end
-
splat.options = @options if splat
-
return args, splat
-
rescue Sass::SyntaxError => e
-
e.modify_backtrace :line => @lexer.line, :filename => @options[:filename]
-
raise e
-
end
-
-
# Parse a single string value, possibly containing interpolation.
-
# Doesn't assert that the scanner is finished after parsing.
-
#
-
# @return [Script::Node] The root node of the parse tree.
-
# @raise [Sass::SyntaxError] if the string isn't valid SassScript
-
2
def parse_string
-
unless (peek = @lexer.peek) &&
-
(peek.type == :string ||
-
(peek.type == :funcall && peek.value.downcase == 'url'))
-
lexer.expected!("string")
-
end
-
-
expr = assert_expr :funcall
-
expr.options = @options
-
@lexer.unpeek!
-
expr
-
rescue Sass::SyntaxError => e
-
e.modify_backtrace :line => @lexer.line, :filename => @options[:filename]
-
raise e
-
end
-
-
# Parses a SassScript expression.
-
#
-
# @overload parse(str, line, offset, filename = nil)
-
# @return [Script::Node] The root node of the parse tree
-
# @see Parser#initialize
-
# @see Parser#parse
-
2
def self.parse(*args)
-
new(*args).parse
-
end
-
-
2
PRECEDENCE = [
-
:comma, :single_eq, :space, :or, :and,
-
[:eq, :neq],
-
[:gt, :gte, :lt, :lte],
-
[:plus, :minus],
-
[:times, :div, :mod],
-
]
-
-
2
ASSOCIATIVE = [:plus, :times]
-
-
2
class << self
-
# Returns an integer representing the precedence
-
# of the given operator.
-
# A lower integer indicates a looser binding.
-
#
-
# @private
-
2
def precedence_of(op)
-
PRECEDENCE.each_with_index do |e, i|
-
return i if Array(e).include?(op)
-
end
-
raise "[BUG] Unknown operator #{op}"
-
end
-
-
# Returns whether or not the given operation is associative.
-
#
-
# @private
-
2
def associative?(op)
-
ASSOCIATIVE.include?(op)
-
end
-
-
2
private
-
-
# Defines a simple left-associative production.
-
# name is the name of the production,
-
# sub is the name of the production beneath it,
-
# and ops is a list of operators for this precedence level
-
2
def production(name, sub, *ops)
-
16
class_eval <<RUBY, __FILE__, __LINE__ + 1
-
def #{name}
-
interp = try_ops_after_interp(#{ops.inspect}, #{name.inspect}) and return interp
-
return unless e = #{sub}
-
30
while tok = try_tok(#{ops.map {|o| o.inspect}.join(', ')})
-
if interp = try_op_before_interp(tok, e)
-
return interp unless other_interp = try_ops_after_interp(#{ops.inspect}, #{name.inspect}, interp)
-
return other_interp
-
end
-
-
line = @lexer.line
-
e = Operation.new(e, assert_expr(#{sub.inspect}), tok.type)
-
e.line = line
-
end
-
e
-
end
-
RUBY
-
end
-
-
2
def unary(op, sub)
-
8
class_eval <<RUBY, __FILE__, __LINE__ + 1
-
def unary_#{op}
-
return #{sub} unless tok = try_tok(:#{op})
-
interp = try_op_before_interp(tok) and return interp
-
line = @lexer.line
-
op = UnaryOperation.new(assert_expr(:unary_#{op}), :#{op})
-
op.line = line
-
op
-
end
-
RUBY
-
end
-
end
-
-
2
private
-
-
# @private
-
1892
def lexer_class; Lexer; end
-
-
2
def expr
-
2344
line = @lexer.line
-
2344
return unless e = interpolation
-
2344
list = node(List.new([e], :comma), line)
-
2344
while tok = try_tok(:comma)
-
50
if interp = try_op_before_interp(tok, list)
-
return interp unless other_interp = try_ops_after_interp([:comma], :expr, interp)
-
return other_interp
-
end
-
50
list.value << assert_expr(:interpolation)
-
end
-
2344
list.value.size == 1 ? list.value.first : list
-
end
-
-
2
production :equals, :interpolation, :single_eq
-
-
2
def try_op_before_interp(op, prev = nil)
-
87
return unless @lexer.peek && @lexer.peek.type == :begin_interpolation
-
wb = @lexer.whitespace?(op)
-
str = Script::String.new(Lexer::OPERATORS_REVERSE[op.type])
-
str.line = @lexer.line
-
interp = Script::Interpolation.new(prev, str, nil, wb, !:wa, :originally_text)
-
interp.line = @lexer.line
-
interpolation(interp)
-
end
-
-
2
def try_ops_after_interp(ops, name, prev = nil)
-
104343
return unless @lexer.after_interpolation?
-
return unless op = try_tok(*ops)
-
interp = try_op_before_interp(op, prev) and return interp
-
-
wa = @lexer.whitespace?
-
str = Script::String.new(Lexer::OPERATORS_REVERSE[op.type])
-
str.line = @lexer.line
-
interp = Script::Interpolation.new(prev, str, assert_expr(name), !:wb, wa, :originally_text)
-
interp.line = @lexer.line
-
return interp
-
end
-
-
2
def interpolation(first = space)
-
7426
e = first
-
7426
while interp = try_tok(:begin_interpolation)
-
wb = @lexer.whitespace?(interp)
-
line = @lexer.line
-
mid = parse_interpolated
-
wa = @lexer.whitespace?
-
e = Script::Interpolation.new(e, mid, space, wb, wa)
-
e.line = line
-
end
-
7426
e
-
end
-
-
2
def space
-
7880
line = @lexer.line
-
7880
return unless e = or_expr
-
7880
arr = [e]
-
7880
while e = or_expr
-
1479
arr << e
-
end
-
7880
arr.size == 1 ? arr.first : node(List.new(arr, :space), line)
-
end
-
-
2
production :or_expr, :and_expr, :or
-
2
production :and_expr, :eq_or_neq, :and
-
2
production :eq_or_neq, :relational, :eq, :neq
-
2
production :relational, :plus_or_minus, :gt, :gte, :lt, :lte
-
2
production :plus_or_minus, :times_div_or_mod, :plus, :minus
-
2
production :times_div_or_mod, :unary_plus, :times, :div, :mod
-
-
2
unary :plus, :unary_minus
-
2
unary :minus, :unary_div
-
2
unary :div, :unary_not # For strings, so /foo/bar works
-
2
unary :not, :ident
-
-
2
def ident
-
17239
return funcall unless @lexer.peek && @lexer.peek.type == :ident
-
951
return if @stop_at && @stop_at.include?(@lexer.peek.value)
-
-
951
name = @lexer.next
-
951
if color = Color::COLOR_NAMES[name.value.downcase]
-
node(Color.new(color))
-
951
elsif name.value == "true"
-
node(Script::Bool.new(true))
-
951
elsif name.value == "false"
-
node(Script::Bool.new(false))
-
951
elsif name.value == "null"
-
node(Script::Null.new)
-
else
-
951
node(Script::String.new(name.value, :identifier))
-
end
-
end
-
-
2
def funcall
-
16288
return raw unless tok = try_tok(:funcall)
-
1773
args, keywords, splat = fn_arglist || [[], {}]
-
1773
assert_tok(:rparen)
-
1773
node(Script::Funcall.new(tok.value, args, keywords, splat))
-
end
-
-
2
def defn_arglist!(must_have_parens)
-
if must_have_parens
-
assert_tok(:lparen)
-
else
-
return [], nil unless try_tok(:lparen)
-
end
-
return [], nil if try_tok(:rparen)
-
-
res = []
-
splat = nil
-
must_have_default = false
-
loop do
-
c = assert_tok(:const)
-
var = Script::Variable.new(c.value)
-
if try_tok(:colon)
-
val = assert_expr(:space)
-
must_have_default = true
-
elsif must_have_default
-
raise SyntaxError.new("Required argument #{var.inspect} must come before any optional arguments.")
-
elsif try_tok(:splat)
-
splat = var
-
break
-
end
-
res << [var, val]
-
break unless try_tok(:comma)
-
end
-
assert_tok(:rparen)
-
return res, splat
-
end
-
-
2
def fn_arglist
-
1773
arglist(:equals, "function argument")
-
end
-
-
2
def mixin_arglist
-
arglist(:interpolation, "mixin argument")
-
end
-
-
2
def arglist(subexpr, description)
-
1773
return unless e = send(subexpr)
-
-
1773
args = []
-
1773
keywords = {}
-
1773
loop do
-
5449
if @lexer.peek && @lexer.peek.type == :colon
-
name = e
-
@lexer.expected!("comma") unless name.is_a?(Variable)
-
assert_tok(:colon)
-
value = assert_expr(subexpr, description)
-
-
if keywords[name.underscored_name]
-
raise SyntaxError.new("Keyword argument \"#{name.to_sass}\" passed more than once")
-
end
-
-
keywords[name.underscored_name] = value
-
else
-
5449
if !keywords.empty?
-
raise SyntaxError.new("Positional arguments must come before keyword arguments.")
-
end
-
-
5449
return args, keywords, e if try_tok(:splat)
-
5449
args << e
-
end
-
-
5449
return args, keywords unless try_tok(:comma)
-
3676
e = assert_expr(subexpr, description)
-
end
-
end
-
-
2
def raw
-
14515
return special_fun unless tok = try_tok(:raw)
-
84
node(Script::String.new(tok.value))
-
end
-
-
2
def special_fun
-
14431
return paren unless tok = try_tok(:special_fun)
-
20
first = node(Script::String.new(tok.value.first))
-
20
Sass::Util.enum_slice(tok.value[1..-1], 2).inject(first) do |l, (i, r)|
-
Script::Interpolation.new(
-
l, i, r && node(Script::String.new(r)),
-
false, false)
-
end
-
end
-
-
2
def paren
-
13736
return variable unless try_tok(:lparen)
-
was_in_parens = @in_parens
-
@in_parens = true
-
line = @lexer.line
-
e = expr
-
assert_tok(:rparen)
-
return e || node(List.new([], :space), line)
-
ensure
-
13736
@in_parens = was_in_parens
-
end
-
-
2
def variable
-
13736
return string unless c = try_tok(:const)
-
node(Variable.new(*c.value))
-
end
-
-
2
def string
-
13736
return number unless first = try_tok(:string)
-
84
return first.value unless try_tok(:begin_interpolation)
-
line = @lexer.line
-
mid = parse_interpolated
-
last = assert_expr(:string)
-
interp = StringInterpolation.new(first.value, mid, last)
-
interp.line = line
-
interp
-
end
-
-
2
def number
-
14327
return literal unless tok = try_tok(:number)
-
6417
num = tok.value
-
6417
num.original = num.to_s unless @in_parens
-
6417
num
-
end
-
-
2
def literal
-
7910
(t = try_tok(:color)) && (return t.value)
-
end
-
-
# It would be possible to have unified #assert and #try methods,
-
# but detecting the method/token difference turns out to be quite expensive.
-
-
2
EXPR_NAMES = {
-
:string => "string",
-
:default => "expression (e.g. 1px, bold)",
-
:mixin_arglist => "mixin argument",
-
:fn_arglist => "function argument",
-
}
-
-
2
def assert_expr(name, expected = nil)
-
6107
(e = send(name)) && (return e)
-
@lexer.expected!(expected || EXPR_NAMES[name] || EXPR_NAMES[:default])
-
end
-
-
2
def assert_tok(*names)
-
1773
(t = try_tok(*names)) && (return t)
-
@lexer.expected!(names.map {|tok| Lexer::TOKEN_NAMES[tok] || tok}.join(" or "))
-
end
-
-
2
def try_tok(*names)
-
258439
peeked = @lexer.peek
-
258439
peeked && names.include?(peeked.type) && @lexer.next
-
end
-
-
2
def assert_done
-
return if @lexer.done?
-
@lexer.expected!(EXPR_NAMES[:default])
-
end
-
-
2
def node(node, line = @lexer.line)
-
6069
node.line = line
-
6069
node
-
end
-
end
-
end
-
end
-
2
require 'sass/script/literal'
-
-
2
module Sass::Script
-
# A SassScript object representing a CSS string *or* a CSS identifier.
-
2
class String < Literal
-
# The Ruby value of the string.
-
#
-
# @return [String]
-
2
attr_reader :value
-
-
# Whether this is a CSS string or a CSS identifier.
-
# The difference is that strings are written with double-quotes,
-
# while identifiers aren't.
-
#
-
# @return [Symbol] `:string` or `:identifier`
-
2
attr_reader :type
-
-
# Creates a new string.
-
#
-
# @param value [String] See \{#value}
-
# @param type [Symbol] See \{#type}
-
2
def initialize(value, type = :identifier)
-
13872
super(value)
-
13872
@type = type
-
end
-
-
# @see Literal#plus
-
2
def plus(other)
-
other_str = other.is_a?(Sass::Script::String) ? other.value : other.to_s
-
Sass::Script::String.new(self.value + other_str, self.type)
-
end
-
-
# @see Node#to_s
-
2
def to_s(opts = {})
-
13639
if @type == :identifier
-
13581
return @value.gsub(/\n\s*/, " ")
-
end
-
-
58
return "\"#{value.gsub('"', "\\\"")}\"" if opts[:quote] == %q{"}
-
58
return "'#{value.gsub("'", "\\'")}'" if opts[:quote] == %q{'}
-
58
return "\"#{value}\"" unless value.include?('"')
-
return "'#{value}'" unless value.include?("'")
-
"\"#{value.gsub('"', "\\\"")}\"" #'
-
end
-
-
# @see Node#to_sass
-
2
def to_sass(opts = {})
-
233
to_s
-
end
-
end
-
end
-
2
module Sass::Script
-
# A SassScript object representing `#{}` interpolation within a string.
-
#
-
# @see Interpolation
-
2
class StringInterpolation < Node
-
# Interpolation in a string is of the form `"before #{mid} after"`,
-
# where `before` and `after` may include more interpolation.
-
#
-
# @param before [Node] The string before the interpolation
-
# @param mid [Node] The SassScript within the interpolation
-
# @param after [Node] The string after the interpolation
-
2
def initialize(before, mid, after)
-
@before = before
-
@mid = mid
-
@after = after
-
end
-
-
# @return [String] A human-readable s-expression representation of the interpolation
-
2
def inspect
-
"(string_interpolation #{@before.inspect} #{@mid.inspect} #{@after.inspect})"
-
end
-
-
# @see Node#to_sass
-
2
def to_sass(opts = {})
-
# We can get rid of all of this when we remove the deprecated :equals context
-
# XXX CE: It's gone now but I'm not sure what can be removed now.
-
before_unquote, before_quote_char, before_str = parse_str(@before.to_sass(opts))
-
after_unquote, after_quote_char, after_str = parse_str(@after.to_sass(opts))
-
unquote = before_unquote || after_unquote ||
-
(before_quote_char && !after_quote_char && !after_str.empty?) ||
-
(!before_quote_char && after_quote_char && !before_str.empty?)
-
quote_char =
-
if before_quote_char && after_quote_char && before_quote_char != after_quote_char
-
before_str.gsub!("\\'", "'")
-
before_str.gsub!('"', "\\\"")
-
after_str.gsub!("\\'", "'")
-
after_str.gsub!('"', "\\\"")
-
'"'
-
else
-
before_quote_char || after_quote_char
-
end
-
-
res = ""
-
res << 'unquote(' if unquote
-
res << quote_char if quote_char
-
res << before_str
-
res << '#{' << @mid.to_sass(opts) << '}'
-
res << after_str
-
res << quote_char if quote_char
-
res << ')' if unquote
-
res
-
end
-
-
# Returns the three components of the interpolation, `before`, `mid`, and `after`.
-
#
-
# @return [Array<Node>]
-
# @see #initialize
-
# @see Node#children
-
2
def children
-
[@before, @mid, @after].compact
-
end
-
-
# @see Node#deep_copy
-
2
def deep_copy
-
node = dup
-
node.instance_variable_set('@before', @before.deep_copy) if @before
-
node.instance_variable_set('@mid', @mid.deep_copy)
-
node.instance_variable_set('@after', @after.deep_copy) if @after
-
node
-
end
-
-
2
protected
-
-
# Evaluates the interpolation.
-
#
-
# @param environment [Sass::Environment] The environment in which to evaluate the SassScript
-
# @return [Sass::Script::String] The SassScript string that is the value of the interpolation
-
2
def _perform(environment)
-
res = ""
-
before = @before.perform(environment)
-
res << before.value
-
mid = @mid.perform(environment)
-
res << (mid.is_a?(Sass::Script::String) ? mid.value : mid.to_s)
-
res << @after.perform(environment).value
-
opts(Sass::Script::String.new(res, before.type))
-
end
-
-
2
private
-
-
2
def parse_str(str)
-
case str
-
when /^unquote\((["'])(.*)\1\)$/
-
return true, $1, $2
-
when '""'
-
return false, nil, ""
-
when /^(["'])(.*)\1$/
-
return false, $1, $2
-
else
-
return false, nil, str
-
end
-
end
-
end
-
end
-
2
module Sass::Script
-
# A SassScript parse node representing a unary operation,
-
# such as `-$b` or `not true`.
-
#
-
# Currently only `-`, `/`, and `not` are unary operators.
-
2
class UnaryOperation < Node
-
# @return [Symbol] The operation to perform
-
2
attr_reader :operator
-
-
# @return [Script::Node] The parse-tree node for the object of the operator
-
2
attr_reader :operand
-
-
# @param operand [Script::Node] See \{#operand}
-
# @param operator [Symbol] See \{#operator}
-
2
def initialize(operand, operator)
-
@operand = operand
-
@operator = operator
-
super()
-
end
-
-
# @return [String] A human-readable s-expression representation of the operation
-
2
def inspect
-
"(#{@operator.inspect} #{@operand.inspect})"
-
end
-
-
# @see Node#to_sass
-
2
def to_sass(opts = {})
-
operand = @operand.to_sass(opts)
-
if @operand.is_a?(Operation) ||
-
(@operator == :minus &&
-
(operand =~ Sass::SCSS::RX::IDENT) == 0)
-
operand = "(#{@operand.to_sass(opts)})"
-
end
-
op = Lexer::OPERATORS_REVERSE[@operator]
-
op + (op =~ /[a-z]/ ? " " : "") + operand
-
end
-
-
# Returns the operand of the operation.
-
#
-
# @return [Array<Node>]
-
# @see Node#children
-
2
def children
-
[@operand]
-
end
-
-
# @see Node#deep_copy
-
2
def deep_copy
-
node = dup
-
node.instance_variable_set('@operand', @operand.deep_copy)
-
node
-
end
-
-
2
protected
-
-
# Evaluates the operation.
-
#
-
# @param environment [Sass::Environment] The environment in which to evaluate the SassScript
-
# @return [Literal] The SassScript object that is the value of the operation
-
# @raise [Sass::SyntaxError] if the operation is undefined for the operand
-
2
def _perform(environment)
-
operator = "unary_#{@operator}"
-
literal = @operand.perform(environment)
-
literal.send(operator)
-
rescue NoMethodError => e
-
raise e unless e.name.to_s == operator.to_s
-
raise Sass::SyntaxError.new("Undefined unary operation: \"#{@operator} #{literal}\".")
-
end
-
end
-
end
-
2
module Sass
-
2
module Script
-
# A SassScript parse node representing a variable.
-
2
class Variable < Node
-
# The name of the variable.
-
#
-
# @return [String]
-
2
attr_reader :name
-
-
# The underscored name of the variable.
-
#
-
# @return [String]
-
2
attr_reader :underscored_name
-
-
# @param name [String] See \{#name}
-
2
def initialize(name)
-
@name = name
-
@underscored_name = name.gsub(/-/,"_")
-
super()
-
end
-
-
# @return [String] A string representation of the variable
-
2
def inspect(opts = {})
-
"$#{dasherize(name, opts)}"
-
end
-
2
alias_method :to_sass, :inspect
-
-
# Returns an empty array.
-
#
-
# @return [Array<Node>] empty
-
# @see Node#children
-
2
def children
-
[]
-
end
-
-
# @see Node#deep_copy
-
2
def deep_copy
-
dup
-
end
-
-
2
protected
-
-
# Evaluates the variable.
-
#
-
# @param environment [Sass::Environment] The environment in which to evaluate the SassScript
-
# @return [Literal] The SassScript object that is the value of the variable
-
# @raise [Sass::SyntaxError] if the variable is undefined
-
2
def _perform(environment)
-
raise SyntaxError.new("Undefined variable: \"$#{name}\".") unless val = environment.var(name)
-
if val.is_a?(Number)
-
val = val.dup
-
val.original = nil
-
end
-
return val
-
end
-
end
-
end
-
end
-
2
require 'sass/scss/rx'
-
2
require 'sass/scss/script_lexer'
-
2
require 'sass/scss/script_parser'
-
2
require 'sass/scss/parser'
-
2
require 'sass/scss/static_parser'
-
2
require 'sass/scss/css_parser'
-
-
2
module Sass
-
# SCSS is the CSS syntax for Sass.
-
# It parses into the same syntax tree as Sass,
-
# and generates the same sort of output CSS.
-
#
-
# This module contains code for the parsing of SCSS.
-
# The evaluation is handled by the broader {Sass} module.
-
2
module SCSS; end
-
end
-
2
require 'sass/script/css_parser'
-
-
2
module Sass
-
2
module SCSS
-
# This is a subclass of {Parser} which only parses plain CSS.
-
# It doesn't support any Sass extensions, such as interpolation,
-
# parent references, nested selectors, and so forth.
-
# It does support all the same CSS hacks as the SCSS parser, though.
-
2
class CssParser < StaticParser
-
2
private
-
-
2
def placeholder_selector; nil; end
-
2
def parent_selector; nil; end
-
2
def interpolation; nil; end
-
2
def use_css_import?; true; end
-
-
2
def block_child(context)
-
case context
-
when :ruleset
-
declaration
-
when :stylesheet
-
directive || ruleset
-
when :directive
-
directive || declaration_or_ruleset
-
end
-
end
-
-
2
def nested_properties!(node, space)
-
expected('expression (e.g. 1px, bold)');
-
end
-
-
2
@sass_script_parser = Class.new(Sass::Script::CssParser)
-
2
@sass_script_parser.send(:include, ScriptParser)
-
end
-
end
-
end
-
2
require 'set'
-
-
2
module Sass
-
2
module SCSS
-
# The parser for SCSS.
-
# It parses a string of code into a tree of {Sass::Tree::Node}s.
-
2
class Parser
-
# @param str [String, StringScanner] The source document to parse.
-
# Note that `Parser` *won't* raise a nice error message if this isn't properly parsed;
-
# for that, you should use the higher-level {Sass::Engine} or {Sass::CSS}.
-
# @param filename [String] The name of the file being parsed. Used for warnings.
-
# @param line [Fixnum] The line on which the source string appeared,
-
# if it's part of another document.
-
2
def initialize(str, filename, line = 1)
-
13377
@template = str
-
13377
@filename = filename
-
13377
@line = line
-
13377
@strs = []
-
end
-
-
# Parses an SCSS document.
-
#
-
# @return [Sass::Tree::RootNode] The root node of the document tree
-
# @raise [Sass::SyntaxError] if there's a syntax error in the document
-
2
def parse
-
1
init_scanner!
-
1
root = stylesheet
-
1
expected("selector or at-rule") unless @scanner.eos?
-
1
root
-
end
-
-
# Parses an identifier with interpolation.
-
# Note that this won't assert that the identifier takes up the entire input string;
-
# it's meant to be used with `StringScanner`s as part of other parsers.
-
#
-
# @return [Array<String, Sass::Script::Node>, nil]
-
# The interpolated identifier, or nil if none could be parsed
-
2
def parse_interp_ident
-
init_scanner!
-
interp_ident
-
end
-
-
# Parses a media query list.
-
#
-
# @return [Sass::Media::QueryList] The parsed query list
-
# @raise [Sass::SyntaxError] if there's a syntax error in the query list,
-
# or if it doesn't take up the entire input string.
-
2
def parse_media_query_list
-
211
init_scanner!
-
211
ql = media_query_list
-
211
expected("media query list") unless @scanner.eos?
-
211
ql
-
end
-
-
# Parses a supports query condition.
-
#
-
# @return [Sass::Supports::Condition] The parsed condition
-
# @raise [Sass::SyntaxError] if there's a syntax error in the condition,
-
# or if it doesn't take up the entire input string.
-
2
def parse_supports_condition
-
init_scanner!
-
condition = supports_condition
-
expected("supports condition") unless @scanner.eos?
-
condition
-
end
-
-
2
private
-
-
2
include Sass::SCSS::RX
-
-
2
def init_scanner!
-
6795
@scanner =
-
if @template.is_a?(StringScanner)
-
@template
-
else
-
6795
Sass::Util::MultibyteStringScanner.new(@template.gsub("\r", ""))
-
end
-
end
-
-
2
def stylesheet
-
1
node = node(Sass::Tree::RootNode.new(@scanner.string))
-
5498
block_contents(node, :stylesheet) {s(node)}
-
end
-
-
2
def s(node)
-
12279
while tok(S) || tok(CDC) || tok(CDO) || (c = tok(SINGLE_LINE_COMMENT)) || (c = tok(COMMENT))
-
5193
next unless c
-
1285
process_comment c, node
-
1285
c = nil
-
end
-
5497
true
-
end
-
-
2
def ss
-
90268
nil while tok(S) || tok(SINGLE_LINE_COMMENT) || tok(COMMENT)
-
90268
true
-
end
-
-
2
def ss_comments(node)
-
36313
while tok(S) || (c = tok(SINGLE_LINE_COMMENT)) || (c = tok(COMMENT))
-
12070
next unless c
-
453
process_comment c, node
-
453
c = nil
-
end
-
-
17930
true
-
end
-
-
2
def whitespace
-
return unless tok(S) || tok(SINGLE_LINE_COMMENT) || tok(COMMENT)
-
ss
-
end
-
-
2
def process_comment(text, node)
-
1738
silent = text =~ /^\/\//
-
1738
loud = !silent && text =~ %r{^/[/*]!}
-
1738
line = @line - text.count("\n")
-
-
1738
if silent
-
value = [text.sub(/^\s*\/\//, '/*').gsub(/^\s*\/\//, ' *') + ' */']
-
else
-
1738
value = Sass::Engine.parse_interp(text, line, @scanner.pos - text.size, :filename => @filename)
-
1738
value.unshift(@scanner.
-
string[0...@scanner.pos].
-
reverse[/.*?\*\/(.*?)($|\Z)/, 1].
-
reverse.gsub(/[^\s]/, ' '))
-
end
-
-
1738
type = if silent then :silent elsif loud then :loud else :normal end
-
1738
comment = Sass::Tree::CommentNode.new(value, type)
-
1738
comment.line = line
-
1738
node << comment
-
end
-
-
2
DIRECTIVES = Set[:mixin, :include, :function, :return, :debug, :warn, :for,
-
:each, :while, :if, :else, :extend, :import, :media, :charset, :content,
-
:_moz_document]
-
-
2
PREFIXED_DIRECTIVES = Set[:supports]
-
-
2
def directive
-
23427
return unless tok(/@/)
-
423
name = tok!(IDENT)
-
423
ss
-
-
423
if dir = special_directive(name)
-
214
return dir
-
elsif dir = prefixed_directive(name)
-
return dir
-
end
-
-
# Most at-rules take expressions (e.g. @import),
-
# but some (e.g. @page) take selector-like arguments.
-
# Some take no arguments at all.
-
209
val = expr || selector
-
209
val = val ? ["@#{name} "] + Sass::Util.strip_string_array(val) : ["@#{name}"]
-
209
directive_body(val)
-
end
-
-
2
def directive_body(value)
-
209
node = node(Sass::Tree::DirectiveNode.new(value))
-
-
209
if tok(/\{/)
-
209
node.has_children = true
-
209
block_contents(node, :directive)
-
209
tok!(/\}/)
-
end
-
-
209
node
-
end
-
-
2
def special_directive(name)
-
423
sym = name.gsub('-', '_').to_sym
-
423
DIRECTIVES.include?(sym) && send("#{sym}_directive")
-
end
-
-
2
def prefixed_directive(name)
-
209
sym = name.gsub(/^-[a-z0-9]+-/i, '').gsub('-', '_').to_sym
-
209
PREFIXED_DIRECTIVES.include?(sym) && send("#{sym}_directive", name)
-
end
-
-
2
def mixin_directive
-
name = tok! IDENT
-
args, splat = sass_script(:parse_mixin_definition_arglist)
-
ss
-
block(node(Sass::Tree::MixinDefNode.new(name, args, splat)), :directive)
-
end
-
-
2
def include_directive
-
name = tok! IDENT
-
args, keywords, splat = sass_script(:parse_mixin_include_arglist)
-
ss
-
include_node = node(Sass::Tree::MixinNode.new(name, args, keywords, splat))
-
if tok?(/\{/)
-
include_node.has_children = true
-
block(include_node, :directive)
-
else
-
include_node
-
end
-
end
-
-
2
def content_directive
-
ss
-
node(Sass::Tree::ContentNode.new)
-
end
-
-
2
def function_directive
-
name = tok! IDENT
-
args, splat = sass_script(:parse_function_definition_arglist)
-
ss
-
block(node(Sass::Tree::FunctionNode.new(name, args, splat)), :function)
-
end
-
-
2
def return_directive
-
node(Sass::Tree::ReturnNode.new(sass_script(:parse)))
-
end
-
-
2
def debug_directive
-
node(Sass::Tree::DebugNode.new(sass_script(:parse)))
-
end
-
-
2
def warn_directive
-
node(Sass::Tree::WarnNode.new(sass_script(:parse)))
-
end
-
-
2
def for_directive
-
tok!(/\$/)
-
var = tok! IDENT
-
ss
-
-
tok!(/from/)
-
from = sass_script(:parse_until, Set["to", "through"])
-
ss
-
-
@expected = '"to" or "through"'
-
exclusive = (tok(/to/) || tok!(/through/)) == 'to'
-
to = sass_script(:parse)
-
ss
-
-
block(node(Sass::Tree::ForNode.new(var, from, to, exclusive)), :directive)
-
end
-
-
2
def each_directive
-
tok!(/\$/)
-
var = tok! IDENT
-
ss
-
-
tok!(/in/)
-
list = sass_script(:parse)
-
ss
-
-
block(node(Sass::Tree::EachNode.new(var, list)), :directive)
-
end
-
-
2
def while_directive
-
expr = sass_script(:parse)
-
ss
-
block(node(Sass::Tree::WhileNode.new(expr)), :directive)
-
end
-
-
2
def if_directive
-
expr = sass_script(:parse)
-
ss
-
node = block(node(Sass::Tree::IfNode.new(expr)), :directive)
-
pos = @scanner.pos
-
line = @line
-
ss
-
-
else_block(node) ||
-
begin
-
# Backtrack in case there are any comments we want to parse
-
@scanner.pos = pos
-
@line = line
-
node
-
end
-
end
-
-
2
def else_block(node)
-
return unless tok(/@else/)
-
ss
-
else_node = block(
-
Sass::Tree::IfNode.new((sass_script(:parse) if tok(/if/))),
-
:directive)
-
node.add_else(else_node)
-
pos = @scanner.pos
-
line = @line
-
ss
-
-
else_block(node) ||
-
begin
-
# Backtrack in case there are any comments we want to parse
-
@scanner.pos = pos
-
@line = line
-
node
-
end
-
end
-
-
2
def else_directive
-
err("Invalid CSS: @else must come after @if")
-
end
-
-
2
def extend_directive
-
1
selector = expr!(:selector_sequence)
-
1
optional = tok(OPTIONAL)
-
1
ss
-
1
node(Sass::Tree::ExtendNode.new(selector, !!optional))
-
end
-
-
2
def import_directive
-
values = []
-
-
loop do
-
values << expr!(:import_arg)
-
break if use_css_import?
-
break unless tok(/,/)
-
ss
-
end
-
-
return values
-
end
-
-
2
def import_arg
-
line = @line
-
return unless (str = tok(STRING)) || (uri = tok?(/url\(/i))
-
if uri
-
str = sass_script(:parse_string)
-
ss
-
media = media_query_list
-
ss
-
return node(Tree::CssImportNode.new(str, media.to_a))
-
end
-
-
path = @scanner[1] || @scanner[2]
-
ss
-
-
media = media_query_list
-
if path =~ /^(https?:)?\/\// || media || use_css_import?
-
node = Sass::Tree::CssImportNode.new(str, media.to_a)
-
else
-
node = Sass::Tree::ImportNode.new(path.strip)
-
end
-
node.line = line
-
node
-
end
-
-
2
def use_css_import?; false; end
-
-
2
def media_directive
-
211
block(node(Sass::Tree::MediaNode.new(expr!(:media_query_list).to_a)), :directive)
-
end
-
-
# http://www.w3.org/TR/css3-mediaqueries/#syntax
-
2
def media_query_list
-
422
return unless query = media_query
-
422
queries = [query]
-
-
422
ss
-
422
while tok(/,/)
-
6
ss; queries << expr!(:media_query)
-
end
-
422
ss
-
-
422
Sass::Media::QueryList.new(queries)
-
end
-
-
2
def media_query
-
428
if ident1 = interp_ident
-
74
ss
-
74
ident2 = interp_ident
-
74
ss
-
74
if ident2 && ident2.length == 1 && ident2[0].is_a?(String) && ident2[0].downcase == 'and'
-
36
query = Sass::Media::Query.new([], ident1, [])
-
else
-
38
if ident2
-
query = Sass::Media::Query.new(ident1, ident2, [])
-
else
-
38
query = Sass::Media::Query.new([], ident1, [])
-
end
-
38
return query unless tok(/and/i)
-
ss
-
end
-
end
-
-
390
if query
-
36
expr = expr!(:media_expr)
-
else
-
354
return unless expr = media_expr
-
end
-
390
query ||= Sass::Media::Query.new([], [], [])
-
390
query.expressions << expr
-
-
390
ss
-
390
while tok(/and/i)
-
68
ss; query.expressions << expr!(:media_expr)
-
end
-
-
390
query
-
end
-
-
2
def media_expr
-
458
interp = interpolation and return interp
-
458
return unless tok(/\(/)
-
458
res = ['(']
-
458
ss
-
458
res << sass_script(:parse)
-
-
458
if tok(/:/)
-
450
res << ': '
-
450
ss
-
450
res << sass_script(:parse)
-
end
-
458
res << tok!(/\)/)
-
458
ss
-
458
res
-
end
-
-
2
def charset_directive
-
2
tok! STRING
-
2
name = @scanner[1] || @scanner[2]
-
2
ss
-
2
node(Sass::Tree::CharsetNode.new(name))
-
end
-
-
# The document directive is specified in
-
# http://www.w3.org/TR/css3-conditional/, but Gecko allows the
-
# `url-prefix` and `domain` functions to omit quotation marks, contrary to
-
# the standard.
-
#
-
# We could parse all document directives according to Mozilla's syntax,
-
# but if someone's using e.g. @-webkit-document we don't want them to
-
# think WebKit works sans quotes.
-
2
def _moz_document_directive
-
res = ["@-moz-document "]
-
loop do
-
res << str{ss} << expr!(:moz_document_function)
-
break unless c = tok(/,/)
-
res << c
-
end
-
directive_body(res.flatten)
-
end
-
-
2
def moz_document_function
-
return unless val = interp_uri || _interp_string(:url_prefix) ||
-
_interp_string(:domain) || function(!:allow_var) || interpolation
-
ss
-
val
-
end
-
-
# http://www.w3.org/TR/css3-conditional/
-
2
def supports_directive(name)
-
condition = expr!(:supports_condition)
-
node = node(Sass::Tree::SupportsNode.new(name, condition))
-
-
tok!(/\{/)
-
node.has_children = true
-
block_contents(node, :directive)
-
tok!(/\}/)
-
-
node
-
end
-
-
2
def supports_condition
-
supports_negation || supports_operator || supports_interpolation
-
end
-
-
2
def supports_negation
-
return unless tok(/not/i)
-
ss
-
Sass::Supports::Negation.new(expr!(:supports_condition_in_parens))
-
end
-
-
2
def supports_operator
-
return unless cond = supports_condition_in_parens
-
return cond unless op = tok(/and|or/i)
-
begin
-
ss
-
cond = Sass::Supports::Operator.new(
-
cond, expr!(:supports_condition_in_parens), op)
-
end while op = tok(/and|or/i)
-
cond
-
end
-
-
2
def supports_condition_in_parens
-
interp = supports_interpolation and return interp
-
return unless tok(/\(/); ss
-
if cond = supports_condition
-
tok!(/\)/); ss
-
cond
-
else
-
name = sass_script(:parse)
-
tok!(/:/); ss
-
value = sass_script(:parse)
-
tok!(/\)/); ss
-
Sass::Supports::Declaration.new(name, value)
-
end
-
end
-
-
2
def supports_declaration_condition
-
return unless tok(/\(/); ss
-
supports_declaration_body
-
end
-
-
2
def supports_interpolation
-
return unless interp = interpolation
-
ss
-
Sass::Supports::Interpolation.new(interp)
-
end
-
-
2
def variable
-
23427
return unless tok(/\$/)
-
name = tok!(IDENT)
-
ss; tok!(/:/); ss
-
-
expr = sass_script(:parse)
-
guarded = tok(DEFAULT)
-
node(Sass::Tree::VariableNode.new(name, expr, guarded))
-
end
-
-
2
def operator
-
# Many of these operators (all except / and ,)
-
# are disallowed by the CSS spec,
-
# but they're included here for compatibility
-
# with some proprietary MS properties
-
2838
str {ss if tok(/[\/,:.=]/)}
-
end
-
-
2
def ruleset
-
6583
return unless rules = selector_sequence
-
6582
block(node(Sass::Tree::RuleNode.new(rules.flatten.compact)), :ruleset)
-
end
-
-
2
def block(node, context)
-
6793
node.has_children = true
-
6793
tok!(/\{/)
-
6793
block_contents(node, context)
-
6793
tok!(/\}/)
-
6793
node
-
end
-
-
# A block may contain declarations and/or rulesets
-
2
def block_contents(node, context)
-
7003
block_given? ? yield : ss_comments(node)
-
7003
node << (child = block_child(context))
-
7003
while tok(/;/) || has_children?(child)
-
16424
block_given? ? yield : ss_comments(node)
-
16424
node << (child = block_child(context))
-
end
-
7003
node
-
end
-
-
2
def block_child(context)
-
23427
return variable || directive if context == :function
-
23427
return variable || directive || ruleset if context == :stylesheet
-
17930
variable || directive || declaration_or_ruleset
-
end
-
-
2
def has_children?(child_or_array)
-
14005
return false unless child_or_array
-
10404
return child_or_array.last.has_children if child_or_array.is_a?(Array)
-
10404
return child_or_array.has_children
-
end
-
-
# This is a nasty hack, and the only place in the parser
-
# that requires a large amount of backtracking.
-
# The reason is that we can't figure out if certain strings
-
# are declarations or rulesets with fixed finite lookahead.
-
# For example, "foo:bar baz baz baz..." could be either a property
-
# or a selector.
-
#
-
# To handle this, we simply check if it works as a property
-
# (which is the most common case)
-
# and, if it doesn't, try it as a ruleset.
-
#
-
# We could eke some more efficiency out of this
-
# by handling some easy cases (first token isn't an identifier,
-
# no colon after the identifier, whitespace after the colon),
-
# but I'm not sure the gains would be worth the added complexity.
-
2
def declaration_or_ruleset
-
17929
old_use_property_exception, @use_property_exception =
-
@use_property_exception, false
-
17929
decl_err = catch_error do
-
17929
decl = declaration
-
16916
unless decl && decl.has_children
-
# We want an exception if it's not there,
-
# but we don't want to consume if it is
-
16916
tok!(/[;}]/) unless tok?(/[;}]/)
-
end
-
16421
return decl
-
end
-
-
3016
ruleset_err = catch_error {return ruleset}
-
rethrow(@use_property_exception ? decl_err : ruleset_err)
-
ensure
-
17929
@use_property_exception = old_use_property_exception
-
end
-
-
2
def selector_sequence
-
6584
if sel = tok(STATIC_SELECTOR, true)
-
4968
return [sel]
-
end
-
-
1616
rules = []
-
1616
return unless v = selector
-
1615
rules.concat v
-
-
1615
ws = ''
-
1615
while tok(/,/)
-
6172
ws << str {ss}
-
3086
if v = selector
-
3086
rules << ',' << ws
-
3086
rules.concat v
-
3086
ws = ''
-
end
-
end
-
1615
rules
-
end
-
-
2
def selector
-
4910
return unless sel = _selector
-
4899
sel.to_a
-
end
-
-
2
def selector_comma_sequence
-
6583
return unless sel = _selector
-
6583
selectors = [sel]
-
6583
ws = ''
-
6583
while tok(/,/)
-
6952
ws << str{ss}
-
3476
if sel = _selector
-
3476
selectors << sel
-
3476
selectors[-1] = Selector::Sequence.new(["\n"] + selectors.last.members) if ws.include?("\n")
-
3476
ws = ''
-
end
-
end
-
6583
Selector::CommaSequence.new(selectors)
-
end
-
-
2
def _selector
-
# The combinator here allows the "> E" hack
-
14969
return unless val = combinator || simple_selector_sequence
-
29916
nl = str{ss}.include?("\n")
-
14958
res = []
-
14958
res << val
-
14958
res << "\n" if nl
-
-
14958
while val = combinator || simple_selector_sequence
-
19892
res << val
-
39784
res << "\n" if str{ss}.include?("\n")
-
end
-
14958
Selector::Sequence.new(res.compact)
-
end
-
-
2
def combinator
-
49819
tok(PLUS) || tok(GREATER) || tok(TILDE) || reference_combinator
-
end
-
-
2
def reference_combinator
-
41932
return unless tok(/\//)
-
res = ['/']
-
ns, name = expr!(:qualified_name)
-
res << ns << '|' if ns
-
res << name << tok!(/\//)
-
res = res.flatten
-
res = res.join '' if res.all? {|e| e.is_a?(String)}
-
res
-
end
-
-
2
def simple_selector_sequence
-
# Returning expr by default allows for stuff like
-
# http://www.w3.org/TR/css3-animations/#keyframes-
-
67905
return expr(!:allow_var) unless e = element_name || id_selector ||
-
class_selector || placeholder_selector || attrib || pseudo ||
-
parent_selector || interpolation_selector
-
25973
res = [e]
-
-
# The tok(/\*/) allows the "E*" hack
-
25973
while v = id_selector || class_selector || placeholder_selector || attrib ||
-
pseudo || interpolation_selector ||
-
25973
(tok(/\*/) && Selector::Universal.new(nil))
-
10823
res << v
-
end
-
-
25973
pos = @scanner.pos
-
25973
line = @line
-
51946
if sel = str? {simple_selector_sequence}
-
@scanner.pos = pos
-
@line = line
-
begin
-
# If we see "*E", don't force a throw because this could be the
-
# "*prop: val" hack.
-
expected('"{"') if res.length == 1 && res[0].is_a?(Selector::Universal)
-
throw_error {expected('"{"')}
-
rescue Sass::SyntaxError => e
-
e.message << "\n\n\"#{sel}\" may only be used at the beginning of a compound selector."
-
raise e
-
end
-
end
-
-
25973
Selector::SimpleSequence.new(res, tok(/!/))
-
end
-
-
2
def parent_selector
-
41932
return unless tok(/&/)
-
Selector::Parent.new
-
end
-
-
2
def class_selector
-
96383
return unless tok(/\./)
-
20266
@expected = "class name"
-
20266
Selector::Class.new(merge(expr!(:interp_ident)))
-
end
-
-
2
def id_selector
-
96426
return unless tok(/#(?!\{)/)
-
43
@expected = "id name"
-
43
Selector::Id.new(merge(expr!(:interp_name)))
-
end
-
-
2
def placeholder_selector
-
76117
return unless tok(/%/)
-
@expected = "placeholder name"
-
Selector::Placeholder.new(merge(expr!(:interp_ident)))
-
end
-
-
2
def element_name
-
67905
ns, name = Sass::Util.destructure(qualified_name(:allow_star_name))
-
67905
return unless ns || name
-
-
8275
if name == '*'
-
17
Selector::Universal.new(merge(ns))
-
else
-
8258
Selector::Element.new(merge(name), merge(ns))
-
end
-
end
-
-
2
def qualified_name(allow_star_name=false)
-
67905
return unless name = interp_ident || tok(/\*/) || (tok?(/\|/) && "")
-
8275
return nil, name unless tok(/\|/)
-
-
return name, expr!(:interp_ident) unless allow_star_name
-
@expected = "identifier or *"
-
return name, interp_ident || tok!(/\*/)
-
end
-
-
2
def interpolation_selector
-
67905
return unless script = interpolation
-
Selector::Interpolation.new(script)
-
end
-
-
2
def attrib
-
76117
return unless tok(/\[/)
-
1240
ss
-
1240
ns, name = attrib_name!
-
1240
ss
-
-
1240
if op = tok(/=/) ||
-
tok(INCLUDES) ||
-
tok(DASHMATCH) ||
-
tok(PREFIXMATCH) ||
-
tok(SUFFIXMATCH) ||
-
tok(SUBSTRINGMATCH)
-
438
@expected = "identifier or string"
-
438
ss
-
438
val = interp_ident || expr!(:interp_string)
-
438
ss
-
end
-
1240
flags = interp_ident || interp_string
-
1240
tok!(/\]/)
-
-
1240
Selector::Attribute.new(merge(name), merge(ns), op, merge(val), merge(flags))
-
end
-
-
2
def attrib_name!
-
1240
if name_or_ns = interp_ident
-
# E, E|E
-
1240
if tok(/\|(?!=)/)
-
ns = name_or_ns
-
name = interp_ident
-
else
-
1240
name = name_or_ns
-
end
-
else
-
# *|E or |E
-
ns = [tok(/\*/) || ""]
-
tok!(/\|/)
-
name = expr!(:interp_ident)
-
end
-
1240
return ns, name
-
end
-
-
2
def pseudo
-
74877
return unless s = tok(/::?/)
-
6972
@expected = "pseudoclass or pseudoelement"
-
6972
name = expr!(:interp_ident)
-
6972
if tok(/\(/)
-
212
ss
-
212
arg = expr!(:pseudo_arg)
-
212
while tok(/,/)
-
arg << ',' << str{ss}
-
arg.concat expr!(:pseudo_arg)
-
end
-
212
tok!(/\)/)
-
end
-
6972
Selector::Pseudo.new(s == ':' ? :class : :element, merge(name), merge(arg))
-
end
-
-
2
def pseudo_arg
-
# In the CSS spec, every pseudo-class/element either takes a pseudo
-
# expression or a selector comma sequence as an argument. However, we
-
# don't want to have to know which takes which, so we handle both at
-
# once.
-
#
-
# However, there are some ambiguities between the two. For instance, "n"
-
# could start a pseudo expression like "n+1", or it could start a
-
# selector like "n|m". In order to handle this, we must regrettably
-
# backtrack.
-
212
expr, sel = nil, nil
-
212
pseudo_err = catch_error do
-
212
expr = pseudo_expr
-
212
next if tok?(/[,)]/)
-
198
expr = nil
-
198
expected '")"'
-
end
-
-
212
return expr if expr
-
396
sel_err = catch_error {sel = selector}
-
198
return sel if sel
-
rethrow pseudo_err if pseudo_err
-
rethrow sel_err if sel_err
-
return
-
end
-
-
2
def pseudo_expr
-
212
return unless e = tok(PLUS) || tok(/[-*]/) || tok(NUMBER) ||
-
interp_string || tok(IDENT) || interpolation
-
28
res = [e, str{ss}]
-
14
while e = tok(PLUS) || tok(/[-*]/) || tok(NUMBER) ||
-
interp_string || tok(IDENT) || interpolation
-
res << e << str{ss}
-
end
-
14
res
-
end
-
-
2
def declaration
-
# This allows the "*prop: val", ":prop: val", and ".prop: val" hacks
-
17929
if s = tok(/[:\*\.]|\#(?!\{)/)
-
904
@use_property_exception = s !~ /[\.\#]/
-
1808
name = [s, str{ss}, *expr!(:interp_ident)]
-
else
-
17025
return unless name = interp_ident
-
12930
name = [name] if name.is_a?(String)
-
end
-
13831
if comment = tok(COMMENT)
-
name << comment
-
end
-
13831
ss
-
-
13831
tok!(/:/)
-
12821
space, value = value!
-
12821
ss
-
12821
require_block = tok?(/\{/)
-
-
12821
node = node(Sass::Tree::PropNode.new(name.flatten.compact, value, :new))
-
-
12821
return node unless require_block
-
nested_properties! node, space
-
end
-
-
2
def value!
-
25642
space = !str {ss}.empty?
-
12821
@use_property_exception ||= space || !tok?(IDENT)
-
-
12821
return true, Sass::Script::String.new("") if tok?(/\{/)
-
# This is a bit of a dirty trick:
-
# if the value is completely static,
-
# we don't parse it at all, and instead return a plain old string
-
# containing the value.
-
# This results in a dramatic speed increase.
-
12821
if val = tok(STATIC_VALUE, true)
-
11385
return space, Sass::Script::String.new(val.strip)
-
end
-
1436
return space, sass_script(:parse)
-
end
-
-
2
def nested_properties!(node, space)
-
err(<<MESSAGE) unless space
-
Invalid CSS: a space is required between a property and its definition
-
when it has other properties nested beneath it.
-
MESSAGE
-
-
@use_property_exception = true
-
@expected = 'expression (e.g. 1px, bold) or "{"'
-
block(node, :property)
-
end
-
-
2
def expr(allow_var = true)
-
42141
return unless t = term(allow_var)
-
2378
res = [t, str{ss}]
-
-
2608
while (o = operator) && (t = term(allow_var))
-
460
res << o << t << str{ss}
-
end
-
-
1189
res.flatten
-
end
-
-
2
def term(allow_var)
-
43560
if e = tok(NUMBER) ||
-
interp_uri ||
-
function(allow_var) ||
-
interp_string ||
-
tok(UNICODERANGE) ||
-
interp_ident ||
-
tok(HEXCOLOR) ||
-
42141
(allow_var && var_expr)
-
1419
return e
-
end
-
-
42141
return unless op = tok(/[+-]/)
-
110
@expected = "number or function"
-
110
return [op, tok(NUMBER) || function(allow_var) ||
-
110
(allow_var && var_expr) || expr!(:interpolation)]
-
end
-
-
2
def function(allow_var)
-
42450
return unless name = tok(FUNCTION)
-
if name == "expression(" || name == "calc("
-
str, _ = Sass::Shared.balance(@scanner, ?(, ?), 1)
-
[name, str]
-
else
-
[name, str{ss}, expr(allow_var), tok!(/\)/)]
-
end
-
end
-
-
2
def var_expr
-
209
return unless tok(/\$/)
-
line = @line
-
var = Sass::Script::Variable.new(tok!(IDENT))
-
var.line = line
-
var
-
end
-
-
2
def interpolation
-
93659
return unless tok(INTERP_START)
-
sass_script(:parse_interpolated)
-
end
-
-
2
def interp_string
-
16149
_interp_string(:double) || _interp_string(:single)
-
end
-
-
2
def interp_uri
-
15272
_interp_string(:uri)
-
end
-
-
2
def _interp_string(type)
-
47422
return unless start = tok(Sass::Script::Lexer::STRING_REGULAR_EXPRESSIONS[type][false])
-
148
res = [start]
-
-
148
mid_re = Sass::Script::Lexer::STRING_REGULAR_EXPRESSIONS[type][true]
-
# @scanner[2].empty? means we've started an interpolated section
-
148
while @scanner[2] == '#{'
-
@scanner.pos -= 2 # Don't consume the #{
-
res.last.slice!(-2..-1)
-
res << expr!(:interpolation) << tok(mid_re)
-
end
-
148
res
-
end
-
-
2
def interp_ident(start = IDENT)
-
68836
return unless val = tok(start) || interpolation || tok(IDENT_HYPHEN_INTERP, true)
-
27855
res = [val]
-
27855
while val = tok(NAME) || interpolation
-
res << val
-
end
-
27855
res
-
end
-
-
2
def interp_ident_or_var
-
(id = interp_ident) and return id
-
(var = var_expr) and return [var]
-
end
-
-
2
def interp_name
-
43
interp_ident NAME
-
end
-
-
2
def str
-
57989
@strs.push ""
-
57989
yield
-
57989
@strs.last
-
ensure
-
57989
@strs.pop
-
end
-
-
2
def str?
-
25973
pos = @scanner.pos
-
25973
line = @line
-
25973
@strs.push ""
-
51946
throw_error {yield} && @strs.last
-
rescue Sass::SyntaxError
-
110
@scanner.pos = pos
-
110
@line = line
-
110
nil
-
ensure
-
25973
@strs.pop
-
end
-
-
2
def node(node)
-
19827
node.line = @line
-
19827
node
-
end
-
-
2
@sass_script_parser = Class.new(Sass::Script::Parser)
-
2
@sass_script_parser.send(:include, ScriptParser)
-
# @private
-
2346
def self.sass_script_parser; @sass_script_parser; end
-
-
2
def sass_script(*args)
-
2344
parser = self.class.sass_script_parser.new(@scanner, @line,
-
2344
@scanner.pos - (@scanner.string[0...@scanner.pos].rindex("\n") || 0))
-
2344
result = parser.send(*args)
-
2344
unless @strs.empty?
-
# Convert to CSS manually so that comments are ignored.
-
src = result.to_sass
-
@strs.each {|s| s << src}
-
end
-
2344
@line = parser.line
-
2344
result
-
rescue Sass::SyntaxError => e
-
throw(:_sass_parser_error, true) if @throw_error
-
raise e
-
end
-
-
2
def merge(arr)
-
55746
arr && Sass::Util.merge_adjacent_strings([arr].flatten)
-
end
-
-
2
EXPR_NAMES = {
-
:media_query => "media query (e.g. print, screen, print and screen)",
-
:media_query_list => "media query (e.g. print, screen, print and screen)",
-
:media_expr => "media expression (e.g. (min-device-width: 800px))",
-
:pseudo_arg => "expression (e.g. fr, 2n+1)",
-
:interp_ident => "identifier",
-
:interp_name => "identifier",
-
:qualified_name => "identifier",
-
:expr => "expression (e.g. 1px, bold)",
-
:_selector => "selector",
-
:selector_comma_sequence => "selector",
-
:simple_selector_sequence => "selector",
-
:import_arg => "file to import (string or url())",
-
:moz_document_function => "matching function (e.g. url-prefix(), domain())",
-
:supports_condition => "@supports condition (e.g. (display: flexbox))",
-
:supports_condition_in_parens => "@supports condition (e.g. (display: flexbox))",
-
}
-
-
2
TOK_NAMES = Sass::Util.to_hash(
-
104
Sass::SCSS::RX.constants.map {|c| [Sass::SCSS::RX.const_get(c), c.downcase]}).
-
merge(IDENT => "identifier", /[;}]/ => '";"')
-
-
2
def tok?(rx)
-
108534
@scanner.match?(rx)
-
end
-
-
2
def expr!(name)
-
35708
(e = send(name)) && (return e)
-
113
expected(EXPR_NAMES[name] || name.to_s)
-
end
-
-
2
def tok!(rx)
-
30456
(t = tok(rx)) && (return t)
-
1505
name = TOK_NAMES[rx]
-
-
1505
unless name
-
# Display basic regexps as plain old strings
-
1010
string = rx.source.gsub(/\\(.)/, '\1')
-
1010
name = rx.source == Regexp.escape(string) ? string.inspect : rx.inspect
-
end
-
-
1505
expected(name)
-
end
-
-
2
def expected(name)
-
1816
throw(:_sass_parser_error, true) if @throw_error
-
110
self.class.expected(@scanner, @expected || name, @line)
-
end
-
-
2
def err(msg)
-
throw(:_sass_parser_error, true) if @throw_error
-
raise Sass::SyntaxError.new(msg, :line => @line)
-
end
-
-
2
def throw_error
-
25973
old_throw_error, @throw_error = @throw_error, false
-
25973
yield
-
ensure
-
25973
@throw_error = old_throw_error
-
end
-
-
2
def catch_error(&block)
-
19847
old_throw_error, @throw_error = @throw_error, true
-
19847
pos = @scanner.pos
-
19847
line = @line
-
19847
expected = @expected
-
39694
if catch(:_sass_parser_error) {yield; false}
-
1706
@scanner.pos = pos
-
1706
@line = line
-
1706
@expected = expected
-
1706
{:pos => pos, :line => line, :expected => @expected, :block => block}
-
end
-
ensure
-
19847
@throw_error = old_throw_error
-
end
-
-
2
def rethrow(err)
-
if @throw_error
-
throw :_sass_parser_error, err
-
else
-
@scanner = Sass::Util::MultibyteStringScanner.new(@scanner.string)
-
@scanner.pos = err[:pos]
-
@line = err[:line]
-
@expected = err[:expected]
-
err[:block].call
-
end
-
end
-
-
# @private
-
2
def self.expected(scanner, expected, line)
-
110
pos = scanner.pos
-
-
110
after = scanner.string[0...pos]
-
# Get rid of whitespace between pos and the last token,
-
# but only if there's a newline in there
-
110
after.gsub!(/\s*\n\s*$/, '')
-
# Also get rid of stuff before the last newline
-
110
after.gsub!(/.*\n/, '')
-
110
after = "..." + after[-15..-1] if after.size > 18
-
-
110
was = scanner.rest.dup
-
# Get rid of whitespace between pos and the next token,
-
# but only if there's a newline in there
-
110
was.gsub!(/^\s*\n\s*/, '')
-
# Also get rid of stuff after the next newline
-
110
was.gsub!(/\n.*/, '')
-
110
was = was[0...15] + "..." if was.size > 18
-
-
110
raise Sass::SyntaxError.new(
-
"Invalid CSS after \"#{after}\": expected #{expected}, was \"#{was}\"",
-
:line => line)
-
end
-
-
# Avoid allocating lots of new strings for `#tok`.
-
# This is important because `#tok` is called all the time.
-
2
NEWLINE = "\n"
-
-
2
def tok(rx, last_group_lookahead = false)
-
1988498
res = @scanner.scan(rx)
-
1988498
if res
-
# This fixes https://github.com/nex3/sass/issues/104, which affects
-
# Ruby 1.8.7 and REE. This fix is to replace the ?= zero-width
-
# positive lookahead operator in the Regexp (which matches without
-
# consuming the matched group), with a match that does consume the
-
# group, but then rewinds the scanner and removes the group from the
-
# end of the matched string. This fix makes the assumption that the
-
# matched group will always occur at the end of the match.
-
197596
if last_group_lookahead && @scanner[-1]
-
16353
@scanner.pos -= @scanner[-1].length
-
16353
res.slice!(-@scanner[-1].length..-1)
-
end
-
197596
@line += res.count(NEWLINE)
-
197596
@expected = nil
-
197596
if !@strs.empty? && rx != COMMENT && rx != SINGLE_LINE_COMMENT
-
50822
@strs.each {|s| s << res}
-
end
-
197596
res
-
end
-
end
-
end
-
end
-
end
-
2
module Sass
-
2
module SCSS
-
# A module containing regular expressions used
-
# for lexing tokens in an SCSS document.
-
# Most of these are taken from [the CSS3 spec](http://www.w3.org/TR/css3-syntax/#lexical),
-
# although some have been modified for various reasons.
-
2
module RX
-
# Takes a string and returns a CSS identifier
-
# that will have the value of the given string.
-
#
-
# @param str [String] The string to escape
-
# @return [String] The escaped string
-
2
def self.escape_ident(str)
-
return "" if str.empty?
-
return "\\#{str}" if str == '-' || str == '_'
-
out = ""
-
value = str.dup
-
out << value.slice!(0...1) if value =~ /^[-_]/
-
if value[0...1] =~ NMSTART
-
out << value.slice!(0...1)
-
else
-
out << escape_char(value.slice!(0...1))
-
end
-
out << value.gsub(/[^a-zA-Z0-9_-]/) {|c| escape_char c}
-
return out
-
end
-
-
# Escapes a single character for a CSS identifier.
-
#
-
# @param c [String] The character to escape. Should have length 1
-
# @return [String] The escaped character
-
# @private
-
2
def self.escape_char(c)
-
return "\\%06x" % Sass::Util.ord(c) unless c =~ /[ -\/:-~]/
-
return "\\#{c}"
-
end
-
-
# Creates a Regexp from a plain text string,
-
# escaping all significant characters.
-
#
-
# @param str [String] The text of the regexp
-
# @param flags [Fixnum] Flags for the created regular expression
-
# @return [Regexp]
-
# @private
-
2
def self.quote(str, flags = 0)
-
16
Regexp.new(Regexp.quote(str), flags)
-
end
-
-
2
H = /[0-9a-fA-F]/
-
2
NL = /\n|\r\n|\r|\f/
-
2
UNICODE = /\\#{H}{1,6}[ \t\r\n\f]?/
-
2
s = if Sass::Util.ruby1_8?
-
'\200-\377'
-
elsif Sass::Util.macruby?
-
'\u0080-\uD7FF\uE000-\uFFFD\U00010000-\U0010FFFF'
-
else
-
2
'\u{80}-\u{D7FF}\u{E000}-\u{FFFD}\u{10000}-\u{10FFFF}'
-
end
-
2
NONASCII = /[#{s}]/
-
2
ESCAPE = /#{UNICODE}|\\[ -~#{s}]/
-
2
NMSTART = /[_a-zA-Z]|#{NONASCII}|#{ESCAPE}/
-
2
NMCHAR = /[a-zA-Z0-9_-]|#{NONASCII}|#{ESCAPE}/
-
2
STRING1 = /\"((?:[^\n\r\f\\"]|\\#{NL}|#{ESCAPE})*)\"/
-
2
STRING2 = /\'((?:[^\n\r\f\\']|\\#{NL}|#{ESCAPE})*)\'/
-
-
2
IDENT = /-?#{NMSTART}#{NMCHAR}*/
-
2
NAME = /#{NMCHAR}+/
-
2
NUM = /[0-9]+|[0-9]*\.[0-9]+/
-
2
STRING = /#{STRING1}|#{STRING2}/
-
2
URLCHAR = /[#%&*-~]|#{NONASCII}|#{ESCAPE}/
-
2
URL = /(#{URLCHAR}*)/
-
2
W = /[ \t\r\n\f]*/
-
2
VARIABLE = /(\$)(#{Sass::SCSS::RX::IDENT})/
-
-
# This is more liberal than the spec's definition,
-
# but that definition didn't work well with the greediness rules
-
2
RANGE = /(?:#{H}|\?){1,6}/
-
-
##
-
-
2
S = /[ \t\r\n\f]+/
-
-
2
COMMENT = /\/\*[^*]*\*+(?:[^\/][^*]*\*+)*\//
-
2
SINGLE_LINE_COMMENT = /\/\/.*(\n[ \t]*\/\/.*)*/
-
-
2
CDO = quote("<!--")
-
2
CDC = quote("-->")
-
2
INCLUDES = quote("~=")
-
2
DASHMATCH = quote("|=")
-
2
PREFIXMATCH = quote("^=")
-
2
SUFFIXMATCH = quote("$=")
-
2
SUBSTRINGMATCH = quote("*=")
-
-
2
HASH = /##{NAME}/
-
-
2
IMPORTANT = /!#{W}important/i
-
2
DEFAULT = /!#{W}default/i
-
-
2
NUMBER = /#{NUM}(?:#{IDENT}|%)?/
-
-
2
URI = /url\(#{W}(?:#{STRING}|#{URL})#{W}\)/i
-
2
FUNCTION = /#{IDENT}\(/
-
-
2
UNICODERANGE = /u\+(?:#{H}{1,6}-#{H}{1,6}|#{RANGE})/i
-
-
# Defined in http://www.w3.org/TR/css3-selectors/#lex
-
2
PLUS = /#{W}\+/
-
2
GREATER = /#{W}>/
-
2
TILDE = /#{W}~/
-
2
NOT = quote(":not(", Regexp::IGNORECASE)
-
-
# Defined in https://developer.mozilla.org/en/CSS/@-moz-document as a
-
# non-standard version of http://www.w3.org/TR/css3-conditional/
-
2
URL_PREFIX = /url-prefix\(#{W}(?:#{STRING}|#{URL})#{W}\)/i
-
2
DOMAIN = /domain\(#{W}(?:#{STRING}|#{URL})#{W}\)/i
-
-
# Custom
-
2
HEXCOLOR = /\#[0-9a-fA-F]+/
-
2
INTERP_START = /#\{/
-
2
ANY = /:(-[-\w]+-)?any\(/i
-
2
OPTIONAL = /!#{W}optional/i
-
-
2
IDENT_HYPHEN_INTERP = /-(#\{)/
-
2
STRING1_NOINTERP = /\"((?:[^\n\r\f\\"#]|#(?!\{)|\\#{NL}|#{ESCAPE})*)\"/
-
2
STRING2_NOINTERP = /\'((?:[^\n\r\f\\'#]|#(?!\{)|\\#{NL}|#{ESCAPE})*)\'/
-
2
STRING_NOINTERP = /#{STRING1_NOINTERP}|#{STRING2_NOINTERP}/
-
-
2
STATIC_COMPONENT = /#{IDENT}|#{STRING_NOINTERP}|#{HEXCOLOR}|[+-]?#{NUMBER}|\!important/i
-
2
STATIC_VALUE = /#{STATIC_COMPONENT}(\s*[\s,\/]\s*#{STATIC_COMPONENT})*([;}])/i
-
2
STATIC_SELECTOR = /(#{NMCHAR}|[ \t]|[,>+*]|[:#.]#{NMSTART}){0,50}([{])/i
-
end
-
end
-
end
-
2
module Sass
-
2
module SCSS
-
# A mixin for subclasses of {Sass::Script::Lexer}
-
# that makes them usable by {SCSS::Parser} to parse SassScript.
-
# In particular, the lexer doesn't support `!` for a variable prefix.
-
2
module ScriptLexer
-
2
private
-
-
2
def variable
-
17239
return [:raw, "!important"] if scan(Sass::SCSS::RX::IMPORTANT)
-
17155
_variable(Sass::SCSS::RX::VARIABLE)
-
end
-
end
-
end
-
end
-
2
module Sass
-
2
module SCSS
-
# A mixin for subclasses of {Sass::Script::Parser}
-
# that makes them usable by {SCSS::Parser} to parse SassScript.
-
# In particular, the parser won't raise an error
-
# when there's more content in the lexer once lexing is done.
-
# In addition, the parser doesn't support `!` for a variable prefix.
-
2
module ScriptParser
-
2
private
-
-
# @private
-
2
def lexer_class
-
2344
klass = Class.new(super)
-
2344
klass.send(:include, ScriptLexer)
-
2344
klass
-
end
-
-
# Instead of raising an error when the parser is done,
-
# rewind the StringScanner so that it hasn't consumed the final token.
-
2
def assert_done
-
2344
@lexer.unpeek!
-
end
-
end
-
end
-
end
-
2
require 'sass/script/css_parser'
-
-
2
module Sass
-
2
module SCSS
-
# A parser for a static SCSS tree.
-
# Parses with SCSS extensions, like nested rules and parent selectors,
-
# but without dynamic SassScript.
-
# This is useful for e.g. \{#parse\_selector parsing selectors}
-
# after resolving the interpolation.
-
2
class StaticParser < Parser
-
# Parses the text as a selector.
-
#
-
# @param filename [String, nil] The file in which the selector appears,
-
# or nil if there is no such file.
-
# Used for error reporting.
-
# @return [Selector::CommaSequence] The parsed selector
-
# @raise [Sass::SyntaxError] if there's a syntax error in the selector
-
2
def parse_selector
-
6583
init_scanner!
-
6583
seq = expr!(:selector_comma_sequence)
-
6583
expected("selector") unless @scanner.eos?
-
6583
seq.line = @line
-
6583
seq.filename = @filename
-
6583
seq
-
end
-
-
2
private
-
-
2
def moz_document_function
-
return unless val = tok(URI) || tok(URL_PREFIX) || tok(DOMAIN) ||
-
function(!:allow_var)
-
ss
-
[val]
-
end
-
-
2
def variable; nil; end
-
2
def script_value; nil; end
-
2
def interpolation; nil; end
-
2
def var_expr; nil; end
-
27947
def interp_string; s = tok(STRING) and [s]; end
-
27070
def interp_uri; s = tok(URI) and [s]; end
-
90041
def interp_ident(ident = IDENT); s = tok(ident) and [s]; end
-
2
def use_css_import?; true; end
-
-
2
def special_directive(name)
-
return unless %w[media import charset -moz-document].include?(name)
-
super
-
end
-
-
2
@sass_script_parser = Class.new(Sass::Script::CssParser)
-
2
@sass_script_parser.send(:include, ScriptParser)
-
end
-
end
-
end
-
2
require 'sass/selector/simple'
-
2
require 'sass/selector/abstract_sequence'
-
2
require 'sass/selector/comma_sequence'
-
2
require 'sass/selector/sequence'
-
2
require 'sass/selector/simple_sequence'
-
-
2
module Sass
-
# A namespace for nodes in the parse tree for selectors.
-
#
-
# {CommaSequence} is the toplevel seelctor,
-
# representing a comma-separated sequence of {Sequence}s,
-
# such as `foo bar, baz bang`.
-
# {Sequence} is the next level,
-
# representing {SimpleSequence}s separated by combinators (e.g. descendant or child),
-
# such as `foo bar` or `foo > bar baz`.
-
# {SimpleSequence} is a sequence of selectors that all apply to a single element,
-
# such as `foo.bar[attr=val]`.
-
# Finally, {Simple} is the superclass of the simplest selectors,
-
# such as `.foo` or `#bar`.
-
2
module Selector
-
# The base used for calculating selector specificity. The spec says this
-
# should be "sufficiently high"; it's extremely unlikely that any single
-
# selector sequence will contain 1,000 simple selectors.
-
#
-
# @type [Fixnum]
-
2
SPECIFICITY_BASE = 1_000
-
-
# A parent-referencing selector (`&` in Sass).
-
# The function of this is to be replaced by the parent selector
-
# in the nested hierarchy.
-
2
class Parent < Simple
-
# @see Selector#to_a
-
2
def to_a
-
["&"]
-
end
-
-
# Always raises an exception.
-
#
-
# @raise [Sass::SyntaxError] Parent selectors should be resolved before unification
-
# @see Selector#unify
-
2
def unify(sels)
-
raise Sass::SyntaxError.new("[BUG] Cannot unify parent selectors.")
-
end
-
end
-
-
# A class selector (e.g. `.foo`).
-
2
class Class < Simple
-
# The class name.
-
#
-
# @return [Array<String, Sass::Script::Node>]
-
2
attr_reader :name
-
-
# @param name [Array<String, Sass::Script::Node>] The class name
-
2
def initialize(name)
-
20266
@name = name
-
end
-
-
# @see Selector#to_a
-
2
def to_a
-
33790
[".", *@name]
-
end
-
-
# @see AbstractSequence#specificity
-
2
def specificity
-
252
SPECIFICITY_BASE
-
end
-
end
-
-
# An id selector (e.g. `#foo`).
-
2
class Id < Simple
-
# The id name.
-
#
-
# @return [Array<String, Sass::Script::Node>]
-
2
attr_reader :name
-
-
# @param name [Array<String, Sass::Script::Node>] The id name
-
2
def initialize(name)
-
43
@name = name
-
end
-
-
# @see Selector#to_a
-
2
def to_a
-
85
["#", *@name]
-
end
-
-
# Returns `nil` if `sels` contains an {Id} selector
-
# with a different name than this one.
-
#
-
# @see Selector#unify
-
2
def unify(sels)
-
return if sels.any? {|sel2| sel2.is_a?(Id) && self.name != sel2.name}
-
super
-
end
-
-
# @see AbstractSequence#specificity
-
2
def specificity
-
SPECIFICITY_BASE**2
-
end
-
end
-
-
# A placeholder selector (e.g. `%foo`).
-
# This exists to be replaced via `@extend`.
-
# Rulesets using this selector will not be printed, but can be extended.
-
# Otherwise, this acts just like a class selector.
-
2
class Placeholder < Simple
-
# The placeholder name.
-
#
-
# @return [Array<String, Sass::Script::Node>]
-
2
attr_reader :name
-
-
# @param name [Array<String, Sass::Script::Node>] The placeholder name
-
2
def initialize(name)
-
@name = name
-
end
-
-
# @see Selector#to_a
-
2
def to_a
-
["%", *@name]
-
end
-
-
# @see AbstractSequence#specificity
-
2
def specificity
-
SPECIFICITY_BASE
-
end
-
end
-
-
# A universal selector (`*` in CSS).
-
2
class Universal < Simple
-
# The selector namespace.
-
# `nil` means the default namespace,
-
# `[""]` means no namespace,
-
# `["*"]` means any namespace.
-
#
-
# @return [Array<String, Sass::Script::Node>, nil]
-
2
attr_reader :namespace
-
-
# @param namespace [Array<String, Sass::Script::Node>, nil] See \{#namespace}
-
2
def initialize(namespace)
-
17
@namespace = namespace
-
end
-
-
# @see Selector#to_a
-
2
def to_a
-
53
@namespace ? @namespace + ["|*"] : ["*"]
-
end
-
-
# Unification of a universal selector is somewhat complicated,
-
# especially when a namespace is specified.
-
# If there is no namespace specified
-
# or any namespace is specified (namespace `"*"`),
-
# then `sel` is returned without change
-
# (unless it's empty, in which case `"*"` is required).
-
#
-
# If a namespace is specified
-
# but `sel` does not specify a namespace,
-
# then the given namespace is applied to `sel`,
-
# either by adding this {Universal} selector
-
# or applying this namespace to an existing {Element} selector.
-
#
-
# If both this selector *and* `sel` specify namespaces,
-
# those namespaces are unified via {Simple#unify_namespaces}
-
# and the unified namespace is used, if possible.
-
#
-
# @todo There are lots of cases that this documentation specifies;
-
# make sure we thoroughly test **all of them**.
-
# @todo Keep track of whether a default namespace has been declared
-
# and handle namespace-unspecified selectors accordingly.
-
# @todo If any branch of a CommaSequence ends up being just `"*"`,
-
# then all other branches should be eliminated
-
#
-
# @see Selector#unify
-
2
def unify(sels)
-
name =
-
case sels.first
-
when Universal; :universal
-
when Element; sels.first.name
-
else
-
return [self] + sels unless namespace.nil? || namespace == ['*']
-
return sels unless sels.empty?
-
return [self]
-
end
-
-
ns, accept = unify_namespaces(namespace, sels.first.namespace)
-
return unless accept
-
[name == :universal ? Universal.new(ns) : Element.new(name, ns)] + sels[1..-1]
-
end
-
-
# @see AbstractSequence#specificity
-
2
def specificity
-
0
-
end
-
end
-
-
# An element selector (e.g. `h1`).
-
2
class Element < Simple
-
# The element name.
-
#
-
# @return [Array<String, Sass::Script::Node>]
-
2
attr_reader :name
-
-
# The selector namespace.
-
# `nil` means the default namespace,
-
# `[""]` means no namespace,
-
# `["*"]` means any namespace.
-
#
-
# @return [Array<String, Sass::Script::Node>, nil]
-
2
attr_reader :namespace
-
-
# @param name [Array<String, Sass::Script::Node>] The element name
-
# @param namespace [Array<String, Sass::Script::Node>, nil] See \{#namespace}
-
2
def initialize(name, namespace)
-
8258
@name = name
-
8258
@namespace = namespace
-
end
-
-
# @see Selector#to_a
-
2
def to_a
-
22304
@namespace ? @namespace + ["|"] + @name : @name
-
end
-
-
# Unification of an element selector is somewhat complicated,
-
# especially when a namespace is specified.
-
# First, if `sel` contains another {Element} with a different \{#name},
-
# then the selectors can't be unified and `nil` is returned.
-
#
-
# Otherwise, if `sel` doesn't specify a namespace,
-
# or it specifies any namespace (via `"*"`),
-
# then it's returned with this element selector
-
# (e.g. `.foo` becomes `a.foo` or `svg|a.foo`).
-
# Similarly, if this selector doesn't specify a namespace,
-
# the namespace from `sel` is used.
-
#
-
# If both this selector *and* `sel` specify namespaces,
-
# those namespaces are unified via {Simple#unify_namespaces}
-
# and the unified namespace is used, if possible.
-
#
-
# @todo There are lots of cases that this documentation specifies;
-
# make sure we thoroughly test **all of them**.
-
# @todo Keep track of whether a default namespace has been declared
-
# and handle namespace-unspecified selectors accordingly.
-
#
-
# @see Selector#unify
-
2
def unify(sels)
-
case sels.first
-
when Universal;
-
when Element; return unless name == sels.first.name
-
else return [self] + sels
-
end
-
-
ns, accept = unify_namespaces(namespace, sels.first.namespace)
-
return unless accept
-
[Element.new(name, ns)] + sels[1..-1]
-
end
-
-
# @see AbstractSequence#specificity
-
2
def specificity
-
24
1
-
end
-
end
-
-
# Selector interpolation (`#{}` in Sass).
-
2
class Interpolation < Simple
-
# The script to run.
-
#
-
# @return [Sass::Script::Node]
-
2
attr_reader :script
-
-
# @param script [Sass::Script::Node] The script to run
-
2
def initialize(script)
-
@script = script
-
end
-
-
# @see Selector#to_a
-
2
def to_a
-
[@script]
-
end
-
-
# Always raises an exception.
-
#
-
# @raise [Sass::SyntaxError] Interpolation selectors should be resolved before unification
-
# @see Selector#unify
-
2
def unify(sels)
-
raise Sass::SyntaxError.new("[BUG] Cannot unify interpolation selectors.")
-
end
-
end
-
-
# An attribute selector (e.g. `[href^="http://"]`).
-
2
class Attribute < Simple
-
# The attribute name.
-
#
-
# @return [Array<String, Sass::Script::Node>]
-
2
attr_reader :name
-
-
# The attribute namespace.
-
# `nil` means the default namespace,
-
# `[""]` means no namespace,
-
# `["*"]` means any namespace.
-
#
-
# @return [Array<String, Sass::Script::Node>, nil]
-
2
attr_reader :namespace
-
-
# The matching operator, e.g. `"="` or `"^="`.
-
#
-
# @return [String]
-
2
attr_reader :operator
-
-
# The right-hand side of the operator.
-
#
-
# @return [Array<String, Sass::Script::Node>]
-
2
attr_reader :value
-
-
# Flags for the attribute selector (e.g. `i`).
-
#
-
# @return [Array<String, Sass::Script::Node>]
-
2
attr_reader :flags
-
-
# @param name [Array<String, Sass::Script::Node>] The attribute name
-
# @param namespace [Array<String, Sass::Script::Node>, nil] See \{#namespace}
-
# @param operator [String] The matching operator, e.g. `"="` or `"^="`
-
# @param value [Array<String, Sass::Script::Node>] See \{#value}
-
# @param value [Array<String, Sass::Script::Node>] See \{#flags}
-
2
def initialize(name, namespace, operator, value, flags)
-
1240
@name = name
-
1240
@namespace = namespace
-
1240
@operator = operator
-
1240
@value = value
-
1240
@flags = flags
-
end
-
-
# @see Selector#to_a
-
2
def to_a
-
1855
res = ["["]
-
1855
res.concat(@namespace) << "|" if @namespace
-
1855
res.concat @name
-
1855
(res << @operator).concat @value if @value
-
1855
(res << " ").concat @flags if @flags
-
1855
res << "]"
-
end
-
-
# @see AbstractSequence#specificity
-
2
def specificity
-
SPECIFICITY_BASE
-
end
-
end
-
-
# A pseudoclass (e.g. `:visited`) or pseudoelement (e.g. `::first-line`) selector.
-
# It can have arguments (e.g. `:nth-child(2n+1)`).
-
2
class Pseudo < Simple
-
# Some psuedo-class-syntax selectors are actually considered
-
# pseudo-elements and must be treated differently. This is a list of such
-
# selectors
-
#
-
# @return [Array<String>]
-
2
ACTUALLY_ELEMENTS = %w[after before first-line first-letter]
-
-
# Like \{#type}, but returns the type of selector this looks like, rather
-
# than the type it is semantically. This only differs from type for
-
# selectors in \{ACTUALLY\_ELEMENTS}.
-
#
-
# @return [Symbol]
-
2
attr_reader :syntactic_type
-
-
# The name of the selector.
-
#
-
# @return [Array<String, Sass::Script::Node>]
-
2
attr_reader :name
-
-
# The argument to the selector,
-
# or `nil` if no argument was given.
-
#
-
# This may include SassScript nodes that will be run during resolution.
-
# Note that this should not include SassScript nodes
-
# after resolution has taken place.
-
#
-
# @return [Array<String, Sass::Script::Node>, nil]
-
2
attr_reader :arg
-
-
# @param type [Symbol] See \{#type}
-
# @param name [Array<String, Sass::Script::Node>] The name of the selector
-
# @param arg [nil, Array<String, Sass::Script::Node>] The argument to the selector,
-
# or nil if no argument was given
-
2
def initialize(type, name, arg)
-
6972
@syntactic_type = type
-
6972
@name = name
-
6972
@arg = arg
-
end
-
-
# The type of the selector. `:class` if this is a pseudoclass selector,
-
# `:element` if it's a pseudoelement.
-
#
-
# @return [Symbol]
-
2
def type
-
4446
ACTUALLY_ELEMENTS.include?(name.first) ? :element : syntactic_type
-
end
-
-
# @see Selector#to_a
-
2
def to_a
-
11413
res = [syntactic_type == :class ? ":" : "::"] + @name
-
11413
(res << "(").concat(Sass::Util.strip_string_array(@arg)) << ")" if @arg
-
11413
res
-
end
-
-
# Returns `nil` if this is a pseudoelement selector
-
# and `sels` contains a pseudoelement selector different than this one.
-
#
-
# @see Selector#unify
-
2
def unify(sels)
-
return if type == :element && sels.any? do |sel|
-
sel.is_a?(Pseudo) && sel.type == :element &&
-
(sel.name != self.name || sel.arg != self.arg)
-
end
-
super
-
end
-
-
# @see AbstractSequence#specificity
-
2
def specificity
-
6
type == :class ? SPECIFICITY_BASE : 1
-
end
-
end
-
-
# A pseudoclass selector whose argument is itself a selector
-
# (e.g. `:not(.foo)` or `:-moz-all(.foo, .bar)`).
-
2
class SelectorPseudoClass < Simple
-
# The name of the pseudoclass.
-
#
-
# @return [String]
-
2
attr_reader :name
-
-
# The selector argument.
-
#
-
# @return [Selector::Sequence]
-
2
attr_reader :selector
-
-
# @param [String] The name of the pseudoclass
-
# @param [Selector::CommaSequence] The selector argument
-
2
def initialize(name, selector)
-
@name = name
-
@selector = selector
-
end
-
-
# @see Selector#to_a
-
2
def to_a
-
[":", @name, "("] + @selector.to_a + [")"]
-
end
-
-
# @see AbstractSequence#specificity
-
2
def specificity
-
SPECIFICITY_BASE
-
end
-
end
-
end
-
end
-
2
module Sass
-
2
module Selector
-
# The abstract parent class of the various selector sequence classes.
-
#
-
# All subclasses should implement a `members` method that returns an array
-
# of object that respond to `#line=` and `#filename=`, as well as a `to_a`
-
# method that returns an array of strings and script nodes.
-
2
class AbstractSequence
-
# The line of the Sass template on which this selector was declared.
-
#
-
# @return [Fixnum]
-
2
attr_reader :line
-
-
# The name of the file in which this selector was declared.
-
#
-
# @return [String, nil]
-
2
attr_reader :filename
-
-
# Sets the line of the Sass template on which this selector was declared.
-
# This also sets the line for all child selectors.
-
#
-
# @param line [Fixnum]
-
# @return [Fixnum]
-
2
def line=(line)
-
111898
members.each {|m| m.line = line}
-
45796
@line = line
-
end
-
-
# Sets the name of the file in which this selector was declared,
-
# or `nil` if it was not declared in a file (e.g. on stdin).
-
# This also sets the filename for all child selectors.
-
#
-
# @param filename [String, nil]
-
# @return [String, nil]
-
2
def filename=(filename)
-
55951
members.each {|m| m.filename = filename}
-
22899
@filename = filename
-
end
-
-
# Returns a hash code for this sequence.
-
#
-
# Subclasses should define `#_hash` rather than overriding this method,
-
# which automatically handles memoizing the result.
-
#
-
# @return [Fixnum]
-
2
def hash
-
85545
@_hash ||= _hash
-
end
-
-
# Checks equality between this and another object.
-
#
-
# Subclasses should define `#_eql?` rather than overriding this method,
-
# which handles checking class equality and hash equality.
-
#
-
# @param other [Object] The object to test equality against
-
# @return [Boolean] Whether or not this is equal to `other`
-
2
def eql?(other)
-
91929
other.class == self.class && other.hash == self.hash && _eql?(other)
-
end
-
2
alias_method :==, :eql?
-
-
# Whether or not this selector sequence contains a placeholder selector.
-
# Checks recursively.
-
2
def has_placeholder?
-
@has_placeholder ||=
-
182620
members.any? {|m| m.is_a?(AbstractSequence) ? m.has_placeholder? : m.is_a?(Placeholder)}
-
end
-
-
# Converts the selector into a string. This is the standard selector
-
# string, along with any SassScript interpolation that may exist.
-
#
-
# @return [String]
-
2
def to_s
-
to_a.map {|e| e.is_a?(Sass::Script::Node) ? "\#{#{e.to_sass}}" : e}.join
-
end
-
-
# Returns the specificity of the selector as an integer. The base is given
-
# by {Sass::Selector::SPECIFICITY_BASE}.
-
#
-
# @return [Fixnum]
-
2
def specificity
-
336
_specificity(members)
-
end
-
-
2
protected
-
-
2
def _specificity(arr)
-
420
spec = 0
-
972
arr.map {|m| spec += m.is_a?(String) ? 0 : m.specificity}
-
420
spec
-
end
-
end
-
end
-
end
-
2
module Sass
-
2
module Selector
-
# A comma-separated sequence of selectors.
-
2
class CommaSequence < AbstractSequence
-
# The comma-separated selector sequences
-
# represented by this class.
-
#
-
# @return [Array<Sequence>]
-
2
attr_reader :members
-
-
# @param seqs [Array<Sequence>] See \{#members}
-
2
def initialize(seqs)
-
13162
@members = seqs
-
end
-
-
# Resolves the {Parent} selectors within this selector
-
# by replacing them with the given parent selector,
-
# handling commas appropriately.
-
#
-
# @param super_cseq [CommaSequence] The parent selector
-
# @return [CommaSequence] This selector, with parent references resolved
-
# @raise [Sass::SyntaxError] If a parent selector is invalid
-
2
def resolve_parent_refs(super_cseq)
-
6582
if super_cseq.nil?
-
6580
if @members.any? do |sel|
-
10056
sel.members.any? do |sel_or_op|
-
45179
sel_or_op.is_a?(SimpleSequence) && sel_or_op.members.any? {|ssel| ssel.is_a?(Parent)}
-
end
-
end
-
raise Sass::SyntaxError.new("Base-level rules cannot contain the parent-selector-referencing character '&'.")
-
end
-
6580
return self
-
end
-
-
2
CommaSequence.new(
-
super_cseq.members.map do |super_seq|
-
4
@members.map {|seq| seq.resolve_parent_refs(super_seq)}
-
end.flatten)
-
end
-
-
# Non-destrucively extends this selector with the extensions specified in a hash
-
# (which should come from {Sass::Tree::Visitors::Cssize}).
-
#
-
# @todo Link this to the reference documentation on `@extend`
-
# when such a thing exists.
-
#
-
# @param extends [Sass::Util::SubsetMap{Selector::Simple =>
-
# Sass::Tree::Visitors::Cssize::Extend}]
-
# The extensions to perform on this selector
-
# @param parent_directives [Array<Sass::Tree::DirectiveNode>]
-
# The directives containing this selector.
-
# @return [CommaSequence] A copy of this selector,
-
# with extensions made according to `extends`
-
2
def do_extend(extends, parent_directives)
-
6577
CommaSequence.new(members.map do |seq|
-
10053
extended = seq.do_extend(extends, parent_directives)
-
# First Law of Extend: the result of extending a selector should
-
# always contain the base selector.
-
#
-
# See https://github.com/nex3/sass/issues/324.
-
10053
extended.unshift seq unless seq.has_placeholder? || extended.include?(seq)
-
10053
extended
-
end.flatten)
-
end
-
-
# Returns a string representation of the sequence.
-
# This is basically the selector string.
-
#
-
# @return [String]
-
2
def inspect
-
members.map {|m| m.inspect}.join(", ")
-
end
-
-
# @see Simple#to_a
-
2
def to_a
-
arr = Sass::Util.intersperse(@members.map {|m| m.to_a}, ", ").flatten
-
arr.delete("\n")
-
arr
-
end
-
-
2
private
-
-
2
def _hash
-
members.hash
-
end
-
-
2
def _eql?(other)
-
other.class == self.class && other.members.eql?(self.members)
-
end
-
end
-
end
-
end
-
2
module Sass
-
2
module Selector
-
# An operator-separated sequence of
-
# {SimpleSequence simple selector sequences}.
-
2
class Sequence < AbstractSequence
-
# Sets the line of the Sass template on which this selector was declared.
-
# This also sets the line for all child selectors.
-
#
-
# @param line [Fixnum]
-
# @return [Fixnum]
-
2
def line=(line)
-
64500
members.each {|m| m.line = line if m.is_a?(SimpleSequence)}
-
20117
line
-
end
-
-
# Sets the name of the file in which this selector was declared,
-
# or `nil` if it was not declared in a file (e.g. on stdin).
-
# This also sets the filename for all child selectors.
-
#
-
# @param filename [String, nil]
-
# @return [String, nil]
-
2
def filename=(filename)
-
32251
members.each {|m| m.filename = filename if m.is_a?(SimpleSequence)}
-
10059
filename
-
end
-
-
# The array of {SimpleSequence simple selector sequences}, operators, and
-
# newlines. The operators are strings such as `"+"` and `">"` representing
-
# the corresponding CSS operators, or interpolated SassScript. Newlines
-
# are also newline strings; these aren't semantically relevant, but they
-
# do affect formatting.
-
#
-
# @return [Array<SimpleSequence, String|Array<Sass::Tree::Node, String>>]
-
2
attr_reader :members
-
-
# @param seqs_and_ops [Array<SimpleSequence, String|Array<Sass::Tree::Node, String>>] See \{#members}
-
2
def initialize(seqs_and_ops)
-
26275
@members = seqs_and_ops
-
end
-
-
# Resolves the {Parent} selectors within this selector
-
# by replacing them with the given parent selector,
-
# handling commas appropriately.
-
#
-
# @param super_seq [Sequence] The parent selector sequence
-
# @return [Sequence] This selector, with parent references resolved
-
# @raise [Sass::SyntaxError] If a parent selector is invalid
-
2
def resolve_parent_refs(super_seq)
-
2
members = @members.dup
-
2
nl = (members.first == "\n" && members.shift)
-
2
unless members.any? do |seq_or_op|
-
2
seq_or_op.is_a?(SimpleSequence) && seq_or_op.members.first.is_a?(Parent)
-
end
-
2
old_members, members = members, []
-
2
members << nl if nl
-
2
members << SimpleSequence.new([Parent.new], false)
-
2
members += old_members
-
end
-
-
2
Sequence.new(
-
members.map do |seq_or_op|
-
4
next seq_or_op unless seq_or_op.is_a?(SimpleSequence)
-
4
seq_or_op.resolve_parent_refs(super_seq)
-
end.flatten)
-
end
-
-
# Non-destructively extends this selector with the extensions specified in a hash
-
# (which should come from {Sass::Tree::Visitors::Cssize}).
-
#
-
# @overload def do_extend(extends, parent_directives)
-
# @param extends [Sass::Util::SubsetMap{Selector::Simple =>
-
# Sass::Tree::Visitors::Cssize::Extend}]
-
# The extensions to perform on this selector
-
# @param parent_directives [Array<Sass::Tree::DirectiveNode>]
-
# The directives containing this selector.
-
# @return [Array<Sequence>] A list of selectors generated
-
# by extending this selector with `extends`.
-
# These correspond to a {CommaSequence}'s {CommaSequence#members members array}.
-
# @see CommaSequence#do_extend
-
2
def do_extend(extends, parent_directives, seen = Set.new)
-
10095
extended_not_expanded = members.map do |sseq_or_op|
-
22225
next [[sseq_or_op]] unless sseq_or_op.is_a?(SimpleSequence)
-
16349
extended = sseq_or_op.do_extend(extends, parent_directives, seen)
-
16391
choices = extended.map {|seq| seq.members}
-
16391
choices.unshift([sseq_or_op]) unless extended.any? {|seq| seq.superselector?(sseq_or_op)}
-
16349
choices
-
end
-
20232
weaves = Sass::Util.paths(extended_not_expanded).map {|path| weave(path)}
-
20232
Sass::Util.flatten(trim(weaves), 1).map {|p| Sequence.new(p)}
-
end
-
-
# Returns whether or not this selector matches all elements
-
# that the given selector matches (as well as possibly more).
-
#
-
# @example
-
# (.foo).superselector?(.foo.bar) #=> true
-
# (.foo).superselector?(.bar) #=> false
-
# (.bar .foo).superselector?(.foo) #=> false
-
# @param sseq [SimpleSequence]
-
# @return [Boolean]
-
2
def superselector?(sseq)
-
42
return false unless members.size == 1
-
42
members.last.superselector?(sseq)
-
end
-
-
# @see Simple#to_a
-
2
def to_a
-
51064
ary = @members.map {|seq_or_op| seq_or_op.is_a?(SimpleSequence) ? seq_or_op.to_a : seq_or_op}
-
14994
Sass::Util.intersperse(ary, " ").flatten.compact
-
end
-
-
# Returns a string representation of the sequence.
-
# This is basically the selector string.
-
#
-
# @return [String]
-
2
def inspect
-
members.map {|m| m.inspect}.join(" ")
-
end
-
-
# Add to the {SimpleSequence#sources} sets of the child simple sequences.
-
# This destructively modifies this sequence's members array, but not the
-
# child simple sequences.
-
#
-
# @param sources [Set<Sequence>]
-
2
def add_sources!(sources)
-
84
members.map! {|m| m.is_a?(SimpleSequence) ? m.with_more_sources(sources) : m}
-
end
-
-
2
private
-
-
# Conceptually, this expands "parenthesized selectors".
-
# That is, if we have `.A .B {@extend .C}` and `.D .C {...}`,
-
# this conceptually expands into `.D .C, .D (.A .B)`,
-
# and this function translates `.D (.A .B)` into `.D .A .B, .A.D .B, .D .A .B`.
-
#
-
# @param path [Array<Array<SimpleSequence or String>>] A list of parenthesized selector groups.
-
# @return [Array<Array<SimpleSequence or String>>] A list of fully-expanded selectors.
-
2
def weave(path)
-
# This function works by moving through the selector path left-to-right,
-
# building all possible prefixes simultaneously. These prefixes are
-
# `befores`, while the remaining parenthesized suffixes is `afters`.
-
10137
befores = [[]]
-
10137
afters = path.dup
-
-
10137
until afters.empty?
-
22318
current = afters.shift.dup
-
22318
last_current = [current.pop]
-
22318
befores = Sass::Util.flatten(befores.map do |before|
-
22318
next [] unless sub = subweave(before, current)
-
44636
sub.map {|seqs| seqs + last_current}
-
end, 1)
-
end
-
10137
return befores
-
end
-
-
# This interweaves two lists of selectors,
-
# returning all possible orderings of them (including using unification)
-
# that maintain the relative ordering of the input arrays.
-
#
-
# For example, given `.foo .bar` and `.baz .bang`,
-
# this would return `.foo .bar .baz .bang`, `.foo .bar.baz .bang`,
-
# `.foo .baz .bar .bang`, `.foo .baz .bar.bang`, `.foo .baz .bang .bar`,
-
# and so on until `.baz .bang .foo .bar`.
-
#
-
# Semantically, for selectors A and B, this returns all selectors `AB_i`
-
# such that the union over all i of elements matched by `AB_i X` is
-
# identical to the intersection of all elements matched by `A X` and all
-
# elements matched by `B X`. Some `AB_i` are elided to reduce the size of
-
# the output.
-
#
-
# @param seq1 [Array<SimpleSequence or String>]
-
# @param seq2 [Array<SimpleSequence or String>]
-
# @return [Array<Array<SimpleSequence or String>>]
-
2
def subweave(seq1, seq2)
-
22318
return [seq2] if seq1.empty?
-
12181
return [seq1] if seq2.empty?
-
-
seq1, seq2 = seq1.dup, seq2.dup
-
return unless init = merge_initial_ops(seq1, seq2)
-
return unless fin = merge_final_ops(seq1, seq2)
-
seq1 = group_selectors(seq1)
-
seq2 = group_selectors(seq2)
-
lcs = Sass::Util.lcs(seq2, seq1) do |s1, s2|
-
next s1 if s1 == s2
-
next unless s1.first.is_a?(SimpleSequence) && s2.first.is_a?(SimpleSequence)
-
next s2 if parent_superselector?(s1, s2)
-
next s1 if parent_superselector?(s2, s1)
-
end
-
-
diff = [[init]]
-
until lcs.empty?
-
diff << chunks(seq1, seq2) {|s| parent_superselector?(s.first, lcs.first)} << [lcs.shift]
-
seq1.shift
-
seq2.shift
-
end
-
diff << chunks(seq1, seq2) {|s| s.empty?}
-
diff += fin.map {|sel| sel.is_a?(Array) ? sel : [sel]}
-
diff.reject! {|c| c.empty?}
-
-
Sass::Util.paths(diff).map {|p| p.flatten}.reject {|p| path_has_two_subjects?(p)}
-
end
-
-
# Extracts initial selector combinators (`"+"`, `">"`, `"~"`, and `"\n"`)
-
# from two sequences and merges them together into a single array of
-
# selector combinators.
-
#
-
# @param seq1 [Array<SimpleSequence or String>]
-
# @param seq2 [Array<SimpleSequence or String>]
-
# @return [Array<String>, nil] If there are no operators in the merged
-
# sequence, this will be the empty array. If the operators cannot be
-
# merged, this will be nil.
-
2
def merge_initial_ops(seq1, seq2)
-
ops1, ops2 = [], []
-
ops1 << seq1.shift while seq1.first.is_a?(String)
-
ops2 << seq2.shift while seq2.first.is_a?(String)
-
-
newline = false
-
newline ||= !!ops1.shift if ops1.first == "\n"
-
newline ||= !!ops2.shift if ops2.first == "\n"
-
-
# If neither sequence is a subsequence of the other, they cannot be
-
# merged successfully
-
lcs = Sass::Util.lcs(ops1, ops2)
-
return unless lcs == ops1 || lcs == ops2
-
return (newline ? ["\n"] : []) + (ops1.size > ops2.size ? ops1 : ops2)
-
end
-
-
# Extracts final selector combinators (`"+"`, `">"`, `"~"`) and the
-
# selectors to which they apply from two sequences and merges them
-
# together into a single array.
-
#
-
# @param seq1 [Array<SimpleSequence or String>]
-
# @param seq2 [Array<SimpleSequence or String>]
-
# @return [Array<SimpleSequence or String or
-
# Array<Array<SimpleSequence or String>>]
-
# If there are no trailing combinators to be merged, this will be the
-
# empty array. If the trailing combinators cannot be merged, this will
-
# be nil. Otherwise, this will contained the merged selector. Array
-
# elements are [Sass::Util#paths]-style options; conceptually, an "or"
-
# of multiple selectors.
-
2
def merge_final_ops(seq1, seq2, res = [])
-
ops1, ops2 = [], []
-
ops1 << seq1.pop while seq1.last.is_a?(String)
-
ops2 << seq2.pop while seq2.last.is_a?(String)
-
-
# Not worth the headache of trying to preserve newlines here. The most
-
# important use of newlines is at the beginning of the selector to wrap
-
# across lines anyway.
-
ops1.reject! {|o| o == "\n"}
-
ops2.reject! {|o| o == "\n"}
-
-
return res if ops1.empty? && ops2.empty?
-
if ops1.size > 1 || ops2.size > 1
-
# If there are multiple operators, something hacky's going on. If one
-
# is a supersequence of the other, use that, otherwise give up.
-
lcs = Sass::Util.lcs(ops1, ops2)
-
return unless lcs == ops1 || lcs == ops2
-
res.unshift(*(ops1.size > ops2.size ? ops1 : ops2).reverse)
-
return res
-
end
-
-
# This code looks complicated, but it's actually just a bunch of special
-
# cases for interactions between different combinators.
-
op1, op2 = ops1.first, ops2.first
-
if op1 && op2
-
sel1 = seq1.pop
-
sel2 = seq2.pop
-
if op1 == '~' && op2 == '~'
-
if sel1.superselector?(sel2)
-
res.unshift sel2, '~'
-
elsif sel2.superselector?(sel1)
-
res.unshift sel1, '~'
-
else
-
merged = sel1.unify(sel2.members, sel2.subject?)
-
res.unshift [
-
[sel1, '~', sel2, '~'],
-
[sel2, '~', sel1, '~'],
-
([merged, '~'] if merged)
-
].compact
-
end
-
elsif (op1 == '~' && op2 == '+') || (op1 == '+' && op2 == '~')
-
if op1 == '~'
-
tilde_sel, plus_sel = sel1, sel2
-
else
-
tilde_sel, plus_sel = sel2, sel1
-
end
-
-
if tilde_sel.superselector?(plus_sel)
-
res.unshift plus_sel, '+'
-
else
-
merged = plus_sel.unify(tilde_sel.members, tilde_sel.subject?)
-
res.unshift [
-
[tilde_sel, '~', plus_sel, '+'],
-
([merged, '+'] if merged)
-
].compact
-
end
-
elsif op1 == '>' && %w[~ +].include?(op2)
-
res.unshift sel2, op2
-
seq1.push sel1, op1
-
elsif op2 == '>' && %w[~ +].include?(op1)
-
res.unshift sel1, op1
-
seq2.push sel2, op2
-
elsif op1 == op2
-
return unless merged = sel1.unify(sel2.members, sel2.subject?)
-
res.unshift merged, op1
-
else
-
# Unknown selector combinators can't be unified
-
return
-
end
-
return merge_final_ops(seq1, seq2, res)
-
elsif op1
-
seq2.pop if op1 == '>' && seq2.last && seq2.last.superselector?(seq1.last)
-
res.unshift seq1.pop, op1
-
return merge_final_ops(seq1, seq2, res)
-
else # op2
-
seq1.pop if op2 == '>' && seq1.last && seq1.last.superselector?(seq2.last)
-
res.unshift seq2.pop, op2
-
return merge_final_ops(seq1, seq2, res)
-
end
-
end
-
-
# Takes initial subsequences of `seq1` and `seq2` and returns all
-
# orderings of those subsequences. The initial subsequences are determined
-
# by a block.
-
#
-
# Destructively removes the initial subsequences of `seq1` and `seq2`.
-
#
-
# For example, given `(A B C | D E)` and `(1 2 | 3 4 5)` (with `|`
-
# denoting the boundary of the initial subsequence), this would return
-
# `[(A B C 1 2), (1 2 A B C)]`. The sequences would then be `(D E)` and
-
# `(3 4 5)`.
-
#
-
# @param seq1 [Array]
-
# @param seq2 [Array]
-
# @yield [a] Used to determine when to cut off the initial subsequences.
-
# Called repeatedly for each sequence until it returns true.
-
# @yieldparam a [Array] A final subsequence of one input sequence after
-
# cutting off some initial subsequence.
-
# @yieldreturn [Boolean] Whether or not to cut off the initial subsequence
-
# here.
-
# @return [Array<Array>] All possible orderings of the initial subsequences.
-
2
def chunks(seq1, seq2)
-
chunk1 = []
-
chunk1 << seq1.shift until yield seq1
-
chunk2 = []
-
chunk2 << seq2.shift until yield seq2
-
return [] if chunk1.empty? && chunk2.empty?
-
return [chunk2] if chunk1.empty?
-
return [chunk1] if chunk2.empty?
-
[chunk1 + chunk2, chunk2 + chunk1]
-
end
-
-
# Groups a sequence into subsequences. The subsequences are determined by
-
# strings; adjacent non-string elements will be put into separate groups,
-
# but any element adjacent to a string will be grouped with that string.
-
#
-
# For example, `(A B "C" D E "F" G "H" "I" J)` will become `[(A) (B "C" D)
-
# (E "F" G "H" "I" J)]`.
-
#
-
# @param seq [Array]
-
# @return [Array<Array>]
-
2
def group_selectors(seq)
-
newseq = []
-
tail = seq.dup
-
until tail.empty?
-
head = []
-
begin
-
head << tail.shift
-
end while !tail.empty? && head.last.is_a?(String) || tail.first.is_a?(String)
-
newseq << head
-
end
-
return newseq
-
end
-
-
# Given two selector sequences, returns whether `seq1` is a
-
# superselector of `seq2`; that is, whether `seq1` matches every
-
# element `seq2` matches.
-
#
-
# @param seq1 [Array<SimpleSequence or String>]
-
# @param seq2 [Array<SimpleSequence or String>]
-
# @return [Boolean]
-
2
def _superselector?(seq1, seq2)
-
270
seq1 = seq1.reject {|e| e == "\n"}
-
270
seq2 = seq2.reject {|e| e == "\n"}
-
# Selectors with leading or trailing operators are neither
-
# superselectors nor subselectors.
-
84
return if seq1.last.is_a?(String) || seq2.last.is_a?(String) ||
-
seq1.first.is_a?(String) || seq2.first.is_a?(String)
-
# More complex selectors are never superselectors of less complex ones
-
84
return if seq1.size > seq2.size
-
84
return seq1.first.superselector?(seq2.last) if seq1.size == 1
-
-
84
_, si = Sass::Util.enum_with_index(seq2).find do |e, i|
-
168
return if i == seq2.size - 1
-
84
next if e.is_a?(String)
-
84
seq1.first.superselector?(e)
-
end
-
return unless si
-
-
if seq1[1].is_a?(String)
-
return unless seq2[si+1].is_a?(String)
-
# .foo ~ .bar is a superselector of .foo + .bar
-
return unless seq1[1] == "~" ? seq2[si+1] != ">" : seq1[1] == seq2[si+1]
-
return _superselector?(seq1[2..-1], seq2[si+2..-1])
-
elsif seq2[si+1].is_a?(String)
-
return unless seq2[si+1] == ">"
-
return _superselector?(seq1[1..-1], seq2[si+2..-1])
-
else
-
return _superselector?(seq1[1..-1], seq2[si+1..-1])
-
end
-
end
-
-
# Like \{#_superselector?}, but compares the selectors in the
-
# context of parent selectors, as though they shared an implicit
-
# base simple selector. For example, `B` is not normally a
-
# superselector of `B A`, since it doesn't match `A` elements.
-
# However, it is a parent superselector, since `B X` is a
-
# superselector of `B A X`.
-
#
-
# @param seq1 [Array<SimpleSequence or String>]
-
# @param seq2 [Array<SimpleSequence or String>]
-
# @return [Boolean]
-
2
def parent_superselector?(seq1, seq2)
-
base = Sass::Selector::SimpleSequence.new([Sass::Selector::Placeholder.new('<temp>')], false)
-
_superselector?(seq1 + [base], seq2 + [base])
-
end
-
-
# Removes redundant selectors from between multiple lists of
-
# selectors. This takes a list of lists of selector sequences;
-
# each individual list is assumed to have no redundancy within
-
# itself. A selector is only removed if it's redundant with a
-
# selector in another list.
-
#
-
# "Redundant" here means that one selector is a superselector of
-
# the other. The more specific selector is removed.
-
#
-
# @param seqses [Array<Array<Array<SimpleSequence or String>>>]
-
# @return [Array<Array<Array<SimpleSequence or String>>>]
-
2
def trim(seqses)
-
# Avoid truly horrific quadratic behavior. TODO: I think there
-
# may be a way to get perfect trimming without going quadratic.
-
10095
return seqses if seqses.size > 100
-
-
# Keep the results in a separate array so we can be sure we aren't
-
# comparing against an already-trimmed selector. This ensures that two
-
# identical selectors don't mutually trim one another.
-
10095
result = seqses.dup
-
-
# This is n^2 on the sequences, but only comparing between
-
# separate sequences should limit the quadratic behavior.
-
10095
seqses.each_with_index do |seqs1, i|
-
10137
result[i] = seqs1.reject do |seq1|
-
10221
max_spec = _sources(seq1).map {|seq| seq.specificity}.max || 0
-
10137
result.any? do |seqs2|
-
10221
next if seqs1.equal?(seqs2)
-
# Second Law of Extend: the specificity of a generated selector
-
# should never be less than the specificity of the extending
-
# selector.
-
#
-
# See https://github.com/nex3/sass/issues/324.
-
168
seqs2.any? {|seq2| _specificity(seq2) >= max_spec && _superselector?(seq2, seq1)}
-
end
-
end
-
end
-
10095
result
-
end
-
-
2
def _hash
-
64474
members.reject {|m| m == "\n"}.hash
-
end
-
-
2
def _eql?(other)
-
54419
other.members.reject {|m| m == "\n"}.eql?(self.members.reject {|m| m == "\n"})
-
end
-
-
2
private
-
-
2
def path_has_two_subjects?(path)
-
subject = false
-
path.each do |sseq_or_op|
-
next unless sseq_or_op.is_a?(SimpleSequence)
-
next unless sseq_or_op.subject?
-
return true if subject
-
subject = true
-
end
-
false
-
end
-
-
2
def _sources(seq)
-
10137
s = Set.new
-
32455
seq.map {|sseq_or_op| s.merge sseq_or_op.sources if sseq_or_op.is_a?(SimpleSequence)}
-
10137
s
-
end
-
-
2
def extended_not_expanded_to_s(extended_not_expanded)
-
extended_not_expanded.map do |choices|
-
choices = choices.map do |sel|
-
next sel.first.to_s if sel.size == 1
-
"#{sel.join ' '}"
-
end
-
next choices.first if choices.size == 1 && !choices.include?(' ')
-
"(#{choices.join ', '})"
-
end.join ' '
-
end
-
end
-
end
-
end
-
2
module Sass
-
2
module Selector
-
# The abstract superclass for simple selectors
-
# (that is, those that don't compose multiple selectors).
-
2
class Simple
-
# The line of the Sass template on which this selector was declared.
-
#
-
# @return [Fixnum]
-
2
attr_accessor :line
-
-
# The name of the file in which this selector was declared,
-
# or `nil` if it was not declared in a file (e.g. on stdin).
-
#
-
# @return [String, nil]
-
2
attr_accessor :filename
-
-
# Returns a representation of the node
-
# as an array of strings and potentially {Sass::Script::Node}s
-
# (if there's interpolation in the selector).
-
# When the interpolation is resolved and the strings are joined together,
-
# this will be the string representation of this node.
-
#
-
# @return [Array<String, Sass::Script::Node>]
-
2
def to_a
-
Sass::Util.abstract(self)
-
end
-
-
# Returns a string representation of the node.
-
# This is basically the selector string.
-
#
-
# @return [String]
-
2
def inspect
-
to_a.map {|e| e.is_a?(Sass::Script::Node) ? "\#{#{e.to_sass}}" : e}.join
-
end
-
-
# @see \{#inspect}
-
# @return [String]
-
2
def to_s
-
inspect
-
end
-
-
# Returns a hash code for this selector object.
-
#
-
# By default, this is based on the value of \{#to\_a},
-
# so if that contains information irrelevant to the identity of the selector,
-
# this should be overridden.
-
#
-
# @return [Fixnum]
-
2
def hash
-
168920
@_hash ||= to_a.hash
-
end
-
-
# Checks equality between this and another object.
-
#
-
# By default, this is based on the value of \{#to\_a},
-
# so if that contains information irrelevant to the identity of the selector,
-
# this should be overridden.
-
#
-
# @param other [Object] The object to test equality against
-
# @return [Boolean] Whether or not this is equal to `other`
-
2
def eql?(other)
-
4829
other.class == self.class && other.hash == self.hash && other.to_a.eql?(to_a)
-
end
-
2
alias_method :==, :eql?
-
-
# Unifies this selector with a {SimpleSequence}'s {SimpleSequence#members members array},
-
# returning another `SimpleSequence` members array
-
# that matches both this selector and the input selector.
-
#
-
# By default, this just appends this selector to the end of the array
-
# (or returns the original array if this selector already exists in it).
-
#
-
# @param sels [Array<Simple>] A {SimpleSequence}'s {SimpleSequence#members members array}
-
# @return [Array<Simple>, nil] A {SimpleSequence} {SimpleSequence#members members array}
-
# matching both `sels` and this selector,
-
# or `nil` if this is impossible (e.g. unifying `#foo` and `#bar`)
-
# @raise [Sass::SyntaxError] If this selector cannot be unified.
-
# This will only ever occur when a dynamic selector,
-
# such as {Parent} or {Interpolation}, is used in unification.
-
# Since these selectors should be resolved
-
# by the time extension and unification happen,
-
# this exception will only ever be raised as a result of programmer error
-
2
def unify(sels)
-
54
return sels if sels.any? {|sel2| eql?(sel2)}
-
42
sels_with_ix = Sass::Util.enum_with_index(sels)
-
42
_, i =
-
if self.is_a?(Pseudo) || self.is_a?(SelectorPseudoClass)
-
sels_with_ix.find {|sel, _| sel.is_a?(Pseudo) && (sels.last.type == :element)}
-
else
-
54
sels_with_ix.find {|sel, _| sel.is_a?(Pseudo) || sel.is_a?(SelectorPseudoClass)}
-
end
-
42
return sels + [self] unless i
-
return sels[0...i] + [self] + sels[i..-1]
-
end
-
-
2
protected
-
-
# Unifies two namespaces,
-
# returning a namespace that works for both of them if possible.
-
#
-
# @param ns1 [String, nil] The first namespace.
-
# `nil` means none specified, e.g. `foo`.
-
# The empty string means no namespace specified, e.g. `|foo`.
-
# `"*"` means any namespace is allowed, e.g. `*|foo`.
-
# @param ns2 [String, nil] The second namespace. See `ns1`.
-
# @return [Array(String or nil, Boolean)]
-
# The first value is the unified namespace, or `nil` for no namespace.
-
# The second value is whether or not a namespace that works for both inputs
-
# could be found at all.
-
# If the second value is `false`, the first should be ignored.
-
2
def unify_namespaces(ns1, ns2)
-
return nil, false unless ns1 == ns2 || ns1.nil? || ns1 == ['*'] || ns2.nil? || ns2 == ['*']
-
return ns2, true if ns1 == ['*']
-
return ns1, true if ns2 == ['*']
-
return ns1 || ns2, true
-
end
-
end
-
end
-
end
-
2
module Sass
-
2
module Selector
-
# A unseparated sequence of selectors
-
# that all apply to a single element.
-
# For example, `.foo#bar[attr=baz]` is a simple sequence
-
# of the selectors `.foo`, `#bar`, and `[attr=baz]`.
-
2
class SimpleSequence < AbstractSequence
-
# The array of individual selectors.
-
#
-
# @return [Array<Simple>]
-
2
attr_accessor :members
-
-
# The extending selectors that caused this selector sequence to be
-
# generated. For example:
-
#
-
# a.foo { ... }
-
# b.bar {@extend a}
-
# c.baz {@extend b}
-
#
-
# The generated selector `b.foo.bar` has `{b.bar}` as its `sources` set,
-
# and the generated selector `c.foo.bar.baz` has `{b.bar, c.baz}` as its
-
# `sources` set.
-
#
-
# This is populated during the {#do_extend} process.
-
#
-
# @return {Set<Sequence>}
-
2
attr_accessor :sources
-
-
# @see \{#subject?}
-
2
attr_writer :subject
-
-
# Returns the element or universal selector in this sequence,
-
# if it exists.
-
#
-
# @return [Element, Universal, nil]
-
2
def base
-
81742
@base ||= (members.first if members.first.is_a?(Element) || members.first.is_a?(Universal))
-
end
-
-
2
def pseudo_elements
-
16348
@pseudo_elements ||= (members - [base]).
-
67558
select {|sel| sel.is_a?(Pseudo) && sel.type == :element}
-
end
-
-
# Returns the non-base, non-pseudo-class selectors in this sequence.
-
#
-
# @return [Set<Simple>]
-
2
def rest
-
49172
@rest ||= Set.new(members - [base] - pseudo_elements)
-
end
-
-
# Whether or not this compound selector is the subject of the parent
-
# selector; that is, whether it is prepended with `$` and represents the
-
# actual element that will be selected.
-
#
-
# @return [Boolean]
-
2
def subject?
-
58746
@subject
-
end
-
-
# @param selectors [Array<Simple>] See \{#members}
-
# @param subject [Boolean] See \{#subject?}
-
# @param sources [Set<Sequence>]
-
2
def initialize(selectors, subject, sources = Set.new)
-
26017
@members = selectors
-
26017
@subject = subject
-
26017
@sources = sources
-
end
-
-
# Resolves the {Parent} selectors within this selector
-
# by replacing them with the given parent selector,
-
# handling commas appropriately.
-
#
-
# @param super_seq [Sequence] The parent selector sequence
-
# @return [Array<SimpleSequence>] This selector, with parent references resolved.
-
# This is an array because the parent selector is itself a {Sequence}
-
# @raise [Sass::SyntaxError] If a parent selector is invalid
-
2
def resolve_parent_refs(super_seq)
-
# Parent selector only appears as the first selector in the sequence
-
4
return [self] unless @members.first.is_a?(Parent)
-
-
2
members = super_seq.members.dup
-
2
newline = members.pop if members.last == "\n"
-
2
return members if @members.size == 1
-
unless members.last.is_a?(SimpleSequence)
-
raise Sass::SyntaxError.new("Invalid parent selector: " + super_seq.to_a.join)
-
end
-
-
members[0...-1] +
-
[SimpleSequence.new(members.last.members + @members[1..-1], subject?)] +
-
[newline].compact
-
end
-
-
# Non-destrucively extends this selector with the extensions specified in a hash
-
# (which should come from {Sass::Tree::Visitors::Cssize}).
-
#
-
# @overload def do_extend(extends, parent_directives)
-
# @param extends [{Selector::Simple =>
-
# Sass::Tree::Visitors::Cssize::Extend}]
-
# The extensions to perform on this selector
-
# @param parent_directives [Array<Sass::Tree::DirectiveNode>]
-
# The directives containing this selector.
-
# @return [Array<Sequence>] A list of selectors generated
-
# by extending this selector with `extends`.
-
# @see CommaSequence#do_extend
-
2
def do_extend(extends, parent_directives, seen = Set.new)
-
42
Sass::Util.group_by_to_a(extends.get(members.to_set)) {|ex, _| ex.extender}.map do |seq, group|
-
84
sels = group.map {|_, s| s}.flatten
-
# If A {@extend B} and C {...},
-
# seq is A, sels is B, and self is C
-
-
42
self_without_sel = Sass::Util.array_minus(self.members, sels)
-
84
group.each {|e, _| e.result = :failed_to_unify unless e.result == :succeeded}
-
42
next unless unified = seq.members.last.unify(self_without_sel, subject?)
-
84
group.each {|e, _| e.result = :succeeded}
-
84
next if group.map {|e, _| check_directives_match!(e, parent_directives)}.none?
-
42
new_seq = Sequence.new(seq.members[0...-1] + [unified])
-
42
new_seq.add_sources!(sources + [seq])
-
42
[sels, new_seq]
-
end.compact.map do |sels, seq|
-
42
seen.include?(sels) ? [] : seq.do_extend(extends, parent_directives, seen + [sels])
-
16349
end.flatten.uniq
-
end
-
-
# Unifies this selector with another {SimpleSequence}'s {SimpleSequence#members members array},
-
# returning another `SimpleSequence`
-
# that matches both this selector and the input selector.
-
#
-
# @param sels [Array<Simple>] A {SimpleSequence}'s {SimpleSequence#members members array}
-
# @param subject [Boolean] Whether the {SimpleSequence} being merged is a subject.
-
# @return [SimpleSequence, nil] A {SimpleSequence} matching both `sels` and this selector,
-
# or `nil` if this is impossible (e.g. unifying `#foo` and `#bar`)
-
# @raise [Sass::SyntaxError] If this selector cannot be unified.
-
# This will only ever occur when a dynamic selector,
-
# such as {Parent} or {Interpolation}, is used in unification.
-
# Since these selectors should be resolved
-
# by the time extension and unification happen,
-
# this exception will only ever be raised as a result of programmer error
-
2
def unify(sels, other_subject)
-
42
return unless sseq = members.inject(sels) do |member, sel|
-
42
return unless member
-
42
sel.unify(member)
-
end
-
42
SimpleSequence.new(sseq, other_subject || subject?)
-
end
-
-
# Returns whether or not this selector matches all elements
-
# that the given selector matches (as well as possibly more).
-
#
-
# @example
-
# (.foo).superselector?(.foo.bar) #=> true
-
# (.foo).superselector?(.bar) #=> false
-
# @param sseq [SimpleSequence]
-
# @return [Boolean]
-
2
def superselector?(sseq)
-
126
(base.nil? || base.eql?(sseq.base)) &&
-
126
pseudo_elements.eql?(sseq.pseudo_elements) &&
-
rest.subset?(sseq.rest)
-
end
-
-
# @see Simple#to_a
-
2
def to_a
-
62932
res = @members.map {|sel| sel.to_a}.flatten
-
26048
res << '!' if subject?
-
26048
res
-
end
-
-
# Returns a string representation of the sequence.
-
# This is basically the selector string.
-
#
-
# @return [String]
-
2
def inspect
-
members.map {|m| m.inspect}.join
-
end
-
-
# Return a copy of this simple sequence with `sources` merged into the
-
# {#sources} set.
-
#
-
# @param sources [Set<Sequence>]
-
# @return [SimpleSequence]
-
2
def with_more_sources(sources)
-
42
sseq = dup
-
42
sseq.members = members.dup
-
42
sseq.sources = self.sources | sources
-
42
sseq
-
end
-
-
2
private
-
-
2
def check_directives_match!(extend, parent_directives)
-
42
dirs1 = extend.directives.map {|d| d.resolved_value}
-
42
dirs2 = parent_directives.map {|d| d.resolved_value}
-
42
return true if Sass::Util.subsequence?(dirs1, dirs2)
-
-
Sass::Util.sass_warn <<WARNING
-
DEPRECATION WARNING on line #{extend.node.line}#{" of #{extend.node.filename}" if extend.node.filename}:
-
@extending an outer selector from within #{extend.directives.last.name} is deprecated.
-
You may only @extend selectors within the same directive.
-
This will be an error in Sass 3.3.
-
It can only work once @extend is supported natively in the browser.
-
WARNING
-
return false
-
end
-
-
2
def _hash
-
16306
[base, Sass::Util.set_hash(rest)].hash
-
end
-
-
2
def _eql?(other)
-
16307
other.base.eql?(self.base) && other.pseudo_elements == pseudo_elements &&
-
Sass::Util.set_eql?(other.rest, self.rest) && other.subject? == self.subject?
-
end
-
end
-
end
-
end
-
2
module Sass
-
# This module contains functionality that's shared between Haml and Sass.
-
2
module Shared
-
2
extend self
-
-
# Scans through a string looking for the interoplation-opening `#{`
-
# and, when it's found, yields the scanner to the calling code
-
# so it can handle it properly.
-
#
-
# The scanner will have any backslashes immediately in front of the `#{`
-
# as the second capture group (`scan[2]`),
-
# and the text prior to that as the first (`scan[1]`).
-
#
-
# @yieldparam scan [StringScanner] The scanner scanning through the string
-
# @return [String] The text remaining in the scanner after all `#{`s have been processed
-
2
def handle_interpolation(str)
-
1758
scan = Sass::Util::MultibyteStringScanner.new(str)
-
1758
yield scan while scan.scan(/(.*?)(\\*)\#\{/m)
-
1758
scan.rest
-
end
-
-
# Moves a scanner through a balanced pair of characters.
-
# For example:
-
#
-
# Foo (Bar (Baz bang) bop) (Bang (bop bip))
-
# ^ ^
-
# from to
-
#
-
# @param scanner [StringScanner] The string scanner to move
-
# @param start [Character] The character opening the balanced pair.
-
# A `Fixnum` in 1.8, a `String` in 1.9
-
# @param finish [Character] The character closing the balanced pair.
-
# A `Fixnum` in 1.8, a `String` in 1.9
-
# @param count [Fixnum] The number of opening characters matched
-
# before calling this method
-
# @return [(String, String)] The string matched within the balanced pair
-
# and the rest of the string.
-
# `["Foo (Bar (Baz bang) bop)", " (Bang (bop bip))"]` in the example above.
-
2
def balance(scanner, start, finish, count = 0)
-
20
str = ''
-
20
scanner = Sass::Util::MultibyteStringScanner.new(scanner) unless scanner.is_a? StringScanner
-
20
regexp = Regexp.new("(.*?)[\\#{start.chr}\\#{finish.chr}]", Regexp::MULTILINE)
-
20
while scanner.scan(regexp)
-
20
str << scanner.matched
-
20
count += 1 if scanner.matched[-1] == start
-
20
count -= 1 if scanner.matched[-1] == finish
-
20
return [str.strip, scanner.rest] if count == 0
-
end
-
end
-
-
# Formats a string for use in error messages about indentation.
-
#
-
# @param indentation [String] The string used for indentation
-
# @param was [Boolean] Whether or not to add `"was"` or `"were"`
-
# (depending on how many characters were in `indentation`)
-
# @return [String] The name of the indentation (e.g. `"12 spaces"`, `"1 tab"`)
-
2
def human_indentation(indentation, was = false)
-
if !indentation.include?(?\t)
-
noun = 'space'
-
elsif !indentation.include?(?\s)
-
noun = 'tab'
-
else
-
return indentation.inspect + (was ? ' was' : '')
-
end
-
-
singular = indentation.length == 1
-
if was
-
was = singular ? ' was' : ' were'
-
else
-
was = ''
-
end
-
-
"#{indentation.length} #{noun}#{'s' unless singular}#{was}"
-
end
-
end
-
end
-
2
module Sass::Tree
-
# A static node representing an unproccessed Sass `@charset` directive.
-
#
-
# @see Sass::Tree
-
2
class CharsetNode < Node
-
# The name of the charset.
-
#
-
# @return [String]
-
2
attr_accessor :name
-
-
# @param name [String] see \{#name}
-
2
def initialize(name)
-
2
@name = name
-
2
super()
-
end
-
-
# @see Node#invisible?
-
2
def invisible?
-
2
!Sass::Util.ruby1_8?
-
end
-
end
-
end
-
2
require 'sass/tree/node'
-
-
2
module Sass::Tree
-
# A static node representing a Sass comment (silent or loud).
-
#
-
# @see Sass::Tree
-
2
class CommentNode < Node
-
# The text of the comment, not including `/*` and `*/`.
-
# Interspersed with {Sass::Script::Node}s representing `#{}`-interpolation
-
# if this is a loud comment.
-
#
-
# @return [Array<String, Sass::Script::Node>]
-
2
attr_accessor :value
-
-
# The text of the comment
-
# after any interpolated SassScript has been resolved.
-
# Only set once \{Tree::Visitors::Perform} has been run.
-
#
-
# @return [String]
-
2
attr_accessor :resolved_value
-
-
# The type of the comment. `:silent` means it's never output to CSS,
-
# `:normal` means it's output in every compile mode except `:compressed`,
-
# and `:loud` means it's output even in `:compressed`.
-
#
-
# @return [Symbol]
-
2
attr_accessor :type
-
-
# @param value [Array<String, Sass::Script::Node>] See \{#value}
-
# @param type [Symbol] See \{#type}
-
2
def initialize(value, type)
-
3476
@value = Sass::Util.with_extracted_values(value) {|str| normalize_indentation str}
-
1738
@type = type
-
1738
super()
-
end
-
-
# Compares the contents of two comments.
-
#
-
# @param other [Object] The object to compare with
-
# @return [Boolean] Whether or not this node and the other object
-
# are the same
-
2
def ==(other)
-
self.class == other.class && value == other.value && type == other.type
-
end
-
-
# Returns `true` if this is a silent comment
-
# or the current style doesn't render comments.
-
#
-
# Comments starting with ! are never invisible (and the ! is removed from the output.)
-
#
-
# @return [Boolean]
-
2
def invisible?
-
1762
case @type
-
36
when :loud; false
-
when :silent; true
-
1726
else; style == :compressed
-
end
-
end
-
-
# Returns the number of lines in the comment.
-
#
-
# @return [Fixnum]
-
2
def lines
-
@value.inject(0) do |s, e|
-
next s + e.count("\n") if e.is_a?(String)
-
next s
-
end
-
end
-
-
2
private
-
-
2
def normalize_indentation(str)
-
1738
ind = str.split("\n").inject(str[/^[ \t]*/].split("")) do |pre, line|
-
1953
line[/^[ \t]*/].split("").zip(pre).inject([]) do |arr, (a, b)|
-
4599
break arr if a != b
-
4518
arr << a
-
end
-
end.join
-
1738
str.gsub(/^#{ind}/, '')
-
end
-
end
-
end
-
2
module Sass
-
2
module Tree
-
# A node representing the placement within a mixin of the include statement's content.
-
#
-
# @see Sass::Tree
-
2
class ContentNode < Node
-
end
-
end
-
end
-
2
module Sass::Tree
-
# A node representing an `@import` rule that's importing plain CSS.
-
#
-
# @see Sass::Tree
-
2
class CssImportNode < DirectiveNode
-
# The URI being imported, either as a plain string or an interpolated
-
# script string.
-
#
-
# @return [String, Sass::Script::Node]
-
2
attr_accessor :uri
-
-
# The text of the URI being imported after any interpolated SassScript has
-
# been resolved. Only set once \{Tree::Visitors::Perform} has been run.
-
#
-
# @return [String]
-
2
attr_accessor :resolved_uri
-
-
# The media query for this rule, interspersed with {Sass::Script::Node}s
-
# representing `#{}`-interpolation. Any adjacent strings will be merged
-
# together.
-
#
-
# @return [Array<String, Sass::Script::Node>]
-
2
attr_accessor :query
-
-
# The media query for this rule, without any unresolved interpolation. It's
-
# only set once {Tree::Node#perform} has been called.
-
#
-
# @return [Sass::Media::QueryList]
-
2
attr_accessor :resolved_query
-
-
# @param uri [String, Sass::Script::Node] See \{#uri}
-
# @param query [Array<String, Sass::Script::Node>] See \{#query}
-
2
def initialize(uri, query = nil)
-
@uri = uri
-
@query = query
-
super('')
-
end
-
-
# @param uri [String] See \{#resolved_uri}
-
# @return [CssImportNode]
-
2
def self.resolved(uri)
-
node = new(uri)
-
node.resolved_uri = uri
-
node
-
end
-
-
# @see DirectiveNode#value
-
2
def value; raise NotImplementedError; end
-
-
# @see DirectiveNode#resolved_value
-
2
def resolved_value
-
@resolved_value ||=
-
begin
-
str = "@import #{resolved_uri}"
-
str << " #{resolved_query.to_css}" if resolved_query
-
str
-
end
-
end
-
end
-
end
-
2
module Sass
-
2
module Tree
-
# A dynamic node representing a Sass `@debug` statement.
-
#
-
# @see Sass::Tree
-
2
class DebugNode < Node
-
# The expression to print.
-
# @return [Script::Node]
-
2
attr_accessor :expr
-
-
# @param expr [Script::Node] The expression to print
-
2
def initialize(expr)
-
@expr = expr
-
super()
-
end
-
end
-
end
-
end
-
2
module Sass::Tree
-
# A static node representing an unproccessed Sass `@`-directive.
-
# Directives known to Sass, like `@for` and `@debug`,
-
# are handled by their own nodes;
-
# only CSS directives like `@media` and `@font-face` become {DirectiveNode}s.
-
#
-
# `@import` and `@charset` are special cases;
-
# they become {ImportNode}s and {CharsetNode}s, respectively.
-
#
-
# @see Sass::Tree
-
2
class DirectiveNode < Node
-
# The text of the directive, `@` and all, with interpolation included.
-
#
-
# @return [Array<String, Sass::Script::Node>]
-
2
attr_accessor :value
-
-
# The text of the directive after any interpolated SassScript has been resolved.
-
# Only set once \{Tree::Visitors::Perform} has been run.
-
#
-
# @return [String]
-
2
attr_accessor :resolved_value
-
-
# @param value [Array<String, Sass::Script::Node>] See \{#value}
-
2
def initialize(value)
-
420
@value = value
-
420
super()
-
end
-
-
# @param value [String] See \{#resolved_value}
-
# @return [DirectiveNode]
-
2
def self.resolved(value)
-
node = new([value])
-
node.resolved_value = value
-
node
-
end
-
-
# @return [String] The name of the directive, including `@`.
-
2
def name
-
value.first.gsub(/ .*$/, '')
-
end
-
end
-
end
-
2
require 'sass/tree/node'
-
-
2
module Sass::Tree
-
# A dynamic node representing a Sass `@each` loop.
-
#
-
# @see Sass::Tree
-
2
class EachNode < Node
-
# The name of the loop variable.
-
# @return [String]
-
2
attr_reader :var
-
-
# The parse tree for the list.
-
# @param [Script::Node]
-
2
attr_accessor :list
-
-
# @param var [String] The name of the loop variable
-
# @param list [Script::Node] The parse tree for the list
-
2
def initialize(var, list)
-
@var = var
-
@list = list
-
super()
-
end
-
end
-
end
-
2
require 'sass/tree/node'
-
-
2
module Sass::Tree
-
# A static node reprenting an `@extend` directive.
-
#
-
# @see Sass::Tree
-
2
class ExtendNode < Node
-
# The parsed selector after interpolation has been resolved.
-
# Only set once {Tree::Visitors::Perform} has been run.
-
#
-
# @return [Selector::CommaSequence]
-
2
attr_accessor :resolved_selector
-
-
# The CSS selector to extend, interspersed with {Sass::Script::Node}s
-
# representing `#{}`-interpolation.
-
#
-
# @return [Array<String, Sass::Script::Node>]
-
2
attr_accessor :selector
-
-
# Whether the `@extend` is allowed to match no selectors or not.
-
#
-
# @return [Boolean]
-
2
def optional?; @optional; end
-
-
# @param selector [Array<String, Sass::Script::Node>]
-
# The CSS selector to extend,
-
# interspersed with {Sass::Script::Node}s
-
# representing `#{}`-interpolation.
-
# @param optional [Boolean] See \{#optional}
-
2
def initialize(selector, optional)
-
1
@selector = selector
-
1
@optional = optional
-
1
super()
-
end
-
end
-
end
-
2
require 'sass/tree/node'
-
-
2
module Sass::Tree
-
# A dynamic node representing a Sass `@for` loop.
-
#
-
# @see Sass::Tree
-
2
class ForNode < Node
-
# The name of the loop variable.
-
# @return [String]
-
2
attr_reader :var
-
-
# The parse tree for the initial expression.
-
# @return [Script::Node]
-
2
attr_accessor :from
-
-
# The parse tree for the final expression.
-
# @return [Script::Node]
-
2
attr_accessor :to
-
-
# Whether to include `to` in the loop or stop just before.
-
# @return [Boolean]
-
2
attr_reader :exclusive
-
-
# @param var [String] See \{#var}
-
# @param from [Script::Node] See \{#from}
-
# @param to [Script::Node] See \{#to}
-
# @param exclusive [Boolean] See \{#exclusive}
-
2
def initialize(var, from, to, exclusive)
-
@var = var
-
@from = from
-
@to = to
-
@exclusive = exclusive
-
super()
-
end
-
end
-
end
-
2
module Sass
-
2
module Tree
-
# A dynamic node representing a function definition.
-
#
-
# @see Sass::Tree
-
2
class FunctionNode < Node
-
# The name of the function.
-
# @return [String]
-
2
attr_reader :name
-
-
# The arguments to the function. Each element is a tuple
-
# containing the variable for argument and the parse tree for
-
# the default value of the argument
-
#
-
# @return [Array<Script::Node>]
-
2
attr_accessor :args
-
-
# The splat argument for this function, if one exists.
-
#
-
# @return [Script::Node?]
-
2
attr_accessor :splat
-
-
# @param name [String] The function name
-
# @param args [Array<(Script::Node, Script::Node)>] The arguments for the function.
-
# @param splat [Script::Node] See \{#splat}
-
2
def initialize(name, args, splat)
-
@name = name
-
@args = args
-
@splat = splat
-
super()
-
end
-
end
-
end
-
end
-
2
require 'sass/tree/node'
-
-
2
module Sass::Tree
-
# A dynamic node representing a Sass `@if` statement.
-
#
-
# {IfNode}s are a little odd, in that they also represent `@else` and `@else if`s.
-
# This is done as a linked list:
-
# each {IfNode} has a link (\{#else}) to the next {IfNode}.
-
#
-
# @see Sass::Tree
-
2
class IfNode < Node
-
# The conditional expression.
-
# If this is nil, this is an `@else` node, not an `@else if`.
-
#
-
# @return [Script::Expr]
-
2
attr_accessor :expr
-
-
# The next {IfNode} in the if-else list, or `nil`.
-
#
-
# @return [IfNode]
-
2
attr_accessor :else
-
-
# @param expr [Script::Expr] See \{#expr}
-
2
def initialize(expr)
-
@expr = expr
-
@last_else = self
-
super()
-
end
-
-
# Append an `@else` node to the end of the list.
-
#
-
# @param node [IfNode] The `@else` node to append
-
2
def add_else(node)
-
@last_else.else = node
-
@last_else = node
-
end
-
-
2
def _dump(f)
-
Marshal.dump([self.expr, self.else, self.children])
-
end
-
-
2
def self._load(data)
-
expr, else_, children = Marshal.load(data)
-
node = IfNode.new(expr)
-
node.else = else_
-
node.children = children
-
node.instance_variable_set('@last_else',
-
node.else ? node.else.instance_variable_get('@last_else') : node)
-
node
-
end
-
end
-
end
-
2
module Sass
-
2
module Tree
-
# A static node that wraps the {Sass::Tree} for an `@import`ed file.
-
# It doesn't have a functional purpose other than to add the `@import`ed file
-
# to the backtrace if an error occurs.
-
2
class ImportNode < RootNode
-
# The name of the imported file as it appears in the Sass document.
-
#
-
# @return [String]
-
2
attr_reader :imported_filename
-
-
# Sets the imported file.
-
2
attr_writer :imported_file
-
-
# @param imported_filename [String] The name of the imported file
-
2
def initialize(imported_filename)
-
@imported_filename = imported_filename
-
super(nil)
-
end
-
-
2
def invisible?; to_s.empty?; end
-
-
# Returns the imported file.
-
#
-
# @return [Sass::Engine]
-
# @raise [Sass::SyntaxError] If no file could be found to import.
-
2
def imported_file
-
@imported_file ||= import
-
end
-
-
# Returns whether or not this import should emit a CSS @import declaration
-
#
-
# @return [Boolean] Whether or not this is a simple CSS @import declaration.
-
2
def css_import?
-
if @imported_filename =~ /\.css$/
-
@imported_filename
-
elsif imported_file.is_a?(String) && imported_file =~ /\.css$/
-
imported_file
-
end
-
end
-
-
2
private
-
-
2
def import
-
paths = @options[:load_paths]
-
-
if @options[:importer]
-
f = @options[:importer].find_relative(
-
@imported_filename, @options[:filename], options_for_importer)
-
return f if f
-
end
-
-
paths.each do |p|
-
if f = p.find(@imported_filename, options_for_importer)
-
return f
-
end
-
end
-
-
message = "File to import not found or unreadable: #{@imported_filename}.\n"
-
if paths.size == 1
-
message << "Load path: #{paths.first}"
-
else
-
message << "Load paths:\n " << paths.join("\n ")
-
end
-
raise SyntaxError.new(message)
-
rescue SyntaxError => e
-
raise SyntaxError.new(e.message, :line => self.line, :filename => @filename)
-
end
-
-
2
def options_for_importer
-
@options.merge(:_line => line)
-
end
-
end
-
end
-
end
-
2
module Sass::Tree
-
# A static node representing a `@media` rule.
-
# `@media` rules behave differently from other directives
-
# in that when they're nested within rules,
-
# they bubble up to top-level.
-
#
-
# @see Sass::Tree
-
2
class MediaNode < DirectiveNode
-
# TODO: parse and cache the query immediately if it has no dynamic elements
-
-
# The media query for this rule, interspersed with {Sass::Script::Node}s
-
# representing `#{}`-interpolation. Any adjacent strings will be merged
-
# together.
-
#
-
# @return [Array<String, Sass::Script::Node>]
-
2
attr_accessor :query
-
-
# The media query for this rule, without any unresolved interpolation. It's
-
# only set once {Tree::Node#perform} has been called.
-
#
-
# @return [Sass::Media::QueryList]
-
2
attr_accessor :resolved_query
-
-
# @see RuleNode#tabs
-
2
attr_accessor :tabs
-
-
# @see RuleNode#group_end
-
2
attr_accessor :group_end
-
-
# @param query [Array<String, Sass::Script::Node>] See \{#query}
-
2
def initialize(query)
-
211
@query = query
-
211
@tabs = 0
-
211
super('')
-
end
-
-
# @see DirectiveNode#value
-
2
def value; raise NotImplementedError; end
-
-
# @see DirectiveNode#name
-
2
def name; '@media'; end
-
-
# @see DirectiveNode#resolved_value
-
2
def resolved_value
-
211
@resolved_value ||= "@media #{resolved_query.to_css}"
-
end
-
-
# True when the directive has no visible children.
-
#
-
# @return [Boolean]
-
2
def invisible?
-
422
children.all? {|c| c.invisible?}
-
end
-
-
# @see Node#bubbles?
-
424
def bubbles?; true; end
-
end
-
end
-
2
module Sass
-
2
module Tree
-
# A dynamic node representing a mixin definition.
-
#
-
# @see Sass::Tree
-
2
class MixinDefNode < Node
-
# The mixin name.
-
# @return [String]
-
2
attr_reader :name
-
-
# The arguments for the mixin.
-
# Each element is a tuple containing the variable for argument
-
# and the parse tree for the default value of the argument.
-
#
-
# @return [Array<(Script::Node, Script::Node)>]
-
2
attr_accessor :args
-
-
# The splat argument for this mixin, if one exists.
-
#
-
# @return [Script::Node?]
-
2
attr_accessor :splat
-
-
# Whether the mixin uses `@content`. Set during the nesting check phase.
-
# @return [Boolean]
-
2
attr_accessor :has_content
-
-
# @param name [String] The mixin name
-
# @param args [Array<(Script::Node, Script::Node)>] See \{#args}
-
# @param splat [Script::Node] See \{#splat}
-
2
def initialize(name, args, splat)
-
@name = name
-
@args = args
-
@splat = splat
-
super()
-
end
-
end
-
end
-
end
-
2
require 'sass/tree/node'
-
-
2
module Sass::Tree
-
# A static node representing a mixin include.
-
# When in a static tree, the sole purpose is to wrap exceptions
-
# to add the mixin to the backtrace.
-
#
-
# @see Sass::Tree
-
2
class MixinNode < Node
-
# The name of the mixin.
-
# @return [String]
-
2
attr_reader :name
-
-
# The arguments to the mixin.
-
# @return [Array<Script::Node>]
-
2
attr_accessor :args
-
-
# A hash from keyword argument names to values.
-
# @return [{String => Script::Node}]
-
2
attr_accessor :keywords
-
-
# The splat argument for this mixin, if one exists.
-
#
-
# @return [Script::Node?]
-
2
attr_accessor :splat
-
-
# @param name [String] The name of the mixin
-
# @param args [Array<Script::Node>] See \{#args}
-
# @param splat [Script::Node] See \{#splat}
-
# @param keywords [{String => Script::Node}] See \{#keywords}
-
2
def initialize(name, args, keywords, splat)
-
@name = name
-
@args = args
-
@keywords = keywords
-
@splat = splat
-
super()
-
end
-
end
-
end
-
2
module Sass
-
# A namespace for nodes in the Sass parse tree.
-
#
-
# The Sass parse tree has three states: dynamic, static Sass, and static CSS.
-
#
-
# When it's first parsed, a Sass document is in the dynamic state.
-
# It has nodes for mixin definitions and `@for` loops and so forth,
-
# in addition to nodes for CSS rules and properties.
-
# Nodes that only appear in this state are called **dynamic nodes**.
-
#
-
# {Tree::Visitors::Perform} creates a static Sass tree, which is different.
-
# It still has nodes for CSS rules and properties
-
# but it doesn't have any dynamic-generation-related nodes.
-
# The nodes in this state are in the same structure as the Sass document:
-
# rules and properties are nested beneath one another.
-
# Nodes that can be in this state or in the dynamic state
-
# are called **static nodes**; nodes that can only be in this state
-
# are called **solely static nodes**.
-
#
-
# {Tree::Visitors::Cssize} is then used to create a static CSS tree.
-
# This is like a static Sass tree,
-
# but the structure exactly mirrors that of the generated CSS.
-
# Rules and properties can't be nested beneath one another in this state.
-
#
-
# Finally, {Tree::Visitors::ToCss} can be called on a static CSS tree
-
# to get the actual CSS code as a string.
-
2
module Tree
-
# The abstract superclass of all parse-tree nodes.
-
2
class Node
-
2
include Enumerable
-
-
# The child nodes of this node.
-
#
-
# @return [Array<Tree::Node>]
-
2
attr_accessor :children
-
-
# Whether or not this node has child nodes.
-
# This may be true even when \{#children} is empty,
-
# in which case this node has an empty block (e.g. `{}`).
-
#
-
# @return [Boolean]
-
2
attr_accessor :has_children
-
-
# The line of the document on which this node appeared.
-
#
-
# @return [Fixnum]
-
2
attr_accessor :line
-
-
# The name of the document on which this node appeared.
-
#
-
# @return [String]
-
2
attr_writer :filename
-
-
# The options hash for the node.
-
# See {file:SASS_REFERENCE.md#sass_options the Sass options documentation}.
-
#
-
# @return [{Symbol => Object}]
-
2
attr_reader :options
-
-
2
def initialize
-
21565
@children = []
-
end
-
-
# Sets the options hash for the node and all its children.
-
#
-
# @param options [{Symbol => Object}] The options
-
# @see #options
-
2
def options=(options)
-
1
Sass::Tree::Visitors::SetOptions.visit(self, options)
-
end
-
-
# @private
-
2
def children=(children)
-
46242
self.has_children ||= !children.empty?
-
46242
@children = children
-
end
-
-
# The name of the document on which this node appeared.
-
#
-
# @return [String]
-
2
def filename
-
6794
@filename || (@options && @options[:filename])
-
end
-
-
# Appends a child to the node.
-
#
-
# @param child [Tree::Node, Array<Tree::Node>] The child node or nodes
-
# @raise [Sass::SyntaxError] if `child` is invalid
-
2
def <<(child)
-
25165
return if child.nil?
-
21564
if child.is_a?(Array)
-
child.each {|c| self << c}
-
else
-
21564
self.has_children = true
-
21564
@children << child
-
end
-
end
-
-
# Compares this node and another object (only other {Tree::Node}s will be equal).
-
# This does a structural comparison;
-
# if the contents of the nodes and all the child nodes are equivalent,
-
# then the nodes are as well.
-
#
-
# Only static nodes need to override this.
-
#
-
# @param other [Object] The object to compare with
-
# @return [Boolean] Whether or not this node and the other object
-
# are the same
-
# @see Sass::Tree
-
2
def ==(other)
-
self.class == other.class && other.children == children
-
end
-
-
# True if \{#to\_s} will return `nil`;
-
# that is, if the node shouldn't be rendered.
-
# Should only be called in a static tree.
-
#
-
# @return [Boolean]
-
211
def invisible?; false; end
-
-
# The output style. See {file:SASS_REFERENCE.md#sass_options the Sass options documentation}.
-
#
-
# @return [Symbol]
-
2
def style
-
86913
@options[:style]
-
end
-
-
# Computes the CSS corresponding to this static CSS tree.
-
#
-
# @return [String, nil] The resulting CSS
-
# @see Sass::Tree
-
2
def to_s
-
1
Sass::Tree::Visitors::ToCss.visit(self)
-
end
-
-
# Returns a representation of the node for debugging purposes.
-
#
-
# @return [String]
-
2
def inspect
-
return self.class.to_s unless has_children
-
"(#{self.class} #{children.map {|c| c.inspect}.join(' ')})"
-
end
-
-
# Iterates through each node in the tree rooted at this node
-
# in a pre-order walk.
-
#
-
# @yield node
-
# @yieldparam node [Node] a node in the tree
-
2
def each
-
yield self
-
children.each {|c| c.each {|n| yield n}}
-
end
-
-
# Converts a node to Sass code that will generate it.
-
#
-
# @param options [{Symbol => Object}] An options hash (see {Sass::CSS#initialize})
-
# @return [String] The Sass code corresponding to the node
-
2
def to_sass(options = {})
-
Sass::Tree::Visitors::Convert.visit(self, options, :sass)
-
end
-
-
# Converts a node to SCSS code that will generate it.
-
#
-
# @param options [{Symbol => Object}] An options hash (see {Sass::CSS#initialize})
-
# @return [String] The Sass code corresponding to the node
-
2
def to_scss(options = {})
-
Sass::Tree::Visitors::Convert.visit(self, options, :scss)
-
end
-
-
# Return a deep clone of this node.
-
# The child nodes are cloned, but options are not.
-
#
-
# @return [Node]
-
2
def deep_copy
-
Sass::Tree::Visitors::DeepCopy.visit(self)
-
end
-
-
# Whether or not this node bubbles up through RuleNodes.
-
#
-
# @return [Boolean]
-
2
def bubbles?
-
66564
false
-
end
-
-
2
protected
-
-
# @see Sass::Shared.balance
-
# @raise [Sass::SyntaxError] if the brackets aren't balanced
-
2
def balance(*args)
-
res = Sass::Shared.balance(*args)
-
return res if res
-
raise Sass::SyntaxError.new("Unbalanced brackets.", :line => line)
-
end
-
end
-
end
-
end
-
2
module Sass::Tree
-
# A static node reprenting a CSS property.
-
#
-
# @see Sass::Tree
-
2
class PropNode < Node
-
# The name of the property,
-
# interspersed with {Sass::Script::Node}s
-
# representing `#{}`-interpolation.
-
# Any adjacent strings will be merged together.
-
#
-
# @return [Array<String, Sass::Script::Node>]
-
2
attr_accessor :name
-
-
# The name of the property
-
# after any interpolated SassScript has been resolved.
-
# Only set once \{Tree::Visitors::Perform} has been run.
-
#
-
# @return [String]
-
2
attr_accessor :resolved_name
-
-
# The value of the property.
-
#
-
# @return [Sass::Script::Node]
-
2
attr_accessor :value
-
-
# The value of the property
-
# after any interpolated SassScript has been resolved.
-
# Only set once \{Tree::Visitors::Perform} has been run.
-
#
-
# @return [String]
-
2
attr_accessor :resolved_value
-
-
# How deep this property is indented
-
# relative to a normal property.
-
# This is only greater than 0 in the case that:
-
#
-
# * This node is in a CSS tree
-
# * The style is :nested
-
# * This is a child property of another property
-
# * The parent property has a value, and thus will be rendered
-
#
-
# @return [Fixnum]
-
2
attr_accessor :tabs
-
-
# @param name [Array<String, Sass::Script::Node>] See \{#name}
-
# @param value [Sass::Script::Node] See \{#value}
-
# @param prop_syntax [Symbol] `:new` if this property uses `a: b`-style syntax,
-
# `:old` if it uses `:a b`-style syntax
-
2
def initialize(name, value, prop_syntax)
-
12821
@name = Sass::Util.strip_string_array(
-
Sass::Util.merge_adjacent_strings(name))
-
12821
@value = value
-
12821
@tabs = 0
-
12821
@prop_syntax = prop_syntax
-
12821
super()
-
end
-
-
# Compares the names and values of two properties.
-
#
-
# @param other [Object] The object to compare with
-
# @return [Boolean] Whether or not this node and the other object
-
# are the same
-
2
def ==(other)
-
self.class == other.class && name == other.name && value == other.value && super
-
end
-
-
# Returns a appropriate message indicating how to escape pseudo-class selectors.
-
# This only applies for old-style properties with no value,
-
# so returns the empty string if this is new-style.
-
#
-
# @return [String] The message
-
2
def pseudo_class_selector_message
-
return "" if @prop_syntax == :new || !value.is_a?(Sass::Script::String) || !value.value.empty?
-
"\nIf #{declaration.dump} should be a selector, use \"\\#{declaration}\" instead."
-
end
-
-
# Computes the Sass or SCSS code for the variable declaration.
-
# This is like \{#to\_scss} or \{#to\_sass},
-
# except it doesn't print any child properties or a trailing semicolon.
-
#
-
# @param opts [{Symbol => Object}] The options hash for the tree.
-
# @param fmt [Symbol] `:scss` or `:sass`.
-
2
def declaration(opts = {:old => @prop_syntax == :old}, fmt = :sass)
-
name = self.name.map {|n| n.is_a?(String) ? n : "\#{#{n.to_sass(opts)}}"}.join
-
if name[0] == ?:
-
raise Sass::SyntaxError.new("The \"#{name}: #{self.class.val_to_sass(value, opts)}\" hack is not allowed in the Sass indented syntax")
-
end
-
-
old = opts[:old] && fmt == :sass
-
initial = old ? ':' : ''
-
mid = old ? '' : ':'
-
"#{initial}#{name}#{mid} #{self.class.val_to_sass(value, opts)}".rstrip
-
end
-
-
# A property node is invisible if its value is empty.
-
#
-
# @return [Boolean]
-
2
def invisible?
-
12821
resolved_value.empty?
-
end
-
-
2
private
-
-
2
def check!
-
12821
if @options[:property_syntax] && @options[:property_syntax] != @prop_syntax
-
raise Sass::SyntaxError.new(
-
"Illegal property syntax: can't use #{@prop_syntax} syntax when :property_syntax => #{@options[:property_syntax].inspect} is set.")
-
end
-
end
-
-
2
class << self
-
# @private
-
2
def val_to_sass(value, opts)
-
val_to_sass_comma(value, opts).to_sass(opts)
-
end
-
-
2
private
-
-
2
def val_to_sass_comma(node, opts)
-
return node unless node.is_a?(Sass::Script::Operation)
-
return val_to_sass_concat(node, opts) unless node.operator == :comma
-
-
Sass::Script::Operation.new(
-
val_to_sass_concat(node.operand1, opts),
-
val_to_sass_comma(node.operand2, opts),
-
node.operator)
-
end
-
-
2
def val_to_sass_concat(node, opts)
-
return node unless node.is_a?(Sass::Script::Operation)
-
return val_to_sass_div(node, opts) unless node.operator == :space
-
-
Sass::Script::Operation.new(
-
val_to_sass_div(node.operand1, opts),
-
val_to_sass_concat(node.operand2, opts),
-
node.operator)
-
end
-
-
2
def val_to_sass_div(node, opts)
-
unless node.is_a?(Sass::Script::Operation) && node.operator == :div &&
-
node.operand1.is_a?(Sass::Script::Number) &&
-
node.operand2.is_a?(Sass::Script::Number) &&
-
(!node.operand1.original || !node.operand2.original)
-
return node
-
end
-
-
Sass::Script::String.new("(#{node.to_sass(opts)})")
-
end
-
-
end
-
end
-
end
-
2
module Sass
-
2
module Tree
-
# A dynamic node representing returning from a function.
-
#
-
# @see Sass::Tree
-
2
class ReturnNode < Node
-
# The expression to return.
-
# @type [Script::Node]
-
2
attr_accessor :expr
-
-
# @param expr [Script::Node] The expression to return
-
2
def initialize(expr)
-
@expr = expr
-
super()
-
end
-
end
-
end
-
end
-
2
module Sass
-
2
module Tree
-
# A static node that is the root node of the Sass document.
-
2
class RootNode < Node
-
# The Sass template from which this node was created
-
#
-
# @param template [String]
-
2
attr_reader :template
-
-
# @param template [String] The Sass template from which this node was created
-
2
def initialize(template)
-
1
super()
-
1
@template = template
-
end
-
-
# Runs the dynamic Sass code *and* computes the CSS for the tree.
-
# @see #to_s
-
2
def render
-
1
Visitors::CheckNesting.visit(self)
-
1
result = Visitors::Perform.visit(self)
-
1
Visitors::CheckNesting.visit(result) # Check again to validate mixins
-
1
result, extends = Visitors::Cssize.visit(result)
-
1
Visitors::Extend.visit(result, extends)
-
1
result.to_s
-
end
-
end
-
end
-
end
-
2
require 'pathname'
-
2
require 'uri'
-
-
2
module Sass::Tree
-
# A static node reprenting a CSS rule.
-
#
-
# @see Sass::Tree
-
2
class RuleNode < Node
-
# The character used to include the parent selector
-
2
PARENT = '&'
-
-
# The CSS selector for this rule,
-
# interspersed with {Sass::Script::Node}s
-
# representing `#{}`-interpolation.
-
# Any adjacent strings will be merged together.
-
#
-
# @return [Array<String, Sass::Script::Node>]
-
2
attr_accessor :rule
-
-
# The CSS selector for this rule,
-
# without any unresolved interpolation
-
# but with parent references still intact.
-
# It's only set once {Tree::Node#perform} has been called.
-
#
-
# @return [Selector::CommaSequence]
-
2
attr_accessor :parsed_rules
-
-
# The CSS selector for this rule,
-
# without any unresolved interpolation or parent references.
-
# It's only set once {Tree::Visitors::Cssize} has been run.
-
#
-
# @return [Selector::CommaSequence]
-
2
attr_accessor :resolved_rules
-
-
# How deep this rule is indented
-
# relative to a base-level rule.
-
# This is only greater than 0 in the case that:
-
#
-
# * This node is in a CSS tree
-
# * The style is :nested
-
# * This is a child rule of another rule
-
# * The parent rule has properties, and thus will be rendered
-
#
-
# @return [Fixnum]
-
2
attr_accessor :tabs
-
-
# Whether or not this rule is the last rule in a nested group.
-
# This is only set in a CSS tree.
-
#
-
# @return [Boolean]
-
2
attr_accessor :group_end
-
-
# The stack trace.
-
# This is only readable in a CSS tree as it is written during the perform step
-
# and only when the :trace_selectors option is set.
-
#
-
# @return [Array<String>]
-
2
attr_accessor :stack_trace
-
-
# @param rule [Array<String, Sass::Script::Node>]
-
# The CSS rule. See \{#rule}
-
2
def initialize(rule)
-
6582
merged = Sass::Util.merge_adjacent_strings(rule)
-
6582
@rule = Sass::Util.strip_string_array(merged)
-
6582
@tabs = 0
-
6582
try_to_parse_non_interpolated_rules
-
6582
super()
-
end
-
-
# If we've precached the parsed selector, set the line on it, too.
-
2
def line=(line)
-
6582
@parsed_rules.line = line if @parsed_rules
-
6582
super
-
end
-
-
# If we've precached the parsed selector, set the filename on it, too.
-
2
def filename=(filename)
-
@parsed_rules.filename = filename if @parsed_rules
-
super
-
end
-
-
# Compares the contents of two rules.
-
#
-
# @param other [Object] The object to compare with
-
# @return [Boolean] Whether or not this node and the other object
-
# are the same
-
2
def ==(other)
-
self.class == other.class && rule == other.rule && super
-
end
-
-
# Adds another {RuleNode}'s rules to this one's.
-
#
-
# @param node [RuleNode] The other node
-
2
def add_rules(node)
-
@rule = Sass::Util.strip_string_array(
-
Sass::Util.merge_adjacent_strings(@rule + ["\n"] + node.rule))
-
try_to_parse_non_interpolated_rules
-
end
-
-
# @return [Boolean] Whether or not this rule is continued on the next line
-
2
def continued?
-
last = @rule.last
-
last.is_a?(String) && last[-1] == ?,
-
end
-
-
# A hash that will be associated with this rule in the CSS document
-
# if the {file:SASS_REFERENCE.md#debug_info-option `:debug_info` option} is enabled.
-
# This data is used by e.g. [the FireSass Firebug extension](https://addons.mozilla.org/en-US/firefox/addon/103988).
-
#
-
# @return [{#to_s => #to_s}]
-
2
def debug_info
-
{:filename => filename && ("file://" + URI.escape(File.expand_path(filename))),
-
:line => self.line}
-
end
-
-
# A rule node is invisible if it has only placeholder selectors.
-
2
def invisible?
-
13576
resolved_rules.members.all? {|seq| seq.has_placeholder?}
-
end
-
-
2
private
-
-
2
def try_to_parse_non_interpolated_rules
-
13164
if @rule.all? {|t| t.kind_of?(String)}
-
# We don't use real filename/line info because we don't have it yet.
-
# When we get it, we'll set it on the parsed rules if possible.
-
6582
parser = Sass::SCSS::StaticParser.new(@rule.join.strip, '', 1)
-
6582
@parsed_rules = parser.parse_selector rescue nil
-
end
-
end
-
end
-
end
-
2
module Sass::Tree
-
# A static node representing a `@supports` rule.
-
# `@supports` rules behave differently from other directives
-
# in that when they're nested within rules,
-
# they bubble up to top-level.
-
#
-
# @see Sass::Tree
-
2
class SupportsNode < DirectiveNode
-
# The name, which may include a browser prefix.
-
#
-
# @return [String]
-
2
attr_accessor :name
-
-
# The supports condition.
-
#
-
# @return [Sass::Supports::Condition]
-
2
attr_accessor :condition
-
-
# @see RuleNode#tabs
-
2
attr_accessor :tabs
-
-
# @see RuleNode#group_end
-
2
attr_accessor :group_end
-
-
# @param condition [Sass::Supports::Condition] See \{#condition}
-
2
def initialize(name, condition)
-
@name = name
-
@condition = condition
-
@tabs = 0
-
super('')
-
end
-
-
# @see DirectiveNode#value
-
2
def value; raise NotImplementedError; end
-
-
# @see DirectiveNode#resolved_value
-
2
def resolved_value
-
@resolved_value ||= "@#{name} #{condition.to_css}"
-
end
-
-
# True when the directive has no visible children.
-
#
-
# @return [Boolean]
-
2
def invisible?
-
children.all? {|c| c.invisible?}
-
end
-
-
# @see Node#bubbles?
-
2
def bubbles?; true; end
-
end
-
end
-
2
require 'sass/tree/node'
-
-
2
module Sass::Tree
-
# A solely static node left over after a mixin include or @content has been performed.
-
# Its sole purpose is to wrap exceptions to add to the backtrace.
-
#
-
# @see Sass::Tree
-
2
class TraceNode < Node
-
# The name of the trace entry to add.
-
# @return [String]
-
2
attr_reader :name
-
-
# @param name [String] The name of the trace entry to add.
-
2
def initialize(name)
-
@name = name
-
self.has_children = true
-
super()
-
end
-
-
# Initializes this node from an existing node.
-
# @param name [String] The name of the trace entry to add.
-
# @param mixin [Node] The node to copy information from.
-
# @return [TraceNode]
-
2
def self.from_node(name, node)
-
trace = new(name)
-
trace.line = node.line
-
trace.filename = node.filename
-
trace.options = node.options
-
trace
-
end
-
end
-
end
-
2
module Sass
-
2
module Tree
-
# A dynamic node representing a variable definition.
-
#
-
# @see Sass::Tree
-
2
class VariableNode < Node
-
# The name of the variable.
-
# @return [String]
-
2
attr_reader :name
-
-
# The parse tree for the variable value.
-
# @return [Script::Node]
-
2
attr_accessor :expr
-
-
# Whether this is a guarded variable assignment (`!default`).
-
# @return [Boolean]
-
2
attr_reader :guarded
-
-
# @param name [String] The name of the variable
-
# @param expr [Script::Node] See \{#expr}
-
# @param guarded [Boolean] See \{#guarded}
-
2
def initialize(name, expr, guarded)
-
@name = name
-
@expr = expr
-
@guarded = guarded
-
super()
-
end
-
end
-
end
-
end
-
# Visitors are used to traverse the Sass parse tree.
-
# Visitors should extend {Visitors::Base},
-
# which provides a small amount of scaffolding for traversal.
-
2
module Sass::Tree::Visitors
-
# The abstract base class for Sass visitors.
-
# Visitors should extend this class,
-
# then implement `visit_*` methods for each node they care about
-
# (e.g. `visit_rule` for {RuleNode} or `visit_for` for {ForNode}).
-
# These methods take the node in question as argument.
-
# They may `yield` to visit the child nodes of the current node.
-
#
-
# *Note*: due to the unusual nature of {Sass::Tree::IfNode},
-
# special care must be taken to ensure that it is properly handled.
-
# In particular, there is no built-in scaffolding
-
# for dealing with the return value of `@else` nodes.
-
#
-
# @abstract
-
2
class Base
-
# Runs the visitor on a tree.
-
#
-
# @param root [Tree::Node] The root node of the Sass tree.
-
# @return [Object] The return value of \{#visit} for the root node.
-
2
def self.visit(root)
-
4
new.send(:visit, root)
-
end
-
-
2
protected
-
-
# Runs the visitor on the given node.
-
# This can be overridden by subclasses that need to do something for each node.
-
#
-
# @param node [Tree::Node] The node to visit.
-
# @return [Object] The return value of the `visit_*` method for this node.
-
2
def visit(node)
-
131246
method = "visit_#{node_name node}"
-
131246
if self.respond_to?(method, true)
-
146678
self.send(method, node) {visit_children(node)}
-
else
-
43833
visit_children(node)
-
end
-
end
-
-
# Visit the child nodes for a given node.
-
# This can be overridden by subclasses that need to do something
-
# with the child nodes' return values.
-
#
-
# This method is run when `visit_*` methods `yield`,
-
# and its return value is returned from the `yield`.
-
#
-
# @param parent [Tree::Node] The parent node of the children to visit.
-
# @return [Array<Object>] The return values of the `visit_*` methods for the children.
-
2
def visit_children(parent)
-
214507
parent.children.map {|c| visit(c)}
-
end
-
-
2
NODE_NAME_RE = /.*::(.*?)Node$/
-
-
# Returns the name of a node as used in the `visit_*` method.
-
#
-
# @param [Tree::Node] node The node.
-
# @return [String] The name.
-
2
def node_name(node)
-
214050
@@node_names ||= {}
-
214050
@@node_names[node.class.name] ||= node.class.name.gsub(NODE_NAME_RE, '\\1').downcase
-
end
-
-
# `yield`s, then runs the visitor on the `@else` clause if the node has one.
-
# This exists to ensure that the contents of the `@else` clause get visited.
-
2
def visit_if(node)
-
yield
-
visit(node.else) if node.else
-
node
-
end
-
end
-
end
-
# A visitor for checking that all nodes are properly nested.
-
2
class Sass::Tree::Visitors::CheckNesting < Sass::Tree::Visitors::Base
-
2
protected
-
-
2
def initialize
-
2
@parents = []
-
end
-
-
2
def visit(node)
-
41404
if error = @parent && (
-
try_send("invalid_#{node_name @parent}_child?", @parent, node) ||
-
41402
try_send("invalid_#{node_name node}_parent?", @parent, node))
-
raise Sass::SyntaxError.new(error)
-
end
-
41404
super
-
rescue Sass::SyntaxError => e
-
e.modify_backtrace(:filename => node.filename, :line => node.line)
-
raise e
-
end
-
-
2
CONTROL_NODES = [Sass::Tree::EachNode, Sass::Tree::ForNode, Sass::Tree::IfNode,
-
Sass::Tree::WhileNode, Sass::Tree::TraceNode]
-
2
SCRIPT_NODES = [Sass::Tree::ImportNode] + CONTROL_NODES
-
2
def visit_children(parent)
-
41404
old_parent = @parent
-
@parent = parent unless is_any_of?(parent, SCRIPT_NODES) ||
-
41404
(parent.bubbles? && !old_parent.is_a?(Sass::Tree::RootNode))
-
41404
@parents.push parent
-
41404
super
-
ensure
-
41404
@parent = old_parent
-
41404
@parents.pop
-
end
-
-
2
def visit_root(node)
-
2
yield
-
rescue Sass::SyntaxError => e
-
e.sass_template ||= node.template
-
raise e
-
end
-
-
2
def visit_import(node)
-
yield
-
rescue Sass::SyntaxError => e
-
e.modify_backtrace(:filename => node.children.first.filename)
-
e.add_backtrace(:filename => node.filename, :line => node.line)
-
raise e
-
end
-
-
2
def visit_mixindef(node)
-
@current_mixin_def, old_mixin_def = node, @current_mixin_def
-
yield
-
ensure
-
@current_mixin_def = old_mixin_def
-
end
-
-
2
def invalid_content_parent?(parent, child)
-
if @current_mixin_def
-
@current_mixin_def.has_content = true
-
nil
-
else
-
"@content may only be used within a mixin."
-
end
-
end
-
-
2
def invalid_charset_parent?(parent, child)
-
4
"@charset may only be used at the root of a document." unless parent.is_a?(Sass::Tree::RootNode)
-
end
-
-
2
VALID_EXTEND_PARENTS = [Sass::Tree::RuleNode, Sass::Tree::MixinDefNode, Sass::Tree::MixinNode]
-
2
def invalid_extend_parent?(parent, child)
-
2
unless is_any_of?(parent, VALID_EXTEND_PARENTS)
-
return "Extend directives may only be used within rules."
-
end
-
end
-
-
2
INVALID_IMPORT_PARENTS = CONTROL_NODES +
-
[Sass::Tree::MixinDefNode, Sass::Tree::MixinNode]
-
2
def invalid_import_parent?(parent, child)
-
unless (@parents.map {|p| p.class} & INVALID_IMPORT_PARENTS).empty?
-
return "Import directives may not be used within control directives or mixins."
-
end
-
return if parent.is_a?(Sass::Tree::RootNode)
-
return "CSS import directives may only be used at the root of a document." if child.css_import?
-
rescue Sass::SyntaxError => e
-
e.modify_backtrace(:filename => child.imported_file.options[:filename])
-
e.add_backtrace(:filename => child.filename, :line => child.line)
-
raise e
-
end
-
-
2
def invalid_mixindef_parent?(parent, child)
-
unless (@parents.map {|p| p.class} & INVALID_IMPORT_PARENTS).empty?
-
return "Mixins may not be defined within control directives or other mixins."
-
end
-
end
-
-
2
def invalid_function_parent?(parent, child)
-
unless (@parents.map {|p| p.class} & INVALID_IMPORT_PARENTS).empty?
-
return "Functions may not be defined within control directives or other mixins."
-
end
-
end
-
-
2
VALID_FUNCTION_CHILDREN = [
-
Sass::Tree::CommentNode, Sass::Tree::DebugNode, Sass::Tree::ReturnNode,
-
Sass::Tree::VariableNode, Sass::Tree::WarnNode
-
] + CONTROL_NODES
-
2
def invalid_function_child?(parent, child)
-
unless is_any_of?(child, VALID_FUNCTION_CHILDREN)
-
"Functions can only contain variable declarations and control directives."
-
end
-
end
-
-
2
VALID_PROP_CHILDREN = [Sass::Tree::CommentNode, Sass::Tree::PropNode, Sass::Tree::MixinNode] + CONTROL_NODES
-
2
def invalid_prop_child?(parent, child)
-
unless is_any_of?(child, VALID_PROP_CHILDREN)
-
"Illegal nesting: Only properties may be nested beneath properties."
-
end
-
end
-
-
2
VALID_PROP_PARENTS = [Sass::Tree::RuleNode, Sass::Tree::PropNode,
-
Sass::Tree::MixinDefNode, Sass::Tree::DirectiveNode,
-
Sass::Tree::MixinNode]
-
2
def invalid_prop_parent?(parent, child)
-
25642
unless is_any_of?(parent, VALID_PROP_PARENTS)
-
"Properties are only allowed within rules, directives, mixin includes, or other properties." + child.pseudo_class_selector_message
-
end
-
end
-
-
2
def invalid_return_parent?(parent, child)
-
"@return may only be used within a function." unless parent.is_a?(Sass::Tree::FunctionNode)
-
end
-
-
2
private
-
-
2
def is_any_of?(val, classes)
-
67048
for c in classes
-
274248
return true if val.is_a?(c)
-
end
-
41404
return false
-
end
-
-
2
def try_send(method, *args)
-
82804
return unless respond_to?(method, true)
-
25648
send(method, *args)
-
end
-
end
-
-
# A visitor for converting a Sass tree into a source string.
-
2
class Sass::Tree::Visitors::Convert < Sass::Tree::Visitors::Base
-
# Runs the visitor on a tree.
-
#
-
# @param root [Tree::Node] The root node of the Sass tree.
-
# @param options [{Symbol => Object}] An options hash (see {Sass::CSS#initialize}).
-
# @param format [Symbol] `:sass` or `:scss`.
-
# @return [String] The Sass or SCSS source for the tree.
-
2
def self.visit(root, options, format)
-
new(options, format).send(:visit, root)
-
end
-
-
2
protected
-
-
2
def initialize(options, format)
-
@options = options
-
@format = format
-
@tabs = 0
-
# 2 spaces by default
-
@tab_chars = @options[:indent] || " "
-
end
-
-
2
def visit_children(parent)
-
@tabs += 1
-
return @format == :sass ? "\n" : " {}\n" if parent.children.empty?
-
(@format == :sass ? "\n" : " {\n") + super.join.rstrip + (@format == :sass ? "\n" : "\n#{ @tab_chars * (@tabs-1)}}\n")
-
ensure
-
@tabs -= 1
-
end
-
-
# Ensures proper spacing between top-level nodes.
-
2
def visit_root(node)
-
Sass::Util.enum_cons(node.children + [nil], 2).map do |child, nxt|
-
visit(child) +
-
if nxt &&
-
(child.is_a?(Sass::Tree::CommentNode) &&
-
child.line + child.lines + 1 == nxt.line) ||
-
(child.is_a?(Sass::Tree::ImportNode) && nxt.is_a?(Sass::Tree::ImportNode) &&
-
child.line + 1 == nxt.line) ||
-
(child.is_a?(Sass::Tree::VariableNode) && nxt.is_a?(Sass::Tree::VariableNode) &&
-
child.line + 1 == nxt.line)
-
""
-
else
-
"\n"
-
end
-
end.join.rstrip + "\n"
-
end
-
-
2
def visit_charset(node)
-
"#{tab_str}@charset \"#{node.name}\"#{semi}\n"
-
end
-
-
2
def visit_comment(node)
-
value = interp_to_src(node.value)
-
content = if @format == :sass
-
content = value.gsub(/\*\/$/, '').rstrip
-
if content =~ /\A[ \t]/
-
# Re-indent SCSS comments like this:
-
# /* foo
-
# bar
-
# baz */
-
content.gsub!(/^/, ' ')
-
content.sub!(/\A([ \t]*)\/\*/, '/*\1')
-
end
-
-
content =
-
unless content.include?("\n")
-
content
-
else
-
content.gsub!(/\n( \*|\/\/)/, "\n ")
-
spaces = content.scan(/\n( *)/).map {|s| s.first.size}.min
-
sep = node.type == :silent ? "\n//" : "\n *"
-
if spaces >= 2
-
content.gsub(/\n /, sep)
-
else
-
content.gsub(/\n#{' ' * spaces}/, sep)
-
end
-
end
-
-
content.gsub!(/\A\/\*/, '//') if node.type == :silent
-
content.gsub!(/^/, tab_str)
-
content.rstrip + "\n"
-
else
-
spaces = (@tab_chars * [@tabs - value[/^ */].size, 0].max)
-
content = if node.type == :silent
-
value.gsub(/^[\/ ]\*/, '//').gsub(/ *\*\/$/, '')
-
else
-
value
-
end.gsub(/^/, spaces) + "\n"
-
content
-
end
-
content
-
end
-
-
2
def visit_debug(node)
-
"#{tab_str}@debug #{node.expr.to_sass(@options)}#{semi}\n"
-
end
-
-
2
def visit_directive(node)
-
res = "#{tab_str}#{interp_to_src(node.value)}"
-
res.gsub!(/^@import \#\{(.*)\}([^}]*)$/, '@import \1\2');
-
return res + "#{semi}\n" unless node.has_children
-
res + yield + "\n"
-
end
-
-
2
def visit_each(node)
-
"#{tab_str}@each $#{dasherize(node.var)} in #{node.list.to_sass(@options)}#{yield}"
-
end
-
-
2
def visit_extend(node)
-
"#{tab_str}@extend #{selector_to_src(node.selector).lstrip}#{semi}#{" !optional" if node.optional?}\n"
-
end
-
-
2
def visit_for(node)
-
"#{tab_str}@for $#{dasherize(node.var)} from #{node.from.to_sass(@options)} " +
-
"#{node.exclusive ? "to" : "through"} #{node.to.to_sass(@options)}#{yield}"
-
end
-
-
2
def visit_function(node)
-
args = node.args.map do |v, d|
-
d ? "#{v.to_sass(@options)}: #{d.to_sass(@options)}" : v.to_sass(@options)
-
end.join(", ")
-
if node.splat
-
args << ", " unless node.args.empty?
-
args << node.splat.to_sass(@options) << "..."
-
end
-
-
"#{tab_str}@function #{dasherize(node.name)}(#{args})#{yield}"
-
end
-
-
2
def visit_if(node)
-
name =
-
if !@is_else; "if"
-
elsif node.expr; "else if"
-
else; "else"
-
end
-
@is_else = false
-
str = "#{tab_str}@#{name}"
-
str << " #{node.expr.to_sass(@options)}" if node.expr
-
str << yield
-
@is_else = true
-
str << visit(node.else) if node.else
-
str
-
ensure
-
@is_else = false
-
end
-
-
2
def visit_import(node)
-
quote = @format == :scss ? '"' : ''
-
"#{tab_str}@import #{quote}#{node.imported_filename}#{quote}#{semi}\n"
-
end
-
-
2
def visit_media(node)
-
"#{tab_str}@media #{media_interp_to_src(node.query)}#{yield}"
-
end
-
-
2
def visit_supports(node)
-
"#{tab_str}@#{node.name} #{node.condition.to_src(@options)}#{yield}"
-
end
-
-
2
def visit_cssimport(node)
-
if node.uri.is_a?(Sass::Script::Node)
-
str = "#{tab_str}@import #{node.uri.to_sass(@options)}"
-
else
-
str = "#{tab_str}@import #{node.uri}"
-
end
-
str << " #{interp_to_src(node.query)}" unless node.query.empty?
-
"#{str}#{semi}\n"
-
end
-
-
2
def visit_mixindef(node)
-
args =
-
if node.args.empty? && node.splat.nil?
-
""
-
else
-
str = '('
-
str << node.args.map do |v, d|
-
if d
-
"#{v.to_sass(@options)}: #{d.to_sass(@options)}"
-
else
-
v.to_sass(@options)
-
end
-
end.join(", ")
-
-
if node.splat
-
str << ", " unless node.args.empty?
-
str << node.splat.to_sass(@options) << '...'
-
end
-
-
str << ')'
-
end
-
-
"#{tab_str}#{@format == :sass ? '=' : '@mixin '}#{dasherize(node.name)}#{args}#{yield}"
-
end
-
-
2
def visit_mixin(node)
-
arg_to_sass = lambda do |arg|
-
sass = arg.to_sass(@options)
-
sass = "(#{sass})" if arg.is_a?(Sass::Script::List) && arg.separator == :comma
-
sass
-
end
-
-
unless node.args.empty? && node.keywords.empty? && node.splat.nil?
-
args = node.args.map(&arg_to_sass).join(", ")
-
keywords = Sass::Util.hash_to_a(node.keywords).
-
map {|k, v| "$#{dasherize(k)}: #{arg_to_sass[v]}"}.join(', ')
-
if node.splat
-
splat = (args.empty? && keywords.empty?) ? "" : ", "
-
splat = "#{splat}#{arg_to_sass[node.splat]}..."
-
end
-
arglist = "(#{args}#{', ' unless args.empty? || keywords.empty?}#{keywords}#{splat})"
-
end
-
"#{tab_str}#{@format == :sass ? '+' : '@include '}#{dasherize(node.name)}#{arglist}#{node.has_children ? yield : semi}\n"
-
end
-
-
2
def visit_content(node)
-
"#{tab_str}@content#{semi}\n"
-
end
-
-
2
def visit_prop(node)
-
res = tab_str + node.declaration(@options, @format)
-
return res + semi + "\n" if node.children.empty?
-
res + yield.rstrip + semi + "\n"
-
end
-
-
2
def visit_return(node)
-
"#{tab_str}@return #{node.expr.to_sass(@options)}#{semi}\n"
-
end
-
-
2
def visit_rule(node)
-
if @format == :sass
-
name = selector_to_sass(node.rule)
-
name = "\\" + name if name[0] == ?:
-
name.gsub(/^/, tab_str) + yield
-
elsif @format == :scss
-
name = selector_to_scss(node.rule)
-
res = name + yield
-
if node.children.last.is_a?(Sass::Tree::CommentNode) && node.children.last.type == :silent
-
res.slice!(-3..-1)
-
res << "\n" << tab_str << "}\n"
-
end
-
res
-
end
-
end
-
-
2
def visit_variable(node)
-
"#{tab_str}$#{dasherize(node.name)}: #{node.expr.to_sass(@options)}#{' !default' if node.guarded}#{semi}\n"
-
end
-
-
2
def visit_warn(node)
-
"#{tab_str}@warn #{node.expr.to_sass(@options)}#{semi}\n"
-
end
-
-
2
def visit_while(node)
-
"#{tab_str}@while #{node.expr.to_sass(@options)}#{yield}"
-
end
-
-
2
private
-
-
2
def interp_to_src(interp)
-
interp.map do |r|
-
next r if r.is_a?(String)
-
"\#{#{r.to_sass(@options)}}"
-
end.join
-
end
-
-
# Like interp_to_src, but removes the unnecessary `#{}` around the keys and
-
# values in media expressions.
-
2
def media_interp_to_src(interp)
-
Sass::Util.enum_with_index(interp).map do |r, i|
-
next r if r.is_a?(String)
-
before, after = interp[i-1], interp[i+1]
-
if before.is_a?(String) && after.is_a?(String) &&
-
((before[-1] == ?( && after[0] == ?:) ||
-
(before =~ /:\s*/ && after[0] == ?)))
-
r.to_sass(@options)
-
else
-
"\#{#{r.to_sass(@options)}}"
-
end
-
end.join
-
end
-
-
2
def selector_to_src(sel)
-
@format == :sass ? selector_to_sass(sel) : selector_to_scss(sel)
-
end
-
-
2
def selector_to_sass(sel)
-
sel.map do |r|
-
if r.is_a?(String)
-
r.gsub(/(,)?([ \t]*)\n\s*/) {$1 ? "#{$1}#{$2}\n" : " "}
-
else
-
"\#{#{r.to_sass(@options)}}"
-
end
-
end.join
-
end
-
-
2
def selector_to_scss(sel)
-
interp_to_src(sel).gsub(/^[ \t]*/, tab_str).gsub(/[ \t]*$/, '')
-
end
-
-
2
def semi
-
@format == :sass ? "" : ";"
-
end
-
-
2
def tab_str
-
@tab_chars * @tabs
-
end
-
-
2
def dasherize(s)
-
if @options[:dasherize]
-
s.gsub('_', '-')
-
else
-
s
-
end
-
end
-
end
-
# A visitor for converting a static Sass tree into a static CSS tree.
-
2
class Sass::Tree::Visitors::Cssize < Sass::Tree::Visitors::Base
-
# @param root [Tree::Node] The root node of the tree to visit.
-
# @return [(Tree::Node, Sass::Util::SubsetMap)] The resulting tree of static nodes
-
# *and* the extensions defined for this tree
-
3
def self.visit(root); super; end
-
-
2
protected
-
-
# Returns the immediate parent of the current node.
-
# @return [Tree::Node]
-
2
attr_reader :parent
-
-
2
def initialize
-
1
@parent_directives = []
-
1
@extends = Sass::Util::SubsetMap.new
-
end
-
-
# If an exception is raised, this adds proper metadata to the backtrace.
-
2
def visit(node)
-
19839
super(node)
-
rescue Sass::SyntaxError => e
-
e.modify_backtrace(:filename => node.filename, :line => node.line)
-
raise e
-
end
-
-
# Keeps track of the current parent node.
-
2
def visit_children(parent)
-
19838
with_parent parent do
-
19838
parent.children = super.flatten
-
19838
parent
-
end
-
end
-
-
2
MERGEABLE_DIRECTIVES = [Sass::Tree::MediaNode]
-
-
# Runs a block of code with the current parent node
-
# replaced with the given node.
-
#
-
# @param parent [Tree::Node] The new parent for the duration of the block.
-
# @yield A block in which the parent is set to `parent`.
-
# @return [Object] The return value of the block.
-
2
def with_parent(parent)
-
19838
if parent.is_a?(Sass::Tree::DirectiveNode)
-
840
if MERGEABLE_DIRECTIVES.any? {|klass| parent.is_a?(klass)}
-
211
old_parent_directive = @parent_directives.pop
-
end
-
420
@parent_directives.push parent
-
end
-
-
19838
old_parent, @parent = @parent, parent
-
19838
yield
-
ensure
-
19838
@parent_directives.pop if parent.is_a?(Sass::Tree::DirectiveNode)
-
19838
@parent_directives.push old_parent_directive if old_parent_directive
-
19838
@parent = old_parent
-
end
-
-
# In Ruby 1.8, ensures that there's only one `@charset` directive
-
# and that it's at the top of the document.
-
#
-
# @return [(Tree::Node, Sass::Util::SubsetMap)] The resulting tree of static nodes
-
# *and* the extensions defined for this tree
-
2
def visit_root(node)
-
1
yield
-
-
1
if parent.nil?
-
# In Ruby 1.9 we can make all @charset nodes invisible
-
# and infer the final @charset from the encoding of the final string.
-
1
if Sass::Util.ruby1_8?
-
charset = node.children.find {|c| c.is_a?(Sass::Tree::CharsetNode)}
-
node.children.reject! {|c| c.is_a?(Sass::Tree::CharsetNode)}
-
node.children.unshift charset if charset
-
end
-
-
1
imports_to_move = []
-
1
import_limit = nil
-
1
i = -1
-
1
node.children.reject! do |n|
-
5505
i += 1
-
5505
if import_limit
-
5502
next false unless n.is_a?(Sass::Tree::CssImportNode)
-
imports_to_move << n
-
next true
-
end
-
-
if !n.is_a?(Sass::Tree::CommentNode) &&
-
3
!n.is_a?(Sass::Tree::CharsetNode) &&
-
!n.is_a?(Sass::Tree::CssImportNode)
-
1
import_limit = i
-
end
-
-
3
false
-
end
-
-
1
if import_limit
-
1
node.children = node.children[0...import_limit] + imports_to_move +
-
node.children[import_limit..-1]
-
end
-
end
-
-
1
return node, @extends
-
rescue Sass::SyntaxError => e
-
e.sass_template ||= node.template
-
raise e
-
end
-
-
# A simple struct wrapping up information about a single `@extend` instance. A
-
# single [ExtendNode] can have multiple Extends if either the parent node or
-
# the extended selector is a comma sequence.
-
#
-
# @attr extender [Sass::Selector::Sequence]
-
# The selector of the CSS rule containing the `@extend`.
-
# @attr target [Array<Sass::Selector::Simple>] The selector being `@extend`ed.
-
# @attr node [Sass::Tree::ExtendNode] The node that produced this extend.
-
# @attr directives [Array<Sass::Tree::DirectiveNode>]
-
# The directives containing the `@extend`.
-
# @attr result [Symbol]
-
# The result of this extend. One of `:not_found` (the target doesn't exist
-
# in the document), `:failed_to_unify` (the target exists but cannot be
-
# unified with the extender), or `:succeeded`.
-
2
Extend = Struct.new(:extender, :target, :node, :directives, :result)
-
-
# Registers an extension in the `@extends` subset map.
-
2
def visit_extend(node)
-
1
node.resolved_selector.members.each do |seq|
-
1
if seq.members.size > 1
-
raise Sass::SyntaxError.new("Can't extend #{seq.to_a.join}: can't extend nested selectors")
-
end
-
-
1
sseq = seq.members.first
-
1
if !sseq.is_a?(Sass::Selector::SimpleSequence)
-
raise Sass::SyntaxError.new("Can't extend #{seq.to_a.join}: invalid selector")
-
1
elsif sseq.members.any? {|ss| ss.is_a?(Sass::Selector::Parent)}
-
raise Sass::SyntaxError.new("Can't extend #{seq.to_a.join}: can't extend parent selectors")
-
end
-
-
1
sel = sseq.members
-
1
parent.resolved_rules.members.each do |member|
-
1
if !member.members.last.is_a?(Sass::Selector::SimpleSequence)
-
raise Sass::SyntaxError.new("#{member} can't extend: invalid selector")
-
end
-
-
1
@extends[sel] = Extend.new(member, sel, node, @parent_directives.dup, :not_found)
-
end
-
end
-
-
1
[]
-
end
-
-
# Modifies exception backtraces to include the imported file.
-
2
def visit_import(node)
-
# Don't use #visit_children to avoid adding the import node to the list of parents.
-
node.children.map {|c| visit(c)}.flatten
-
rescue Sass::SyntaxError => e
-
e.modify_backtrace(:filename => node.children.first.filename)
-
e.add_backtrace(:filename => node.filename, :line => node.line)
-
raise e
-
end
-
-
# Bubbles the `@media` directive up through RuleNodes
-
# and merges it with other `@media` directives.
-
2
def visit_media(node)
-
211
yield unless bubble(node)
-
1194
media = node.children.select {|c| c.is_a?(Sass::Tree::MediaNode)}
-
1194
node.children.reject! {|c| c.is_a?(Sass::Tree::MediaNode)}
-
211
media = media.select {|n| n.resolved_query = n.resolved_query.merge(node.resolved_query)}
-
211
(node.children.empty? ? [] : [node]) + media
-
end
-
-
# Bubbles the `@supports` directive up through RuleNodes.
-
2
def visit_supports(node)
-
yield unless bubble(node)
-
node
-
end
-
-
# Asserts that all the traced children are valid in their new location.
-
2
def visit_trace(node)
-
# Don't use #visit_children to avoid adding the trace node to the list of parents.
-
node.children.map {|c| visit(c)}.flatten
-
rescue Sass::SyntaxError => e
-
e.modify_backtrace(:mixin => node.name, :filename => node.filename, :line => node.line)
-
e.add_backtrace(:filename => node.filename, :line => node.line)
-
raise e
-
end
-
-
# Converts nested properties into flat properties
-
# and updates the indentation of the prop node based on the nesting level.
-
2
def visit_prop(node)
-
12821
if parent.is_a?(Sass::Tree::PropNode)
-
node.resolved_name = "#{parent.resolved_name}-#{node.resolved_name}"
-
node.tabs = parent.tabs + (parent.resolved_value.empty? ? 0 : 1) if node.style == :nested
-
end
-
-
12821
yield
-
-
12821
result = node.children.dup
-
12821
if !node.resolved_value.empty? || node.children.empty?
-
12821
node.send(:check!)
-
12821
result.unshift(node)
-
end
-
-
12821
result
-
end
-
-
# Resolves parent references and nested selectors,
-
# and updates the indentation of the rule node based on the nesting level.
-
2
def visit_rule(node)
-
6582
parent_resolved_rules = parent.is_a?(Sass::Tree::RuleNode) ? parent.resolved_rules : nil
-
# It's possible for resolved_rules to be set if we've duplicated this node during @media bubbling
-
6582
node.resolved_rules ||= node.parsed_rules.resolve_parent_refs(parent_resolved_rules)
-
-
6582
yield
-
-
19375
rules = node.children.select {|c| c.is_a?(Sass::Tree::RuleNode) || c.bubbles?}
-
19375
props = node.children.reject {|c| c.is_a?(Sass::Tree::RuleNode) || c.bubbles? || c.invisible?}
-
-
6582
unless props.empty?
-
6577
node.children = props
-
6577
rules.each {|r| r.tabs += 1} if node.style == :nested
-
6577
rules.unshift(node)
-
end
-
-
6582
rules.last.group_end = true unless parent.is_a?(Sass::Tree::RuleNode) || rules.empty?
-
-
6582
rules
-
end
-
-
2
private
-
-
2
def bubble(node)
-
211
return unless parent.is_a?(Sass::Tree::RuleNode)
-
new_rule = parent.dup
-
new_rule.children = node.children
-
node.children = with_parent(node) {Array(visit(new_rule))}
-
# If the last child is actually the end of the group,
-
# the parent's cssize will set it properly
-
node.children.last.group_end = false unless node.children.empty?
-
true
-
end
-
end
-
# A visitor for performing selector inheritance on a static CSS tree.
-
#
-
# Destructively modifies the tree.
-
2
class Sass::Tree::Visitors::Extend < Sass::Tree::Visitors::Base
-
# Performs the given extensions on the static CSS tree based in `root`, then
-
# validates that all extends matched some selector.
-
#
-
# @param root [Tree::Node] The root node of the tree to visit.
-
# @param extends [Sass::Util::SubsetMap{Selector::Simple =>
-
# Sass::Tree::Visitors::Cssize::Extend}]
-
# The extensions to perform on this tree.
-
# @return [Object] The return value of \{#visit} for the root node.
-
2
def self.visit(root, extends)
-
1
return if extends.empty?
-
1
new(extends).send(:visit, root)
-
1
check_extends_fired! extends
-
end
-
-
2
protected
-
-
2
def initialize(extends)
-
1
@parent_directives = []
-
1
@extends = extends
-
end
-
-
# If an exception is raised, this adds proper metadata to the backtrace.
-
2
def visit(node)
-
7042
super(node)
-
rescue Sass::SyntaxError => e
-
e.modify_backtrace(:filename => node.filename, :line => node.line)
-
raise e
-
end
-
-
# Keeps track of the current parent directives.
-
2
def visit_children(parent)
-
465
@parent_directives.push parent if parent.is_a?(Sass::Tree::DirectiveNode)
-
465
super
-
ensure
-
465
@parent_directives.pop if parent.is_a?(Sass::Tree::DirectiveNode)
-
end
-
-
# Applies the extend to a single rule's selector.
-
2
def visit_rule(node)
-
6577
node.resolved_rules = node.resolved_rules.do_extend(@extends, @parent_directives)
-
end
-
-
2
private
-
-
2
def self.check_extends_fired!(extends)
-
1
extends.each_value do |ex|
-
1
next if ex.result == :succeeded || ex.node.optional?
-
warn = "\"#{ex.extender}\" failed to @extend \"#{ex.target.join}\"."
-
reason =
-
if ex.result == :not_found
-
"The selector \"#{ex.target.join}\" was not found."
-
else
-
"No selectors matching \"#{ex.target.join}\" could be unified with \"#{ex.extender}\"."
-
end
-
-
Sass::Util.sass_warn <<WARN
-
WARNING on line #{ex.node.line}#{" of #{ex.node.filename}" if ex.node.filename}: #{warn}
-
#{reason}
-
This will be an error in future releases of Sass.
-
Use "@extend #{ex.target.join} !optional" if the extend should be able to fail.
-
WARN
-
end
-
end
-
end
-
# A visitor for converting a dynamic Sass tree into a static Sass tree.
-
2
class Sass::Tree::Visitors::Perform < Sass::Tree::Visitors::Base
-
# @param root [Tree::Node] The root node of the tree to visit.
-
# @param environment [Sass::Environment] The lexical environment.
-
# @return [Tree::Node] The resulting tree of static nodes.
-
2
def self.visit(root, environment = Sass::Environment.new)
-
1
new(environment).send(:visit, root)
-
end
-
-
# @api private
-
2
def self.perform_arguments(callable, args, keywords, splat)
-
desc = "#{callable.type.capitalize} #{callable.name}"
-
downcase_desc = "#{callable.type} #{callable.name}"
-
-
begin
-
unless keywords.empty?
-
unknown_args = Sass::Util.array_minus(keywords.keys,
-
callable.args.map {|var| var.first.underscored_name})
-
if callable.splat && unknown_args.include?(callable.splat.underscored_name)
-
raise Sass::SyntaxError.new("Argument $#{callable.splat.name} of #{downcase_desc} cannot be used as a named argument.")
-
elsif unknown_args.any?
-
description = unknown_args.length > 1 ? 'the following arguments:' : 'an argument named'
-
raise Sass::SyntaxError.new("#{desc} doesn't have #{description} #{unknown_args.map {|name| "$#{name}"}.join ', '}.")
-
end
-
end
-
rescue Sass::SyntaxError => keyword_exception
-
end
-
-
# If there's no splat, raise the keyword exception immediately. The actual
-
# raising happens in the ensure clause at the end of this function.
-
return if keyword_exception && !callable.splat
-
-
if args.size > callable.args.size && !callable.splat
-
takes = callable.args.size
-
passed = args.size
-
raise Sass::SyntaxError.new(
-
"#{desc} takes #{takes} argument#{'s' unless takes == 1} " +
-
"but #{passed} #{passed == 1 ? 'was' : 'were'} passed.")
-
end
-
-
splat_sep = :comma
-
if splat
-
args += splat.to_a
-
splat_sep = splat.separator if splat.is_a?(Sass::Script::List)
-
# If the splat argument exists, there won't be any keywords passed in
-
# manually, so we can safely overwrite rather than merge here.
-
keywords = splat.keywords if splat.is_a?(Sass::Script::ArgList)
-
end
-
-
keywords = keywords.dup
-
env = Sass::Environment.new(callable.environment)
-
callable.args.zip(args[0...callable.args.length]) do |(var, default), value|
-
if value && keywords.include?(var.underscored_name)
-
raise Sass::SyntaxError.new("#{desc} was passed argument $#{var.name} both by position and by name.")
-
end
-
-
value ||= keywords.delete(var.underscored_name)
-
value ||= default && default.perform(env)
-
raise Sass::SyntaxError.new("#{desc} is missing argument #{var.inspect}.") unless value
-
env.set_local_var(var.name, value)
-
end
-
-
if callable.splat
-
rest = args[callable.args.length..-1]
-
arg_list = Sass::Script::ArgList.new(rest, keywords.dup, splat_sep)
-
arg_list.options = env.options
-
env.set_local_var(callable.splat.name, arg_list)
-
end
-
-
yield env
-
rescue Exception => e
-
ensure
-
# If there's a keyword exception, we don't want to throw it immediately,
-
# because the invalid keywords may be part of a glob argument that should be
-
# passed on to another function. So we only raise it if we reach the end of
-
# this function *and* the keywords attached to the argument list glob object
-
# haven't been accessed.
-
#
-
# The keyword exception takes precedence over any Sass errors, but not over
-
# non-Sass exceptions.
-
if keyword_exception &&
-
!(arg_list && arg_list.keywords_accessed) &&
-
(e.nil? || e.is_a?(Sass::SyntaxError))
-
raise keyword_exception
-
elsif e
-
raise e
-
end
-
end
-
-
2
protected
-
-
2
def initialize(env)
-
1
@environment = env
-
# Stack trace information, including mixin includes and imports.
-
1
@stack = []
-
end
-
-
# If an exception is raised, this adds proper metadata to the backtrace.
-
2
def visit(node)
-
21565
super(node.dup)
-
rescue Sass::SyntaxError => e
-
e.modify_backtrace(:filename => node.filename, :line => node.line)
-
raise e
-
end
-
-
# Keeps track of the current environment.
-
2
def visit_children(parent)
-
19826
with_environment Sass::Environment.new(@environment, parent.options) do
-
19826
parent.children = super.flatten
-
19826
parent
-
end
-
end
-
-
# Runs a block of code with the current environment replaced with the given one.
-
#
-
# @param env [Sass::Environment] The new environment for the duration of the block.
-
# @yield A block in which the environment is set to `env`.
-
# @return [Object] The return value of the block.
-
2
def with_environment(env)
-
19826
old_env, @environment = @environment, env
-
19826
yield
-
ensure
-
19826
@environment = old_env
-
end
-
-
# Sets the options on the environment if this is the top-level root.
-
2
def visit_root(node)
-
1
yield
-
rescue Sass::SyntaxError => e
-
e.sass_template ||= node.template
-
raise e
-
end
-
-
# Removes this node from the tree if it's a silent comment.
-
2
def visit_comment(node)
-
1738
return [] if node.invisible?
-
12
node.resolved_value = run_interp_no_strip(node.value)
-
12
node.resolved_value.gsub!(/\\([\\#])/, '\1')
-
12
node
-
end
-
-
# Prints the expression to STDERR.
-
2
def visit_debug(node)
-
res = node.expr.perform(@environment)
-
res = res.value if res.is_a?(Sass::Script::String)
-
if node.filename
-
Sass::Util.sass_warn "#{node.filename}:#{node.line} DEBUG: #{res}"
-
else
-
Sass::Util.sass_warn "Line #{node.line} DEBUG: #{res}"
-
end
-
[]
-
end
-
-
# Runs the child nodes once for each value in the list.
-
2
def visit_each(node)
-
list = node.list.perform(@environment)
-
-
with_environment Sass::Environment.new(@environment) do
-
list.to_a.map do |v|
-
@environment.set_local_var(node.var, v)
-
node.children.map {|c| visit(c)}
-
end.flatten
-
end
-
end
-
-
# Runs SassScript interpolation in the selector,
-
# and then parses the result into a {Sass::Selector::CommaSequence}.
-
2
def visit_extend(node)
-
1
parser = Sass::SCSS::StaticParser.new(run_interp(node.selector), node.filename, node.line)
-
1
node.resolved_selector = parser.parse_selector
-
1
node
-
end
-
-
# Runs the child nodes once for each time through the loop, varying the variable each time.
-
2
def visit_for(node)
-
from = node.from.perform(@environment)
-
to = node.to.perform(@environment)
-
from.assert_int!
-
to.assert_int!
-
-
to = to.coerce(from.numerator_units, from.denominator_units)
-
range = Range.new(from.to_i, to.to_i, node.exclusive)
-
-
with_environment Sass::Environment.new(@environment) do
-
range.map do |i|
-
@environment.set_local_var(node.var,
-
Sass::Script::Number.new(i, from.numerator_units, from.denominator_units))
-
node.children.map {|c| visit(c)}
-
end.flatten
-
end
-
end
-
-
# Loads the function into the environment.
-
2
def visit_function(node)
-
env = Sass::Environment.new(@environment, node.options)
-
@environment.set_local_function(node.name,
-
Sass::Callable.new(node.name, node.args, node.splat, env, node.children, !:has_content, "function"))
-
[]
-
end
-
-
# Runs the child nodes if the conditional expression is true;
-
# otherwise, tries the else nodes.
-
2
def visit_if(node)
-
if node.expr.nil? || node.expr.perform(@environment).to_bool
-
yield
-
node.children
-
elsif node.else
-
visit(node.else)
-
else
-
[]
-
end
-
end
-
-
# Returns a static DirectiveNode if this is importing a CSS file,
-
# or parses and includes the imported Sass file.
-
2
def visit_import(node)
-
if path = node.css_import?
-
return Sass::Tree::CssImportNode.resolved("url(#{path})")
-
end
-
file = node.imported_file
-
handle_import_loop!(node) if @stack.any? {|e| e[:filename] == file.options[:filename]}
-
-
begin
-
@stack.push(:filename => node.filename, :line => node.line)
-
root = file.to_tree
-
Sass::Tree::Visitors::CheckNesting.visit(root)
-
node.children = root.children.map {|c| visit(c)}.flatten
-
node
-
rescue Sass::SyntaxError => e
-
e.modify_backtrace(:filename => node.imported_file.options[:filename])
-
e.add_backtrace(:filename => node.filename, :line => node.line)
-
raise e
-
end
-
ensure
-
@stack.pop unless path
-
end
-
-
# Loads a mixin into the environment.
-
2
def visit_mixindef(node)
-
env = Sass::Environment.new(@environment, node.options)
-
@environment.set_local_mixin(node.name,
-
Sass::Callable.new(node.name, node.args, node.splat, env, node.children, node.has_content, "mixin"))
-
[]
-
end
-
-
# Runs a mixin.
-
2
def visit_mixin(node)
-
include_loop = true
-
handle_include_loop!(node) if @stack.any? {|e| e[:name] == node.name}
-
include_loop = false
-
-
@stack.push(:filename => node.filename, :line => node.line, :name => node.name)
-
raise Sass::SyntaxError.new("Undefined mixin '#{node.name}'.") unless mixin = @environment.mixin(node.name)
-
-
if node.children.any? && !mixin.has_content
-
raise Sass::SyntaxError.new(%Q{Mixin "#{node.name}" does not accept a content block.})
-
end
-
-
args = node.args.map {|a| a.perform(@environment)}
-
keywords = Sass::Util.map_hash(node.keywords) {|k, v| [k, v.perform(@environment)]}
-
splat = node.splat.perform(@environment) if node.splat
-
-
self.class.perform_arguments(mixin, args, keywords, splat) do |env|
-
env.caller = Sass::Environment.new(@environment)
-
env.content = node.children if node.has_children
-
-
trace_node = Sass::Tree::TraceNode.from_node(node.name, node)
-
with_environment(env) {trace_node.children = mixin.tree.map {|c| visit(c)}.flatten}
-
trace_node
-
end
-
rescue Sass::SyntaxError => e
-
unless include_loop
-
e.modify_backtrace(:mixin => node.name, :line => node.line)
-
e.add_backtrace(:line => node.line)
-
end
-
raise e
-
ensure
-
@stack.pop unless include_loop
-
end
-
-
2
def visit_content(node)
-
return [] unless content = @environment.content
-
@stack.push(:filename => node.filename, :line => node.line, :name => '@content')
-
trace_node = Sass::Tree::TraceNode.from_node('@content', node)
-
with_environment(@environment.caller) {trace_node.children = content.map {|c| visit(c.dup)}.flatten}
-
trace_node
-
rescue Sass::SyntaxError => e
-
e.modify_backtrace(:mixin => '@content', :line => node.line)
-
e.add_backtrace(:line => node.line)
-
raise e
-
ensure
-
@stack.pop if content
-
end
-
-
# Runs any SassScript that may be embedded in a property.
-
2
def visit_prop(node)
-
12821
node.resolved_name = run_interp(node.name)
-
12821
val = node.value.perform(@environment)
-
12821
node.resolved_value = val.to_s
-
12821
yield
-
end
-
-
# Returns the value of the expression.
-
2
def visit_return(node)
-
throw :_sass_return, node.expr.perform(@environment)
-
end
-
-
# Runs SassScript interpolation in the selector,
-
# and then parses the result into a {Sass::Selector::CommaSequence}.
-
2
def visit_rule(node)
-
6582
rule = node.rule
-
13164
rule = rule.map {|e| e.is_a?(String) && e != ' ' ? e.strip : e} if node.style == :compressed
-
6582
parser = Sass::SCSS::StaticParser.new(run_interp(node.rule), node.filename, node.line)
-
6582
node.parsed_rules ||= parser.parse_selector
-
6582
if node.options[:trace_selectors]
-
@stack.push(:filename => node.filename, :line => node.line)
-
node.stack_trace = stack_trace
-
@stack.pop
-
end
-
6582
yield
-
end
-
-
# Loads the new variable value into the environment.
-
2
def visit_variable(node)
-
var = @environment.var(node.name)
-
return [] if node.guarded && var && !var.null?
-
val = node.expr.perform(@environment)
-
@environment.set_var(node.name, val)
-
[]
-
end
-
-
# Prints the expression to STDERR with a stylesheet trace.
-
2
def visit_warn(node)
-
@stack.push(:filename => node.filename, :line => node.line)
-
res = node.expr.perform(@environment)
-
res = res.value if res.is_a?(Sass::Script::String)
-
msg = "WARNING: #{res}\n "
-
msg << stack_trace.join("\n ") << "\n"
-
Sass::Util.sass_warn msg
-
[]
-
ensure
-
@stack.pop
-
end
-
-
# Runs the child nodes until the continuation expression becomes false.
-
2
def visit_while(node)
-
children = []
-
with_environment Sass::Environment.new(@environment) do
-
children += node.children.map {|c| visit(c)} while node.expr.perform(@environment).to_bool
-
end
-
children.flatten
-
end
-
-
2
def visit_directive(node)
-
209
node.resolved_value = run_interp(node.value)
-
209
yield
-
end
-
-
2
def visit_media(node)
-
211
parser = Sass::SCSS::StaticParser.new(run_interp(node.query), node.filename, node.line)
-
211
node.resolved_query ||= parser.parse_media_query_list
-
211
yield
-
end
-
-
2
def visit_supports(node)
-
node.condition = node.condition.deep_copy
-
node.condition.perform(@environment)
-
yield
-
end
-
-
2
def visit_cssimport(node)
-
node.resolved_uri = run_interp([node.uri])
-
if node.query
-
parser = Sass::SCSS::StaticParser.new(run_interp(node.query), node.filename, node.line)
-
node.resolved_query ||= parser.parse_media_query_list
-
end
-
yield
-
end
-
-
2
private
-
-
2
def stack_trace
-
trace = []
-
stack = @stack.map {|e| e.dup}.reverse
-
stack.each_cons(2) {|(e1, e2)| e1[:caller] = e2[:name]; [e1, e2]}
-
stack.each_with_index do |entry, i|
-
msg = "#{i == 0 ? "on" : "from"} line #{entry[:line]}"
-
msg << " of #{entry[:filename] || "an unknown file"}"
-
msg << ", in `#{entry[:caller]}'" if entry[:caller]
-
trace << msg
-
end
-
trace
-
end
-
-
2
def run_interp_no_strip(text)
-
text.map do |r|
-
21253
next r if r.is_a?(String)
-
454
val = r.perform(@environment)
-
# Interpolated strings should never render with quotes
-
454
next val.value if val.is_a?(Sass::Script::String)
-
221
val.to_s
-
19836
end.join
-
end
-
-
2
def run_interp(text)
-
19824
run_interp_no_strip(text).strip
-
end
-
-
2
def handle_include_loop!(node)
-
msg = "An @include loop has been found:"
-
content_count = 0
-
mixins = @stack.reverse.map {|s| s[:name]}.compact.select do |s|
-
if s == '@content'
-
content_count += 1
-
false
-
elsif content_count > 0
-
content_count -= 1
-
false
-
else
-
true
-
end
-
end
-
-
return unless mixins.include?(node.name)
-
raise Sass::SyntaxError.new("#{msg} #{node.name} includes itself") if mixins.size == 1
-
-
msg << "\n" << Sass::Util.enum_cons(mixins.reverse + [node.name], 2).map do |m1, m2|
-
" #{m1} includes #{m2}"
-
end.join("\n")
-
raise Sass::SyntaxError.new(msg)
-
end
-
-
2
def handle_import_loop!(node)
-
msg = "An @import loop has been found:"
-
files = @stack.map {|s| s[:filename]}.compact
-
if node.filename == node.imported_file.options[:filename]
-
raise Sass::SyntaxError.new("#{msg} #{node.filename} imports itself")
-
end
-
-
files << node.filename << node.imported_file.options[:filename]
-
msg << "\n" << Sass::Util.enum_cons(files, 2).map do |m1, m2|
-
" #{m1} imports #{m2}"
-
end.join("\n")
-
raise Sass::SyntaxError.new(msg)
-
end
-
end
-
# A visitor for converting a Sass tree into CSS.
-
2
class Sass::Tree::Visitors::ToCss < Sass::Tree::Visitors::Base
-
2
protected
-
-
2
def initialize
-
1
@tabs = 0
-
end
-
-
2
def visit(node)
-
19831
super
-
rescue Sass::SyntaxError => e
-
e.modify_backtrace(:filename => node.filename, :line => node.line)
-
raise e
-
end
-
-
2
def with_tabs(tabs)
-
14901
old_tabs, @tabs = @tabs, tabs
-
14901
yield
-
ensure
-
14901
@tabs = old_tabs
-
end
-
-
2
def visit_root(node)
-
1
result = String.new
-
1
node.children.each do |child|
-
5505
next if child.invisible?
-
5503
child_str = visit(child)
-
5503
result << child_str + (node.style == :compressed ? '' : "\n")
-
end
-
1
result.rstrip!
-
1
return "" if result.empty?
-
1
result << "\n"
-
1
unless Sass::Util.ruby1_8? || result.ascii_only?
-
if node.children.first.is_a?(Sass::Tree::CharsetNode)
-
begin
-
encoding = node.children.first.name
-
# Default to big-endian encoding, because we have to decide somehow
-
encoding << 'BE' if encoding =~ /\Autf-(16|32)\Z/i
-
result = result.encode(Encoding.find(encoding))
-
rescue EncodingError
-
end
-
end
-
-
result = "@charset \"#{result.encoding.name}\";#{
-
node.style == :compressed ? '' : "\n"
-
}".encode(result.encoding) + result
-
end
-
1
result
-
rescue Sass::SyntaxError => e
-
e.sass_template ||= node.template
-
raise e
-
end
-
-
2
def visit_charset(node)
-
"@charset \"#{node.name}\";"
-
end
-
-
2
def visit_comment(node)
-
12
return if node.invisible?
-
12
spaces = (' ' * [@tabs - node.resolved_value[/^ */].size, 0].max)
-
-
12
content = node.resolved_value.gsub(/^/, spaces)
-
12
content.gsub!(%r{^(\s*)//(.*)$}) {|md| "#{$1}/*#{$2} */"} if node.type == :silent
-
12
content.gsub!(/\n +(\* *(?!\/))?/, ' ') if (node.style == :compact || node.style == :compressed) && node.type != :loud
-
12
content
-
end
-
-
2
def visit_directive(node)
-
420
was_in_directive = @in_directive
-
420
tab_str = ' ' * @tabs
-
420
return tab_str + node.resolved_value + ";" unless node.has_children
-
420
return tab_str + node.resolved_value + " {}" if node.children.empty?
-
420
@in_directive = @in_directive || !node.is_a?(Sass::Tree::MediaNode)
-
420
result = if node.style == :compressed
-
420
"#{node.resolved_value}{"
-
else
-
"#{tab_str}#{node.resolved_value} {" + (node.style == :compact ? ' ' : "\n")
-
end
-
420
was_prop = false
-
420
first = true
-
420
node.children.each do |child|
-
1536
next if child.invisible?
-
1536
if node.style == :compact
-
if child.is_a?(Sass::Tree::PropNode)
-
with_tabs(first || was_prop ? 0 : @tabs + 1) {result << visit(child) << ' '}
-
else
-
result[-1] = "\n" if was_prop
-
rendered = with_tabs(@tabs + 1) {visit(child).dup}
-
rendered = rendered.lstrip if first
-
result << rendered.rstrip + "\n"
-
end
-
was_prop = child.is_a?(Sass::Tree::PropNode)
-
first = false
-
elsif node.style == :compressed
-
3072
result << (was_prop ? ";" : "") << with_tabs(0) {visit(child)}
-
1536
was_prop = child.is_a?(Sass::Tree::PropNode)
-
else
-
result << with_tabs(@tabs + 1) {visit(child)} + "\n"
-
end
-
end
-
result.rstrip + if node.style == :compressed
-
420
"}"
-
else
-
(node.style == :expanded ? "\n" : " ") + "}\n"
-
420
end
-
ensure
-
420
@in_directive = was_in_directive
-
end
-
-
2
def visit_media(node)
-
422
str = with_tabs(@tabs + node.tabs) {visit_directive(node)}
-
211
str.gsub!(/\n\Z/, '') unless node.style == :compressed || node.group_end
-
211
str
-
end
-
-
2
def visit_supports(node)
-
visit_media(node)
-
end
-
-
2
def visit_cssimport(node)
-
visit_directive(node)
-
end
-
-
2
def visit_prop(node)
-
12821
return if node.resolved_value.empty?
-
12821
tab_str = ' ' * (@tabs + node.tabs)
-
12821
if node.style == :compressed
-
12821
"#{tab_str}#{node.resolved_name}:#{node.resolved_value}"
-
else
-
"#{tab_str}#{node.resolved_name}: #{node.resolved_value};"
-
end
-
end
-
-
2
def visit_rule(node)
-
6577
with_tabs(@tabs + node.tabs) do
-
6577
rule_separator = node.style == :compressed ? ',' : ', '
-
6577
line_separator =
-
case node.style
-
when :nested, :expanded; "\n"
-
6577
when :compressed; ""
-
else; " "
-
end
-
6577
rule_indent = ' ' * @tabs
-
6577
per_rule_indent, total_indent = [:nested, :expanded].include?(node.style) ? [rule_indent, ''] : ['', rule_indent]
-
-
6577
joined_rules = node.resolved_rules.members.map do |seq|
-
10095
next if seq.has_placeholder?
-
10095
rule_part = seq.to_a.join
-
10095
if node.style == :compressed
-
10095
rule_part.gsub!(/([^,])\s*\n\s*/m, '\1 ')
-
10095
rule_part.gsub!(/\s*([,+>])\s*/m, '\1')
-
10095
rule_part.strip!
-
end
-
10095
rule_part
-
end.compact.join(rule_separator)
-
-
6577
joined_rules.sub!(/\A\s*/, per_rule_indent)
-
6577
joined_rules.gsub!(/\s*\n\s*/, "#{line_separator}#{per_rule_indent}")
-
6577
total_rule = total_indent << joined_rules
-
-
6577
to_return = ''
-
6577
old_spaces = ' ' * @tabs
-
6577
if node.style != :compressed
-
if node.options[:debug_info] && !@in_directive
-
to_return << visit(debug_info_rule(node.debug_info, node.options)) << "\n"
-
elsif node.options[:trace_selectors]
-
to_return << "#{old_spaces}/* "
-
to_return << node.stack_trace.join("\n #{old_spaces}")
-
to_return << " */\n"
-
elsif node.options[:line_comments]
-
to_return << "#{old_spaces}/* line #{node.line}"
-
-
if node.filename
-
relative_filename = if node.options[:css_filename]
-
begin
-
Pathname.new(node.filename).relative_path_from(
-
Pathname.new(File.dirname(node.options[:css_filename]))).to_s
-
rescue ArgumentError
-
nil
-
end
-
end
-
relative_filename ||= node.filename
-
to_return << ", #{relative_filename}"
-
end
-
-
to_return << " */\n"
-
end
-
end
-
-
6577
if node.style == :compact
-
properties = with_tabs(0) {node.children.map {|a| visit(a)}.join(' ')}
-
to_return << "#{total_rule} { #{properties} }#{"\n" if node.group_end}"
-
elsif node.style == :compressed
-
25945
properties = with_tabs(0) {node.children.map {|a| visit(a)}.join(';')}
-
6577
to_return << "#{total_rule}{#{properties}}"
-
else
-
properties = with_tabs(@tabs + 1) {node.children.map {|a| visit(a)}.join("\n")}
-
end_props = (node.style == :expanded ? "\n" + old_spaces : ' ')
-
to_return << "#{total_rule} {\n#{properties}#{end_props}}#{"\n" if node.group_end}"
-
end
-
-
6577
to_return
-
end
-
end
-
-
2
private
-
-
2
def debug_info_rule(debug_info, options)
-
node = Sass::Tree::DirectiveNode.resolved("@media -sass-debug-info")
-
Sass::Util.hash_to_a(debug_info.map {|k, v| [k.to_s, v.to_s]}).each do |k, v|
-
rule = Sass::Tree::RuleNode.new([""])
-
rule.resolved_rules = Sass::Selector::CommaSequence.new(
-
[Sass::Selector::Sequence.new(
-
[Sass::Selector::SimpleSequence.new(
-
[Sass::Selector::Element.new(k.to_s.gsub(/[^\w-]/, "\\\\\\0"), nil)],
-
false)
-
])
-
])
-
prop = Sass::Tree::PropNode.new([""], Sass::Script::String.new(''), :new)
-
prop.resolved_name = "font-family"
-
prop.resolved_value = Sass::SCSS::RX.escape_ident(v.to_s)
-
rule << prop
-
node << rule
-
end
-
node.options = options.merge(:debug_info => false, :line_comments => false, :style => :compressed)
-
node
-
end
-
end
-
2
module Sass
-
2
module Tree
-
# A dynamic node representing a Sass `@warn` statement.
-
#
-
# @see Sass::Tree
-
2
class WarnNode < Node
-
# The expression to print.
-
# @return [Script::Node]
-
2
attr_accessor :expr
-
-
# @param expr [Script::Node] The expression to print
-
2
def initialize(expr)
-
@expr = expr
-
super()
-
end
-
end
-
end
-
end
-
2
require 'sass/tree/node'
-
-
2
module Sass::Tree
-
# A dynamic node representing a Sass `@while` loop.
-
#
-
# @see Sass::Tree
-
2
class WhileNode < Node
-
# The parse tree for the continuation expression.
-
# @return [Script::Node]
-
2
attr_accessor :expr
-
-
# @param expr [Script::Node] See \{#expr}
-
2
def initialize(expr)
-
@expr = expr
-
super()
-
end
-
end
-
end
-
2
require 'erb'
-
2
require 'set'
-
2
require 'enumerator'
-
2
require 'stringio'
-
2
require 'rbconfig'
-
2
require 'thread'
-
-
2
require 'sass/root'
-
2
require 'sass/util/subset_map'
-
-
2
module Sass
-
# A module containing various useful functions.
-
2
module Util
-
2
extend self
-
-
# An array of ints representing the Ruby version number.
-
# @api public
-
8
RUBY_VERSION = ::RUBY_VERSION.split(".").map {|s| s.to_i}
-
-
# The Ruby engine we're running under. Defaults to `"ruby"`
-
# if the top-level constant is undefined.
-
# @api public
-
2
RUBY_ENGINE = defined?(::RUBY_ENGINE) ? ::RUBY_ENGINE : "ruby"
-
-
# Returns the path of a file relative to the Sass root directory.
-
#
-
# @param file [String] The filename relative to the Sass root
-
# @return [String] The filename relative to the the working directory
-
2
def scope(file)
-
14
File.join(Sass::ROOT_DIR, file)
-
end
-
-
# Converts an array of `[key, value]` pairs to a hash.
-
#
-
# @example
-
# to_hash([[:foo, "bar"], [:baz, "bang"]])
-
# #=> {:foo => "bar", :baz => "bang"}
-
# @param arr [Array<(Object, Object)>] An array of pairs
-
# @return [Hash] A hash
-
2
def to_hash(arr)
-
505
Hash[arr.compact]
-
end
-
-
# Maps the keys in a hash according to a block.
-
#
-
# @example
-
# map_keys({:foo => "bar", :baz => "bang"}) {|k| k.to_s}
-
# #=> {"foo" => "bar", "baz" => "bang"}
-
# @param hash [Hash] The hash to map
-
# @yield [key] A block in which the keys are transformed
-
# @yieldparam key [Object] The key that should be mapped
-
# @yieldreturn [Object] The new value for the key
-
# @return [Hash] The mapped hash
-
# @see #map_vals
-
# @see #map_hash
-
2
def map_keys(hash)
-
to_hash(hash.map {|k, v| [yield(k), v]})
-
end
-
-
# Maps the values in a hash according to a block.
-
#
-
# @example
-
# map_values({:foo => "bar", :baz => "bang"}) {|v| v.to_sym}
-
# #=> {:foo => :bar, :baz => :bang}
-
# @param hash [Hash] The hash to map
-
# @yield [value] A block in which the values are transformed
-
# @yieldparam value [Object] The value that should be mapped
-
# @yieldreturn [Object] The new value for the value
-
# @return [Hash] The mapped hash
-
# @see #map_keys
-
# @see #map_hash
-
2
def map_vals(hash)
-
294
to_hash(hash.map {|k, v| [k, yield(v)]})
-
end
-
-
# Maps the key-value pairs of a hash according to a block.
-
#
-
# @example
-
# map_hash({:foo => "bar", :baz => "bang"}) {|k, v| [k.to_s, v.to_sym]}
-
# #=> {"foo" => :bar, "baz" => :bang}
-
# @param hash [Hash] The hash to map
-
# @yield [key, value] A block in which the key-value pairs are transformed
-
# @yieldparam [key] The hash key
-
# @yieldparam [value] The hash value
-
# @yieldreturn [(Object, Object)] The new value for the `[key, value]` pair
-
# @return [Hash] The mapped hash
-
# @see #map_keys
-
# @see #map_vals
-
2
def map_hash(hash)
-
# Using &block here completely hoses performance on 1.8.
-
889
to_hash(hash.map {|k, v| yield k, v})
-
end
-
-
# Computes the powerset of the given array.
-
# This is the set of all subsets of the array.
-
#
-
# @example
-
# powerset([1, 2, 3]) #=>
-
# Set[Set[], Set[1], Set[2], Set[3], Set[1, 2], Set[2, 3], Set[1, 3], Set[1, 2, 3]]
-
# @param arr [Enumerable]
-
# @return [Set<Set>] The subsets of `arr`
-
2
def powerset(arr)
-
arr.inject([Set.new].to_set) do |powerset, el|
-
new_powerset = Set.new
-
powerset.each do |subset|
-
new_powerset << subset
-
new_powerset << subset + [el]
-
end
-
new_powerset
-
end
-
end
-
-
# Restricts a number to falling within a given range.
-
# Returns the number if it falls within the range,
-
# or the closest value in the range if it doesn't.
-
#
-
# @param value [Numeric]
-
# @param range [Range<Numeric>]
-
# @return [Numeric]
-
2
def restrict(value, range)
-
[[value, range.first].max, range.last].min
-
end
-
-
# Concatenates all strings that are adjacent in an array,
-
# while leaving other elements as they are.
-
#
-
# @example
-
# merge_adjacent_strings([1, "foo", "bar", 2, "baz"])
-
# #=> [1, "foobar", 2, "baz"]
-
# @param arr [Array]
-
# @return [Array] The enumerable with strings merged
-
2
def merge_adjacent_strings(arr)
-
# Optimize for the common case of one element
-
56852
return arr if arr.size < 2
-
1848
arr.inject([]) do |a, e|
-
45520
if e.is_a?(String)
-
45520
if a.last.is_a?(String)
-
43672
a.last << e
-
else
-
1848
a << e.dup
-
end
-
else
-
a << e
-
end
-
45520
a
-
end
-
end
-
-
# Intersperses a value in an enumerable, as would be done with `Array#join`
-
# but without concatenating the array together afterwards.
-
#
-
# @param enum [Enumerable]
-
# @param val
-
# @return [Array]
-
2
def intersperse(enum, val)
-
51932
enum.inject([]) {|a, e| a << e << val}[0...-1]
-
end
-
-
# Substitutes a sub-array of one array with another sub-array.
-
#
-
# @param ary [Array] The array in which to make the substitution
-
# @param from [Array] The sequence of elements to replace with `to`
-
# @param to [Array] The sequence of elements to replace `from` with
-
2
def substitute(ary, from, to)
-
res = ary.dup
-
i = 0
-
while i < res.size
-
if res[i...i+from.size] == from
-
res[i...i+from.size] = to
-
end
-
i += 1
-
end
-
res
-
end
-
-
# Destructively strips whitespace from the beginning and end
-
# of the first and last elements, respectively,
-
# in the array (if those elements are strings).
-
#
-
# @param arr [Array]
-
# @return [Array] `arr`
-
2
def strip_string_array(arr)
-
19920
arr.first.lstrip! if arr.first.is_a?(String)
-
19920
arr.last.rstrip! if arr.last.is_a?(String)
-
19920
arr
-
end
-
-
# Return an array of all possible paths through the given arrays.
-
#
-
# @param arrs [Array<Array>]
-
# @return [Array<Arrays>]
-
#
-
# @example
-
# paths([[1, 2], [3, 4], [5]]) #=>
-
# # [[1, 3, 5],
-
# # [2, 3, 5],
-
# # [1, 4, 5],
-
# # [2, 4, 5]]
-
2
def paths(arrs)
-
10095
arrs.inject([[]]) do |paths, arr|
-
66801
flatten(arr.map {|e| paths.map {|path| path + [e]}}, 1)
-
end
-
end
-
-
# Computes a single longest common subsequence for `x` and `y`.
-
# If there are more than one longest common subsequences,
-
# the one returned is that which starts first in `x`.
-
#
-
# @param x [Array]
-
# @param y [Array]
-
# @yield [a, b] An optional block to use in place of a check for equality
-
# between elements of `x` and `y`.
-
# @yieldreturn [Object, nil] If the two values register as equal,
-
# this will return the value to use in the LCS array.
-
# @return [Array] The LCS
-
2
def lcs(x, y, &block)
-
x = [nil, *x]
-
y = [nil, *y]
-
block ||= proc {|a, b| a == b && a}
-
lcs_backtrace(lcs_table(x, y, &block), x, y, x.size-1, y.size-1, &block)
-
end
-
-
# Converts a Hash to an Array. This is usually identical to `Hash#to_a`,
-
# with the following exceptions:
-
#
-
# * In Ruby 1.8, `Hash#to_a` is not deterministically ordered, but this is.
-
# * In Ruby 1.9 when running tests, this is ordered in the same way it would
-
# be under Ruby 1.8 (sorted key order rather than insertion order).
-
#
-
# @param hash [Hash]
-
# @return [Array]
-
2
def hash_to_a(hash)
-
2
return hash.to_a unless ruby1_8? || defined?(Test::Unit)
-
return hash.sort_by {|k, v| k}
-
end
-
-
# Performs the equivalent of `enum.group_by.to_a`, but with a guaranteed
-
# order. Unlike [#hash_to_a], the resulting order isn't sorted key order;
-
# instead, it's the same order as `#group_by` has under Ruby 1.9 (key
-
# appearance order).
-
#
-
# @param enum [Enumerable]
-
# @return [Array<[Object, Array]>] An array of pairs.
-
2
def group_by_to_a(enum, &block)
-
16349
return enum.group_by(&block).to_a unless ruby1_8?
-
order = {}
-
arr = []
-
enum.group_by do |e|
-
res = block[e]
-
unless order.include?(res)
-
order[res] = order.size
-
end
-
res
-
end.each do |key, vals|
-
arr[order[key]] = [key, vals]
-
end
-
arr
-
end
-
-
# Returns a sub-array of `minuend` containing only elements that are also in
-
# `subtrahend`. Ensures that the return value has the same order as
-
# `minuend`, even on Rubinius where that's not guaranteed by {Array#-}.
-
#
-
# @param minuend [Array]
-
# @param subtrahend [Array]
-
# @return [Array]
-
2
def array_minus(minuend, subtrahend)
-
42
return minuend - subtrahend unless rbx?
-
set = Set.new(minuend) - subtrahend
-
minuend.select {|e| set.include?(e)}
-
end
-
-
# Returns a string description of the character that caused an
-
# `Encoding::UndefinedConversionError`.
-
#
-
# @param [Encoding::UndefinedConversionError]
-
# @return [String]
-
2
def undefined_conversion_error_char(e)
-
# Rubinius (as of 2.0.0.rc1) pre-quotes the error character.
-
return e.error_char if rbx?
-
# JRuby (as of 1.7.2) doesn't have an error_char field on
-
# Encoding::UndefinedConversionError.
-
return e.error_char.dump unless jruby?
-
e.message[/^"[^"]+"/] #"
-
end
-
-
# Asserts that `value` falls within `range` (inclusive), leaving
-
# room for slight floating-point errors.
-
#
-
# @param name [String] The name of the value. Used in the error message.
-
# @param range [Range] The allowed range of values.
-
# @param value [Numeric, Sass::Script::Number] The value to check.
-
# @param unit [String] The unit of the value. Used in error reporting.
-
# @return [Numeric] `value` adjusted to fall within range, if it
-
# was outside by a floating-point margin.
-
2
def check_range(name, range, value, unit='')
-
5644
grace = (-0.00001..0.00001)
-
5644
str = value.to_s
-
5644
value = value.value if value.is_a?(Sass::Script::Number)
-
5644
return value if range.include?(value)
-
return range.first if grace.include?(value - range.first)
-
return range.last if grace.include?(value - range.last)
-
raise ArgumentError.new(
-
"#{name} #{str} must be between #{range.first}#{unit} and #{range.last}#{unit}")
-
end
-
-
# Returns whether or not `seq1` is a subsequence of `seq2`. That is, whether
-
# or not `seq2` contains every element in `seq1` in the same order (and
-
# possibly more elements besides).
-
#
-
# @param seq1 [Array]
-
# @param seq2 [Array]
-
# @return [Boolean]
-
2
def subsequence?(seq1, seq2)
-
42
i = j = 0
-
42
loop do
-
42
return true if i == seq1.size
-
return false if j == seq2.size
-
i += 1 if seq1[i] == seq2[j]
-
j += 1
-
end
-
end
-
-
# Returns information about the caller of the previous method.
-
#
-
# @param entry [String] An entry in the `#caller` list, or a similarly formatted string
-
# @return [[String, Fixnum, (String, nil)]] An array containing the filename, line, and method name of the caller.
-
# The method name may be nil
-
2
def caller_info(entry = nil)
-
# JRuby evaluates `caller` incorrectly when it's in an actual default argument.
-
entry ||= caller[1]
-
info = entry.scan(/^(.*?):(-?.*?)(?::.*`(.+)')?$/).first
-
info[1] = info[1].to_i
-
# This is added by Rubinius to designate a block, but we don't care about it.
-
info[2].sub!(/ \{\}\Z/, '') if info[2]
-
info
-
end
-
-
# Returns whether one version string represents a more recent version than another.
-
#
-
# @param v1 [String] A version string.
-
# @param v2 [String] Another version string.
-
# @return [Boolean]
-
2
def version_gt(v1, v2)
-
# Construct an array to make sure the shorter version is padded with nil
-
2
Array.new([v1.length, v2.length].max).zip(v1.split("."), v2.split(".")) do |_, p1, p2|
-
2
p1 ||= "0"
-
2
p2 ||= "0"
-
2
release1 = p1 =~ /^[0-9]+$/
-
2
release2 = p2 =~ /^[0-9]+$/
-
2
if release1 && release2
-
# Integer comparison if both are full releases
-
2
p1, p2 = p1.to_i, p2.to_i
-
2
next if p1 == p2
-
2
return p1 > p2
-
elsif !release1 && !release2
-
# String comparison if both are prereleases
-
next if p1 == p2
-
return p1 > p2
-
else
-
# If only one is a release, that one is newer
-
return release1
-
end
-
end
-
end
-
-
# Returns whether one version string represents the same or a more
-
# recent version than another.
-
#
-
# @param v1 [String] A version string.
-
# @param v2 [String] Another version string.
-
# @return [Boolean]
-
2
def version_geq(v1, v2)
-
2
version_gt(v1, v2) || !version_gt(v2, v1)
-
end
-
-
# Throws a NotImplementedError for an abstract method.
-
#
-
# @param obj [Object] `self`
-
# @raise [NotImplementedError]
-
2
def abstract(obj)
-
raise NotImplementedError.new("#{obj.class} must implement ##{caller_info[2]}")
-
end
-
-
# Silence all output to STDERR within a block.
-
#
-
# @yield A block in which no output will be printed to STDERR
-
2
def silence_warnings
-
the_real_stderr, $stderr = $stderr, StringIO.new
-
yield
-
ensure
-
$stderr = the_real_stderr
-
end
-
-
2
@@silence_warnings = false
-
# Silences all Sass warnings within a block.
-
#
-
# @yield A block in which no Sass warnings will be printed
-
2
def silence_sass_warnings
-
old_level, Sass.logger.log_level = Sass.logger.log_level, :error
-
yield
-
ensure
-
Sass.logger.log_level = old_level
-
end
-
-
# The same as `Kernel#warn`, but is silenced by \{#silence\_sass\_warnings}.
-
#
-
# @param msg [String]
-
2
def sass_warn(msg)
-
msg = msg + "\n" unless ruby1?
-
Sass.logger.warn(msg)
-
end
-
-
## Cross Rails Version Compatibility
-
-
# Returns the root of the Rails application,
-
# if this is running in a Rails context.
-
# Returns `nil` if no such root is defined.
-
#
-
# @return [String, nil]
-
2
def rails_root
-
if defined?(::Rails.root)
-
return ::Rails.root.to_s if ::Rails.root
-
raise "ERROR: Rails.root is nil!"
-
end
-
return RAILS_ROOT.to_s if defined?(RAILS_ROOT)
-
return nil
-
end
-
-
# Returns the environment of the Rails application,
-
# if this is running in a Rails context.
-
# Returns `nil` if no such environment is defined.
-
#
-
# @return [String, nil]
-
2
def rails_env
-
return ::Rails.env.to_s if defined?(::Rails.env)
-
return RAILS_ENV.to_s if defined?(RAILS_ENV)
-
return nil
-
end
-
-
# Returns whether this environment is using ActionPack
-
# version 3.0.0 or greater.
-
#
-
# @return [Boolean]
-
2
def ap_geq_3?
-
ap_geq?("3.0.0.beta1")
-
end
-
-
# Returns whether this environment is using ActionPack
-
# of a version greater than or equal to that specified.
-
#
-
# @param version [String] The string version number to check against.
-
# Should be greater than or equal to Rails 3,
-
# because otherwise ActionPack::VERSION isn't autoloaded
-
# @return [Boolean]
-
2
def ap_geq?(version)
-
# The ActionPack module is always loaded automatically in Rails >= 3
-
2
return false unless defined?(ActionPack) && defined?(ActionPack::VERSION) &&
-
defined?(ActionPack::VERSION::STRING)
-
-
2
version_geq(ActionPack::VERSION::STRING, version)
-
end
-
-
# Returns an ActionView::Template* class.
-
# In pre-3.0 versions of Rails, most of these classes
-
# were of the form `ActionView::TemplateFoo`,
-
# while afterwards they were of the form `ActionView;:Template::Foo`.
-
#
-
# @param name [#to_s] The name of the class to get.
-
# For example, `:Error` will return `ActionView::TemplateError`
-
# or `ActionView::Template::Error`.
-
2
def av_template_class(name)
-
return ActionView.const_get("Template#{name}") if ActionView.const_defined?("Template#{name}")
-
return ActionView::Template.const_get(name.to_s)
-
end
-
-
## Cross-OS Compatibility
-
-
# Whether or not this is running on Windows.
-
#
-
# @return [Boolean]
-
2
def windows?
-
RbConfig::CONFIG['host_os'] =~ /mswin|windows|mingw/i
-
end
-
-
# Whether or not this is running on IronRuby.
-
#
-
# @return [Boolean]
-
2
def ironruby?
-
120112
RUBY_ENGINE == "ironruby"
-
end
-
-
# Whether or not this is running on Rubinius.
-
#
-
# @return [Boolean]
-
2
def rbx?
-
44
RUBY_ENGINE == "rbx"
-
end
-
-
# Whether or not this is running on JRuby.
-
#
-
# @return [Boolean]
-
2
def jruby?
-
RUBY_PLATFORM =~ /java/
-
end
-
-
# Returns an array of ints representing the JRuby version number.
-
#
-
# @return [Array<Fixnum>]
-
2
def jruby_version
-
$jruby_version ||= ::JRUBY_VERSION.split(".").map {|s| s.to_i}
-
end
-
-
# Like `Dir.glob`, but works with backslash-separated paths on Windows.
-
#
-
# @param path [String]
-
2
def glob(path, &block)
-
path = path.gsub('\\', '/') if windows?
-
Dir.glob(path, &block)
-
end
-
-
# Prepare a value for a destructuring assignment (e.g. `a, b =
-
# val`). This works around a performance bug when using
-
# ActiveSupport, and only needs to be called when `val` is likely
-
# to be `nil` reasonably often.
-
#
-
# See [this bug report](http://redmine.ruby-lang.org/issues/4917).
-
#
-
# @param val [Object]
-
# @return [Object]
-
2
def destructure(val)
-
67905
val || []
-
end
-
-
## Cross-Ruby-Version Compatibility
-
-
# Whether or not this is running under a Ruby version under 2.0.
-
#
-
# @return [Boolean]
-
2
def ruby1?
-
Sass::Util::RUBY_VERSION[0] <= 1
-
end
-
-
# Whether or not this is running under Ruby 1.8 or lower.
-
#
-
# Note that IronRuby counts as Ruby 1.8,
-
# because it doesn't support the Ruby 1.9 encoding API.
-
#
-
# @return [Boolean]
-
2
def ruby1_8?
-
# IronRuby says its version is 1.9, but doesn't support any of the encoding APIs.
-
# We have to fall back to 1.8 behavior.
-
120112
ironruby? || (Sass::Util::RUBY_VERSION[0] == 1 && Sass::Util::RUBY_VERSION[1] < 9)
-
end
-
-
# Whether or not this is running under Ruby 1.8.6 or lower.
-
# Note that lower versions are not officially supported.
-
#
-
# @return [Boolean]
-
2
def ruby1_8_6?
-
103600
ruby1_8? && Sass::Util::RUBY_VERSION[2] < 7
-
end
-
-
# Wehter or not this is running under JRuby 1.6 or lower.
-
2
def jruby1_6?
-
jruby? && jruby_version[0] == 1 && jruby_version[1] < 7
-
end
-
-
# Whether or not this is running under MacRuby.
-
#
-
# @return [Boolean]
-
2
def macruby?
-
2
RUBY_ENGINE == 'macruby'
-
end
-
-
# Checks that the encoding of a string is valid in Ruby 1.9
-
# and cleans up potential encoding gotchas like the UTF-8 BOM.
-
# If it's not, yields an error string describing the invalid character
-
# and the line on which it occurrs.
-
#
-
# @param str [String] The string of which to check the encoding
-
# @yield [msg] A block in which an encoding error can be raised.
-
# Only yields if there is an encoding error
-
# @yieldparam msg [String] The error message to be raised
-
# @return [String] `str`, potentially with encoding gotchas like BOMs removed
-
2
def check_encoding(str)
-
1
if ruby1_8?
-
return str.gsub(/\A\xEF\xBB\xBF/, '') # Get rid of the UTF-8 BOM
-
elsif str.valid_encoding?
-
# Get rid of the Unicode BOM if possible
-
1
if str.encoding.name =~ /^UTF-(8|16|32)(BE|LE)?$/
-
1
return str.gsub(Regexp.new("\\A\uFEFF".encode(str.encoding.name)), '')
-
else
-
return str
-
end
-
end
-
-
encoding = str.encoding
-
newlines = Regexp.new("\r\n|\r|\n".encode(encoding).force_encoding("binary"))
-
str.force_encoding("binary").split(newlines).each_with_index do |line, i|
-
begin
-
line.encode(encoding)
-
rescue Encoding::UndefinedConversionError => e
-
yield <<MSG.rstrip, i + 1
-
Invalid #{encoding.name} character #{undefined_conversion_error_char(e)}
-
MSG
-
end
-
end
-
return str
-
end
-
-
# Like {\#check\_encoding}, but also checks for a `@charset` declaration
-
# at the beginning of the file and uses that encoding if it exists.
-
#
-
# The Sass encoding rules are simple.
-
# If a `@charset` declaration exists,
-
# we assume that that's the original encoding of the document.
-
# Otherwise, we use whatever encoding Ruby has.
-
# Then we convert that to UTF-8 to process internally.
-
# The UTF-8 end result is what's returned by this method.
-
#
-
# @param str [String] The string of which to check the encoding
-
# @yield [msg] A block in which an encoding error can be raised.
-
# Only yields if there is an encoding error
-
# @yieldparam msg [String] The error message to be raised
-
# @return [(String, Encoding)] The original string encoded as UTF-8,
-
# and the source encoding of the string (or `nil` under Ruby 1.8)
-
# @raise [Encoding::UndefinedConversionError] if the source encoding
-
# cannot be converted to UTF-8
-
# @raise [ArgumentError] if the document uses an unknown encoding with `@charset`
-
2
def check_sass_encoding(str, &block)
-
1
return check_encoding(str, &block), nil if ruby1_8?
-
# We allow any printable ASCII characters but double quotes in the charset decl
-
1
bin = str.dup.force_encoding("BINARY")
-
1
encoding = Sass::Util::ENCODINGS_TO_CHECK.find do |enc|
-
1
re = Sass::Util::CHARSET_REGEXPS[enc]
-
1
re && bin =~ re
-
end
-
1
charset, bom = $1, $2
-
1
if charset
-
1
charset = charset.force_encoding(encoding).encode("UTF-8")
-
1
if endianness = encoding[/[BL]E$/]
-
begin
-
Encoding.find(charset + endianness)
-
charset << endianness
-
rescue ArgumentError # Encoding charset + endianness doesn't exist
-
end
-
end
-
1
str.force_encoding(charset)
-
elsif bom
-
str.force_encoding(encoding)
-
end
-
-
1
str = check_encoding(str, &block)
-
1
return str.encode("UTF-8"), str.encoding
-
end
-
-
2
unless ruby1_8?
-
# @private
-
2
def _enc(string, encoding)
-
4
string.encode(encoding).force_encoding("BINARY")
-
end
-
-
# We could automatically add in any non-ASCII-compatible encodings here,
-
# but there's not really a good way to do that
-
# without manually checking that each encoding
-
# encodes all ASCII characters properly,
-
# which takes long enough to affect the startup time of the CLI.
-
2
ENCODINGS_TO_CHECK = %w[UTF-8 UTF-16BE UTF-16LE UTF-32BE UTF-32LE]
-
-
2
CHARSET_REGEXPS = Hash.new do |h, e|
-
1
h[e] =
-
begin
-
# /\A(?:\uFEFF)?@charset "(.*?)"|\A(\uFEFF)/
-
1
Regexp.new(/\A(?:#{_enc("\uFEFF", e)})?#{
-
_enc('@charset "', e)}(.*?)#{_enc('"', e)}|\A(#{
-
_enc("\uFEFF", e)})/)
-
rescue Encoding::ConverterNotFoundError => _
-
nil # JRuby on Java 5 doesn't support UTF-32
-
rescue
-
# /\A@charset "(.*?)"/
-
Regexp.new(/\A#{_enc('@charset "', e)}(.*?)#{_enc('"', e)}/)
-
end
-
end
-
end
-
-
# Checks to see if a class has a given method.
-
# For example:
-
#
-
# Sass::Util.has?(:public_instance_method, String, :gsub) #=> true
-
#
-
# Method collections like `Class#instance_methods`
-
# return strings in Ruby 1.8 and symbols in Ruby 1.9 and on,
-
# so this handles checking for them in a compatible way.
-
#
-
# @param attr [#to_s] The (singular) name of the method-collection method
-
# (e.g. `:instance_methods`, `:private_methods`)
-
# @param klass [Module] The class to check the methods of which to check
-
# @param method [String, Symbol] The name of the method do check for
-
# @return [Boolean] Whether or not the given collection has the given method
-
2
def has?(attr, klass, method)
-
2
klass.send("#{attr}s").include?(ruby1_8? ? method.to_s : method.to_sym)
-
end
-
-
# A version of `Enumerable#enum_with_index` that works in Ruby 1.8 and 1.9.
-
#
-
# @param enum [Enumerable] The enumerable to get the enumerator for
-
# @return [Enumerator] The with-index enumerator
-
2
def enum_with_index(enum)
-
126
ruby1_8? ? enum.enum_with_index : enum.each_with_index
-
end
-
-
# A version of `Enumerable#enum_cons` that works in Ruby 1.8 and 1.9.
-
#
-
# @param enum [Enumerable] The enumerable to get the enumerator for
-
# @param n [Fixnum] The size of each cons
-
# @return [Enumerator] The consed enumerator
-
2
def enum_cons(enum, n)
-
ruby1_8? ? enum.enum_cons(n) : enum.each_cons(n)
-
end
-
-
# A version of `Enumerable#enum_slice` that works in Ruby 1.8 and 1.9.
-
#
-
# @param enum [Enumerable] The enumerable to get the enumerator for
-
# @param n [Fixnum] The size of each slice
-
# @return [Enumerator] The consed enumerator
-
2
def enum_slice(enum, n)
-
20
ruby1_8? ? enum.enum_slice(n) : enum.each_slice(n)
-
end
-
-
# Destructively removes all elements from an array that match a block, and
-
# returns the removed elements.
-
#
-
# @param array [Array] The array from which to remove elements.
-
# @yield [el] Called for each element.
-
# @yieldparam el [*] The element to test.
-
# @yieldreturn [Boolean] Whether or not to extract the element.
-
# @return [Array] The extracted elements.
-
2
def extract!(array)
-
out = []
-
array.reject! do |e|
-
next false unless yield e
-
out << e
-
true
-
end
-
out
-
end
-
-
# Returns the ASCII code of the given character.
-
#
-
# @param c [String] All characters but the first are ignored.
-
# @return [Fixnum] The ASCII code of `c`.
-
2
def ord(c)
-
ruby1_8? ? c[0] : c.ord
-
end
-
-
# Flattens the first `n` nested arrays in a cross-version manner.
-
#
-
# @param arr [Array] The array to flatten
-
# @param n [Fixnum] The number of levels to flatten
-
# @return [Array] The flattened array
-
2
def flatten(arr, n)
-
70987
return arr.flatten(n) unless ruby1_8_6?
-
return arr if n == 0
-
arr.inject([]) {|res, e| e.is_a?(Array) ? res.concat(flatten(e, n - 1)) : res << e}
-
end
-
-
# Returns the hash code for a set in a cross-version manner.
-
# Aggravatingly, this is order-dependent in Ruby 1.8.6.
-
#
-
# @param set [Set]
-
# @return [Fixnum] The order-independent hashcode of `set`
-
2
def set_hash(set)
-
16306
return set.hash unless ruby1_8_6?
-
set.map {|e| e.hash}.uniq.sort.hash
-
end
-
-
# Tests the hash-equality of two sets in a cross-version manner.
-
# Aggravatingly, this is order-dependent in Ruby 1.8.6.
-
#
-
# @param set1 [Set]
-
# @param set2 [Set]
-
# @return [Boolean] Whether or not the sets are hashcode equal
-
2
def set_eql?(set1, set2)
-
16307
return set1.eql?(set2) unless ruby1_8_6?
-
set1.to_a.uniq.sort_by {|e| e.hash}.eql?(set2.to_a.uniq.sort_by {|e| e.hash})
-
end
-
-
# Like `Object#inspect`, but preserves non-ASCII characters rather than escaping them under Ruby 1.9.2.
-
# This is necessary so that the precompiled Haml template can be `#encode`d into `@options[:encoding]`
-
# before being evaluated.
-
#
-
# @param obj {Object}
-
# @return {String}
-
2
def inspect_obj(obj)
-
return obj.inspect unless version_geq(::RUBY_VERSION, "1.9.2")
-
return ':' + inspect_obj(obj.to_s) if obj.is_a?(Symbol)
-
return obj.inspect unless obj.is_a?(String)
-
'"' + obj.gsub(/[\x00-\x7F]+/) {|s| s.inspect[1...-1]} + '"'
-
end
-
-
# Extracts the non-string vlaues from an array containing both strings and non-strings.
-
# These values are replaced with escape sequences.
-
# This can be undone using \{#inject\_values}.
-
#
-
# This is useful e.g. when we want to do string manipulation
-
# on an interpolated string.
-
#
-
# The precise format of the resulting string is not guaranteed.
-
# However, it is guaranteed that newlines and whitespace won't be affected.
-
#
-
# @param arr [Array] The array from which values are extracted.
-
# @return [(String, Array)] The resulting string, and an array of extracted values.
-
2
def extract_values(arr)
-
1738
values = []
-
return arr.map do |e|
-
3476
next e.gsub('{', '{{') if e.is_a?(String)
-
values << e
-
next "{#{values.count - 1}}"
-
1738
end.join, values
-
end
-
-
# Undoes \{#extract\_values} by transforming a string with escape sequences
-
# into an array of strings and non-string values.
-
#
-
# @param str [String] The string with escape sequences.
-
# @param values [Array] The array of values to inject.
-
# @return [Array] The array of strings and values.
-
2
def inject_values(str, values)
-
1738
return [str.gsub('{{', '{')] if values.empty?
-
# Add an extra { so that we process the tail end of the string
-
result = (str + '{{').scan(/(.*?)(?:(\{\{)|\{(\d+)\})/m).map do |(pre, esc, n)|
-
[pre, esc ? '{' : '', n ? values[n.to_i] : '']
-
end.flatten(1)
-
result[-2] = '' # Get rid of the extra {
-
merge_adjacent_strings(result).reject {|s| s == ''}
-
end
-
-
# Allows modifications to be performed on the string form
-
# of an array containing both strings and non-strings.
-
#
-
# @param arr [Array] The array from which values are extracted.
-
# @yield [str] A block in which string manipulation can be done to the array.
-
# @yieldparam str [String] The string form of `arr`.
-
# @yieldreturn [String] The modified string.
-
# @return [Array] The modified, interpolated array.
-
2
def with_extracted_values(arr)
-
1738
str, vals = extract_values(arr)
-
1738
str = yield str
-
1738
inject_values(str, vals)
-
end
-
-
## Static Method Stuff
-
-
# The context in which the ERB for \{#def\_static\_method} will be run.
-
2
class StaticConditionalContext
-
# @param set [#include?] The set of variables that are defined for this context.
-
2
def initialize(set)
-
@set = set
-
end
-
-
# Checks whether or not a variable is defined for this context.
-
#
-
# @param name [Symbol] The name of the variable
-
# @return [Boolean]
-
2
def method_missing(name, *args, &block)
-
super unless args.empty? && block.nil?
-
@set.include?(name)
-
end
-
end
-
-
# @private
-
2
ATOMIC_WRITE_MUTEX = Mutex.new
-
-
-
# This creates a temp file and yields it for writing. When the
-
# write is complete, the file is moved into the desired location.
-
# The atomicity of this operation is provided by the filesystem's
-
# rename operation.
-
#
-
# @param filename [String] The file to write to.
-
# @param perms [Integer] The permissions used for creating this file.
-
# Will be masked by the process umask. Defaults to readable/writeable
-
# by all users however the umask usually changes this to only be writable
-
# by the process's user.
-
# @yieldparam tmpfile [Tempfile] The temp file that can be written to.
-
# @return The value returned by the block.
-
2
def atomic_create_and_write_file(filename, perms = 0666)
-
require 'tempfile'
-
tmpfile = Tempfile.new(File.basename(filename), File.dirname(filename))
-
tmpfile.binmode if tmpfile.respond_to?(:binmode)
-
result = yield tmpfile
-
tmpfile.flush # ensure all writes are flushed to the OS
-
begin
-
tmpfile.fsync # ensure all buffered data in the OS is sync'd to disk.
-
rescue NotImplementedError
-
# Not all OSes support fsync
-
end
-
tmpfile.close # Windows cannot rename an open file.
-
# Make file readable and writeable to all but respect umask (usually 022).
-
File.chmod(perms & ~File.umask, tmpfile.path)
-
ATOMIC_WRITE_MUTEX.synchronize do
-
File.rename tmpfile.path, filename
-
end
-
result
-
ensure
-
# close and remove the tempfile if it still exists,
-
# presumably due to an error during write
-
tmpfile.close if tmpfile
-
tmpfile.unlink if tmpfile
-
end
-
-
2
private
-
-
# Calculates the memoization table for the Least Common Subsequence algorithm.
-
# Algorithm from [Wikipedia](http://en.wikipedia.org/wiki/Longest_common_subsequence_problem#Computing_the_length_of_the_LCS)
-
2
def lcs_table(x, y)
-
c = Array.new(x.size) {[]}
-
x.size.times {|i| c[i][0] = 0}
-
y.size.times {|j| c[0][j] = 0}
-
(1...x.size).each do |i|
-
(1...y.size).each do |j|
-
c[i][j] =
-
if yield x[i], y[j]
-
c[i-1][j-1] + 1
-
else
-
[c[i][j-1], c[i-1][j]].max
-
end
-
end
-
end
-
return c
-
end
-
-
# Computes a single longest common subsequence for arrays x and y.
-
# Algorithm from [Wikipedia](http://en.wikipedia.org/wiki/Longest_common_subsequence_problem#Reading_out_an_LCS)
-
2
def lcs_backtrace(c, x, y, i, j, &block)
-
return [] if i == 0 || j == 0
-
if v = yield(x[i], y[j])
-
return lcs_backtrace(c, x, y, i-1, j-1, &block) << v
-
end
-
-
return lcs_backtrace(c, x, y, i, j-1, &block) if c[i][j-1] > c[i-1][j]
-
return lcs_backtrace(c, x, y, i-1, j, &block)
-
end
-
end
-
end
-
-
2
require 'sass/util/multibyte_string_scanner'
-
2
require 'strscan'
-
-
2
if Sass::Util.ruby1_8?
-
Sass::Util::MultibyteStringScanner = StringScanner
-
else
-
2
if Sass::Util.rbx?
-
# Rubinius's StringScanner class implements some of its methods in terms of
-
# others, which causes us to double-count bytes in some cases if we do
-
# straightforward inheritance. To work around this, we use a delegate class.
-
require 'delegate'
-
class Sass::Util::MultibyteStringScanner < DelegateClass(StringScanner)
-
def initialize(str)
-
super(StringScanner.new(str))
-
@mb_pos = 0
-
@mb_matched_size = nil
-
@mb_last_pos = nil
-
end
-
-
def is_a?(klass)
-
__getobj__.is_a?(klass) || super
-
end
-
end
-
else
-
2
class Sass::Util::MultibyteStringScanner < StringScanner
-
2
def initialize(str)
-
super
-
@mb_pos = 0
-
@mb_matched_size = nil
-
@mb_last_pos = nil
-
end
-
end
-
end
-
-
# A wrapper of the native StringScanner class that works correctly with
-
# multibyte character encodings. The native class deals only in bytes, not
-
# characters, for methods like [#pos] and [#matched_size]. This class deals
-
# only in characters, instead.
-
2
class Sass::Util::MultibyteStringScanner
-
2
def self.new(str)
-
8553
return StringScanner.new(str) if str.ascii_only?
-
super
-
end
-
-
2
alias_method :byte_pos, :pos
-
2
alias_method :byte_matched_size, :matched_size
-
-
2
def check(pattern); _match super; end
-
2
def check_until(pattern); _matched super; end
-
2
def getch; _forward _match super; end
-
2
def match?(pattern); _size check(pattern); end
-
2
def matched_size; @mb_matched_size; end
-
2
def peek(len); string[@mb_pos, len]; end
-
2
alias_method :peep, :peek
-
2
def pos; @mb_pos; end
-
2
alias_method :pointer, :pos
-
2
def rest_size; rest.size; end
-
2
def scan(pattern); _forward _match super; end
-
2
def scan_until(pattern); _forward _matched super; end
-
2
def skip(pattern); _size scan(pattern); end
-
2
def skip_until(pattern); _matched _size scan_until(pattern); end
-
-
2
def get_byte
-
raise "MultibyteStringScanner doesn't support #get_byte."
-
end
-
-
2
def getbyte
-
raise "MultibyteStringScanner doesn't support #getbyte."
-
end
-
-
2
def pos=(n)
-
@mb_last_pos = nil
-
-
# We set position kind of a lot during parsing, so we want it to be as
-
# efficient as possible. This is complicated by the fact that UTF-8 is a
-
# variable-length encoding, so it's difficult to find the byte length that
-
# corresponds to a given character length.
-
#
-
# Our heuristic here is to try to count the fewest possible characters. So
-
# if the new position is close to the current one, just count the
-
# characters between the two; if the new position is closer to the
-
# beginning of the string, just count the characters from there.
-
if @mb_pos - n < @mb_pos / 2
-
# New position is close to old position
-
byte_delta = @mb_pos > n ? -string[n...@mb_pos].bytesize : string[@mb_pos...n].bytesize
-
super(byte_pos + byte_delta)
-
else
-
# New position is close to BOS
-
super(string[0...n].bytesize)
-
end
-
@mb_pos = n
-
end
-
-
2
def reset
-
@mb_pos = 0
-
@mb_matched_size = nil
-
@mb_last_pos = nil
-
super
-
end
-
-
2
def scan_full(pattern, advance_pointer_p, return_string_p)
-
res = _match super(pattern, advance_pointer_p, true)
-
_forward res if advance_pointer_p
-
return res if return_string_p
-
end
-
-
2
def search_full(pattern, advance_pointer_p, return_string_p)
-
res = super(pattern, advance_pointer_p, true)
-
_forward res if advance_pointer_p
-
_matched((res if return_string_p))
-
end
-
-
2
def string=(str)
-
@mb_pos = 0
-
@mb_matched_size = nil
-
@mb_last_pos = nil
-
super
-
end
-
-
2
def terminate
-
@mb_pos = string.size
-
@mb_matched_size = nil
-
@mb_last_pos = nil
-
super
-
end
-
2
alias_method :clear, :terminate
-
-
2
def unscan
-
super
-
@mb_pos = @mb_last_pos
-
@mb_last_pos = @mb_matched_size = nil
-
end
-
-
2
private
-
-
2
def _size(str)
-
str && str.size
-
end
-
-
2
def _match(str)
-
@mb_matched_size = str && str.size
-
str
-
end
-
-
2
def _matched(res)
-
_match matched
-
res
-
end
-
-
2
def _forward(str)
-
@mb_last_pos = @mb_pos
-
@mb_pos += str.size if str
-
str
-
end
-
end
-
end
-
2
require 'set'
-
-
2
module Sass
-
2
module Util
-
# A map from sets to values.
-
# A value is \{#\[]= set} by providing a set (the "set-set") and a value,
-
# which is then recorded as corresponding to that set.
-
# Values are \{#\[] accessed} by providing a set (the "get-set")
-
# and returning all values that correspond to set-sets
-
# that are subsets of the get-set.
-
#
-
# SubsetMap preserves the order of values as they're inserted.
-
#
-
# @example
-
# ssm = SubsetMap.new
-
# ssm[Set[1, 2]] = "Foo"
-
# ssm[Set[2, 3]] = "Bar"
-
# ssm[Set[1, 2, 3]] = "Baz"
-
#
-
# ssm[Set[1, 2, 3]] #=> ["Foo", "Bar", "Baz"]
-
2
class SubsetMap
-
# Creates a new, empty SubsetMap.
-
2
def initialize
-
1
@hash = {}
-
1
@vals = []
-
end
-
-
# Whether or not this SubsetMap has any key-value pairs.
-
#
-
# @return [Boolean]
-
2
def empty?
-
1
@hash.empty?
-
end
-
-
# Associates a value with a set.
-
# When `set` or any of its supersets is accessed,
-
# `value` will be among the values returned.
-
#
-
# Note that if the same `set` is passed to this method multiple times,
-
# all given `value`s will be associated with that `set`.
-
#
-
# This runs in `O(n)` time, where `n` is the size of `set`.
-
#
-
# @param set [#to_set] The set to use as the map key. May not be empty.
-
# @param value [Object] The value to associate with `set`.
-
# @raise [ArgumentError] If `set` is empty.
-
2
def []=(set, value)
-
1
raise ArgumentError.new("SubsetMap keys may not be empty.") if set.empty?
-
-
1
index = @vals.size
-
1
@vals << value
-
1
set.each do |k|
-
1
@hash[k] ||= []
-
1
@hash[k] << [set, set.to_set, index]
-
end
-
end
-
-
# Returns all values associated with subsets of `set`.
-
#
-
# In the worst case, this runs in `O(m*max(n, log m))` time,
-
# where `n` is the size of `set`
-
# and `m` is the number of assocations in the map.
-
# However, unless many keys in the map overlap with `set`,
-
# `m` will typically be much smaller.
-
#
-
# @param set [Set] The set to use as the map key.
-
# @return [Array<(Object, #to_set)>] An array of pairs,
-
# where the first value is the value associated with a subset of `set`,
-
# and the second value is that subset of `set`
-
# (or whatever `#to_set` object was used to set the value)
-
# This array is in insertion order.
-
# @see #[]
-
2
def get(set)
-
16349
res = set.map do |k|
-
23036
next unless subsets = @hash[k]
-
42
subsets.map do |subenum, subset, index|
-
42
next unless subset.subset?(set)
-
42
[index, subenum]
-
end
-
end
-
16349
res = Sass::Util.flatten(res, 1)
-
16349
res.compact!
-
16349
res.uniq!
-
16349
res.sort!
-
16391
res.map! {|i, s| [@vals[i], s]}
-
16349
return res
-
end
-
-
# Same as \{#get}, but doesn't return the subsets of the argument
-
# for which values were found.
-
#
-
# @param set [Set] The set to use as the map key.
-
# @return [Array] The array of all values
-
# associated with subsets of `set`, in insertion order.
-
# @see #get
-
2
def [](set)
-
get(set).map {|v, _| v}
-
end
-
-
# Iterates over each value in the subset map. Ignores keys completely. If
-
# multiple keys have the same value, this will return them multiple times.
-
#
-
# @yield [Object] Each value in the map.
-
2
def each_value
-
2
@vals.each {|v| yield v}
-
end
-
end
-
end
-
end
-
2
require 'date'
-
-
# This is necessary for loading Sass when Haml is required in Rails 3.
-
# Once the split is complete, we can remove it.
-
2
require File.dirname(__FILE__) + '/../sass'
-
2
require 'sass/util'
-
-
2
module Sass
-
# Handles Sass version-reporting.
-
# Sass not only reports the standard three version numbers,
-
# but its Git revision hash as well,
-
# if it was installed from Git.
-
2
module Version
-
2
include Sass::Util
-
-
# Returns a hash representing the version of Sass.
-
# The `:major`, `:minor`, and `:teeny` keys have their respective numbers as Fixnums.
-
# The `:name` key has the name of the version.
-
# The `:string` key contains a human-readable string representation of the version.
-
# The `:number` key is the major, minor, and teeny keys separated by periods.
-
# The `:date` key, which is not guaranteed to be defined, is the [DateTime] at which this release was cut.
-
# If Sass is checked out from Git, the `:rev` key will have the revision hash.
-
# For example:
-
#
-
# {
-
# :string => "2.1.0.9616393",
-
# :rev => "9616393b8924ef36639c7e82aa88a51a24d16949",
-
# :number => "2.1.0",
-
# :date => DateTime.parse("Apr 30 13:52:01 2009 -0700"),
-
# :major => 2, :minor => 1, :teeny => 0
-
# }
-
#
-
# If a prerelease version of Sass is being used,
-
# the `:string` and `:number` fields will reflect the full version
-
# (e.g. `"2.2.beta.1"`), and the `:teeny` field will be `-1`.
-
# A `:prerelease` key will contain the name of the prerelease (e.g. `"beta"`),
-
# and a `:prerelease_number` key will contain the rerelease number.
-
# For example:
-
#
-
# {
-
# :string => "3.0.beta.1",
-
# :number => "3.0.beta.1",
-
# :date => DateTime.parse("Mar 31 00:38:04 2010 -0700"),
-
# :major => 3, :minor => 0, :teeny => -1,
-
# :prerelease => "beta",
-
# :prerelease_number => 1
-
# }
-
#
-
# @return [{Symbol => String/Fixnum}] The version hash
-
2
def version
-
2
return @@version if defined?(@@version)
-
-
2
numbers = File.read(scope('VERSION')).strip.split('.').
-
6
map {|n| n =~ /^[0-9]+$/ ? n.to_i : n}
-
2
name = File.read(scope('VERSION_NAME')).strip
-
2
@@version = {
-
:major => numbers[0],
-
:minor => numbers[1],
-
:teeny => numbers[2],
-
:name => name
-
}
-
-
2
if date = version_date
-
2
@@version[:date] = date
-
end
-
-
2
if numbers[3].is_a?(String)
-
@@version[:teeny] = -1
-
@@version[:prerelease] = numbers[3]
-
@@version[:prerelease_number] = numbers[4]
-
end
-
-
2
@@version[:number] = numbers.join('.')
-
2
@@version[:string] = @@version[:number].dup
-
-
2
if rev = revision_number
-
@@version[:rev] = rev
-
unless rev[0] == ?(
-
@@version[:string] << "." << rev[0...7]
-
end
-
end
-
-
2
@@version[:string] << " (#{name})"
-
2
@@version
-
end
-
-
2
private
-
-
2
def revision_number
-
2
if File.exists?(scope('REVISION'))
-
2
rev = File.read(scope('REVISION')).strip
-
2
return rev unless rev =~ /^([a-f0-9]+|\(.*\))$/ || rev == '(unknown)'
-
end
-
-
2
return unless File.exists?(scope('.git/HEAD'))
-
rev = File.read(scope('.git/HEAD')).strip
-
return rev unless rev =~ /^ref: (.*)$/
-
-
ref_name = $1
-
ref_file = scope(".git/#{ref_name}")
-
info_file = scope(".git/info/refs")
-
return File.read(ref_file).strip if File.exists?(ref_file)
-
return unless File.exists?(info_file)
-
File.open(info_file) do |f|
-
f.each do |l|
-
sha, ref = l.strip.split("\t", 2)
-
next unless ref == ref_name
-
return sha
-
end
-
end
-
return nil
-
end
-
-
2
def version_date
-
2
return unless File.exists?(scope('VERSION_DATE'))
-
2
return DateTime.parse(File.read(scope('VERSION_DATE')).strip)
-
end
-
end
-
-
2
extend Sass::Version
-
-
# A string representing the version of Sass.
-
# A more fine-grained representation is available from Sass.version.
-
# @api public
-
2
VERSION = version[:string] unless defined?(Sass::VERSION)
-
end
-
2
module Sass
-
2
module Rails
-
2
autoload :Logger, 'sass/rails/logger'
-
end
-
end
-
-
2
require 'sass/rails/version'
-
2
require 'sass/rails/helpers'
-
2
require 'sass/rails/importer'
-
2
require 'sass/rails/template'
-
2
require 'sass/rails/railtie'
-
2
require 'sprockets/sass_functions'
-
2
require 'active_support/deprecation'
-
-
2
module Sprockets
-
2
module SassFunctions
-
2
if instance_methods.map(&:to_sym).include?(:asset_path)
-
2
undef_method :asset_path
-
end
-
-
2
def asset_path(path, kind = nil)
-
ActiveSupport::Deprecation.warn "asset_path with two arguments is deprecated. Use asset_path(#{path}) instead." if kind
-
-
Sass::Script::String.new(sprockets_context.asset_path(path.value), :string)
-
end
-
-
2
if instance_methods.map(&:to_sym).include?(:asset_url)
-
2
undef_method :asset_url
-
end
-
-
2
def asset_url(path, kind = nil)
-
ActiveSupport::Deprecation.warn "asset_url with two arguments is deprecated. Use asset_url(#{path}) instead." if kind
-
-
Sass::Script::String.new("url(" + sprockets_context.asset_path(path.value) + ")")
-
end
-
-
2
def asset_data_url(path)
-
Sass::Script::String.new("url(" + sprockets_context.asset_data_uri(path.value) + ")")
-
end
-
end
-
end
-
2
require 'sass'
-
2
require 'sprockets/sass_importer'
-
-
2
module Sprockets
-
2
class SassImporter < Sass::Importers::Filesystem
-
2
GLOB = /\*|\[.+\]/
-
-
2
attr_reader :context
-
2
private :context
-
-
2
def initialize(context, root)
-
@context = context
-
super root.to_s
-
end
-
-
2
def extensions
-
{
-
'css' => :scss,
-
'css.scss' => :scss,
-
'css.sass' => :sass,
-
'css.erb' => :scss,
-
'scss.erb' => :scss,
-
'sass.erb' => :sass,
-
'css.scss.erb' => :scss,
-
'css.sass.erb' => :sass
-
}.merge!(super)
-
end
-
-
2
def find_relative(name, base, options)
-
if name =~ GLOB
-
glob_imports(name, Pathname.new(base), options)
-
else
-
engine_from_path(name, File.dirname(base), options)
-
end
-
end
-
-
2
def find(name, options)
-
if name =~ GLOB
-
nil # globs must be relative
-
else
-
engine_from_path(name, root, options)
-
end
-
end
-
-
2
def each_globbed_file(glob, base_pathname, options)
-
Dir["#{base_pathname}/#{glob}"].sort.each do |filename|
-
next if filename == options[:filename]
-
yield filename if File.directory?(filename) || context.asset_requirable?(filename)
-
end
-
end
-
-
2
def glob_imports(glob, base_pathname, options)
-
contents = ""
-
each_globbed_file(glob, base_pathname.dirname, options) do |filename|
-
if File.directory?(filename)
-
depend_on(filename)
-
elsif context.asset_requirable?(filename)
-
depend_on(filename)
-
contents << "@import #{Pathname.new(filename).relative_path_from(base_pathname.dirname).to_s.inspect};\n"
-
end
-
end
-
return nil if contents.empty?
-
Sass::Engine.new(contents, options.merge(
-
:filename => base_pathname.to_s,
-
:importer => self,
-
:syntax => :scss
-
))
-
end
-
-
2
private
-
-
2
def depend_on(filename)
-
context.depend_on(filename)
-
context.depend_on(globbed_file_parent(filename))
-
end
-
-
2
def globbed_file_parent(filename)
-
if File.directory?(filename)
-
File.expand_path('..', filename)
-
else
-
File.dirname(filename)
-
end
-
end
-
-
2
def engine_from_path(name, dir, options)
-
full_filename, syntax = Sass::Util.destructure(find_real_file(dir, name, options))
-
return unless full_filename && File.readable?(full_filename)
-
-
engine = Sass::Engine.new(evaluate(full_filename), options.merge(
-
syntax: syntax,
-
filename: full_filename,
-
importer: self
-
))
-
-
if engine && (filename = engine.options[:filename])
-
@context.depend_on(filename)
-
end
-
-
engine
-
end
-
-
2
def evaluate(filename)
-
attributes = context.environment.attributes_for(filename)
-
processors = context.environment.preprocessors(attributes.content_type) +
-
attributes.engines.reverse - [Sprockets::ScssTemplate, Sprockets::SassTemplate]
-
-
context.evaluate(filename, processors: processors)
-
end
-
end
-
end
-
2
require 'sass/logger'
-
-
2
module Sass
-
2
module Rails
-
2
class Logger < Sass::Logger::Base
-
2
def _log(level, message)
-
-
case level
-
when :trace, :debug
-
::Rails.logger.debug message
-
when :warn
-
::Rails.logger.warn message
-
when :error
-
::Rails.logger.error message
-
when :info
-
::Rails.logger.info message
-
end
-
end
-
end
-
end
-
end
-
2
require 'sprockets/railtie'
-
-
2
module Sass::Rails
-
2
class Railtie < ::Rails::Railtie
-
2
module SassContext
-
2
attr_accessor :sass_config
-
end
-
-
2
config.sass = ActiveSupport::OrderedOptions.new
-
-
# Establish static configuration defaults
-
# Emit scss files during stylesheet generation of scaffold
-
2
config.sass.preferred_syntax = :scss
-
# Write sass cache files for performance
-
2
config.sass.cache = true
-
# Read sass cache files for performance
-
2
config.sass.read_cache = true
-
# Display line comments above each selector as a debugging aid
-
2
config.sass.line_comments = true
-
# Initialize the load paths to an empty array
-
2
config.sass.load_paths = []
-
# Send Sass logs to Rails.logger
-
2
config.sass.logger = Sass::Rails::Logger.new
-
-
# Set the default stylesheet engine
-
# It can be overridedden by passing:
-
# --stylesheet_engine=sass
-
# to the rails generate command
-
2
config.app_generators.stylesheet_engine config.sass.preferred_syntax
-
-
# Remove the sass middleware if it gets inadvertently enabled by applications.
-
2
config.after_initialize do |app|
-
2
app.config.middleware.delete(Sass::Plugin::Rack) if defined?(Sass::Plugin::Rack)
-
end
-
-
2
initializer :setup_sass, group: :all do |app|
-
# Only emit one kind of syntax because though we have registered two kinds of generators
-
2
syntax = app.config.sass.preferred_syntax.to_sym
-
2
alt_syntax = syntax == :sass ? "scss" : "sass"
-
2
app.config.generators.hide_namespace alt_syntax
-
-
# Override stylesheet engine to the preferred syntax
-
2
config.app_generators.stylesheet_engine syntax
-
-
# Set the sass cache location
-
2
config.sass.cache_location = File.join(Rails.root, "tmp/cache/sass")
-
-
# Establish configuration defaults that are evironmental in nature
-
2
if config.sass.full_exception.nil?
-
# Display a stack trace in the css output when in development-like environments.
-
2
config.sass.full_exception = app.config.consider_all_requests_local
-
end
-
-
2
if app.assets
-
2
app.assets.context_class.extend(SassContext)
-
2
app.assets.context_class.sass_config = app.config.sass
-
end
-
-
2
Sass.logger = app.config.sass.logger
-
end
-
-
2
initializer :setup_compression, group: :all do |app|
-
2
unless Rails.env.development?
-
2
app.config.assets.css_compressor ||= :sass
-
else
-
# Use expanded output instead of the sass default of :nested unless specified
-
app.config.sass.style ||= :expanded
-
end
-
end
-
end
-
end
-
2
require "sprockets/sass_template"
-
-
2
module Sprockets
-
2
class SassTemplate
-
2
def evaluate(context, locals, &block)
-
cache_store = SassCacheStore.new(context.environment)
-
-
options = {
-
:filename => eval_file,
-
:line => line,
-
:syntax => syntax,
-
:cache_store => cache_store,
-
:importer => SassImporter.new(context, context.pathname),
-
:load_paths => context.environment.paths.map { |path| SassImporter.new(context, path) },
-
:sprockets => {
-
:context => context,
-
:environment => context.environment
-
}
-
}
-
-
sass_config = context.environment.context_class.sass_config.merge(options)
-
::Sass::Engine.new(data, sass_config).render
-
rescue ::Sass::SyntaxError => e
-
context.__LINE__ = e.sass_backtrace.first[:line]
-
raise e
-
end
-
end
-
end
-
2
module Sass
-
2
module Rails
-
2
VERSION = "4.0.5"
-
end
-
end
-
# encoding: utf-8
-
#
-
# Licensed to the Software Freedom Conservancy (SFC) under one
-
# or more contributor license agreements. See the NOTICE file
-
# distributed with this work for additional information
-
# regarding copyright ownership. The SFC licenses this file
-
# to you under the Apache License, Version 2.0 (the
-
# "License"); you may not use this file except in compliance
-
# with the License. You may obtain a copy of the License at
-
#
-
# http://www.apache.org/licenses/LICENSE-2.0
-
#
-
# Unless required by applicable law or agreed to in writing,
-
# software distributed under the License is distributed on an
-
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-
# KIND, either express or implied. See the License for the
-
# specific language governing permissions and limitations
-
# under the License.
-
-
2
require 'selenium/webdriver'
-
# encoding: utf-8
-
#
-
# Licensed to the Software Freedom Conservancy (SFC) under one
-
# or more contributor license agreements. See the NOTICE file
-
# distributed with this work for additional information
-
# regarding copyright ownership. The SFC licenses this file
-
# to you under the Apache License, Version 2.0 (the
-
# "License"); you may not use this file except in compliance
-
# with the License. You may obtain a copy of the License at
-
#
-
# http://www.apache.org/licenses/LICENSE-2.0
-
#
-
# Unless required by applicable law or agreed to in writing,
-
# software distributed under the License is distributed on an
-
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-
# KIND, either express or implied. See the License for the
-
# specific language governing permissions and limitations
-
# under the License.
-
-
2
require 'childprocess'
-
2
require 'tmpdir'
-
2
require 'fileutils'
-
2
require 'date'
-
2
require 'json'
-
-
2
require 'selenium/webdriver/common'
-
-
2
module Selenium
-
2
module WebDriver
-
2
Point = Struct.new(:x, :y)
-
2
Dimension = Struct.new(:width, :height)
-
2
Location = Struct.new(:latitude, :longitude, :altitude)
-
-
2
autoload :Android, 'selenium/webdriver/android'
-
2
autoload :Chrome, 'selenium/webdriver/chrome'
-
2
autoload :Edge, 'selenium/webdriver/edge'
-
2
autoload :Firefox, 'selenium/webdriver/firefox'
-
2
autoload :IE, 'selenium/webdriver/ie'
-
2
autoload :IPhone, 'selenium/webdriver/iphone'
-
2
autoload :PhantomJS, 'selenium/webdriver/phantomjs'
-
2
autoload :Remote, 'selenium/webdriver/remote'
-
2
autoload :Safari, 'selenium/webdriver/safari'
-
2
autoload :Support, 'selenium/webdriver/support'
-
-
# @api private
-
-
2
def self.root
-
@root ||= File.expand_path("../..", __FILE__)
-
end
-
-
#
-
# Create a new Driver instance with the correct bridge for the given browser
-
#
-
# @param browser [:ie, :internet_explorer, :edge, :remote, :chrome, :firefox, :ff, :android, :iphone, :phantomjs, :safari]
-
# the driver type to use
-
# @param *rest
-
# arguments passed to Bridge.new
-
#
-
# @return [Driver]
-
#
-
# @see Selenium::WebDriver::Remote::Bridge
-
# @see Selenium::WebDriver::Firefox::Bridge
-
# @see Selenium::WebDriver::IE::Bridge
-
# @see Selenium::WebDriver::Edge::Bridge
-
# @see Selenium::WebDriver::Chrome::Bridge
-
# @see Selenium::WebDriver::Android::Bridge
-
# @see Selenium::WebDriver::IPhone::Bridge
-
# @see Selenium::WebDriver::PhantomJS::Bridge
-
# @see Selenium::WebDriver::Safari::Bridge
-
#
-
# @example
-
#
-
# WebDriver.for :firefox, :profile => "some-profile"
-
# WebDriver.for :firefox, :profile => Profile.new
-
# WebDriver.for :remote, :url => "http://localhost:4444/wd/hub", :desired_capabilities => caps
-
#
-
# One special argument is not passed on to the bridges, :listener. You can pass a listener for this option
-
# to get notified of WebDriver events. The passed object must respond to #call or implement the methods from AbstractEventListener.
-
#
-
# @see Selenium::WebDriver::Support::AbstractEventListener
-
#
-
-
2
def self.for(*args)
-
WebDriver::Driver.for(*args)
-
end
-
-
end # WebDriver
-
end # Selenium
-
# encoding: utf-8
-
#
-
# Licensed to the Software Freedom Conservancy (SFC) under one
-
# or more contributor license agreements. See the NOTICE file
-
# distributed with this work for additional information
-
# regarding copyright ownership. The SFC licenses this file
-
# to you under the Apache License, Version 2.0 (the
-
# "License"); you may not use this file except in compliance
-
# with the License. You may obtain a copy of the License at
-
#
-
# http://www.apache.org/licenses/LICENSE-2.0
-
#
-
# Unless required by applicable law or agreed to in writing,
-
# software distributed under the License is distributed on an
-
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-
# KIND, either express or implied. See the License for the
-
# specific language governing permissions and limitations
-
# under the License.
-
-
2
require 'selenium/webdriver/common/core_ext/dir'
-
2
require 'selenium/webdriver/common/core_ext/base64'
-
2
require 'selenium/webdriver/common/w3c_error'
-
2
require 'selenium/webdriver/common/error'
-
2
require 'selenium/webdriver/common/platform'
-
2
require 'selenium/webdriver/common/proxy'
-
2
require 'selenium/webdriver/common/log_entry'
-
2
require 'selenium/webdriver/common/file_reaper'
-
2
require 'selenium/webdriver/common/socket_lock'
-
2
require 'selenium/webdriver/common/socket_poller'
-
2
require 'selenium/webdriver/common/port_prober'
-
2
require 'selenium/webdriver/common/zipper'
-
2
require 'selenium/webdriver/common/wait'
-
2
require 'selenium/webdriver/common/alert'
-
2
require 'selenium/webdriver/common/mouse'
-
2
require 'selenium/webdriver/common/keyboard'
-
2
require 'selenium/webdriver/common/touch_screen'
-
2
require 'selenium/webdriver/common/target_locator'
-
2
require 'selenium/webdriver/common/navigation'
-
2
require 'selenium/webdriver/common/timeouts'
-
2
require 'selenium/webdriver/common/window'
-
2
require 'selenium/webdriver/common/logs'
-
2
require 'selenium/webdriver/common/options'
-
2
require 'selenium/webdriver/common/search_context'
-
2
require 'selenium/webdriver/common/action_builder'
-
2
require 'selenium/webdriver/common/touch_action_builder'
-
2
require 'selenium/webdriver/common/html5/shared_web_storage'
-
2
require 'selenium/webdriver/common/html5/local_storage'
-
2
require 'selenium/webdriver/common/html5/session_storage'
-
2
require 'selenium/webdriver/common/driver_extensions/takes_screenshot'
-
2
require 'selenium/webdriver/common/driver_extensions/rotatable'
-
2
require 'selenium/webdriver/common/driver_extensions/has_input_devices'
-
2
require 'selenium/webdriver/common/driver_extensions/has_web_storage'
-
2
require 'selenium/webdriver/common/driver_extensions/has_location'
-
2
require 'selenium/webdriver/common/driver_extensions/has_session_id'
-
2
require 'selenium/webdriver/common/driver_extensions/has_touch_screen'
-
2
require 'selenium/webdriver/common/driver_extensions/has_remote_status'
-
2
require 'selenium/webdriver/common/driver_extensions/has_network_connection'
-
2
require 'selenium/webdriver/common/driver_extensions/uploads_files'
-
2
require 'selenium/webdriver/common/keys'
-
2
require 'selenium/webdriver/common/bridge_helper'
-
2
require 'selenium/webdriver/common/profile_helper'
-
2
require 'selenium/webdriver/common/driver'
-
2
require 'selenium/webdriver/common/element'
-
# encoding: utf-8
-
#
-
# Licensed to the Software Freedom Conservancy (SFC) under one
-
# or more contributor license agreements. See the NOTICE file
-
# distributed with this work for additional information
-
# regarding copyright ownership. The SFC licenses this file
-
# to you under the Apache License, Version 2.0 (the
-
# "License"); you may not use this file except in compliance
-
# with the License. You may obtain a copy of the License at
-
#
-
# http://www.apache.org/licenses/LICENSE-2.0
-
#
-
# Unless required by applicable law or agreed to in writing,
-
# software distributed under the License is distributed on an
-
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-
# KIND, either express or implied. See the License for the
-
# specific language governing permissions and limitations
-
# under the License.
-
-
2
module Selenium
-
2
module WebDriver
-
-
#
-
# The ActionBuilder provides the user a way to set up and perform
-
# complex user interactions.
-
#
-
# This class should not be instantiated directly, but is created by
-
# Selenium::WebDriver::DriverExtensions::HasInputDevices#action, which
-
# is available on Driver instances that support the user interaction API.
-
#
-
# @example
-
#
-
# driver.action.key_down(:shift).
-
# click(element).
-
# click(second_element).
-
# key_up(:shift).
-
# drag_and_drop(element, third_element).
-
# perform
-
#
-
-
2
class ActionBuilder
-
-
#
-
# @api private
-
#
-
-
2
def initialize(mouse, keyboard)
-
@devices = {
-
:mouse => mouse,
-
:keyboard => keyboard
-
}
-
-
@actions = []
-
end
-
-
#
-
# Performs a modifier key press. Does not release
-
# the modifier key - subsequent interactions may assume it's kept pressed.
-
# Note that the modifier key is never released implicitly - either
-
# #key_up(key) or #send_keys(:null) must be called to release the modifier.
-
#
-
# Equivalent to:
-
# driver.action.click(element).send_keys(key)
-
# # or
-
# driver.action.click.send_keys(key)
-
#
-
# @example Press a key
-
#
-
# driver.action.key_down(:control).perform
-
#
-
# @example Press a key on an element
-
#
-
# el = driver.find_element(:id, "some_id")
-
# driver.action.key_down(el, :shift).perform
-
#
-
# @param [:shift, :alt, :control, :command, :meta] The key to press.
-
# @param [Selenium::WebDriver::Element] element An optional element
-
# @raise [ArgumentError] if the given key is not a modifier
-
# @return [ActionBuilder] A self reference.
-
#
-
-
2
def key_down(*args)
-
if args.first.kind_of? Element
-
@actions << [:mouse, :click, [args.shift]]
-
end
-
-
@actions << [:keyboard, :press, args]
-
self
-
end
-
-
#
-
# Performs a modifier key release.
-
# Releasing a non-depressed modifier key will yield undefined behaviour.
-
#
-
# @example Release a key
-
#
-
# driver.action.key_up(:shift).perform
-
#
-
# @example Release a key from an element
-
#
-
# el = driver.find_element(:id, "some_id")
-
# driver.action.key_up(el, :alt).perform
-
#
-
# @param [:shift, :alt, :control, :command, :meta] The modifier key to release.
-
# @param [Selenium::WebDriver::Element] element An optional element
-
# @raise [ArgumentError] if the given key is not a modifier key
-
# @return [ActionBuilder] A self reference.
-
#
-
-
2
def key_up(*args)
-
if args.first.kind_of? Element
-
@actions << [:mouse, :click, [args.shift]]
-
end
-
-
@actions << [:keyboard, :release, args]
-
self
-
end
-
-
#
-
# Sends keys to the active element. This differs from calling
-
# Element#send_keys(keys) on the active element in two ways:
-
#
-
# * The modifier keys included in this call are not released.
-
# * There is no attempt to re-focus the element - so send_keys(:tab) for switching elements should work.
-
#
-
# @example Send the text "help" to an element
-
#
-
# el = driver.find_element(:id, "some_id")
-
# driver.action.send_keys(el, "help").perform
-
#
-
# @example Send the text "help" to the currently focused element
-
#
-
# driver.action.send_keys("help").perform
-
#
-
# @param [Selenium::WebDriver::Element] element An optional element
-
# @param [String] keys The keys to be sent.
-
# @return [ActionBuilder] A self reference.
-
#
-
-
2
def send_keys(*args)
-
if args.first.kind_of? Element
-
@actions << [:mouse, :click, [args.shift]]
-
end
-
-
@actions << [:keyboard, :send_keys, args]
-
self
-
end
-
-
#
-
# Clicks (without releasing) in the middle of the given element. This is
-
# equivalent to:
-
#
-
# driver.action.move_to(element).click_and_hold
-
#
-
# @example Clicking and holding on some element
-
#
-
# el = driver.find_element(:id, "some_id")
-
# driver.action.click_and_hold(el).perform
-
#
-
# @param [Selenium::WebDriver::Element] element the element to move to and click.
-
# @return [ActionBuilder] A self reference.
-
#
-
-
2
def click_and_hold(element = nil)
-
@actions << [:mouse, :down, [element]]
-
self
-
end
-
-
#
-
# Releases the depressed left mouse button at the current mouse location.
-
#
-
# @example Releasing an element after clicking and holding it
-
#
-
# el = driver.find_element(:id, "some_id")
-
# driver.action.click_and_hold(el).release.perform
-
#
-
# @return [ActionBuilder] A self reference.
-
#
-
-
2
def release(element = nil)
-
@actions << [:mouse, :up, [element]]
-
self
-
end
-
-
#
-
# Clicks in the middle of the given element. Equivalent to:
-
#
-
# driver.action.move_to(element).click
-
#
-
# When no element is passed, the current mouse position will be clicked.
-
#
-
# @example Clicking on an element
-
#
-
# el = driver.find_element(:id, "some_id")
-
# driver.action.click(el).perform
-
#
-
# @example Clicking at the current mouse position
-
#
-
# driver.action.click.perform
-
#
-
# @param [Selenium::WebDriver::Element] element An optional element to click.
-
# @return [ActionBuilder] A self reference.
-
#
-
-
2
def click(element = nil)
-
@actions << [:mouse, :click, [element]]
-
self
-
end
-
-
#
-
# Performs a double-click at middle of the given element. Equivalent to:
-
#
-
# driver.action.move_to(element).double_click
-
#
-
# @example Double click an element
-
#
-
# el = driver.find_element(:id, "some_id")
-
# driver.action.double_click(el).perform
-
#
-
# @param [Selenium::WebDriver::Element] element An optional element to move to.
-
# @return [ActionBuilder] A self reference.
-
#
-
-
2
def double_click(element = nil)
-
@actions << [:mouse, :double_click, [element]]
-
self
-
end
-
-
#
-
# Moves the mouse to the middle of the given element. The element is scrolled into
-
# view and its location is calculated using getBoundingClientRect. Then the
-
# mouse is moved to optional offset coordinates from the element.
-
#
-
# Note that when using offsets, both coordinates need to be passed.
-
#
-
# @example Scroll element into view and move the mouse to it
-
#
-
# el = driver.find_element(:id, "some_id")
-
# driver.action.move_to(el).perform
-
#
-
# @example
-
#
-
# el = driver.find_element(:id, "some_id")
-
# driver.action.move_to(el, 100, 100).perform
-
#
-
# @param [Selenium::WebDriver::Element] element to move to.
-
# @param [Integer] right_by Optional offset from the top-left corner. A negative value means
-
# coordinates right from the element.
-
# @param [Integer] down_by Optional offset from the top-left corner. A negative value means
-
# coordinates above the element.
-
# @return [ActionBuilder] A self reference.
-
#
-
-
2
def move_to(element, right_by = nil, down_by = nil)
-
if right_by && down_by
-
@actions << [:mouse, :move_to, [element, right_by, down_by]]
-
else
-
@actions << [:mouse, :move_to, [element]]
-
end
-
-
self
-
end
-
-
#
-
# Moves the mouse from its current position (or 0,0) by the given offset.
-
# If the coordinates provided are outside the viewport (the mouse will
-
# end up outside the browser window) then the viewport is scrolled to
-
# match.
-
#
-
# @example Move the mouse to a certain offset from its current position
-
#
-
# driver.action.move_by(100, 100).perform
-
#
-
# @param [Integer] right_by horizontal offset. A negative value means moving the
-
# mouse left.
-
# @param [Integer] down_by vertical offset. A negative value means moving the mouse
-
# up.
-
# @return [ActionBuilder] A self reference.
-
# @raise [MoveTargetOutOfBoundsError] if the provided offset is outside
-
# the document's boundaries.
-
#
-
-
2
def move_by(right_by, down_by)
-
@actions << [:mouse, :move_by, [right_by, down_by]]
-
self
-
end
-
-
#
-
# Performs a context-click at middle of the given element. First performs
-
# a move_to to the location of the element.
-
#
-
# @example Context-click at middle of given element
-
#
-
# el = driver.find_element(:id, "some_id")
-
# driver.action.context_click(el).perform
-
#
-
# @param [Selenium::WebDriver::Element] element An element to context click.
-
# @return [ActionBuilder] A self reference.
-
#
-
-
2
def context_click(element = nil)
-
@actions << [:mouse, :context_click, [element]]
-
self
-
end
-
-
#
-
# A convenience method that performs click-and-hold at the location of the
-
# source element, moves to the location of the target element, then
-
# releases the mouse.
-
#
-
# @example Drag and drop one element onto another
-
#
-
# el1 = driver.find_element(:id, "some_id1")
-
# el2 = driver.find_element(:id, "some_id2")
-
# driver.action.drag_and_drop(el1, el2).perform
-
#
-
# @param [Selenium::WebDriver::Element] source element to emulate button down at.
-
# @param [Selenium::WebDriver::Element] target element to move to and release the
-
# mouse at.
-
# @return [ActionBuilder] A self reference.
-
#
-
-
2
def drag_and_drop(source, target)
-
click_and_hold source
-
move_to target
-
release target
-
-
self
-
end
-
-
#
-
# A convenience method that performs click-and-hold at the location of
-
# the source element, moves by a given offset, then releases the mouse.
-
#
-
# @example Drag and drop an element by offset
-
#
-
# el = driver.find_element(:id, "some_id1")
-
# driver.action.drag_and_drop_by(el, 100, 100).perform
-
#
-
# @param [Selenium::WebDriver::Element] source Element to emulate button down at.
-
# @param [Integer] right_by horizontal move offset.
-
# @param [Integer] down_by vertical move offset.
-
# @param [Selenium::WebDriver::Element] target Element to move to and release the
-
# mouse at.
-
# @return [ActionBuilder] A self reference.
-
#
-
-
2
def drag_and_drop_by(source, right_by, down_by)
-
click_and_hold source
-
move_by right_by, down_by
-
release
-
-
self
-
end
-
-
-
#
-
# Executes the actions added to the builder.
-
#
-
-
2
def perform
-
@actions.each { |receiver, method, args|
-
@devices.fetch(receiver).__send__(method, *args)
-
}
-
-
nil
-
end
-
-
end # ActionBuilder
-
end # WebDriver
-
end # Selenium
-
# encoding: utf-8
-
#
-
# Licensed to the Software Freedom Conservancy (SFC) under one
-
# or more contributor license agreements. See the NOTICE file
-
# distributed with this work for additional information
-
# regarding copyright ownership. The SFC licenses this file
-
# to you under the Apache License, Version 2.0 (the
-
# "License"); you may not use this file except in compliance
-
# with the License. You may obtain a copy of the License at
-
#
-
# http://www.apache.org/licenses/LICENSE-2.0
-
#
-
# Unless required by applicable law or agreed to in writing,
-
# software distributed under the License is distributed on an
-
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-
# KIND, either express or implied. See the License for the
-
# specific language governing permissions and limitations
-
# under the License.
-
-
2
module Selenium
-
2
module WebDriver
-
2
class Alert
-
-
2
def initialize(bridge)
-
@bridge = bridge
-
-
# fail fast if the alert doesn't exist
-
bridge.getAlertText
-
end
-
-
2
def accept
-
@bridge.acceptAlert
-
end
-
-
2
def dismiss
-
@bridge.dismissAlert
-
end
-
-
2
def send_keys(keys)
-
@bridge.setAlertValue keys
-
end
-
-
2
def text
-
@bridge.getAlertText
-
end
-
-
2
def authenticate(username, password)
-
@bridge.setAuthentication username: username, password: password
-
accept
-
end
-
-
end # Alert
-
end # WebDriver
-
end # Selenium
-
-
# encoding: utf-8
-
#
-
# Licensed to the Software Freedom Conservancy (SFC) under one
-
# or more contributor license agreements. See the NOTICE file
-
# distributed with this work for additional information
-
# regarding copyright ownership. The SFC licenses this file
-
# to you under the Apache License, Version 2.0 (the
-
# "License"); you may not use this file except in compliance
-
# with the License. You may obtain a copy of the License at
-
#
-
# http://www.apache.org/licenses/LICENSE-2.0
-
#
-
# Unless required by applicable law or agreed to in writing,
-
# software distributed under the License is distributed on an
-
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-
# KIND, either express or implied. See the License for the
-
# specific language governing permissions and limitations
-
# under the License.
-
-
2
module Selenium
-
2
module WebDriver
-
-
#
-
# Shared across bridges
-
#
-
# @api private
-
#
-
-
2
module BridgeHelper
-
-
2
def unwrap_script_result(arg)
-
case arg
-
when Array
-
arg.map { |e| unwrap_script_result(e) }
-
when Hash
-
if id = element_id_from(arg)
-
Element.new self, id
-
else
-
arg.each { |k, v| arg[k] = unwrap_script_result(v) }
-
end
-
else
-
arg
-
end
-
end
-
-
2
def element_id_from(id)
-
id['ELEMENT'] or id['element-6066-11e4-a52e-4f735466cecf']
-
end
-
-
2
def parse_cookie_string(str)
-
result = {
-
'name' => '',
-
'value' => '',
-
'domain' => '',
-
'path' => '',
-
'expires' => '',
-
'secure' => false
-
}
-
-
str.split(";").each do |attribute|
-
if attribute.include? "="
-
key, value = attribute.strip.split("=", 2)
-
if result['name'].empty?
-
result['name'] = key
-
result['value'] = value
-
elsif key == 'domain' && value.strip =~ /^\.(.+)/
-
result['domain'] = $1
-
elsif key && value
-
result[key] = value
-
end
-
elsif attribute == "secure"
-
result['secure'] = true
-
end
-
-
unless [nil, "", "0"].include?(result['expires'])
-
# firefox stores expiry as number of seconds
-
result['expires'] = Time.at(result['expires'].to_i)
-
end
-
end
-
-
result
-
end
-
-
end # BridgeHelper
-
end # WebDriver
-
end # Selenium
-
# encoding: utf-8
-
#
-
# Licensed to the Software Freedom Conservancy (SFC) under one
-
# or more contributor license agreements. See the NOTICE file
-
# distributed with this work for additional information
-
# regarding copyright ownership. The SFC licenses this file
-
# to you under the Apache License, Version 2.0 (the
-
# "License"); you may not use this file except in compliance
-
# with the License. You may obtain a copy of the License at
-
#
-
# http://www.apache.org/licenses/LICENSE-2.0
-
#
-
# Unless required by applicable law or agreed to in writing,
-
# software distributed under the License is distributed on an
-
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-
# KIND, either express or implied. See the License for the
-
# specific language governing permissions and limitations
-
# under the License.
-
-
2
require 'base64'
-
-
2
module Base64
-
-
def self.strict_encode64(str)
-
encode64(str).gsub(/\n/, '')
-
2
end unless respond_to?(:strict_encode64) # added in 1.9
-
-
end
-
# encoding: utf-8
-
#
-
# Licensed to the Software Freedom Conservancy (SFC) under one
-
# or more contributor license agreements. See the NOTICE file
-
# distributed with this work for additional information
-
# regarding copyright ownership. The SFC licenses this file
-
# to you under the Apache License, Version 2.0 (the
-
# "License"); you may not use this file except in compliance
-
# with the License. You may obtain a copy of the License at
-
#
-
# http://www.apache.org/licenses/LICENSE-2.0
-
#
-
# Unless required by applicable law or agreed to in writing,
-
# software distributed under the License is distributed on an
-
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-
# KIND, either express or implied. See the License for the
-
# specific language governing permissions and limitations
-
# under the License.
-
-
2
class Dir
-
# @api private
-
def self.mktmpdir(prefix_suffix=nil, tmpdir=nil)
-
case prefix_suffix
-
when nil
-
prefix = "d"
-
suffix = ""
-
when String
-
prefix = prefix_suffix
-
suffix = ""
-
when Array
-
prefix = prefix_suffix[0]
-
suffix = prefix_suffix[1]
-
else
-
raise ArgumentError, "unexpected prefix_suffix: #{prefix_suffix.inspect}"
-
end
-
tmpdir ||= Dir.tmpdir
-
t = Time.now.strftime("%Y%m%d")
-
n = nil
-
begin
-
path = "#{tmpdir}/#{prefix}#{t}-#{$$}-#{rand(0x100000000).to_s(36)}"
-
path << "-#{n}" if n
-
path << suffix
-
Dir.mkdir(path, 0700)
-
rescue Errno::EEXIST
-
n ||= 0
-
n += 1
-
retry
-
end
-
-
if block_given?
-
begin
-
yield path
-
ensure
-
FileUtils.remove_entry_secure path
-
end
-
else
-
path
-
end
-
2
end unless respond_to? :mktmpdir # > 1.8.7
-
end
-
-
# encoding: utf-8
-
#
-
# Licensed to the Software Freedom Conservancy (SFC) under one
-
# or more contributor license agreements. See the NOTICE file
-
# distributed with this work for additional information
-
# regarding copyright ownership. The SFC licenses this file
-
# to you under the Apache License, Version 2.0 (the
-
# "License"); you may not use this file except in compliance
-
# with the License. You may obtain a copy of the License at
-
#
-
# http://www.apache.org/licenses/LICENSE-2.0
-
#
-
# Unless required by applicable law or agreed to in writing,
-
# software distributed under the License is distributed on an
-
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-
# KIND, either express or implied. See the License for the
-
# specific language governing permissions and limitations
-
# under the License.
-
-
2
module Selenium
-
2
module WebDriver
-
-
#
-
# The main class through which you control the browser.
-
#
-
# @see SearchContext
-
# @see Navigation
-
# @see TargetLocator
-
# @see Options
-
#
-
-
2
class Driver
-
2
include SearchContext
-
-
2
class << self
-
-
#
-
# @api private
-
#
-
# @see Selenium::WebDriver.for
-
#
-
# @return [Driver]
-
#
-
-
2
def for(browser, opts = {})
-
listener = opts.delete(:listener)
-
-
bridge = case browser
-
when :firefox, :ff, :marionette
-
if Remote::W3CCapabilities.w3c?(opts)
-
Firefox::W3CBridge.new(opts)
-
else
-
Firefox::Bridge.new(opts)
-
end
-
when :remote
-
if Remote::W3CCapabilities.w3c?(opts)
-
Remote::W3CBridge.new(opts)
-
else
-
Remote::Bridge.new(opts)
-
end
-
when :ie, :internet_explorer
-
IE::Bridge.new(opts)
-
when :chrome
-
Chrome::Bridge.new(opts)
-
when :edge
-
Edge::Bridge.new(opts)
-
when :android
-
Android::Bridge.new(opts)
-
when :iphone
-
IPhone::Bridge.new(opts)
-
when :phantomjs
-
PhantomJS::Bridge.new(opts)
-
when :safari
-
Safari::Bridge.new(opts)
-
else
-
raise ArgumentError, "unknown driver: #{browser.inspect}"
-
end
-
-
bridge = Support::EventFiringBridge.new(bridge, listener) if listener
-
-
new(bridge)
-
end
-
end
-
-
#
-
# A new Driver instance with the given bridge.
-
# End users should use Selenium::WebDriver.for instead of using this directly.
-
#
-
# @api private
-
#
-
-
2
def initialize(bridge)
-
@bridge = bridge
-
-
# TODO: refactor this away
-
unless bridge.driver_extensions.empty?
-
extend(*bridge.driver_extensions)
-
end
-
end
-
-
2
def inspect
-
'#<%s:0x%x browser=%s>' % [self.class, hash*2, bridge.browser.inspect]
-
end
-
-
#
-
# @return [Navigation]
-
# @see Navigation
-
#
-
-
2
def navigate
-
@navigate ||= WebDriver::Navigation.new(bridge)
-
end
-
-
#
-
# @return [TargetLocator]
-
# @see TargetLocator
-
#
-
-
2
def switch_to
-
@switch_to ||= WebDriver::TargetLocator.new(bridge)
-
end
-
-
#
-
# @return [Options]
-
# @see Options
-
#
-
-
2
def manage
-
@manage ||= WebDriver::Options.new(bridge)
-
end
-
-
#
-
# Opens the specified URL in the browser.
-
#
-
-
2
def get(url)
-
navigate.to(url)
-
end
-
-
#
-
# Get the URL of the current page
-
#
-
# @return [String]
-
#
-
-
2
def current_url
-
bridge.getCurrentUrl
-
end
-
-
#
-
# Get the title of the current page
-
#
-
# @return [String]
-
#
-
-
2
def title
-
bridge.getTitle
-
end
-
-
#
-
# Get the source of the current page
-
#
-
# @return [String]
-
#
-
-
2
def page_source
-
bridge.getPageSource
-
end
-
-
#
-
# Quit the browser
-
#
-
-
2
def quit
-
bridge.quit
-
end
-
-
#
-
# Close the current window, or the browser if no windows are left.
-
#
-
-
2
def close
-
bridge.close
-
end
-
-
#
-
# Get the window handles of open browser windows.
-
#
-
# @return [Array]
-
# @see TargetLocator#window
-
#
-
-
2
def window_handles
-
bridge.getWindowHandles
-
end
-
-
#
-
# Get the current window handle
-
#
-
# @return [String]
-
#
-
-
2
def window_handle
-
bridge.getCurrentWindowHandle
-
end
-
-
#
-
# Execute the given JavaScript
-
#
-
# @param [String] script
-
# JavaScript source to execute
-
# @param [WebDriver::Element,Integer, Float, Boolean, NilClass, String, Array] *args
-
# Arguments will be available in the given script in the 'arguments' pseudo-array.
-
#
-
# @return [WebDriver::Element,Integer,Float,Boolean,NilClass,String,Array]
-
# The value returned from the script.
-
#
-
-
2
def execute_script(script, *args)
-
bridge.executeScript(script, *args)
-
end
-
-
# Execute an asynchronous piece of JavaScript in the context of the
-
# currently selected frame or window. Unlike executing
-
# execute_script (synchronous JavaScript), scripts
-
# executed with this method must explicitly signal they are finished by
-
# invoking the provided callback. This callback is always injected into the
-
# executed function as the last argument.
-
#
-
# @param [String] script
-
# JavaScript source to execute
-
# @param [WebDriver::Element,Integer, Float, Boolean, NilClass, String, Array] *args
-
# Arguments to the script. May be empty.
-
#
-
# @return [WebDriver::Element,Integer,Float,Boolean,NilClass,String,Array]
-
#
-
-
2
def execute_async_script(script, *args)
-
bridge.executeAsyncScript(script, *args)
-
end
-
-
-
#-------------------------------- sugar --------------------------------
-
-
#
-
# driver.first(:id, 'foo')
-
#
-
-
2
alias_method :first, :find_element
-
-
#
-
# driver.all(:class, 'bar') #=> [#<WebDriver::Element:0x1011c3b88, ...]
-
#
-
-
2
alias_method :all, :find_elements
-
-
#
-
# driver.script('function() { ... };')
-
#
-
-
2
alias_method :script, :execute_script
-
-
# Get the first element matching the given selector. If given a
-
# String or Symbol, it will be used as the id of the element.
-
#
-
# @param [String,Hash] id or selector
-
# @return [WebDriver::Element]
-
#
-
# Examples:
-
#
-
# driver['someElementId'] #=> #<WebDriver::Element:0x1011c3b88>
-
# driver[:tag_name => 'div'] #=> #<WebDriver::Element:0x1011c3b88>
-
#
-
-
2
def [](sel)
-
if sel.kind_of?(String) || sel.kind_of?(Symbol)
-
sel = { :id => sel }
-
end
-
-
find_element sel
-
end
-
-
2
def browser
-
bridge.browser
-
end
-
-
2
def capabilities
-
bridge.capabilities
-
end
-
-
#
-
# @api private
-
# @see SearchContext
-
#
-
-
2
def ref
-
nil
-
end
-
-
2
private
-
-
2
def bridge
-
@bridge
-
end
-
-
end # Driver
-
end # WebDriver
-
end # Selenium
-
# encoding: utf-8
-
#
-
# Licensed to the Software Freedom Conservancy (SFC) under one
-
# or more contributor license agreements. See the NOTICE file
-
# distributed with this work for additional information
-
# regarding copyright ownership. The SFC licenses this file
-
# to you under the Apache License, Version 2.0 (the
-
# "License"); you may not use this file except in compliance
-
# with the License. You may obtain a copy of the License at
-
#
-
# http://www.apache.org/licenses/LICENSE-2.0
-
#
-
# Unless required by applicable law or agreed to in writing,
-
# software distributed under the License is distributed on an
-
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-
# KIND, either express or implied. See the License for the
-
# specific language governing permissions and limitations
-
# under the License.
-
-
2
module Selenium
-
2
module WebDriver
-
-
#
-
# @api private
-
#
-
-
2
module DriverExtensions
-
2
module HasInputDevices
-
-
#
-
# @return [ActionBuilder]
-
# @api public
-
#
-
-
2
def action
-
ActionBuilder.new mouse, keyboard
-
end
-
-
#
-
# @api private
-
#
-
-
2
def mouse
-
Mouse.new @bridge
-
end
-
-
#
-
# @api private
-
#
-
-
2
def keyboard
-
Keyboard.new @bridge
-
end
-
-
end # HasInputDevices
-
end # DriverExtensions
-
end # WebDriver
-
end # Selenium
-
# encoding: utf-8
-
#
-
# Licensed to the Software Freedom Conservancy (SFC) under one
-
# or more contributor license agreements. See the NOTICE file
-
# distributed with this work for additional information
-
# regarding copyright ownership. The SFC licenses this file
-
# to you under the Apache License, Version 2.0 (the
-
# "License"); you may not use this file except in compliance
-
# with the License. You may obtain a copy of the License at
-
#
-
# http://www.apache.org/licenses/LICENSE-2.0
-
#
-
# Unless required by applicable law or agreed to in writing,
-
# software distributed under the License is distributed on an
-
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-
# KIND, either express or implied. See the License for the
-
# specific language governing permissions and limitations
-
# under the License.
-
-
2
module Selenium
-
2
module WebDriver
-
2
module DriverExtensions
-
-
2
module HasLocation
-
2
def location
-
@bridge.getLocation
-
end
-
-
2
def location=(loc)
-
unless loc.kind_of?(Location)
-
raise TypeError, "expected #{Location}, got #{loc.inspect}:#{loc.class}"
-
end
-
-
@bridge.setLocation loc.latitude, loc.longitude, loc.altitude
-
end
-
-
2
def set_location(lat, lon, alt)
-
self.location = Location.new(Float(lat), Float(lon), Float(alt))
-
end
-
-
end #HasLocation
-
end # DriverExtensions
-
end # WebDriver
-
end # Selenium
-
# encoding: utf-8
-
#
-
# Licensed to the Software Freedom Conservancy (SFC) under one
-
# or more contributor license agreements. See the NOTICE file
-
# distributed with this work for additional information
-
# regarding copyright ownership. The SFC licenses this file
-
# to you under the Apache License, Version 2.0 (the
-
# "License"); you may not use this file except in compliance
-
# with the License. You may obtain a copy of the License at
-
#
-
# http://www.apache.org/licenses/LICENSE-2.0
-
#
-
# Unless required by applicable law or agreed to in writing,
-
# software distributed under the License is distributed on an
-
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-
# KIND, either express or implied. See the License for the
-
# specific language governing permissions and limitations
-
# under the License.
-
-
2
module Selenium
-
2
module WebDriver
-
2
module DriverExtensions
-
2
module HasNetworkConnection
-
2
def network_connection_type
-
connection_value = @bridge.getNetworkConnection
-
-
connection_type = values_to_type[connection_value]
-
-
# In case the connection type is not recognized return the
-
# connection value.
-
connection_type || connection_value
-
end
-
-
2
def network_connection_type=(connection_type)
-
raise ArgumentError, "Invalid connection type" unless valid_type? connection_type
-
-
connection_value = type_to_values[connection_type]
-
-
@bridge.setNetworkConnection connection_value
-
end
-
-
2
private
-
-
2
def type_to_values
-
{:airplane_mode => 1, :wifi => 2, :data => 4, :all => 6, :none => 0}
-
end
-
-
2
def values_to_type
-
type_to_values.invert
-
end
-
-
2
def valid_type?(type)
-
type_to_values.keys.include? type
-
end
-
-
end # HasNetworkConnection
-
end # DriverExtensions
-
end # WebDriver
-
end # Selenium
-
# encoding: utf-8
-
#
-
# Licensed to the Software Freedom Conservancy (SFC) under one
-
# or more contributor license agreements. See the NOTICE file
-
# distributed with this work for additional information
-
# regarding copyright ownership. The SFC licenses this file
-
# to you under the Apache License, Version 2.0 (the
-
# "License"); you may not use this file except in compliance
-
# with the License. You may obtain a copy of the License at
-
#
-
# http://www.apache.org/licenses/LICENSE-2.0
-
#
-
# Unless required by applicable law or agreed to in writing,
-
# software distributed under the License is distributed on an
-
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-
# KIND, either express or implied. See the License for the
-
# specific language governing permissions and limitations
-
# under the License.
-
-
2
module Selenium
-
2
module WebDriver
-
2
module DriverExtensions
-
2
module HasRemoteStatus
-
-
2
def remote_status
-
@bridge.status
-
end
-
-
end # HasRemoteStatus
-
end # DriverExtensions
-
end # WebDriver
-
end # Selenium
-
# encoding: utf-8
-
#
-
# Licensed to the Software Freedom Conservancy (SFC) under one
-
# or more contributor license agreements. See the NOTICE file
-
# distributed with this work for additional information
-
# regarding copyright ownership. The SFC licenses this file
-
# to you under the Apache License, Version 2.0 (the
-
# "License"); you may not use this file except in compliance
-
# with the License. You may obtain a copy of the License at
-
#
-
# http://www.apache.org/licenses/LICENSE-2.0
-
#
-
# Unless required by applicable law or agreed to in writing,
-
# software distributed under the License is distributed on an
-
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-
# KIND, either express or implied. See the License for the
-
# specific language governing permissions and limitations
-
# under the License.
-
-
2
module Selenium
-
2
module WebDriver
-
-
#
-
# @api private
-
#
-
-
2
module DriverExtensions
-
2
module HasSessionId
-
-
#
-
# @return [String] the session id
-
# @api public
-
#
-
-
2
def session_id
-
@bridge.session_id
-
end
-
end # HasSessionId
-
end # DriverExtensions
-
end # WebDriver
-
end # Selenium
-
# encoding: utf-8
-
#
-
# Licensed to the Software Freedom Conservancy (SFC) under one
-
# or more contributor license agreements. See the NOTICE file
-
# distributed with this work for additional information
-
# regarding copyright ownership. The SFC licenses this file
-
# to you under the Apache License, Version 2.0 (the
-
# "License"); you may not use this file except in compliance
-
# with the License. You may obtain a copy of the License at
-
#
-
# http://www.apache.org/licenses/LICENSE-2.0
-
#
-
# Unless required by applicable law or agreed to in writing,
-
# software distributed under the License is distributed on an
-
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-
# KIND, either express or implied. See the License for the
-
# specific language governing permissions and limitations
-
# under the License.
-
-
2
module Selenium
-
2
module WebDriver
-
2
module DriverExtensions
-
-
2
module HasTouchScreen
-
2
def touch
-
TouchActionBuilder.new mouse, keyboard, touch_screen
-
end
-
-
2
private
-
-
2
def touch_screen
-
TouchScreen.new @bridge
-
end
-
-
end # HasTouchScreen
-
end # DriverExtensions
-
end # WebDriver
-
end # Selenium
-
# encoding: utf-8
-
#
-
# Licensed to the Software Freedom Conservancy (SFC) under one
-
# or more contributor license agreements. See the NOTICE file
-
# distributed with this work for additional information
-
# regarding copyright ownership. The SFC licenses this file
-
# to you under the Apache License, Version 2.0 (the
-
# "License"); you may not use this file except in compliance
-
# with the License. You may obtain a copy of the License at
-
#
-
# http://www.apache.org/licenses/LICENSE-2.0
-
#
-
# Unless required by applicable law or agreed to in writing,
-
# software distributed under the License is distributed on an
-
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-
# KIND, either express or implied. See the License for the
-
# specific language governing permissions and limitations
-
# under the License.
-
-
2
module Selenium
-
2
module WebDriver
-
-
#
-
# @api private
-
#
-
-
2
module DriverExtensions
-
2
module HasWebStorage
-
-
2
def local_storage
-
HTML5::LocalStorage.new @bridge
-
end
-
-
2
def session_storage
-
HTML5::SessionStorage.new @bridge
-
end
-
-
end # HasWebStorage
-
end # DriverExtensions
-
end # WebDriver
-
end # Selenium
-
# encoding: utf-8
-
#
-
# Licensed to the Software Freedom Conservancy (SFC) under one
-
# or more contributor license agreements. See the NOTICE file
-
# distributed with this work for additional information
-
# regarding copyright ownership. The SFC licenses this file
-
# to you under the Apache License, Version 2.0 (the
-
# "License"); you may not use this file except in compliance
-
# with the License. You may obtain a copy of the License at
-
#
-
# http://www.apache.org/licenses/LICENSE-2.0
-
#
-
# Unless required by applicable law or agreed to in writing,
-
# software distributed under the License is distributed on an
-
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-
# KIND, either express or implied. See the License for the
-
# specific language governing permissions and limitations
-
# under the License.
-
-
2
module Selenium
-
2
module WebDriver
-
-
#
-
# @api private
-
#
-
-
2
module DriverExtensions
-
2
module Rotatable
-
-
2
ORIENTATIONS = [:landscape, :portrait]
-
-
#
-
# Change the screen orientation
-
#
-
# @param [:landscape, :portrait] Orientation
-
#
-
# @api public
-
#
-
-
2
def rotation=(orientation)
-
unless ORIENTATIONS.include?(orientation)
-
raise ArgumentError, "expected #{ORIENTATIONS.inspect}, got #{orientation.inspect}"
-
end
-
-
bridge.setScreenOrientation(orientation.to_s.upcase)
-
end
-
2
alias_method :rotate, :rotation=
-
-
#
-
# Get the current screen orientation
-
#
-
# @return [:landscape, :portrait] orientation
-
#
-
# @api public
-
#
-
-
2
def orientation
-
bridge.getScreenOrientation.to_sym.downcase
-
end
-
-
end # Rotatable
-
end # DriverExtensions
-
end # WebDriver
-
end # Selenium
-
# encoding: utf-8
-
#
-
# Licensed to the Software Freedom Conservancy (SFC) under one
-
# or more contributor license agreements. See the NOTICE file
-
# distributed with this work for additional information
-
# regarding copyright ownership. The SFC licenses this file
-
# to you under the Apache License, Version 2.0 (the
-
# "License"); you may not use this file except in compliance
-
# with the License. You may obtain a copy of the License at
-
#
-
# http://www.apache.org/licenses/LICENSE-2.0
-
#
-
# Unless required by applicable law or agreed to in writing,
-
# software distributed under the License is distributed on an
-
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-
# KIND, either express or implied. See the License for the
-
# specific language governing permissions and limitations
-
# under the License.
-
-
2
module Selenium
-
2
module WebDriver
-
-
#
-
# @api private
-
#
-
-
2
module DriverExtensions
-
2
module TakesScreenshot
-
-
#
-
# Save a PNG screenshot to the given path
-
#
-
# @api public
-
#
-
-
2
def save_screenshot(png_path)
-
File.open(png_path, 'wb') { |f| f << screenshot_as(:png) }
-
end
-
-
#
-
# Return a PNG screenshot in the given format as a string
-
#
-
# @param [:base64, :png] format
-
# @return String screenshot
-
#
-
# @api public
-
-
2
def screenshot_as(format)
-
case format
-
when :base64
-
bridge.getScreenshot
-
when :png
-
bridge.getScreenshot.unpack("m")[0]
-
else
-
raise Error::UnsupportedOperationError, "unsupported format: #{format.inspect}"
-
end
-
end
-
-
end # TakesScreenshot
-
end # DriverExtensions
-
end # WebDriver
-
end # Selenium
-
# encoding: utf-8
-
#
-
# Licensed to the Software Freedom Conservancy (SFC) under one
-
# or more contributor license agreements. See the NOTICE file
-
# distributed with this work for additional information
-
# regarding copyright ownership. The SFC licenses this file
-
# to you under the Apache License, Version 2.0 (the
-
# "License"); you may not use this file except in compliance
-
# with the License. You may obtain a copy of the License at
-
#
-
# http://www.apache.org/licenses/LICENSE-2.0
-
#
-
# Unless required by applicable law or agreed to in writing,
-
# software distributed under the License is distributed on an
-
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-
# KIND, either express or implied. See the License for the
-
# specific language governing permissions and limitations
-
# under the License.
-
-
2
module Selenium
-
2
module WebDriver
-
-
#
-
# @api private
-
#
-
-
2
module DriverExtensions
-
2
module UploadsFiles
-
-
#
-
# Set the file detector to pass local files to a remote WebDriver.
-
#
-
# The detector is an object that responds to #call, and when called
-
# will determine if the given string represents a file. If it does,
-
# the path to the file on the local file system should be returned,
-
# otherwise nil or false.
-
#
-
# Example:
-
#
-
# driver = Selenium::WebDriver.for :remote
-
# driver.file_detector = lambda do |args|
-
# # args => ["/path/to/file"]
-
# str = args.first.to_s
-
# str if File.exist?(str)
-
# end
-
#
-
# driver.find_element(:id => "upload").send_keys "/path/to/file"
-
#
-
# By default, no file detection is performed.
-
#
-
# @api public
-
#
-
-
2
def file_detector=(detector)
-
unless detector.nil? or detector.respond_to? :call
-
raise ArgumentError, "detector must respond to #call"
-
end
-
-
bridge.file_detector = detector
-
end
-
-
end # UploadsFiles
-
end # DriverExtensions
-
end # WebDriver
-
end # Selenium
-
# encoding: utf-8
-
#
-
# Licensed to the Software Freedom Conservancy (SFC) under one
-
# or more contributor license agreements. See the NOTICE file
-
# distributed with this work for additional information
-
# regarding copyright ownership. The SFC licenses this file
-
# to you under the Apache License, Version 2.0 (the
-
# "License"); you may not use this file except in compliance
-
# with the License. You may obtain a copy of the License at
-
#
-
# http://www.apache.org/licenses/LICENSE-2.0
-
#
-
# Unless required by applicable law or agreed to in writing,
-
# software distributed under the License is distributed on an
-
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-
# KIND, either express or implied. See the License for the
-
# specific language governing permissions and limitations
-
# under the License.
-
-
2
module Selenium
-
2
module WebDriver
-
2
class Element
-
2
include SearchContext
-
-
#
-
# Creates a new Element
-
#
-
# @api private
-
#
-
-
2
def initialize(bridge, id)
-
@bridge, @id = bridge, id
-
end
-
-
2
def inspect
-
'#<%s:0x%x id=%s>' % [self.class, hash*2, @id.inspect]
-
end
-
-
2
def ==(other)
-
other.kind_of?(self.class) && ref == other.ref
-
end
-
2
alias_method :eql?, :==
-
-
2
def hash
-
@id.hash ^ @bridge.hash
-
end
-
-
#
-
# Click this element. If this causes a new page to load, this method will
-
# attempt to block until the page has loaded. At this point, you should
-
# discard all references to this element and any further operations
-
# performed on this element will raise a StaleElementReferenceError
-
# unless you know that the element and the page will still be present. If
-
# click() causes a new page to be loaded via an event or is done by
-
# sending a native event then the method will *not* wait for it to be
-
# loaded and the caller should verify that a new page has been loaded.
-
#
-
# There are some preconditions for an element to be clicked. The element
-
# must be visible and it must have a height and width greater then 0.
-
#
-
# Equivalent to:
-
# driver.action.click(element)
-
#
-
# @example Click on a button
-
#
-
# driver.find_element(:tag_name, "button").click
-
#
-
# @raise [StaleElementReferenceError] if the element no longer exists as
-
# defined
-
#
-
-
2
def click
-
bridge.clickElement @id
-
end
-
-
#
-
# Get the tag name of the element.
-
#
-
# @example Get the tagname of an INPUT element(returns "input")
-
#
-
# driver.find_element(:xpath, "//input").tag_name
-
#
-
# @return [String] The tag name of this element.
-
#
-
-
2
def tag_name
-
bridge.getElementTagName @id
-
end
-
-
#
-
# Get the value of a the given attribute of the element. Will return the current value, even if
-
# this has been modified after the page has been loaded. More exactly, this method will return
-
# the value of the given attribute, unless that attribute is not present, in which case the
-
# value of the property with the same name is returned. If neither value is set, nil is
-
# returned. The "style" attribute is converted as best can be to a text representation with a
-
# trailing semi-colon. The following are deemed to be "boolean" attributes, and will
-
# return either "true" or "false":
-
#
-
# async, autofocus, autoplay, checked, compact, complete, controls, declare, defaultchecked,
-
# defaultselected, defer, disabled, draggable, ended, formnovalidate, hidden, indeterminate,
-
# iscontenteditable, ismap, itemscope, loop, multiple, muted, nohref, noresize, noshade, novalidate,
-
# nowrap, open, paused, pubdate, readonly, required, reversed, scoped, seamless, seeking,
-
# selected, spellcheck, truespeed, willvalidate
-
#
-
# Finally, the following commonly mis-capitalized attribute/property names are evaluated as
-
# expected:
-
#
-
# class, readonly
-
#
-
# @param [String]
-
# attribute name
-
# @return [String,nil]
-
# attribute value
-
#
-
-
2
def attribute(name)
-
bridge.getElementAttribute @id, name
-
end
-
-
#
-
# Get the text content of this element
-
#
-
# @return [String]
-
#
-
-
2
def text
-
bridge.getElementText @id
-
end
-
-
#
-
# Send keystrokes to this element
-
#
-
# @param [String, Symbol, Array]
-
#
-
# Examples:
-
#
-
# element.send_keys "foo" #=> value: 'foo'
-
# element.send_keys "tet", :arrow_left, "s" #=> value: 'test'
-
# element.send_keys [:control, 'a'], :space #=> value: ' '
-
#
-
# @see Keys::KEYS
-
#
-
-
2
def send_keys(*args)
-
bridge.sendKeysToElement @id, Keys.encode(args)
-
end
-
2
alias_method :send_key, :send_keys
-
-
#
-
# If this element is a text entry element, this will clear the value. Has no effect on other
-
# elements. Text entry elements are INPUT and TEXTAREA elements.
-
#
-
# Note that the events fired by this event may not be as you'd expect. In particular, we don't
-
# fire any keyboard or mouse events. If you want to ensure keyboard events are
-
# fired, consider using #send_keys with the backspace key. To ensure you get a change event,
-
# consider following with a call to #send_keys with the tab key.
-
#
-
-
2
def clear
-
bridge.clearElement @id
-
end
-
-
#
-
# Is the element enabled?
-
#
-
# @return [Boolean]
-
#
-
-
2
def enabled?
-
bridge.isElementEnabled @id
-
end
-
-
#
-
# Is the element selected?
-
#
-
# @return [Boolean]
-
#
-
-
2
def selected?
-
bridge.isElementSelected @id
-
end
-
-
#
-
# Is the element displayed?
-
#
-
# @return [Boolean]
-
#
-
-
2
def displayed?
-
bridge.isElementDisplayed @id
-
end
-
-
#
-
# Submit this element
-
#
-
-
2
def submit
-
bridge.submitElement @id
-
end
-
-
#
-
# Get the value of the given CSS property
-
#
-
# Note that shorthand CSS properties (e.g. background, font, border, border-top, margin,
-
# margin-top, padding, padding-top, list-style, outline, pause, cue) are not returned,
-
# in accordance with the DOM CSS2 specification - you should directly access the longhand
-
# properties (e.g. background-color) to access the desired values.
-
#
-
# @see http://www.w3.org/TR/DOM-Level-2-Style/css.html#CSS-CSSStyleDeclaration
-
#
-
-
2
def css_value(prop)
-
bridge.getElementValueOfCssProperty @id, prop
-
end
-
2
alias_method :style, :css_value
-
-
#
-
# Get the location of this element.
-
#
-
# @return [WebDriver::Point]
-
#
-
-
2
def location
-
bridge.getElementLocation @id
-
end
-
-
#
-
# Determine an element's location on the screen once it has been scrolled into view.
-
#
-
# @return [WebDriver::Point]
-
#
-
-
2
def location_once_scrolled_into_view
-
bridge.getElementLocationOnceScrolledIntoView @id
-
end
-
-
#
-
# Get the size of this element
-
#
-
# @return [WebDriver::Dimension]
-
#
-
-
2
def size
-
bridge.getElementSize @id
-
end
-
-
#-------------------------------- sugar --------------------------------
-
-
#
-
# element.first(:id, 'foo')
-
#
-
-
2
alias_method :first, :find_element
-
-
#
-
# element.all(:class, 'bar')
-
#
-
-
2
alias_method :all, :find_elements
-
-
#
-
# element['class'] or element[:class] #=> "someclass"
-
#
-
2
alias_method :[], :attribute
-
-
#
-
# for SearchContext and execute_script
-
#
-
# @api private
-
#
-
-
2
def ref
-
@id
-
end
-
-
#
-
# Convert to a WebElement JSON Object for transmission over the wire.
-
# @see https://github.com/SeleniumHQ/selenium/wiki/JsonWireProtocol#basic-terms-and-concepts
-
#
-
# @api private
-
#
-
-
2
def to_json(*args)
-
JSON.generate as_json
-
end
-
-
#
-
# For Rails 3 - http://jonathanjulian.com/2010/04/rails-to_json-or-as_json/
-
#
-
# @api private
-
#
-
-
2
def as_json(opts = nil)
-
{
-
:ELEMENT => @id,
-
"element-6066-11e4-a52e-4f735466cecf" => @id
-
}
-
end
-
-
2
private
-
-
2
def bridge
-
@bridge
-
end
-
-
2
def selectable?
-
tn = tag_name.downcase
-
type = attribute(:type).to_s.downcase
-
-
tn == "option" || (tn == "input" && %w[radio checkbox].include?(type))
-
end
-
-
end # Element
-
end # WebDriver
-
end # Selenium
-
# encoding: utf-8
-
#
-
# Licensed to the Software Freedom Conservancy (SFC) under one
-
# or more contributor license agreements. See the NOTICE file
-
# distributed with this work for additional information
-
# regarding copyright ownership. The SFC licenses this file
-
# to you under the Apache License, Version 2.0 (the
-
# "License"); you may not use this file except in compliance
-
# with the License. You may obtain a copy of the License at
-
#
-
# http://www.apache.org/licenses/LICENSE-2.0
-
#
-
# Unless required by applicable law or agreed to in writing,
-
# software distributed under the License is distributed on an
-
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-
# KIND, either express or implied. See the License for the
-
# specific language governing permissions and limitations
-
# under the License.
-
-
2
module Selenium
-
2
module WebDriver
-
2
module Error
-
-
2
class WebDriverError < StandardError; end
-
2
class UnsupportedOperationError < WebDriverError; end
-
-
2
class IndexOutOfBoundsError < WebDriverError; end # 1
-
2
class NoCollectionError < WebDriverError; end # 2
-
2
class NoStringError < WebDriverError; end # 3
-
2
class NoStringLengthError < WebDriverError; end # 4
-
2
class NoStringWrapperError < WebDriverError; end # 5
-
2
class NoSuchDriverError < WebDriverError; end # 6
-
-
#
-
# An element could not be located on the page using the given search
-
# parameters.
-
#
-
-
2
class NoSuchElementError < WebDriverError; end # 7
-
-
#
-
# A request to switch to a frame could not be satisfied because the
-
# frame could not be found.
-
#
-
-
2
class NoSuchFrameError < WebDriverError; end # 8
-
2
class UnknownCommandError < WebDriverError; end # 9
-
-
-
#
-
# Indicates that a reference to an element is now "stale" - the element
-
# no longer appears in the DOM of the page.
-
#
-
-
2
class StaleElementReferenceError < WebDriverError; end # 10
-
-
#
-
# Raised to indicate that although an element is present on the DOM,
-
# it is not visible, and so is not able to be interacted with.
-
#
-
-
2
class ElementNotVisibleError < WebDriverError; end # 11
-
-
#
-
# Raised when an interaction could not be performed because the element
-
# is in an invalid state (e.g. attempting to click a disabled element).
-
#
-
-
2
class InvalidElementStateError < WebDriverError; end # 12
-
-
#
-
# An unknown server-side error occurred while processing the command.
-
#
-
-
2
class UnknownError < WebDriverError; end # 13
-
2
class ExpectedError < WebDriverError; end # 14
-
-
#
-
# An attempt was made to select an element that cannot be selected.
-
#
-
-
2
class ElementNotSelectableError < WebDriverError; end # 15
-
2
class NoSuchDocumentError < WebDriverError; end # 16
-
-
#
-
# An error occurred while executing user supplied JavaScript.
-
#
-
-
2
class JavascriptError < WebDriverError; end # 17
-
2
class NoScriptResultError < WebDriverError; end # 18
-
-
#
-
# An error occurred while searching for an element by XPath.
-
#
-
-
2
class XPathLookupError < WebDriverError; end # 19
-
2
class NoSuchCollectionError < WebDriverError; end # 20
-
-
#
-
# Raised when a command does not complete in enough time.
-
#
-
-
2
class TimeOutError < WebDriverError; end # 21
-
2
class NullPointerError < WebDriverError; end # 22
-
2
class NoSuchWindowError < WebDriverError; end # 23
-
-
#
-
# Raised when attempting to add a cookie under a different domain than
-
# the current URL.
-
#
-
-
2
class InvalidCookieDomainError < WebDriverError; end # 24
-
-
#
-
# Raised when a driver fails to set a cookie.
-
#
-
-
2
class UnableToSetCookieError < WebDriverError; end # 25
-
-
#
-
# Raised when an alert dialog is present that has not been dealt with.
-
#
-
2
class UnhandledAlertError < WebDriverError; end # 26
-
-
#
-
# Indicates that a user has tried to access an alert when one is not present.
-
#
-
-
2
class NoAlertPresentError < WebDriverError; end # 27
-
-
#
-
# A script did not complete before its timeout expired.
-
#
-
-
2
class ScriptTimeOutError < WebDriverError; end # 28
-
-
#
-
# The coordinates provided to an interactions operation are invalid.
-
#
-
-
2
class InvalidElementCoordinatesError < WebDriverError; end # 29
-
-
#
-
# Indicates that IME support is not available. This exception is rasied
-
# for every IME-related method call if IME support is not available on
-
# the machine.
-
#
-
-
2
class IMENotAvailableError < WebDriverError; end # 30
-
-
#
-
# Indicates that activating an IME engine has failed.
-
#
-
-
2
class IMEEngineActivationFailedError < WebDriverError; end # 31
-
-
#
-
# Argument was an invalid selector (e.g. XPath/CSS).
-
#
-
-
2
class InvalidSelectorError < WebDriverError; end # 32
-
-
#
-
# A new session could not be created.
-
#
-
-
2
class SessionNotCreatedError < WebDriverError; end # 33
-
-
#
-
# Indicates that the target provided to the actions #move method is
-
# invalid, e.g. outside of the bounds of the window.
-
#
-
-
2
class MoveTargetOutOfBoundsError < WebDriverError; end # 34
-
-
# @api private
-
2
Errors = [
-
IndexOutOfBoundsError, # 1
-
NoCollectionError, # 2
-
NoStringError, # 3
-
NoStringLengthError, # 4
-
NoStringWrapperError, # 5
-
NoSuchDriverError, # 6
-
NoSuchElementError, # 7
-
NoSuchFrameError, # 8
-
UnknownCommandError, # 9
-
StaleElementReferenceError, # 10
-
ElementNotVisibleError, # 11
-
InvalidElementStateError, # 12
-
UnknownError, # 13
-
ExpectedError, # 14
-
ElementNotSelectableError, # 15
-
NoSuchDocumentError, # 16
-
JavascriptError, # 17
-
NoScriptResultError, # 18
-
XPathLookupError, # 19
-
NoSuchCollectionError, # 20
-
TimeOutError, # 21
-
NullPointerError, # 22
-
NoSuchWindowError, # 23
-
InvalidCookieDomainError, # 24
-
UnableToSetCookieError, # 25
-
UnhandledAlertError, # 26
-
NoAlertPresentError, # 27
-
ScriptTimeOutError, # 28
-
InvalidElementCoordinatesError, # 29
-
IMENotAvailableError, # 30
-
IMEEngineActivationFailedError, # 31
-
InvalidSelectorError, # 32
-
SessionNotCreatedError, # 33
-
MoveTargetOutOfBoundsError # 34
-
]
-
-
2
class << self
-
2
def for_code(code)
-
return if [nil, 0].include? code
-
return Errors[code - 1] if code.is_a? Fixnum
-
-
klass_name = code.split(' ').map(&:capitalize).join
-
Error.const_get("#{klass_name.gsub('Error','')}Error")
-
rescue NameError
-
WebDriverError
-
end
-
end
-
-
end # Error
-
end # WebDriver
-
end # Selenium
-
# encoding: utf-8
-
#
-
# Licensed to the Software Freedom Conservancy (SFC) under one
-
# or more contributor license agreements. See the NOTICE file
-
# distributed with this work for additional information
-
# regarding copyright ownership. The SFC licenses this file
-
# to you under the Apache License, Version 2.0 (the
-
# "License"); you may not use this file except in compliance
-
# with the License. You may obtain a copy of the License at
-
#
-
# http://www.apache.org/licenses/LICENSE-2.0
-
#
-
# Unless required by applicable law or agreed to in writing,
-
# software distributed under the License is distributed on an
-
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-
# KIND, either express or implied. See the License for the
-
# specific language governing permissions and limitations
-
# under the License.
-
-
2
module Selenium
-
2
module WebDriver
-
-
#
-
# @api private
-
#
-
-
2
module FileReaper
-
-
2
class << self
-
2
def reap=(bool)
-
@reap = bool
-
end
-
-
2
def reap?
-
2
@reap = true unless defined?(@reap)
-
2
!!@reap
-
end
-
-
2
def tmp_files
-
4
@tmp_files ||= Hash.new { |hash, pid| hash[pid] = [] }
-
2
@tmp_files[Process.pid]
-
end
-
-
2
def <<(file)
-
tmp_files << file
-
end
-
-
2
def reap(file)
-
return unless reap?
-
-
unless tmp_files.include?(file)
-
raise Error::WebDriverError, "file not added for reaping: #{file.inspect}"
-
end
-
-
FileUtils.rm_rf tmp_files.delete(file)
-
end
-
-
2
def reap!
-
2
if reap?
-
2
tmp_files.each { |file| FileUtils.rm_rf(file) }
-
2
true
-
else
-
false
-
end
-
end
-
end
-
-
# we *do* want child process reaping, so not using Platform.exit_hook here.
-
4
at_exit { reap! }
-
-
end # FileReaper
-
end # WebDriver
-
end # Selenium
-
# encoding: utf-8
-
#
-
# Licensed to the Software Freedom Conservancy (SFC) under one
-
# or more contributor license agreements. See the NOTICE file
-
# distributed with this work for additional information
-
# regarding copyright ownership. The SFC licenses this file
-
# to you under the Apache License, Version 2.0 (the
-
# "License"); you may not use this file except in compliance
-
# with the License. You may obtain a copy of the License at
-
#
-
# http://www.apache.org/licenses/LICENSE-2.0
-
#
-
# Unless required by applicable law or agreed to in writing,
-
# software distributed under the License is distributed on an
-
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-
# KIND, either express or implied. See the License for the
-
# specific language governing permissions and limitations
-
# under the License.
-
-
2
module Selenium
-
2
module WebDriver
-
2
module HTML5
-
-
2
class LocalStorage
-
2
include SharedWebStorage
-
-
#
-
# @api private
-
#
-
2
def initialize(bridge)
-
@bridge = bridge
-
end
-
-
2
def [](key)
-
@bridge.getLocalStorageItem key
-
end
-
-
2
def []=(key, value)
-
@bridge.setLocalStorageItem key, value
-
end
-
-
2
def delete(key)
-
@bridge.removeLocalStorageItem key
-
end
-
-
2
def clear
-
@bridge.clearLocalStorage
-
end
-
-
2
def size
-
@bridge.getLocalStorageSize
-
end
-
-
2
def keys
-
@bridge.getLocalStorageKeys.reverse
-
end
-
-
end # LocalStorage
-
end # HTML5
-
end # WebDriver
-
end # Selenium
-
# encoding: utf-8
-
#
-
# Licensed to the Software Freedom Conservancy (SFC) under one
-
# or more contributor license agreements. See the NOTICE file
-
# distributed with this work for additional information
-
# regarding copyright ownership. The SFC licenses this file
-
# to you under the Apache License, Version 2.0 (the
-
# "License"); you may not use this file except in compliance
-
# with the License. You may obtain a copy of the License at
-
#
-
# http://www.apache.org/licenses/LICENSE-2.0
-
#
-
# Unless required by applicable law or agreed to in writing,
-
# software distributed under the License is distributed on an
-
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-
# KIND, either express or implied. See the License for the
-
# specific language governing permissions and limitations
-
# under the License.
-
-
2
module Selenium
-
2
module WebDriver
-
2
module HTML5
-
-
2
class SessionStorage
-
2
include Enumerable
-
2
include SharedWebStorage
-
-
2
def [](key)
-
@bridge.getSessionStorageItem key
-
end
-
-
2
def []=(key, value)
-
@bridge.setSessionStorageItem key, value
-
end
-
-
2
def delete(key)
-
@bridge.removeSessionStorageItem key
-
end
-
-
2
def clear
-
@bridge.clearSessionStorage
-
end
-
-
2
def size
-
@bridge.getSessionStorageSize
-
end
-
-
2
def keys
-
@bridge.getSessionStorageKeys.reverse
-
end
-
-
#
-
# @api private
-
#
-
-
2
def initialize(bridge)
-
@bridge = bridge
-
end
-
-
end # SessionStorage
-
end # HTML5
-
end # WebDriver
-
end # Selenium
-
# encoding: utf-8
-
#
-
# Licensed to the Software Freedom Conservancy (SFC) under one
-
# or more contributor license agreements. See the NOTICE file
-
# distributed with this work for additional information
-
# regarding copyright ownership. The SFC licenses this file
-
# to you under the Apache License, Version 2.0 (the
-
# "License"); you may not use this file except in compliance
-
# with the License. You may obtain a copy of the License at
-
#
-
# http://www.apache.org/licenses/LICENSE-2.0
-
#
-
# Unless required by applicable law or agreed to in writing,
-
# software distributed under the License is distributed on an
-
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-
# KIND, either express or implied. See the License for the
-
# specific language governing permissions and limitations
-
# under the License.
-
-
2
module Selenium
-
2
module WebDriver
-
2
module HTML5
-
-
2
module SharedWebStorage
-
2
include Enumerable
-
-
2
def key?(key)
-
keys.include? key
-
end
-
2
alias_method :member?, :key?
-
2
alias_method :has_key?, :key?
-
-
2
def fetch(key, &blk)
-
if self.key? key
-
return self[key]
-
end
-
-
if block_given?
-
yield key
-
else
-
# should be KeyError, but it's 1.9-specific
-
raise IndexError, "missing key #{key.inspect}"
-
end
-
end
-
-
2
def empty?
-
size == 0
-
end
-
-
2
def each(&blk)
-
return enum_for(:each) unless block_given?
-
-
keys.each do |k|
-
yield k, self[k]
-
end
-
end
-
-
end # SharedWebStorage
-
end # HTML5
-
end # WebDriver
-
end # Selenium
-
# encoding: utf-8
-
#
-
# Licensed to the Software Freedom Conservancy (SFC) under one
-
# or more contributor license agreements. See the NOTICE file
-
# distributed with this work for additional information
-
# regarding copyright ownership. The SFC licenses this file
-
# to you under the Apache License, Version 2.0 (the
-
# "License"); you may not use this file except in compliance
-
# with the License. You may obtain a copy of the License at
-
#
-
# http://www.apache.org/licenses/LICENSE-2.0
-
#
-
# Unless required by applicable law or agreed to in writing,
-
# software distributed under the License is distributed on an
-
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-
# KIND, either express or implied. See the License for the
-
# specific language governing permissions and limitations
-
# under the License.
-
-
2
module Selenium
-
2
module WebDriver
-
-
#
-
# @api private
-
# @see ActionBuilder
-
-
2
class Keyboard
-
-
2
def initialize(bridge)
-
@bridge = bridge
-
end
-
-
2
def send_keys(*keys)
-
@bridge.sendKeysToActiveElement Keys.encode(keys)
-
end
-
-
#
-
# Press a modifier key
-
#
-
# @see Selenium::WebDriver::Keys
-
#
-
-
2
def press(key)
-
assert_modifier key
-
-
@bridge.sendKeysToActiveElement Keys.encode([key])
-
end
-
-
#
-
# Release a modifier key
-
#
-
# @see Selenium::WebDriver::Keys
-
#
-
-
2
def release(key)
-
assert_modifier key
-
-
@bridge.sendKeysToActiveElement Keys.encode([key])
-
end
-
-
2
private
-
-
2
MODIFIERS = [:control, :shift, :alt, :command, :meta]
-
-
2
def assert_modifier(key)
-
unless MODIFIERS.include? key
-
raise ArgumentError,
-
"#{key.inspect} is not a modifier key, expected one of #{MODIFIERS.inspect}"
-
end
-
end
-
-
end # Keyboard
-
end # WebDriver
-
end # Selenium
-
# encoding: utf-8
-
#
-
# Licensed to the Software Freedom Conservancy (SFC) under one
-
# or more contributor license agreements. See the NOTICE file
-
# distributed with this work for additional information
-
# regarding copyright ownership. The SFC licenses this file
-
# to you under the Apache License, Version 2.0 (the
-
# "License"); you may not use this file except in compliance
-
# with the License. You may obtain a copy of the License at
-
#
-
# http://www.apache.org/licenses/LICENSE-2.0
-
#
-
# Unless required by applicable law or agreed to in writing,
-
# software distributed under the License is distributed on an
-
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-
# KIND, either express or implied. See the License for the
-
# specific language governing permissions and limitations
-
# under the License.
-
-
2
module Selenium
-
2
module WebDriver
-
2
module Keys
-
-
#
-
# @see Element#send_keys
-
# @see http://www.google.com.au/search?&q=unicode+pua&btnG=Search
-
#
-
-
2
KEYS = {
-
# \x works on both 1.8.6/1.9
-
:null => "\xEE\x80\x80",
-
:cancel => "\xEE\x80\x81",
-
:help => "\xEE\x80\x82",
-
:backspace => "\xEE\x80\x83",
-
:tab => "\xEE\x80\x84",
-
:clear => "\xEE\x80\x85",
-
:return => "\xEE\x80\x86",
-
:enter => "\xEE\x80\x87",
-
:shift => "\xEE\x80\x88",
-
:left_shift => "\xEE\x80\x88",
-
:control => "\xEE\x80\x89",
-
:left_control => "\xEE\x80\x89",
-
:alt => "\xEE\x80\x8A",
-
:left_alt => "\xEE\x80\x8A",
-
:pause => "\xEE\x80\x8B",
-
:escape => "\xEE\x80\x8C",
-
:space => "\xEE\x80\x8D",
-
:page_up => "\xEE\x80\x8E",
-
:page_down => "\xEE\x80\x8F",
-
:end => "\xEE\x80\x90",
-
:home => "\xEE\x80\x91",
-
:left => "\xEE\x80\x92",
-
:arrow_left => "\xEE\x80\x92",
-
:up => "\xEE\x80\x93",
-
:arrow_up => "\xEE\x80\x93",
-
:right => "\xEE\x80\x94",
-
:arrow_right => "\xEE\x80\x94",
-
:down => "\xEE\x80\x95",
-
:arrow_down => "\xEE\x80\x95",
-
:insert => "\xEE\x80\x96",
-
:delete => "\xEE\x80\x97",
-
:semicolon => "\xEE\x80\x98",
-
:equals => "\xEE\x80\x99",
-
:numpad0 => "\xEE\x80\x9A",
-
:numpad1 => "\xEE\x80\x9B",
-
:numpad2 => "\xEE\x80\x9C",
-
:numpad3 => "\xEE\x80\x9D",
-
:numpad4 => "\xEE\x80\x9E",
-
:numpad5 => "\xEE\x80\x9F",
-
:numpad6 => "\xEE\x80\xA0",
-
:numpad7 => "\xEE\x80\xA1",
-
:numpad8 => "\xEE\x80\xA2",
-
:numpad9 => "\xEE\x80\xA3",
-
:multiply => "\xEE\x80\xA4",
-
:add => "\xEE\x80\xA5",
-
:separator => "\xEE\x80\xA6",
-
:subtract => "\xEE\x80\xA7",
-
:decimal => "\xEE\x80\xA8",
-
:divide => "\xEE\x80\xA9",
-
:f1 => "\xEE\x80\xB1",
-
:f2 => "\xEE\x80\xB2",
-
:f3 => "\xEE\x80\xB3",
-
:f4 => "\xEE\x80\xB4",
-
:f5 => "\xEE\x80\xB5",
-
:f6 => "\xEE\x80\xB6",
-
:f7 => "\xEE\x80\xB7",
-
:f8 => "\xEE\x80\xB8",
-
:f9 => "\xEE\x80\xB9",
-
:f10 => "\xEE\x80\xBA",
-
:f11 => "\xEE\x80\xBB",
-
:f12 => "\xEE\x80\xBC",
-
:meta => "\xEE\x80\xBD",
-
:command => "\xEE\x80\xBD" # alias
-
}
-
-
#
-
# @api private
-
#
-
-
2
def self.[](key)
-
KEYS[key] or raise Error::UnsupportedOperationError, "no such key #{key.inspect}"
-
end
-
-
#
-
# @api private
-
#
-
-
2
def self.encode(keys)
-
keys.map do |arg|
-
case arg
-
when Symbol
-
Keys[arg]
-
when Array
-
arg = arg.map { |e| e.kind_of?(Symbol) ? Keys[e] : e }.join
-
arg << Keys[:null]
-
-
arg
-
else
-
arg.to_s
-
end
-
end
-
end
-
-
end # Keys
-
end # WebDriver
-
end # Selenium
-
# encoding: utf-8
-
#
-
# Licensed to the Software Freedom Conservancy (SFC) under one
-
# or more contributor license agreements. See the NOTICE file
-
# distributed with this work for additional information
-
# regarding copyright ownership. The SFC licenses this file
-
# to you under the Apache License, Version 2.0 (the
-
# "License"); you may not use this file except in compliance
-
# with the License. You may obtain a copy of the License at
-
#
-
# http://www.apache.org/licenses/LICENSE-2.0
-
#
-
# Unless required by applicable law or agreed to in writing,
-
# software distributed under the License is distributed on an
-
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-
# KIND, either express or implied. See the License for the
-
# specific language governing permissions and limitations
-
# under the License.
-
-
2
module Selenium
-
2
module WebDriver
-
2
class LogEntry
-
2
attr_reader :level, :timestamp, :message
-
-
2
def initialize(level, timestamp, message)
-
@level = level
-
@timestamp = timestamp
-
@message = message
-
end
-
-
2
def as_json(opts = nil)
-
{
-
'level' => level,
-
'timestamp' => timestamp,
-
'message' => message
-
}
-
end
-
-
2
def to_s
-
"#{level} #{time}: #{message}"
-
end
-
-
2
def time
-
Time.at timestamp / 1000
-
end
-
-
end # LogEntry
-
end # WebDriver
-
end # Selenium
-
# encoding: utf-8
-
#
-
# Licensed to the Software Freedom Conservancy (SFC) under one
-
# or more contributor license agreements. See the NOTICE file
-
# distributed with this work for additional information
-
# regarding copyright ownership. The SFC licenses this file
-
# to you under the Apache License, Version 2.0 (the
-
# "License"); you may not use this file except in compliance
-
# with the License. You may obtain a copy of the License at
-
#
-
# http://www.apache.org/licenses/LICENSE-2.0
-
#
-
# Unless required by applicable law or agreed to in writing,
-
# software distributed under the License is distributed on an
-
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-
# KIND, either express or implied. See the License for the
-
# specific language governing permissions and limitations
-
# under the License.
-
-
2
module Selenium
-
2
module WebDriver
-
2
class Logs
-
-
#
-
# @api private
-
#
-
-
2
def initialize(bridge)
-
@bridge = bridge
-
end
-
-
2
def get(type)
-
@bridge.getLog type
-
end
-
-
2
def available_types
-
@bridge.getAvailableLogTypes
-
end
-
-
end # Logs
-
end # WebDriver
-
end # Selenium
-
# encoding: utf-8
-
#
-
# Licensed to the Software Freedom Conservancy (SFC) under one
-
# or more contributor license agreements. See the NOTICE file
-
# distributed with this work for additional information
-
# regarding copyright ownership. The SFC licenses this file
-
# to you under the Apache License, Version 2.0 (the
-
# "License"); you may not use this file except in compliance
-
# with the License. You may obtain a copy of the License at
-
#
-
# http://www.apache.org/licenses/LICENSE-2.0
-
#
-
# Unless required by applicable law or agreed to in writing,
-
# software distributed under the License is distributed on an
-
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-
# KIND, either express or implied. See the License for the
-
# specific language governing permissions and limitations
-
# under the License.
-
-
2
module Selenium
-
2
module WebDriver
-
-
#
-
# @api private
-
# @see ActionBuilder
-
#
-
-
2
class Mouse
-
-
2
def initialize(bridge)
-
@bridge = bridge
-
end
-
-
2
def click(element = nil)
-
move_if_needed element
-
@bridge.click
-
end
-
-
2
def double_click(element = nil)
-
move_if_needed element
-
@bridge.doubleClick
-
end
-
-
2
def context_click(element = nil)
-
move_if_needed element
-
@bridge.contextClick
-
end
-
-
2
def down(element = nil)
-
move_if_needed element
-
@bridge.mouseDown
-
end
-
-
2
def up(element = nil)
-
move_if_needed element
-
@bridge.mouseUp
-
end
-
-
#
-
# Move the mouse.
-
#
-
# Examples:
-
#
-
# driver.mouse.move_to(element)
-
# driver.mouse.move_to(element, 5, 5)
-
#
-
-
2
def move_to(element, right_by = nil, down_by = nil)
-
assert_element element
-
-
@bridge.mouseMoveTo element.ref, right_by, down_by
-
end
-
-
2
def move_by(right_by, down_by)
-
@bridge.mouseMoveTo nil, Integer(right_by), Integer(down_by)
-
end
-
-
2
private
-
-
2
def move_if_needed(element)
-
move_to element if element
-
end
-
-
2
def assert_element(element)
-
unless element.kind_of? Element
-
raise TypeError, "expected #{Element}, got #{element.inspect}:#{element.class}"
-
end
-
end
-
end # Mouse
-
end # WebDriver
-
end # Selenium
-
# encoding: utf-8
-
#
-
# Licensed to the Software Freedom Conservancy (SFC) under one
-
# or more contributor license agreements. See the NOTICE file
-
# distributed with this work for additional information
-
# regarding copyright ownership. The SFC licenses this file
-
# to you under the Apache License, Version 2.0 (the
-
# "License"); you may not use this file except in compliance
-
# with the License. You may obtain a copy of the License at
-
#
-
# http://www.apache.org/licenses/LICENSE-2.0
-
#
-
# Unless required by applicable law or agreed to in writing,
-
# software distributed under the License is distributed on an
-
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-
# KIND, either express or implied. See the License for the
-
# specific language governing permissions and limitations
-
# under the License.
-
-
2
module Selenium
-
2
module WebDriver
-
2
class Navigation
-
-
2
def initialize(bridge)
-
@bridge = bridge
-
end
-
-
#
-
# Navigate to the given URL
-
#
-
-
2
def to(url)
-
@bridge.get url
-
end
-
-
#
-
# Move back a single entry in the browser's history.
-
#
-
-
2
def back
-
@bridge.goBack
-
end
-
-
#
-
# Move forward a single entry in the browser's history.
-
#
-
-
2
def forward
-
@bridge.goForward
-
end
-
-
#
-
# Refresh the current page.
-
#
-
-
2
def refresh
-
@bridge.refresh
-
end
-
-
end # Navigation
-
end # WebDriver
-
end # Selenium
-
# encoding: utf-8
-
#
-
# Licensed to the Software Freedom Conservancy (SFC) under one
-
# or more contributor license agreements. See the NOTICE file
-
# distributed with this work for additional information
-
# regarding copyright ownership. The SFC licenses this file
-
# to you under the Apache License, Version 2.0 (the
-
# "License"); you may not use this file except in compliance
-
# with the License. You may obtain a copy of the License at
-
#
-
# http://www.apache.org/licenses/LICENSE-2.0
-
#
-
# Unless required by applicable law or agreed to in writing,
-
# software distributed under the License is distributed on an
-
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-
# KIND, either express or implied. See the License for the
-
# specific language governing permissions and limitations
-
# under the License.
-
-
2
module Selenium
-
2
module WebDriver
-
2
class Options
-
-
#
-
# @api private
-
#
-
-
2
def initialize(bridge)
-
@bridge = bridge
-
end
-
-
#
-
# Add a cookie to the browser
-
#
-
# @param [Hash] opts the options to create a cookie with.
-
# @option opts [String] :name A name
-
# @option opts [String] :value A value
-
# @option opts [String] :path ('/') A path
-
# @option opts [String] :secure (false) A boolean
-
# @option opts [Time,DateTime,Numeric,nil] :expires (nil) Expiry date, either as a Time, DateTime, or seconds since epoch.
-
#
-
# @raise [ArgumentError] if :name or :value is not specified
-
#
-
-
2
def add_cookie(opts = {})
-
raise ArgumentError, "name is required" unless opts[:name]
-
raise ArgumentError, "value is required" unless opts[:value]
-
-
opts[:path] ||= "/"
-
opts[:secure] ||= false
-
-
if obj = opts.delete(:expires)
-
opts[:expiry] = seconds_from(obj).to_i
-
end
-
-
@bridge.addCookie opts
-
end
-
-
#
-
# Get the cookie with the given name
-
#
-
# @param [String] name the name of the cookie
-
# @return [Hash, nil] the cookie, or nil if it wasn't found.
-
#
-
-
2
def cookie_named(name)
-
all_cookies.find { |c| c[:name] == name }
-
end
-
-
#
-
# Delete the cookie with the given name
-
#
-
# @param [String] name the name of the cookie to delete
-
#
-
-
2
def delete_cookie(name)
-
@bridge.deleteCookie name
-
end
-
-
#
-
# Delete all cookies
-
#
-
-
2
def delete_all_cookies
-
@bridge.deleteAllCookies
-
end
-
-
#
-
# Get all cookies
-
#
-
# @return [Array<Hash>] list of cookies
-
#
-
-
2
def all_cookies
-
@bridge.getAllCookies.map do |cookie|
-
{
-
:name => cookie["name"],
-
:value => cookie["value"],
-
:path => cookie["path"],
-
:domain => cookie["domain"] && strip_port(cookie["domain"]),
-
:expires => cookie["expiry"] && datetime_at(cookie['expiry']),
-
:secure => cookie["secure"]
-
}
-
end
-
end
-
-
2
def timeouts
-
@timeouts ||= Timeouts.new(@bridge)
-
end
-
-
#
-
# @api beta This API may be changed or removed in a future release.
-
#
-
-
2
def logs
-
@logs ||= Logs.new(@bridge)
-
end
-
-
#
-
# @api beta This API may be changed or removed in a future release.
-
#
-
-
2
def window
-
@window ||= Window.new(@bridge)
-
end
-
-
2
private
-
-
2
SECONDS_PER_DAY = 86_400.0
-
-
2
def datetime_at(int)
-
DateTime.civil(1970) + (int / SECONDS_PER_DAY)
-
end
-
-
2
def seconds_from(obj)
-
case obj
-
when Time
-
obj.to_f
-
when DateTime
-
(obj - DateTime.civil(1970)) * SECONDS_PER_DAY
-
when Numeric
-
obj
-
else
-
raise ArgumentError, "invalid value for expiration date: #{obj.inspect}"
-
end
-
end
-
-
2
def strip_port(str)
-
str.split(":", 2).first
-
end
-
-
end # Options
-
end # WebDriver
-
end # Selenium
-
# encoding: utf-8
-
#
-
# Licensed to the Software Freedom Conservancy (SFC) under one
-
# or more contributor license agreements. See the NOTICE file
-
# distributed with this work for additional information
-
# regarding copyright ownership. The SFC licenses this file
-
# to you under the Apache License, Version 2.0 (the
-
# "License"); you may not use this file except in compliance
-
# with the License. You may obtain a copy of the License at
-
#
-
# http://www.apache.org/licenses/LICENSE-2.0
-
#
-
# Unless required by applicable law or agreed to in writing,
-
# software distributed under the License is distributed on an
-
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-
# KIND, either express or implied. See the License for the
-
# specific language governing permissions and limitations
-
# under the License.
-
-
2
require 'rbconfig'
-
2
require 'socket'
-
-
2
module Selenium
-
2
module WebDriver
-
-
# @api private
-
2
module Platform
-
-
2
module_function
-
-
2
def home
-
# jruby has an issue with ENV['HOME'] on Windows
-
@home ||= jruby? ? ENV_JAVA['user.home'] : ENV['HOME']
-
end
-
-
2
def engine
-
@engine ||= (
-
2
if defined? RUBY_ENGINE
-
2
RUBY_ENGINE.to_sym
-
else
-
:ruby
-
end
-
2
)
-
end
-
-
2
def os
-
@os ||= (
-
2
host_os = RbConfig::CONFIG['host_os']
-
2
case host_os
-
when /mswin|msys|mingw|cygwin|bccwin|wince|emc/
-
:windows
-
when /darwin|mac os/
-
:macosx
-
when /linux/
-
2
:linux
-
when /solaris|bsd/
-
:unix
-
else
-
raise Error::WebDriverError, "unknown os: #{host_os.inspect}"
-
end
-
2
)
-
end
-
-
2
def ci
-
if ENV['TRAVIS']
-
:travis
-
elsif ENV['JENKINS']
-
:jenkins
-
end
-
end
-
-
2
def bitsize
-
@bitsize ||= (
-
if defined?(FFI::Platform::ADDRESS_SIZE)
-
FFI::Platform::ADDRESS_SIZE
-
elsif defined?(FFI)
-
FFI.type_size(:pointer) == 4 ? 32 : 64
-
elsif jruby?
-
Integer(ENV_JAVA['sun.arch.data.model'])
-
else
-
1.size == 4 ? 32 : 64
-
end
-
)
-
end
-
-
2
def jruby?
-
2
engine == :jruby
-
end
-
-
2
def ironruby?
-
engine == :ironruby
-
end
-
-
2
def ruby187?
-
!!(RUBY_VERSION =~ /^1\.8\.7/)
-
end
-
-
2
def ruby19?
-
!!(RUBY_VERSION =~ /^1\.9/)
-
end
-
-
2
def windows?
-
2
os == :windows
-
end
-
-
2
def mac?
-
os == :macosx
-
end
-
-
2
def linux?
-
os == :linux
-
end
-
-
2
def cygwin?
-
4
!!(RUBY_PLATFORM =~ /cygwin/)
-
end
-
-
2
def null_device
-
@null_device ||= (
-
if defined?(File::NULL)
-
File::NULL
-
else
-
Platform.windows? ? 'NUL' : '/dev/null'
-
end
-
)
-
end
-
-
2
def wrap_in_quotes_if_necessary(str)
-
windows? && !cygwin? ? %{"#{str}"} : str
-
end
-
-
2
def cygwin_path(path, opts = {})
-
flags = []
-
opts.each { |k,v| flags << "--#{k}" if v }
-
-
`cygpath #{flags.join ' '} "#{path}"`.strip
-
end
-
-
2
def make_writable(file)
-
File.chmod 0766, file
-
end
-
-
2
def assert_file(path)
-
unless File.file? path
-
raise Error::WebDriverError, "not a file: #{path.inspect}"
-
end
-
end
-
-
2
def assert_executable(path)
-
assert_file(path)
-
-
unless File.executable? path
-
raise Error::WebDriverError, "not executable: #{path.inspect}"
-
end
-
end
-
-
2
def exit_hook(&blk)
-
pid = Process.pid
-
-
at_exit do
-
yield if Process.pid == pid
-
end
-
end
-
-
2
def find_binary(*binary_names)
-
paths = ENV['PATH'].split(File::PATH_SEPARATOR)
-
binary_names.map! { |n| "#{n}.exe" } if windows?
-
-
binary_names.each do |binary_name|
-
paths.each do |path|
-
exe = File.join(path, binary_name)
-
return exe if File.executable?(exe)
-
end
-
end
-
-
nil
-
end
-
-
2
def find_in_program_files(*binary_names)
-
paths = [
-
ENV['PROGRAMFILES'] || "\\Program Files",
-
ENV['ProgramFiles(x86)'] || "\\Program Files (x86)"
-
]
-
-
paths.each do |root|
-
binary_names.each do |name|
-
exe = File.join(root, name)
-
return exe if File.executable?(exe)
-
end
-
end
-
-
nil
-
end
-
-
2
def localhost
-
info = Socket.getaddrinfo "localhost", 80, Socket::AF_INET, Socket::SOCK_STREAM
-
-
if info.empty?
-
raise Error::WebDriverError, "unable to translate 'localhost' for TCP + IPv4"
-
end
-
-
info[0][3]
-
end
-
-
2
def ip
-
orig = Socket.do_not_reverse_lookup
-
Socket.do_not_reverse_lookup = true
-
-
begin
-
UDPSocket.open do |s|
-
s.connect '8.8.8.8', 53
-
return s.addr.last
-
end
-
ensure
-
Socket.do_not_reverse_lookup = orig
-
end
-
rescue Errno::ENETUNREACH, Errno::EHOSTUNREACH
-
# no external ip
-
end
-
-
2
def interfaces
-
interfaces = Socket.getaddrinfo("localhost", 8080).map { |e| e[3] }
-
interfaces += ["0.0.0.0", Platform.ip]
-
-
interfaces.compact.uniq
-
end
-
-
end # Platform
-
end # WebDriver
-
end # Selenium
-
-
2
if __FILE__ == $0
-
p :engine => Selenium::WebDriver::Platform.engine,
-
:os => Selenium::WebDriver::Platform.os,
-
:ruby187? => Selenium::WebDriver::Platform.ruby187?,
-
:ruby19? => Selenium::WebDriver::Platform.ruby19?,
-
:jruby? => Selenium::WebDriver::Platform.jruby?,
-
:windows? => Selenium::WebDriver::Platform.windows?,
-
:home => Selenium::WebDriver::Platform.home,
-
:bitsize => Selenium::WebDriver::Platform.bitsize,
-
:localhost => Selenium::WebDriver::Platform.localhost,
-
:ip => Selenium::WebDriver::Platform.ip,
-
:interfaces => Selenium::WebDriver::Platform.interfaces,
-
:null_device => Selenium::WebDriver::Platform.null_device
-
end
-
# encoding: utf-8
-
#
-
# Licensed to the Software Freedom Conservancy (SFC) under one
-
# or more contributor license agreements. See the NOTICE file
-
# distributed with this work for additional information
-
# regarding copyright ownership. The SFC licenses this file
-
# to you under the Apache License, Version 2.0 (the
-
# "License"); you may not use this file except in compliance
-
# with the License. You may obtain a copy of the License at
-
#
-
# http://www.apache.org/licenses/LICENSE-2.0
-
#
-
# Unless required by applicable law or agreed to in writing,
-
# software distributed under the License is distributed on an
-
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-
# KIND, either express or implied. See the License for the
-
# specific language governing permissions and limitations
-
# under the License.
-
-
2
module Selenium
-
2
module WebDriver
-
2
class PortProber
-
2
def self.above(port)
-
port += 1 until free? port
-
port
-
end
-
-
2
def self.random
-
# TODO: Avoid this
-
#
-
# (a) should pick a port that's guaranteed to be free on all interfaces
-
# (b) should pick a random port outside the ephemeral port range
-
#
-
server = TCPServer.new(Platform.localhost, 0)
-
port = server.addr[1]
-
server.close
-
-
port
-
end
-
-
2
IGNORED_ERRORS = [Errno::EADDRNOTAVAIL]
-
2
IGNORED_ERRORS << Errno::EBADF if Platform.cygwin?
-
-
2
def self.free?(port)
-
Platform.interfaces.each do |host|
-
begin
-
TCPServer.new(host, port).close
-
rescue *IGNORED_ERRORS => ex
-
$stderr.puts "port prober could not bind to #{host}:#{port} (#{ex.message})" if $DEBUG
-
# ignored - some machines appear unable to bind to some of their interfaces
-
end
-
end
-
-
true
-
rescue SocketError, Errno::EADDRINUSE
-
false
-
end
-
-
end # PortProber
-
end # WebDriver
-
end # Selenium
-
# encoding: utf-8
-
#
-
# Licensed to the Software Freedom Conservancy (SFC) under one
-
# or more contributor license agreements. See the NOTICE file
-
# distributed with this work for additional information
-
# regarding copyright ownership. The SFC licenses this file
-
# to you under the Apache License, Version 2.0 (the
-
# "License"); you may not use this file except in compliance
-
# with the License. You may obtain a copy of the License at
-
#
-
# http://www.apache.org/licenses/LICENSE-2.0
-
#
-
# Unless required by applicable law or agreed to in writing,
-
# software distributed under the License is distributed on an
-
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-
# KIND, either express or implied. See the License for the
-
# specific language governing permissions and limitations
-
# under the License.
-
-
2
module Selenium
-
2
module WebDriver
-
-
#
-
# @api private
-
#
-
# Common methods for Chrome::Profile and Firefox::Profile
-
# Includers must implement #layout_on_disk
-
#
-
-
2
module ProfileHelper
-
-
2
def self.included(base)
-
base.extend ClassMethods
-
end
-
-
2
def as_json(opts = nil)
-
{'zip' => Zipper.zip(layout_on_disk)}
-
end
-
-
2
def to_json(*args)
-
JSON.generate as_json
-
end
-
-
2
private
-
-
2
def create_tmp_copy(directory)
-
tmp_directory = Dir.mktmpdir("webdriver-rb-profilecopy")
-
-
# TODO: must be a better way..
-
FileUtils.rm_rf tmp_directory
-
FileUtils.mkdir_p File.dirname(tmp_directory), :mode => 0700
-
FileUtils.cp_r directory, tmp_directory
-
-
tmp_directory
-
end
-
-
2
def verify_model(model)
-
return unless model
-
-
raise Errno::ENOENT, model unless File.exist?(model)
-
raise Errno::ENOTDIR, model unless File.directory?(model)
-
-
model
-
end
-
-
2
module ClassMethods
-
2
def from_json(json)
-
data = JSON.parse(json).fetch('zip')
-
-
# can't use Tempfile here since it doesn't support File::BINARY mode on 1.8
-
# can't use Dir.mktmpdir(&blk) because of http://jira.codehaus.org/browse/JRUBY-4082
-
tmp_dir = Dir.mktmpdir
-
begin
-
zip_path = File.join(tmp_dir, "webdriver-profile-duplicate-#{json.hash}.zip")
-
File.open(zip_path, "wb") { |zip_file| zip_file << Base64.decode64(data) }
-
-
new Zipper.unzip(zip_path)
-
ensure
-
FileUtils.rm_rf tmp_dir
-
end
-
end
-
end # ClassMethods
-
-
end # ProfileHelper
-
end # WebDriver
-
end # Selenium
-
# encoding: utf-8
-
#
-
# Licensed to the Software Freedom Conservancy (SFC) under one
-
# or more contributor license agreements. See the NOTICE file
-
# distributed with this work for additional information
-
# regarding copyright ownership. The SFC licenses this file
-
# to you under the Apache License, Version 2.0 (the
-
# "License"); you may not use this file except in compliance
-
# with the License. You may obtain a copy of the License at
-
#
-
# http://www.apache.org/licenses/LICENSE-2.0
-
#
-
# Unless required by applicable law or agreed to in writing,
-
# software distributed under the License is distributed on an
-
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-
# KIND, either express or implied. See the License for the
-
# specific language governing permissions and limitations
-
# under the License.
-
-
2
module Selenium
-
2
module WebDriver
-
2
class Proxy
-
2
TYPES = {
-
:direct => "DIRECT", # Direct connection, no proxy (default on Windows).
-
:manual => "MANUAL", # Manual proxy settings (e.g., for httpProxy).
-
:pac => "PAC", # Proxy autoconfiguration from URL.
-
:auto_detect => "AUTODETECT", # Proxy autodetection (presumably with WPAD).
-
:system => "SYSTEM" # Use system settings (default on Linux).
-
}
-
-
2
attr_reader :type,
-
:ftp,
-
:http,
-
:socks,
-
:socks_username,
-
:socks_password,
-
:no_proxy,
-
:pac,
-
:ssl,
-
:auto_detect
-
-
2
def initialize(opts = {})
-
opts = opts.dup
-
-
self.type = opts.delete(:type) if opts.has_key? :type
-
self.ftp = opts.delete(:ftp) if opts.has_key? :ftp
-
self.http = opts.delete(:http) if opts.has_key? :http
-
self.no_proxy = opts.delete(:no_proxy) if opts.has_key? :no_proxy
-
self.ssl = opts.delete(:ssl) if opts.has_key? :ssl
-
self.pac = opts.delete(:pac) if opts.has_key? :pac
-
self.auto_detect = opts.delete(:auto_detect) if opts.has_key? :auto_detect
-
self.socks = opts.delete(:socks) if opts.has_key? :socks
-
self.socks_username = opts.delete(:socks_username) if opts.has_key? :socks_username
-
self.socks_password = opts.delete(:socks_password) if opts.has_key? :socks_password
-
-
unless opts.empty?
-
raise ArgumentError, "unknown option#{'s' if opts.size != 1}: #{opts.inspect}"
-
end
-
end
-
-
2
def ==(other)
-
other.kind_of?(self.class) && as_json == other.as_json
-
end
-
2
alias_method :eql?, :==
-
-
2
def ftp=(value)
-
self.type = :manual
-
@ftp = value
-
end
-
-
2
def http=(value)
-
self.type = :manual
-
@http = value
-
end
-
-
2
def no_proxy=(value)
-
self.type = :manual
-
@no_proxy = value
-
end
-
-
2
def ssl=(value)
-
self.type = :manual
-
@ssl = value
-
end
-
-
2
def pac=(url)
-
self.type = :pac
-
@pac = url
-
end
-
-
2
def auto_detect=(bool)
-
self.type = :auto_detect
-
@auto_detect = bool
-
end
-
-
2
def socks=(value)
-
self.type = :manual
-
@socks = value
-
end
-
-
2
def socks_username=(value)
-
self.type = :manual
-
@socks_username = value
-
end
-
-
2
def socks_password=(value)
-
self.type = :manual
-
@socks_password = value
-
end
-
-
2
def type=(type)
-
unless TYPES.has_key? type
-
raise ArgumentError, "invalid proxy type: #{type.inspect}, expected one of #{TYPES.keys.inspect}"
-
end
-
-
if defined?(@type) && type != @type
-
raise ArgumentError, "incompatible proxy type #{type.inspect} (already set to #{@type.inspect})"
-
end
-
-
@type = type
-
end
-
-
2
def as_json(opts = nil)
-
json_result = {
-
"proxyType" => TYPES[type]
-
}
-
-
json_result["ftpProxy"] = ftp if ftp
-
json_result["httpProxy"] = http if http
-
json_result["noProxy"] = no_proxy if no_proxy
-
json_result["proxyAutoconfigUrl"] = pac if pac
-
json_result["sslProxy"] = ssl if ssl
-
json_result["autodetect"] = auto_detect if auto_detect
-
json_result["socksProxy"] = socks if socks
-
json_result["socksUsername"] = socks_username if socks_username
-
json_result["socksPassword"] = socks_password if socks_password
-
-
json_result if json_result.length > 1
-
end
-
-
2
def to_json(*args)
-
JSON.generate as_json
-
end
-
-
2
class << self
-
2
def json_create(data)
-
return if data['proxyType'] == 'UNSPECIFIED'
-
-
proxy = new
-
-
proxy.type = data['proxyType'].downcase.to_sym if data.has_key? 'proxyType'
-
proxy.ftp = data['ftpProxy'] if data.has_key? 'ftpProxy'
-
proxy.http = data['httpProxy'] if data.has_key? 'httpProxy'
-
proxy.no_proxy = data['noProxy'] if data.has_key? 'noProxy'
-
proxy.pac = data['proxyAutoconfigUrl'] if data.has_key? 'proxyAutoconfigUrl'
-
proxy.ssl = data['sslProxy'] if data.has_key? 'sslProxy'
-
proxy.auto_detect = data['autodetect'] if data.has_key? 'autodetect'
-
proxy.socks = data['socksProxy'] if data.has_key? 'socksProxy'
-
proxy.socks_username = data['socksUsername'] if data.has_key? 'socksUsername'
-
proxy.socks_password = data['socksPassword'] if data.has_key? 'socksPassword'
-
-
proxy
-
end
-
end # class << self
-
-
end # Proxy
-
end # WebDriver
-
end # Selenium
-
# encoding: utf-8
-
#
-
# Licensed to the Software Freedom Conservancy (SFC) under one
-
# or more contributor license agreements. See the NOTICE file
-
# distributed with this work for additional information
-
# regarding copyright ownership. The SFC licenses this file
-
# to you under the Apache License, Version 2.0 (the
-
# "License"); you may not use this file except in compliance
-
# with the License. You may obtain a copy of the License at
-
#
-
# http://www.apache.org/licenses/LICENSE-2.0
-
#
-
# Unless required by applicable law or agreed to in writing,
-
# software distributed under the License is distributed on an
-
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-
# KIND, either express or implied. See the License for the
-
# specific language governing permissions and limitations
-
# under the License.
-
-
2
module Selenium
-
2
module WebDriver
-
2
module SearchContext
-
-
# @api private
-
2
FINDERS = {
-
:class => 'class name',
-
:class_name => 'class name',
-
:css => 'css selector',
-
:id => 'id',
-
:link => 'link text',
-
:link_text => 'link text',
-
:name => 'name',
-
:partial_link_text => 'partial link text',
-
:tag_name => 'tag name',
-
:xpath => 'xpath',
-
}
-
-
#
-
# Find the first element matching the given arguments.
-
#
-
# When using Element#find_element with :xpath, be aware that webdriver
-
# follows standard conventions: a search prefixed with "//" will search
-
# the entire document, not just the children of this current node. Use
-
# ".//" to limit your search to the children of the receiving Element.
-
#
-
# @param [:class, :class_name, :css, :id, :link_text, :link, :partial_link_text, :name, :tag_name, :xpath] how
-
# @param [String] what
-
# @return [Element]
-
#
-
# @raise [Error::NoSuchElementError] if the element doesn't exist
-
#
-
#
-
-
2
def find_element(*args)
-
how, what = extract_args(args)
-
-
unless by = FINDERS[how.to_sym]
-
raise ArgumentError, "cannot find element by #{how.inspect}"
-
end
-
-
bridge.find_element_by by, what.to_s, ref
-
rescue Selenium::WebDriver::Error::TimeOutError
-
# Implicit Wait times out in Edge
-
raise Selenium::WebDriver::Error::NoSuchElementError
-
end
-
-
#
-
# Find all elements matching the given arguments
-
#
-
# @see SearchContext#find_element
-
#
-
# @param [:class, :class_name, :css, :id, :link_text, :link, :partial_link_text, :name, :tag_name, :xpath] how
-
# @param [String] what
-
# @return [Array<Element>]
-
#
-
-
2
def find_elements(*args)
-
how, what = extract_args(args)
-
-
unless by = FINDERS[how.to_sym]
-
raise ArgumentError, "cannot find elements by #{how.inspect}"
-
end
-
-
bridge.find_elements_by by, what.to_s, ref
-
rescue Selenium::WebDriver::Error::TimeOutError
-
# Implicit Wait times out in Edge
-
[]
-
end
-
-
2
private
-
-
2
def extract_args(args)
-
case args.size
-
when 2
-
args
-
when 1
-
arg = args.first
-
-
unless arg.respond_to?(:shift)
-
raise ArgumentError, "expected #{arg.inspect}:#{arg.class} to respond to #shift"
-
end
-
-
# this will be a single-entry hash, so use #shift over #first or #[]
-
arr = arg.dup.shift
-
unless arr.size == 2
-
raise ArgumentError, "expected #{arr.inspect} to have 2 elements"
-
end
-
-
arr
-
else
-
raise ArgumentError, "wrong number of arguments (#{args.size} for 2)"
-
end
-
end
-
-
end # SearchContext
-
end # WebDriver
-
end # Selenium
-
# encoding: utf-8
-
#
-
# Licensed to the Software Freedom Conservancy (SFC) under one
-
# or more contributor license agreements. See the NOTICE file
-
# distributed with this work for additional information
-
# regarding copyright ownership. The SFC licenses this file
-
# to you under the Apache License, Version 2.0 (the
-
# "License"); you may not use this file except in compliance
-
# with the License. You may obtain a copy of the License at
-
#
-
# http://www.apache.org/licenses/LICENSE-2.0
-
#
-
# Unless required by applicable law or agreed to in writing,
-
# software distributed under the License is distributed on an
-
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-
# KIND, either express or implied. See the License for the
-
# specific language governing permissions and limitations
-
# under the License.
-
-
2
module Selenium
-
2
module WebDriver
-
-
#
-
# @api private
-
#
-
-
2
class SocketLock
-
-
2
def initialize(port, timeout)
-
@port = port
-
@timeout = timeout
-
end
-
-
#
-
# Attempt to acquire a lock on the given port. Control is yielded to an
-
# execution block if the lock could be successfully obtained.
-
#
-
-
2
def locked(&blk)
-
lock
-
-
begin
-
yield
-
ensure
-
release
-
end
-
end
-
-
2
private
-
-
2
def lock
-
max_time = Time.now + @timeout
-
-
until can_lock? || Time.now >= max_time
-
sleep 0.1
-
end
-
-
unless did_lock?
-
raise Error::WebDriverError, "unable to bind to locking port #{@port} within #{@timeout} seconds"
-
end
-
end
-
-
2
def release
-
@server && @server.close
-
end
-
-
2
def can_lock?
-
@server = TCPServer.new(Platform.localhost, @port)
-
ChildProcess.close_on_exec @server
-
-
true
-
rescue SocketError, Errno::EADDRINUSE, Errno::EBADF => ex
-
$stderr.puts "#{self}: #{ex.message}" if $DEBUG
-
false
-
end
-
-
2
def did_lock?
-
!!@server
-
end
-
-
end # SocketLock
-
end # WebDriver
-
end # Selenium
-
# encoding: utf-8
-
#
-
# Licensed to the Software Freedom Conservancy (SFC) under one
-
# or more contributor license agreements. See the NOTICE file
-
# distributed with this work for additional information
-
# regarding copyright ownership. The SFC licenses this file
-
# to you under the Apache License, Version 2.0 (the
-
# "License"); you may not use this file except in compliance
-
# with the License. You may obtain a copy of the License at
-
#
-
# http://www.apache.org/licenses/LICENSE-2.0
-
#
-
# Unless required by applicable law or agreed to in writing,
-
# software distributed under the License is distributed on an
-
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-
# KIND, either express or implied. See the License for the
-
# specific language governing permissions and limitations
-
# under the License.
-
-
2
require 'selenium/webdriver/common/platform'
-
2
require 'socket'
-
-
2
module Selenium
-
2
module WebDriver
-
2
class SocketPoller
-
-
2
def initialize(host, port, timeout = 0, interval = 0.25)
-
@host = host
-
@port = Integer(port)
-
@timeout = Float(timeout)
-
@interval = interval
-
end
-
-
#
-
# Returns true if the server is listening within the given timeout,
-
# false otherwise.
-
#
-
# @return [Boolean]
-
#
-
-
2
def connected?
-
with_timeout { listening? }
-
end
-
-
#
-
# Returns true if the server has stopped listening within the given timeout,
-
# false otherwise.
-
#
-
# @return [Boolean]
-
#
-
-
2
def closed?
-
with_timeout { not listening? }
-
end
-
-
2
private
-
-
2
CONNECT_TIMEOUT = 5
-
-
2
NOT_CONNECTED_ERRORS = [Errno::ECONNREFUSED, Errno::ENOTCONN, SocketError]
-
2
NOT_CONNECTED_ERRORS << Errno::EPERM if Platform.cygwin?
-
-
2
CONNECTED_ERRORS = [Errno::EISCONN]
-
2
CONNECTED_ERRORS << Errno::EINVAL if Platform.windows?
-
-
2
if Platform.jruby?
-
# we use a plain TCPSocket here since JRuby has issues select()ing on a connecting socket
-
# see http://jira.codehaus.org/browse/JRUBY-5165
-
def listening?
-
TCPSocket.new(@host, @port).close
-
true
-
rescue *NOT_CONNECTED_ERRORS
-
false
-
end
-
else
-
2
def listening?
-
addr = Socket.getaddrinfo(@host, @port, Socket::AF_INET, Socket::SOCK_STREAM)
-
sock = Socket.new(Socket::AF_INET, Socket::SOCK_STREAM, 0)
-
sockaddr = Socket.pack_sockaddr_in(@port, addr[0][3])
-
-
begin
-
sock.connect_nonblock sockaddr
-
rescue Errno::EINPROGRESS
-
if IO.select(nil, [sock], nil, CONNECT_TIMEOUT)
-
retry
-
else
-
raise Errno::ECONNREFUSED
-
end
-
rescue *CONNECTED_ERRORS
-
# yay!
-
end
-
-
sock.close
-
true
-
rescue *NOT_CONNECTED_ERRORS
-
sock.close if sock
-
$stderr.puts [@host, @port].inspect if $DEBUG
-
false
-
end
-
end
-
-
2
def with_timeout(&blk)
-
max_time = time_now + @timeout
-
-
(
-
return true if yield
-
wait
-
) until time_now > max_time
-
-
false
-
end
-
-
2
def wait
-
sleep @interval
-
end
-
-
# for testability
-
2
def time_now
-
Time.now
-
end
-
-
end # SocketPoller
-
end # WebDriver
-
end # Selenium
-
# encoding: utf-8
-
#
-
# Licensed to the Software Freedom Conservancy (SFC) under one
-
# or more contributor license agreements. See the NOTICE file
-
# distributed with this work for additional information
-
# regarding copyright ownership. The SFC licenses this file
-
# to you under the Apache License, Version 2.0 (the
-
# "License"); you may not use this file except in compliance
-
# with the License. You may obtain a copy of the License at
-
#
-
# http://www.apache.org/licenses/LICENSE-2.0
-
#
-
# Unless required by applicable law or agreed to in writing,
-
# software distributed under the License is distributed on an
-
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-
# KIND, either express or implied. See the License for the
-
# specific language governing permissions and limitations
-
# under the License.
-
-
2
module Selenium
-
2
module WebDriver
-
2
class Timeouts
-
-
2
def initialize(bridge)
-
@bridge = bridge
-
end
-
-
#
-
# Set the amount of time the driver should wait when searching for elements.
-
#
-
-
2
def implicit_wait=(seconds)
-
@bridge.setImplicitWaitTimeout Integer(seconds * 1000)
-
end
-
-
#
-
# Sets the amount of time to wait for an asynchronous script to finish
-
# execution before throwing an error. If the timeout is negative, then the
-
# script will be allowed to run indefinitely.
-
#
-
-
2
def script_timeout=(seconds)
-
@bridge.setScriptTimeout Integer(seconds * 1000)
-
end
-
-
#
-
# Sets the amount of time to wait for a page load to complete before throwing an error.
-
# If the timeout is negative, page loads can be indefinite.
-
#
-
-
2
def page_load=(seconds)
-
@bridge.setTimeout 'page load', Integer(seconds * 1000)
-
end
-
-
end # Timeouts
-
end # WebDriver
-
end # Selenium
-
# encoding: utf-8
-
#
-
# Licensed to the Software Freedom Conservancy (SFC) under one
-
# or more contributor license agreements. See the NOTICE file
-
# distributed with this work for additional information
-
# regarding copyright ownership. The SFC licenses this file
-
# to you under the Apache License, Version 2.0 (the
-
# "License"); you may not use this file except in compliance
-
# with the License. You may obtain a copy of the License at
-
#
-
# http://www.apache.org/licenses/LICENSE-2.0
-
#
-
# Unless required by applicable law or agreed to in writing,
-
# software distributed under the License is distributed on an
-
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-
# KIND, either express or implied. See the License for the
-
# specific language governing permissions and limitations
-
# under the License.
-
-
2
module Selenium
-
2
module WebDriver
-
2
class TouchActionBuilder < ActionBuilder
-
-
#
-
# @api private
-
#
-
-
2
def initialize(mouse, keyboard, touch_screen)
-
super(mouse, keyboard)
-
@devices[:touch_screen] = touch_screen
-
end
-
-
2
def scroll(*args)
-
unless [2,3].include? args.size
-
raise ArgumentError, "wrong number of arguments, expected 2..3, got #{args.size}"
-
end
-
-
@actions << [:touch_screen, :scroll, args]
-
self
-
end
-
-
2
def flick(*args)
-
unless [2,4].include? args.size
-
raise ArgumentError, "wrong number of arguments, expected 2 or 4, got #{args.size}"
-
end
-
-
@actions << [:touch_screen, :flick, args]
-
self
-
end
-
-
2
def single_tap(element)
-
@actions << [:touch_screen, :single_tap, [element]]
-
self
-
end
-
-
2
def double_tap(element)
-
@actions << [:touch_screen, :double_tap, [element]]
-
self
-
end
-
-
2
def long_press(element)
-
@actions << [:touch_screen, :long_press, [element]]
-
self
-
end
-
-
2
def down(x, y = nil)
-
@actions << [:touch_screen, :down, [x, y]]
-
self
-
end
-
-
2
def up(x, y = nil)
-
@actions << [:touch_screen, :up, [x, y]]
-
self
-
end
-
-
2
def move(x, y = nil)
-
@actions << [:touch_screen, :move, [x, y]]
-
self
-
end
-
-
end # TouchActionBuilder
-
end # WebDriver
-
end # Selenium
-
# encoding: utf-8
-
#
-
# Licensed to the Software Freedom Conservancy (SFC) under one
-
# or more contributor license agreements. See the NOTICE file
-
# distributed with this work for additional information
-
# regarding copyright ownership. The SFC licenses this file
-
# to you under the Apache License, Version 2.0 (the
-
# "License"); you may not use this file except in compliance
-
# with the License. You may obtain a copy of the License at
-
#
-
# http://www.apache.org/licenses/LICENSE-2.0
-
#
-
# Unless required by applicable law or agreed to in writing,
-
# software distributed under the License is distributed on an
-
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-
# KIND, either express or implied. See the License for the
-
# specific language governing permissions and limitations
-
# under the License.
-
-
2
module Selenium
-
2
module WebDriver
-
2
class TouchScreen
-
2
FLICK_SPEED = { :normal => 0, :fast => 1}
-
-
-
#
-
# @api private
-
#
-
-
2
def initialize(bridge)
-
@bridge = bridge
-
end
-
-
2
def single_tap(element)
-
assert_element element
-
@bridge.touchSingleTap element.ref
-
end
-
-
2
def double_tap(element)
-
assert_element element
-
@bridge.touchDoubleTap element.ref
-
end
-
-
2
def long_press(element)
-
assert_element element
-
@bridge.touchLongPress element.ref
-
end
-
-
2
def down(x, y = nil)
-
x, y = coords_from x, y
-
@bridge.touchDown x, y
-
end
-
-
2
def up(x, y = nil)
-
x, y = coords_from x, y
-
@bridge.touchUp x, y
-
end
-
-
2
def move(x, y = nil)
-
x, y = coords_from x, y
-
@bridge.touchMove x, y
-
end
-
-
2
def scroll(*args)
-
case args.size
-
when 2
-
x_offset, y_offset = args
-
@bridge.touchScroll nil, Integer(x_offset), Integer(y_offset)
-
when 3
-
element, x_offset, y_offset = args
-
assert_element element
-
@bridge.touchScroll element.ref, Integer(x_offset), Integer(y_offset)
-
else
-
raise ArgumentError, "wrong number of arguments, expected 2..3, got #{args.size}"
-
end
-
end
-
-
2
def flick(*args)
-
case args.size
-
when 2
-
x_speed, y_speed = args
-
@bridge.touchFlick Integer(x_speed), Integer(y_speed)
-
when 4
-
element, xoffset, yoffset, speed = args
-
-
assert_element element
-
flick_speed = FLICK_SPEED[speed.to_sym]
-
-
unless flick_speed
-
raise ArgumentError, "expected one of #{FLICK_SPEED.keys.inspect}, got #{speed.inspect}"
-
end
-
-
@bridge.touchElementFlick element.ref, Integer(xoffset), Integer(yoffset), flick_speed
-
else
-
raise ArgumentError, "wrong number of arguments, expected 2 or 4, got #{args.size}"
-
end
-
-
end
-
-
2
private
-
-
2
def coords_from(x, y)
-
if y.nil?
-
point = x
-
-
unless point.respond_to?(:x) && point.respond_to?(:y)
-
raise ArgumentError, "expected #{point.inspect} to respond to :x and :y"
-
end
-
-
x, y = point.x, point.y
-
end
-
-
[Integer(x), Integer(y)]
-
end
-
-
2
def assert_element(element)
-
unless element.kind_of? Element
-
raise TypeError, "expected #{Element}, got #{element.inspect}:#{element.class}"
-
end
-
end
-
-
end # TouchScreen
-
end # WebDriver
-
end # Selenium
-
# encoding: utf-8
-
#
-
# Licensed to the Software Freedom Conservancy (SFC) under one
-
# or more contributor license agreements. See the NOTICE file
-
# distributed with this work for additional information
-
# regarding copyright ownership. The SFC licenses this file
-
# to you under the Apache License, Version 2.0 (the
-
# "License"); you may not use this file except in compliance
-
# with the License. You may obtain a copy of the License at
-
#
-
# http://www.apache.org/licenses/LICENSE-2.0
-
#
-
# Unless required by applicable law or agreed to in writing,
-
# software distributed under the License is distributed on an
-
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-
# KIND, either express or implied. See the License for the
-
# specific language governing permissions and limitations
-
# under the License.
-
-
2
module Selenium
-
2
module WebDriver
-
2
class Wait
-
-
2
DEFAULT_TIMEOUT = 5
-
2
DEFAULT_INTERVAL = 0.2
-
-
#
-
# Create a new Wait instance
-
#
-
# @param [Hash] opts Options for this instance
-
# @option opts [Numeric] :timeout (5) Seconds to wait before timing out.
-
# @option opts [Numeric] :interval (0.2) Seconds to sleep between polls.
-
# @option opts [String] :message Exception mesage if timed out.
-
# @option opts [Array, Exception] :ignore Exceptions to ignore while polling (default: Error::NoSuchElementError)
-
#
-
-
2
def initialize(opts = {})
-
@timeout = opts.fetch(:timeout, DEFAULT_TIMEOUT)
-
@interval = opts.fetch(:interval, DEFAULT_INTERVAL)
-
@message = opts[:message]
-
@ignored = Array(opts[:ignore] || Error::NoSuchElementError)
-
end
-
-
-
#
-
# Wait until the given block returns a true value.
-
#
-
# @raise [Error::TimeOutError]
-
# @return [Object] the result of the block
-
#
-
-
2
def until(&blk)
-
end_time = Time.now + @timeout
-
last_error = nil
-
-
until Time.now > end_time
-
begin
-
result = yield
-
return result if result
-
rescue *@ignored => last_error
-
# swallowed
-
end
-
-
sleep @interval
-
end
-
-
-
if @message
-
msg = @message.dup
-
else
-
msg = "timed out after #{@timeout} seconds"
-
end
-
-
msg << " (#{last_error.message})" if last_error
-
-
raise Error::TimeOutError, msg
-
end
-
-
end # Wait
-
end # WebDriver
-
end # Selenium
-
-
# encoding: utf-8
-
#
-
# Licensed to the Software Freedom Conservancy (SFC) under one
-
# or more contributor license agreements. See the NOTICE file
-
# distributed with this work for additional information
-
# regarding copyright ownership. The SFC licenses this file
-
# to you under the Apache License, Version 2.0 (the
-
# "License"); you may not use this file except in compliance
-
# with the License. You may obtain a copy of the License at
-
#
-
# http://www.apache.org/licenses/LICENSE-2.0
-
#
-
# Unless required by applicable law or agreed to in writing,
-
# software distributed under the License is distributed on an
-
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-
# KIND, either express or implied. See the License for the
-
# specific language governing permissions and limitations
-
# under the License.
-
-
2
module Selenium
-
2
module WebDriver
-
-
#
-
# @api beta This API may be changed or removed in a future release.
-
#
-
-
2
class Window
-
-
#
-
# @api private
-
#
-
-
2
def initialize(bridge)
-
@bridge = bridge
-
end
-
-
#
-
# Resize the current window to the given dimension.
-
#
-
# @param [Selenium::WebDriver::Dimension, #width and #height] dimension The new size.
-
#
-
-
2
def size=(dimension)
-
unless dimension.respond_to?(:width) && dimension.respond_to?(:height)
-
raise ArgumentError, "expected #{dimension.inspect}:#{dimension.class}" +
-
" to respond to #width and #height"
-
end
-
-
@bridge.setWindowSize dimension.width, dimension.height
-
end
-
-
#
-
# Get the size of the current window.
-
#
-
# @return [Selenium::WebDriver::Dimension] The size.
-
#
-
-
2
def size
-
@bridge.getWindowSize
-
end
-
-
#
-
# Move the current window to the given position.
-
#
-
# @param [Selenium::WebDriver::Point, #x and #y] point The new position.
-
#
-
-
2
def position=(point)
-
unless point.respond_to?(:x) && point.respond_to?(:y)
-
raise ArgumentError, "expected #{point.inspect}:#{point.class}" +
-
" to respond to #x and #y"
-
end
-
-
@bridge.setWindowPosition point.x, point.y
-
end
-
-
#
-
# Get the position of the current window.
-
#
-
# @return [Selenium::WebDriver::Point] The position.
-
#
-
-
2
def position
-
@bridge.getWindowPosition
-
end
-
-
#
-
# Equivalent to #size=, but accepts width and height arguments.
-
#
-
# @example Maximize the window.
-
#
-
# max_width, max_height = driver.execute_script("return [window.screen.availWidth, window.screen.availHeight];")
-
# driver.manage.window.resize_to(max_width, max_height)
-
#
-
-
2
def resize_to(width, height)
-
@bridge.setWindowSize Integer(width), Integer(height)
-
end
-
-
#
-
# Equivalent to #position=, but accepts x and y arguments.
-
#
-
# @example
-
#
-
# driver.manage.window.move_to(300, 400)
-
#
-
-
2
def move_to(x, y)
-
@bridge.setWindowPosition Integer(x), Integer(y)
-
end
-
-
#
-
# Maximize the current window
-
#
-
-
2
def maximize
-
@bridge.maximizeWindow
-
end
-
-
#
-
# Make current window full screen
-
#
-
-
2
def full_screen
-
@bridge.fullscreenWindow
-
end
-
-
end # Window
-
end # WebDriver
-
end # Selenium
-
# encoding: utf-8
-
#
-
# Licensed to the Software Freedom Conservancy (SFC) under one
-
# or more contributor license agreements. See the NOTICE file
-
# distributed with this work for additional information
-
# regarding copyright ownership. The SFC licenses this file
-
# to you under the Apache License, Version 2.0 (the
-
# "License"); you may not use this file except in compliance
-
# with the License. You may obtain a copy of the License at
-
#
-
# http://www.apache.org/licenses/LICENSE-2.0
-
#
-
# Unless required by applicable law or agreed to in writing,
-
# software distributed under the License is distributed on an
-
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-
# KIND, either express or implied. See the License for the
-
# specific language governing permissions and limitations
-
# under the License.
-
-
2
require 'zip'
-
2
require 'tempfile'
-
2
require 'find'
-
-
2
module Selenium
-
2
module WebDriver
-
#
-
# @api private
-
#
-
-
2
module Zipper
-
-
2
EXTENSIONS = %w[.zip .xpi]
-
-
2
class << self
-
-
2
def unzip(path)
-
destination = Dir.mktmpdir("webdriver-unzip")
-
FileReaper << destination
-
-
Zip::File.open(path) do |zip|
-
zip.each do |entry|
-
to = File.join(destination, entry.name)
-
dirname = File.dirname(to)
-
-
FileUtils.mkdir_p dirname unless File.exist? dirname
-
zip.extract(entry, to)
-
end
-
end
-
-
destination
-
end
-
-
2
def zip(path)
-
with_tmp_zip do |zip|
-
::Find.find(path) do |file|
-
unless File.directory?(file)
-
add_zip_entry zip, file, file.sub("#{path}/", '')
-
end
-
end
-
-
zip.commit
-
File.open(zip.name, "rb") { |io| Base64.strict_encode64 io.read }
-
end
-
end
-
-
2
def zip_file(path)
-
with_tmp_zip do |zip|
-
add_zip_entry zip, path, File.basename(path)
-
-
zip.commit
-
File.open(zip.name, "rb") { |io| Base64.strict_encode64 io.read }
-
end
-
end
-
-
2
private
-
-
2
def with_tmp_zip(&blk)
-
# can't use Tempfile here since it doesn't support File::BINARY mode on 1.8
-
# can't use Dir.mktmpdir(&blk) because of http://jira.codehaus.org/browse/JRUBY-4082
-
tmp_dir = Dir.mktmpdir
-
zip_path = File.join(tmp_dir, "webdriver-zip")
-
-
begin
-
Zip::File.open(zip_path, Zip::File::CREATE, &blk)
-
ensure
-
FileUtils.rm_rf tmp_dir
-
FileUtils.rm_rf zip_path
-
end
-
end
-
-
2
def add_zip_entry(zip, file, entry_name)
-
entry = Zip::Entry.new(zip.name, entry_name)
-
entry.follow_symlinks = true
-
-
zip.add entry, file
-
end
-
-
end
-
end # Zipper
-
end # WebDriver
-
end # Selenium
-
2
require "open3"
-
-
2
module Shellany
-
# The Guard sheller abstract the actual subshell
-
# calls and allow easier stubbing.
-
#
-
2
class Sheller
-
2
attr_reader :status
-
-
# Creates a new Guard::Sheller object.
-
#
-
# @param [String] args a command to run in a subshell
-
# @param [Array<String>] args an array of command parts to run in a subshell
-
# @param [*String] args a list of command parts to run in a subshell
-
#
-
2
def initialize(*args)
-
fail ArgumentError, "no command given" if args.empty?
-
@command = args
-
@ran = false
-
end
-
-
# Shortcut for new(command).run
-
#
-
2
def self.run(*args)
-
new(*args).run
-
end
-
-
# Shortcut for new(command).run.stdout
-
#
-
2
def self.stdout(*args)
-
new(*args).stdout
-
end
-
-
# Shortcut for new(command).run.stderr
-
#
-
2
def self.stderr(*args)
-
new(*args).stderr
-
end
-
-
# Runs the command.
-
#
-
# @return [Boolean] whether or not the command succeeded.
-
#
-
2
def run
-
unless ran?
-
status, output, errors = self.class._system_with_capture(*@command)
-
@ran = true
-
@stdout = output
-
@stderr = errors
-
@status = status
-
end
-
-
ok?
-
end
-
-
# Returns true if the command has already been run, false otherwise.
-
#
-
# @return [Boolean] whether or not the command has already been run
-
#
-
2
def ran?
-
@ran
-
end
-
-
# Returns true if the command succeeded, false otherwise.
-
#
-
# @return [Boolean] whether or not the command succeeded
-
#
-
2
def ok?
-
run unless ran?
-
-
@status && @status.success?
-
end
-
-
# Returns the command's output.
-
#
-
# @return [String] the command output
-
#
-
2
def stdout
-
run unless ran?
-
-
@stdout
-
end
-
-
# Returns the command's error output.
-
#
-
# @return [String] the command output
-
#
-
2
def stderr
-
run unless ran?
-
-
@stderr
-
end
-
-
# No output capturing
-
#
-
# NOTE: `$stdout.puts system('cls')` on Windows won't work like
-
# it does for on systems with ansi terminals, so we need to be
-
# able to call Kernel.system directly.
-
2
def self.system(*args)
-
_system_with_no_capture(*args)
-
end
-
-
2
def self._system_with_no_capture(*args)
-
Kernel.system(*args)
-
result = $?
-
errors = (result == 0) || "Guard failed to run: #{args.inspect}"
-
[result, nil, errors]
-
end
-
-
2
def self._system_with_capture(*args)
-
# We use popen3, because it started working on recent versions
-
# of JRuby, while JRuby doesn't handle options to Kernel.system
-
args = _shellize_if_needed(args)
-
-
stdout, stderr, status = nil
-
Open3.popen3(*args) do |_stdin, _stdout, _stderr, _thr|
-
stdout = _stdout.read
-
stderr = _stderr.read
-
status = _thr.value
-
end
-
-
[status, stdout, stderr]
-
rescue Errno::ENOENT, IOError => e
-
[nil, nil, "Guard::Sheller failed (#{e.inspect})"]
-
end
-
-
# Only needed on JRUBY, because MRI properly detects ';' and metachars
-
2
def self._shellize_if_needed(args)
-
return args unless RUBY_PLATFORM == "java"
-
return args unless args.size == 1
-
return args unless /[;<>]/ =~ args.first
-
-
# NOTE: Sheller was originally meant for Guard (which basically only uses
-
# UNIX commands anyway) and JRuby doesn't support options to
-
# Kernel.system (and doesn't automatically shell when there's a
-
# metacharacter in the command).
-
#
-
# So ... I'm assuming /bin/sh exists - if not, PRs are welcome,
-
# because I have no clue what to do if /bin/sh doesn't exist.
-
# (use ENV["RUBYSHELL"] ? Detect cmd.exe ?)
-
["/bin/sh", "-c", args.first]
-
end
-
end
-
end
-
2
require 'action_view'
-
2
require 'simple_form/action_view_extensions/form_helper'
-
2
require 'simple_form/action_view_extensions/builder'
-
2
require 'active_support/core_ext/hash/slice'
-
2
require 'active_support/core_ext/hash/except'
-
2
require 'active_support/core_ext/hash/reverse_merge'
-
-
2
module SimpleForm
-
2
extend ActiveSupport::Autoload
-
-
2
autoload :Helpers
-
2
autoload :Wrappers
-
-
2
eager_autoload do
-
2
autoload :Components
-
2
autoload :ErrorNotification
-
2
autoload :FormBuilder
-
2
autoload :Inputs
-
end
-
-
2
def self.eager_load!
-
super
-
SimpleForm::Inputs.eager_load!
-
SimpleForm::Components.eager_load!
-
end
-
-
2
CUSTOM_INPUT_DEPRECATION_WARN = <<-WARN
-
%{name} method now accepts a `wrapper_options` argument. The method definition without the argument is deprecated and will be removed in the next Simple Form version. Change your code from:
-
-
def %{name}
-
-
to
-
-
def %{name}(wrapper_options)
-
-
See https://github.com/plataformatec/simple_form/pull/997 for more information.
-
WARN
-
-
2
@@configured = false
-
-
2
def self.configured? #:nodoc:
-
2
@@configured
-
end
-
-
## CONFIGURATION OPTIONS
-
-
# Method used to tidy up errors.
-
2
mattr_accessor :error_method
-
2
@@error_method = :first
-
-
# Default tag used for error notification helper.
-
2
mattr_accessor :error_notification_tag
-
2
@@error_notification_tag = :p
-
-
# CSS class to add for error notification helper.
-
2
mattr_accessor :error_notification_class
-
2
@@error_notification_class = :error_notification
-
-
# Series of attemps to detect a default label method for collection.
-
2
mattr_accessor :collection_label_methods
-
2
@@collection_label_methods = [:to_label, :name, :title, :to_s]
-
-
# Series of attemps to detect a default value method for collection.
-
2
mattr_accessor :collection_value_methods
-
2
@@collection_value_methods = [:id, :to_s]
-
-
# You can wrap a collection of radio/check boxes in a pre-defined tag, defaulting to none.
-
2
mattr_accessor :collection_wrapper_tag
-
2
@@collection_wrapper_tag = nil
-
-
# You can define the class to use on all collection wrappers, defaulting to none.
-
2
mattr_accessor :collection_wrapper_class
-
2
@@collection_wrapper_class = nil
-
-
# You can wrap each item in a collection of radio/check boxes with a tag,
-
# defaulting to span. Please note that when using :boolean_style = :nested,
-
# SimpleForm will force this option to be a :label.
-
2
mattr_accessor :item_wrapper_tag
-
2
@@item_wrapper_tag = :span
-
-
# You can define the class to use on all item wrappers, defaulting to none.
-
2
mattr_accessor :item_wrapper_class
-
2
@@item_wrapper_class = nil
-
-
# How the label text should be generated altogether with the required text.
-
2
mattr_accessor :label_text
-
2
@@label_text = lambda { |label, required, explicit_label| "#{required} #{label}" }
-
-
# You can define the class to be used on all labels. Defaults to none.
-
2
mattr_accessor :label_class
-
2
@@label_class = nil
-
-
# Define the way to render check boxes / radio buttons with labels.
-
# inline: input + label (default)
-
# nested: label > input
-
2
mattr_accessor :boolean_style
-
2
@@boolean_style = :inline
-
-
# DEPRECATED: You can define the class to be used on all forms. Default is
-
# simple_form.
-
2
mattr_reader :form_class
-
2
@@form_class = :simple_form
-
-
# You can define the default class to be used on all forms. Can be overriden
-
# with `html: { :class }`. Defaults to none.
-
2
mattr_accessor :default_form_class
-
2
@@default_form_class = nil
-
-
# You can define which elements should obtain additional classes.
-
2
mattr_accessor :generate_additional_classes_for
-
2
@@generate_additional_classes_for = [:wrapper, :label, :input]
-
-
# Whether attributes are required by default or not.
-
2
mattr_accessor :required_by_default
-
2
@@required_by_default = true
-
-
# Tell browsers whether to use default HTML5 validations (novalidate option).
-
2
mattr_accessor :browser_validations
-
2
@@browser_validations = true
-
-
# Collection of methods to detect if a file type was given.
-
2
mattr_accessor :file_methods
-
2
@@file_methods = [:mounted_as, :file?, :public_filename]
-
-
# Custom mappings for input types. This should be a hash containing a regexp
-
# to match as key, and the input type that will be used when the field name
-
# matches the regexp as value, such as { /count/ => :integer }.
-
2
mattr_accessor :input_mappings
-
2
@@input_mappings = nil
-
-
# Custom wrappers for input types. This should be a hash containing an input
-
# type as key and the wrapper that will be used for all inputs with specified type.
-
# e.g { string: :string_wrapper, boolean: :boolean_wrapper }
-
# You can also set a wrapper mapping per form basis.
-
# e.g simple_form_for(@foo, wrapper_mappings: { check_boxes: :bootstrap_checkbox })
-
2
mattr_accessor :wrapper_mappings
-
2
@@wrapper_mappings = nil
-
-
# Namespaces where SimpleForm should look for custom input classes that override
-
# default inputs. Namespaces are given as string to allow lazy loading inputs.
-
# e.g. config.custom_inputs_namespaces << "CustomInputs"
-
# will try to find CustomInputs::NumericInput when an :integer
-
# field is called.
-
2
mattr_accessor :custom_inputs_namespaces
-
2
@@custom_inputs_namespaces = []
-
-
# Default priority for time_zone inputs.
-
2
mattr_accessor :time_zone_priority
-
2
@@time_zone_priority = nil
-
-
# Default priority for country inputs.
-
2
mattr_accessor :country_priority
-
2
@@country_priority = nil
-
-
# DEPRECATED: Maximum size allowed for inputs.
-
2
mattr_accessor :default_input_size
-
2
@@default_input_size = nil
-
-
# When off, do not use translations in labels. Disabling translation in
-
# hints and placeholders can be done manually in the wrapper API.
-
2
mattr_accessor :translate_labels
-
2
@@translate_labels = true
-
-
# Automatically discover new inputs in Rails' autoload path.
-
2
mattr_accessor :inputs_discovery
-
2
@@inputs_discovery = true
-
-
# Cache SimpleForm inputs discovery.
-
2
mattr_accessor :cache_discovery
-
2
@@cache_discovery = defined?(Rails) && !Rails.env.development?
-
-
# Adds a class to each generated button, mostly for compatiblity.
-
2
mattr_accessor :button_class
-
2
@@button_class = 'button'
-
-
# Override the default ActiveModelHelper behaviour of wrapping the input.
-
# This gets taken care of semantically by adding an error class to the wrapper tag
-
# containing the input.
-
2
mattr_accessor :field_error_proc
-
2
@@field_error_proc = proc do |html_tag, instance_tag|
-
html_tag
-
end
-
-
# Adds a class to each generated inputs
-
2
mattr_accessor :input_class
-
2
@@input_class = nil
-
-
# Defines if an input wrapper class should be included or not
-
2
mattr_accessor :include_default_input_wrapper_class
-
2
@@include_default_input_wrapper_class = true
-
-
# Define the default class of the input wrapper of the boolean input.
-
2
mattr_accessor :boolean_label_class
-
2
@@boolean_label_class = 'checkbox'
-
-
## WRAPPER CONFIGURATION
-
# The default wrapper to be used by the FormBuilder.
-
2
mattr_accessor :default_wrapper
-
2
@@default_wrapper = :default
-
2
@@wrappers = {} #:nodoc:
-
-
2
mattr_accessor :i18n_scope
-
2
@@i18n_scope = 'simple_form'
-
-
# Retrieves a given wrapper
-
2
def self.wrapper(name)
-
@@wrappers[name.to_s] or raise WrapperNotFound, "Couldn't find wrapper with name #{name}"
-
end
-
-
# Raised when fails to find a given wrapper name
-
2
class WrapperNotFound < StandardError
-
end
-
-
# Define a new wrapper using SimpleForm::Wrappers::Builder
-
# and store it in the given name.
-
2
def self.wrappers(*args, &block)
-
24
if block_given?
-
24
options = args.extract_options!
-
24
name = args.first || :default
-
24
@@wrappers[name.to_s] = build(options, &block)
-
else
-
@@wrappers
-
end
-
end
-
-
# Builds a new wrapper using SimpleForm::Wrappers::Builder.
-
2
def self.build(options = {})
-
24
options[:tag] = :div if options[:tag].nil?
-
24
builder = SimpleForm::Wrappers::Builder.new(options)
-
24
yield builder
-
24
SimpleForm::Wrappers::Root.new(builder.to_a, options)
-
end
-
-
2
wrappers class: :input, hint_class: :field_with_hint, error_class: :field_with_errors do |b|
-
2
b.use :html5
-
-
2
b.use :min_max
-
2
b.use :maxlength
-
2
b.use :placeholder
-
2
b.optional :pattern
-
2
b.optional :readonly
-
-
2
b.use :label_input
-
2
b.use :hint, wrap_with: { tag: :span, class: :hint }
-
2
b.use :error, wrap_with: { tag: :span, class: :error }
-
end
-
-
2
def self.additional_classes_for(component)
-
generate_additional_classes_for.include?(component) ? yield : []
-
end
-
-
## SETUP
-
-
2
def self.default_input_size=(*)
-
ActiveSupport::Deprecation.warn "[SIMPLE_FORM] SimpleForm.default_input_size= is deprecated and has no effect", caller
-
end
-
-
2
def self.form_class=(value)
-
ActiveSupport::Deprecation.warn "[SIMPLE_FORM] SimpleForm.form_class= is deprecated and will be removed in 4.x. Use SimpleForm.default_form_class= instead", caller
-
@@form_class = value
-
end
-
-
# Default way to setup Simple Form. Run rails generate simple_form:install
-
# to create a fresh initializer with all configuration values.
-
2
def self.setup
-
4
@@configured = true
-
4
yield self
-
end
-
end
-
-
2
require 'simple_form/railtie' if defined?(Rails)
-
2
module SimpleForm
-
2
module ActionViewExtensions
-
# A collection of methods required by simple_form but added to rails default form.
-
# This means that you can use such methods outside simple_form context.
-
2
module Builder
-
-
# Wrapper for using SimpleForm inside a default rails form.
-
# Example:
-
#
-
# form_for @user do |f|
-
# f.simple_fields_for :posts do |posts_form|
-
# # Here you have all simple_form methods available
-
# posts_form.input :title
-
# end
-
# end
-
2
def simple_fields_for(*args, &block)
-
options = args.extract_options!
-
options[:wrapper] = self.options[:wrapper] if options[:wrapper].nil?
-
options[:defaults] ||= self.options[:defaults]
-
options[:wrapper_mappings] ||= self.options[:wrapper_mappings]
-
-
if self.class < ActionView::Helpers::FormBuilder
-
options[:builder] ||= self.class
-
else
-
options[:builder] ||= SimpleForm::FormBuilder
-
end
-
fields_for(*args, options, &block)
-
end
-
end
-
end
-
end
-
-
2
module ActionView::Helpers
-
2
class FormBuilder
-
2
include SimpleForm::ActionViewExtensions::Builder
-
end
-
end
-
2
module SimpleForm
-
2
module ActionViewExtensions
-
# This module creates SimpleForm wrappers around default form_for and fields_for.
-
#
-
# Example:
-
#
-
# simple_form_for @user do |f|
-
# f.input :name, hint: 'My hint'
-
# end
-
#
-
2
module FormHelper
-
-
2
def simple_form_for(record, options = {}, &block)
-
options[:builder] ||= SimpleForm::FormBuilder
-
options[:html] ||= {}
-
unless options[:html].key?(:novalidate)
-
options[:html][:novalidate] = !SimpleForm.browser_validations
-
end
-
if options[:html].key?(:class)
-
options[:html][:class] = [SimpleForm.form_class, options[:html][:class]].compact
-
else
-
options[:html][:class] = [SimpleForm.form_class, SimpleForm.default_form_class, simple_form_css_class(record, options)].compact
-
end
-
-
with_simple_form_field_error_proc do
-
form_for(record, options, &block)
-
end
-
end
-
-
2
def simple_fields_for(record_name, record_object = nil, options = {}, &block)
-
options, record_object = record_object, nil if record_object.is_a?(Hash) && record_object.extractable_options?
-
options[:builder] ||= SimpleForm::FormBuilder
-
-
with_simple_form_field_error_proc do
-
fields_for(record_name, record_object, options, &block)
-
end
-
end
-
-
2
private
-
-
2
def with_simple_form_field_error_proc
-
default_field_error_proc = ::ActionView::Base.field_error_proc
-
begin
-
::ActionView::Base.field_error_proc = SimpleForm.field_error_proc
-
yield
-
ensure
-
::ActionView::Base.field_error_proc = default_field_error_proc
-
end
-
end
-
-
2
def simple_form_css_class(record, options)
-
html_options = options[:html]
-
as = options[:as]
-
-
if html_options.key?(:class)
-
html_options[:class]
-
elsif record.is_a?(String) || record.is_a?(Symbol)
-
as || record
-
else
-
record = record.last if record.is_a?(Array)
-
action = record.respond_to?(:persisted?) && record.persisted? ? :edit : :new
-
as ? "#{action}_#{as}" : dom_class(record, action)
-
end
-
end
-
end
-
end
-
end
-
-
2
ActionView::Base.send :include, SimpleForm::ActionViewExtensions::FormHelper
-
2
require 'rails/railtie'
-
-
2
module SimpleForm
-
2
class Railtie < Rails::Railtie
-
2
config.eager_load_namespaces << SimpleForm
-
-
2
config.after_initialize do
-
2
unless SimpleForm.configured?
-
warn '[Simple Form] Simple Form is not configured in the application and will use the default values.' +
-
' Use `rails generate simple_form:install` to generate the Simple Form configuration.'
-
end
-
end
-
end
-
end
-
2
module SimpleForm
-
2
module Wrappers
-
2
autoload :Builder, 'simple_form/wrappers/builder'
-
2
autoload :Many, 'simple_form/wrappers/many'
-
2
autoload :Root, 'simple_form/wrappers/root'
-
2
autoload :Single, 'simple_form/wrappers/single'
-
2
autoload :Leaf, 'simple_form/wrappers/leaf'
-
end
-
end
-
2
module SimpleForm
-
2
module Wrappers
-
# Provides the builder syntax for components. The builder provides
-
# three methods `use`, `optional` and `wrapper` and they allow the following invocations:
-
#
-
# config.wrappers do |b|
-
# # Use a single component
-
# b.use :html5
-
#
-
# # Use the component, but do not automatically lookup. It will only be triggered when
-
# # :placeholder is explicitly set.
-
# b.optional :placeholder
-
#
-
# # Use a component with specific wrapper options
-
# b.use :error, wrap_with: { tag: "span", class: "error" }
-
#
-
# # Use a set of components by wrapping them in a tag+class.
-
# b.wrapper tag: "div", class: "another" do |ba|
-
# ba.use :label
-
# ba.use :input
-
# end
-
#
-
# # Use a set of components by wrapping them in a tag+class.
-
# # This wrapper is identified by :label_input, which means it can
-
# # be turned off on demand with `f.input :name, label_input: false`
-
# b.wrapper :label_input, tag: "div", class: "another" do |ba|
-
# ba.use :label
-
# ba.use :input
-
# end
-
# end
-
#
-
# The builder also accepts default options at the root level. This is usually
-
# used if you want a component to be disabled by default:
-
#
-
# config.wrappers hint: false do |b|
-
# b.use :hint
-
# b.use :label_input
-
# end
-
#
-
# In the example above, hint defaults to false, which means it won't automatically
-
# do the lookup anymore. It will only be triggered when :hint is explicitly set.
-
2
class Builder
-
2
def initialize(options)
-
38
@options = options
-
38
@components = []
-
end
-
-
2
def use(name, options = {})
-
184
if options && wrapper = options[:wrap_with]
-
48
@components << Single.new(name, wrapper, options.except(:wrap_with))
-
else
-
136
@components << Leaf.new(name, options)
-
end
-
end
-
-
2
def optional(name, options = {}, &block)
-
54
@options[name] = false
-
54
use(name, options)
-
end
-
-
2
def wrapper(name, options = nil)
-
14
if block_given?
-
14
name, options = nil, name if name.is_a?(Hash)
-
14
builder = self.class.new(@options)
-
14
options ||= {}
-
14
options[:tag] = :div if options[:tag].nil?
-
14
yield builder
-
14
@components << Many.new(name, builder.to_a, options)
-
else
-
raise ArgumentError, "A block is required as argument to wrapper"
-
end
-
end
-
-
2
def to_a
-
38
@components
-
end
-
end
-
end
-
end
-
2
module SimpleForm
-
2
module Wrappers
-
2
class Leaf
-
2
attr_reader :namespace
-
-
2
def initialize(namespace, options = {})
-
184
@namespace = namespace
-
184
@options = options
-
end
-
-
2
def render(input)
-
method = input.method(@namespace)
-
-
if method.arity == 0
-
ActiveSupport::Deprecation.warn(SimpleForm::CUSTOM_INPUT_DEPRECATION_WARN % { name: @namespace })
-
-
method.call
-
else
-
method.call(@options)
-
end
-
end
-
-
2
def find(name)
-
self if @namespace == name
-
end
-
end
-
end
-
end
-
2
module SimpleForm
-
2
module Wrappers
-
# A wrapper is an object that holds several components and render them.
-
# A component may be any object that responds to `render`.
-
# This API allows inputs/components to be easily wrapped, removing the
-
# need to modify the code only to wrap input in an extra tag.
-
#
-
# `Many` represents a wrapper around several components at the same time.
-
# It may optionally receive a namespace, allowing it to be configured
-
# on demand on input generation.
-
2
class Many
-
2
attr_reader :namespace, :defaults, :components
-
-
2
def initialize(namespace, components, defaults = {})
-
86
@namespace = namespace
-
86
@components = components
-
86
@defaults = defaults
-
86
@defaults[:tag] = :div unless @defaults.key?(:tag)
-
86
@defaults[:class] = Array(@defaults[:class])
-
end
-
-
2
def render(input)
-
content = "".html_safe
-
options = input.options
-
-
components.each do |component|
-
next if options[component.namespace] == false
-
rendered = component.render(input)
-
content.safe_concat rendered.to_s if rendered
-
end
-
-
wrap(input, options, content)
-
end
-
-
2
def find(name)
-
return self if namespace == name
-
-
@components.each do |c|
-
if c.is_a?(Symbol)
-
return nil if c == namespace
-
elsif value = c.find(name)
-
return value
-
end
-
end
-
-
nil
-
end
-
-
2
private
-
-
2
def wrap(input, options, content)
-
return content if options[namespace] == false
-
return if defaults[:unless_blank] && content.empty?
-
-
tag = (namespace && options[:"#{namespace}_tag"]) || @defaults[:tag]
-
return content unless tag
-
-
klass = html_classes(input, options)
-
opts = html_options(options)
-
opts[:class] = (klass << opts[:class]).join(' ').strip unless klass.empty?
-
input.template.content_tag(tag, content, opts)
-
end
-
-
2
def html_options(options)
-
(@defaults[:html] || {}).merge(options[:"#{namespace}_html"] || {})
-
end
-
-
2
def html_classes(input, options)
-
@defaults[:class].dup
-
end
-
end
-
end
-
end
-
2
module SimpleForm
-
2
module Wrappers
-
# `Root` is the root wrapper for all components. It is special cased to
-
# always have a namespace and to add special html classes.
-
2
class Root < Many
-
2
attr_reader :options
-
-
2
def initialize(*args)
-
24
super(:wrapper, *args)
-
24
@options = @defaults.except(:tag, :class, :error_class, :hint_class)
-
end
-
-
2
def render(input)
-
input.options.reverse_merge!(@options)
-
super
-
end
-
-
# Provide a fallback if name cannot be found.
-
2
def find(name)
-
super || SimpleForm::Wrappers::Many.new(name, [Leaf.new(name)])
-
end
-
-
2
private
-
-
2
def html_classes(input, options)
-
css = options[:wrapper_class] ? Array(options[:wrapper_class]) : @defaults[:class]
-
css += SimpleForm.additional_classes_for(:wrapper) do
-
input.additional_classes + [input.input_class]
-
end
-
css << (options[:wrapper_error_class] || @defaults[:error_class]) if input.has_errors?
-
css << (options[:wrapper_hint_class] || @defaults[:hint_class]) if input.has_hint?
-
css.compact
-
end
-
end
-
end
-
end
-
2
module SimpleForm
-
2
module Wrappers
-
# `Single` is an optimization for a wrapper that has only one component.
-
2
class Single < Many
-
2
def initialize(name, wrapper_options = {}, options = {})
-
48
@component = Leaf.new(name, options)
-
-
48
super(name, [@component], wrapper_options)
-
end
-
-
2
def render(input)
-
options = input.options
-
if options[namespace] != false
-
content = @component.render(input)
-
wrap(input, options, content) if content
-
end
-
end
-
-
2
private
-
-
2
def html_options(options)
-
[:label, :input].include?(namespace) ? {} : super
-
end
-
end
-
end
-
end
-
2
require 'sprockets/version'
-
-
2
module Sprockets
-
# Environment
-
2
autoload :Base, "sprockets/base"
-
2
autoload :Environment, "sprockets/environment"
-
2
autoload :Index, "sprockets/index"
-
2
autoload :Manifest, "sprockets/manifest"
-
-
# Assets
-
2
autoload :Asset, "sprockets/asset"
-
2
autoload :BundledAsset, "sprockets/bundled_asset"
-
2
autoload :ProcessedAsset, "sprockets/processed_asset"
-
2
autoload :StaticAsset, "sprockets/static_asset"
-
-
# Processing
-
2
autoload :Context, "sprockets/context"
-
2
autoload :EcoTemplate, "sprockets/eco_template"
-
2
autoload :EjsTemplate, "sprockets/ejs_template"
-
2
autoload :JstProcessor, "sprockets/jst_processor"
-
2
autoload :Processor, "sprockets/processor"
-
2
autoload :SassCacheStore, "sprockets/sass_cache_store"
-
2
autoload :SassFunctions, "sprockets/sass_functions"
-
2
autoload :SassImporter, "sprockets/sass_importer"
-
2
autoload :SassTemplate, "sprockets/sass_template"
-
2
autoload :ScssTemplate, "sprockets/scss_template"
-
-
# Internal utilities
-
2
autoload :ArgumentError, "sprockets/errors"
-
2
autoload :AssetAttributes, "sprockets/asset_attributes"
-
2
autoload :CircularDependencyError, "sprockets/errors"
-
2
autoload :ContentTypeMismatch, "sprockets/errors"
-
2
autoload :EngineError, "sprockets/errors"
-
2
autoload :Error, "sprockets/errors"
-
2
autoload :FileNotFound, "sprockets/errors"
-
2
autoload :Utils, "sprockets/utils"
-
-
2
module Cache
-
2
autoload :FileStore, "sprockets/cache/file_store"
-
end
-
-
# Extend Sprockets module to provide global registry
-
2
require 'hike'
-
2
require 'sprockets/engines'
-
2
require 'sprockets/mime'
-
2
require 'sprockets/processing'
-
2
require 'sprockets/compressing'
-
2
require 'sprockets/paths'
-
2
extend Engines, Mime, Processing, Compressing, Paths
-
-
2
@trail = Hike::Trail.new(File.expand_path('..', __FILE__))
-
2
@mime_types = {}
-
2
@engines = {}
-
6
@preprocessors = Hash.new { |h, k| h[k] = [] }
-
4
@postprocessors = Hash.new { |h, k| h[k] = [] }
-
4
@bundle_processors = Hash.new { |h, k| h[k] = [] }
-
6
@compressors = Hash.new { |h, k| h[k] = {} }
-
-
2
register_mime_type 'text/css', '.css'
-
2
register_mime_type 'application/javascript', '.js'
-
-
2
require 'sprockets/directive_processor'
-
2
register_preprocessor 'text/css', DirectiveProcessor
-
2
register_preprocessor 'application/javascript', DirectiveProcessor
-
-
2
require 'sprockets/safety_colons'
-
2
register_postprocessor 'application/javascript', SafetyColons
-
-
2
require 'sprockets/charset_normalizer'
-
2
register_bundle_processor 'text/css', CharsetNormalizer
-
-
2
require 'sprockets/sass_compressor'
-
2
register_compressor 'text/css', :sass, SassCompressor
-
2
register_compressor 'text/css', :scss, SassCompressor
-
-
2
require 'sprockets/yui_compressor'
-
2
register_compressor 'text/css', :yui, YUICompressor
-
-
2
require 'sprockets/closure_compressor'
-
2
register_compressor 'application/javascript', :closure, ClosureCompressor
-
-
2
require 'sprockets/uglifier_compressor'
-
2
register_compressor 'application/javascript', :uglifier, UglifierCompressor
-
2
register_compressor 'application/javascript', :uglify, UglifierCompressor
-
-
2
require 'sprockets/yui_compressor'
-
2
register_compressor 'application/javascript', :yui, YUICompressor
-
-
# Cherry pick the default Tilt engines that make sense for
-
# Sprockets. We don't need ones that only generate html like HAML.
-
-
# Mmm, CoffeeScript
-
2
register_engine '.coffee', Tilt::CoffeeScriptTemplate
-
-
# JST engines
-
2
register_engine '.jst', JstProcessor
-
2
register_engine '.eco', EcoTemplate
-
2
register_engine '.ejs', EjsTemplate
-
-
# CSS engines
-
2
register_engine '.less', Tilt::LessTemplate
-
2
register_engine '.sass', SassTemplate
-
2
register_engine '.scss', ScssTemplate
-
-
# Other
-
2
register_engine '.erb', Tilt::ERBTemplate
-
2
register_engine '.str', Tilt::StringTemplate
-
end
-
2
require 'time'
-
2
require 'set'
-
-
2
module Sprockets
-
# `Asset` is the base class for `BundledAsset` and `StaticAsset`.
-
2
class Asset
-
# Internal initializer to load `Asset` from serialized `Hash`.
-
2
def self.from_hash(environment, hash)
-
91
return unless hash.is_a?(Hash)
-
-
91
klass = case hash['class']
-
when 'BundledAsset'
-
2
BundledAsset
-
when 'ProcessedAsset'
-
88
ProcessedAsset
-
when 'StaticAsset'
-
1
StaticAsset
-
else
-
nil
-
end
-
-
91
if klass
-
91
asset = klass.allocate
-
91
asset.init_with(environment, hash)
-
89
asset
-
end
-
rescue UnserializeError
-
2
nil
-
end
-
-
2
attr_reader :logical_path, :pathname
-
2
attr_reader :content_type, :mtime, :length, :digest
-
2
alias_method :bytesize, :length
-
-
2
def initialize(environment, logical_path, pathname)
-
4
raise ArgumentError, "Asset logical path has no extension: #{logical_path}" if File.extname(logical_path) == ""
-
-
4
@root = environment.root
-
4
@logical_path = logical_path.to_s
-
4
@pathname = Pathname.new(pathname)
-
4
@content_type = environment.content_type_of(pathname)
-
# drop precision to 1 second, same pattern followed elsewhere
-
4
@mtime = Time.at(environment.stat(pathname).mtime.to_i)
-
4
@length = environment.stat(pathname).size
-
4
@digest = environment.file_digest(pathname).hexdigest
-
end
-
-
# Initialize `Asset` from serialized `Hash`.
-
2
def init_with(environment, coder)
-
91
@root = environment.root
-
-
91
@logical_path = coder['logical_path']
-
91
@content_type = coder['content_type']
-
91
@digest = coder['digest']
-
-
91
if pathname = coder['pathname']
-
# Expand `$root` placeholder and wrapper string in a `Pathname`
-
91
@pathname = Pathname.new(expand_root_path(pathname))
-
end
-
-
91
if mtime = coder['mtime']
-
91
@mtime = Time.at(mtime)
-
end
-
-
91
if length = coder['length']
-
# Convert length to an `Integer`
-
91
@length = Integer(length)
-
end
-
end
-
-
# Copy serialized attributes to the coder object
-
2
def encode_with(coder)
-
4
coder['class'] = self.class.name.sub(/Sprockets::/, '')
-
4
coder['logical_path'] = logical_path
-
4
coder['pathname'] = relativize_root_path(pathname).to_s
-
4
coder['content_type'] = content_type
-
4
coder['mtime'] = mtime.to_i
-
4
coder['length'] = length
-
4
coder['digest'] = digest
-
end
-
-
# Return logical path with digest spliced in.
-
#
-
# "foo/bar-37b51d194a7513e45b56f6524f2d51f2.js"
-
#
-
2
def digest_path
-
78
logical_path.sub(/\.(\w+)$/) { |ext| "-#{digest}#{ext}" }
-
end
-
-
# Return an `Array` of `Asset` files that are declared dependencies.
-
2
def dependencies
-
[]
-
end
-
-
# Expand asset into an `Array` of parts.
-
#
-
# Appending all of an assets body parts together should give you
-
# the asset's contents as a whole.
-
#
-
# This allows you to link to individual files for debugging
-
# purposes.
-
2
def to_a
-
[self]
-
end
-
-
# `body` is aliased to source by default if it can't have any dependencies.
-
2
def body
-
source
-
end
-
-
# Return `String` of concatenated source.
-
2
def to_s
-
88
source
-
end
-
-
# Add enumerator to allow `Asset` instances to be used as Rack
-
# compatible body objects.
-
2
def each
-
yield to_s
-
end
-
-
# Checks if Asset is fresh by comparing the actual mtime and
-
# digest to the inmemory model.
-
#
-
# Used to test if cached models need to be rebuilt.
-
2
def fresh?(environment)
-
# Check current mtime and digest
-
1
dependency_fresh?(environment, self)
-
end
-
-
# Checks if Asset is stale by comparing the actual mtime and
-
# digest to the inmemory model.
-
#
-
# Subclass must override `fresh?` or `stale?`.
-
2
def stale?(environment)
-
!fresh?(environment)
-
end
-
-
# Save asset to disk.
-
2
def write_to(filename, options = {})
-
# Gzip contents if filename has '.gz'
-
unless options.key?(:compress)
-
options[:compress] = File.extname(filename) == '.gz' && File.extname(logical_path) != '.gz'
-
end
-
-
FileUtils.mkdir_p File.dirname(filename)
-
-
File.open("#{filename}+", 'wb') do |f|
-
if options[:compress]
-
# Run contents through `Zlib`
-
gz = Zlib::GzipWriter.new(f, Zlib::BEST_COMPRESSION)
-
gz.mtime = mtime.to_i
-
gz.write to_s
-
gz.close
-
else
-
# Write out as is
-
f.write to_s
-
end
-
end
-
-
# Atomic write
-
FileUtils.mv("#{filename}+", filename)
-
-
# Set mtime correctly
-
File.utime(mtime, mtime, filename)
-
-
nil
-
ensure
-
# Ensure tmp file gets cleaned up
-
FileUtils.rm("#{filename}+") if File.exist?("#{filename}+")
-
end
-
-
# Pretty inspect
-
2
def inspect
-
"#<#{self.class}:0x#{object_id.to_s(16)} " +
-
"pathname=#{pathname.to_s.inspect}, " +
-
"mtime=#{mtime.inspect}, " +
-
"digest=#{digest.inspect}" +
-
">"
-
end
-
-
2
def hash
-
267
digest.hash
-
end
-
-
# Assets are equal if they share the same path, mtime and digest.
-
2
def eql?(other)
-
other.class == self.class &&
-
342
other.logical_path == self.logical_path &&
-
other.mtime.to_i == self.mtime.to_i &&
-
other.digest == self.digest
-
end
-
2
alias_method :==, :eql?
-
-
2
protected
-
# Internal: String paths that are marked as dependencies after processing.
-
#
-
# Default to an empty `Array`.
-
2
def dependency_paths
-
52
@dependency_paths ||= []
-
end
-
-
# Internal: `ProccessedAsset`s that are required after processing.
-
#
-
# Default to an empty `Array`.
-
2
def required_assets
-
64
@required_assets ||= []
-
end
-
-
# Get pathname with its root stripped.
-
2
def relative_pathname
-
@relative_pathname ||= Pathname.new(relativize_root_path(pathname))
-
end
-
-
# Replace `$root` placeholder with actual environment root.
-
2
def expand_root_path(path)
-
575
path.to_s.sub(/^\$root/, @root)
-
end
-
-
# Replace actual environment root with `$root` placeholder.
-
2
def relativize_root_path(path)
-
202
path.to_s.sub(/^#{Regexp.escape(@root)}/, '$root')
-
end
-
-
# Check if dependency is fresh.
-
#
-
# `dep` is a `Hash` with `path`, `mtime` and `hexdigest` keys.
-
#
-
# A `Hash` is used rather than other `Asset` object because we
-
# want to test non-asset files and directories.
-
2
def dependency_fresh?(environment, dep)
-
159
path, mtime, hexdigest = dep.pathname.to_s, dep.mtime, dep.digest
-
-
159
stat = environment.stat(path)
-
-
# If path no longer exists, its definitely stale.
-
159
if stat.nil?
-
return false
-
end
-
-
# Compare dependency mtime to the actual mtime. If the
-
# dependency mtime is newer than the actual mtime, the file
-
# hasn't changed since we created this `Asset` instance.
-
#
-
# However, if the mtime is newer it doesn't mean the asset is
-
# stale. Many deployment environments may recopy or recheckout
-
# assets on each deploy. In this case the mtime would be the
-
# time of deploy rather than modified time.
-
#
-
# Note: to_i is used in eql? and write_to we assume fidelity of 1 second
-
# if people save files more frequently than 1 second sprockets may
-
# not pick it up, by design
-
159
if mtime.to_i >= stat.mtime.to_i
-
156
return true
-
end
-
-
3
digest = environment.file_digest(path)
-
-
# If the mtime is newer, do a full digest comparsion. Return
-
# fresh if the digests match.
-
3
if hexdigest == digest.hexdigest
-
1
return true
-
end
-
-
# Otherwise, its stale.
-
2
false
-
end
-
end
-
end
-
2
require 'pathname'
-
-
2
module Sprockets
-
# `AssetAttributes` is a wrapper similar to `Pathname` that provides
-
# some helper accessors.
-
#
-
# These methods should be considered internalish.
-
2
class AssetAttributes
-
2
attr_reader :environment, :pathname
-
-
2
def initialize(environment, path)
-
440
@environment = environment
-
440
@pathname = path.is_a?(Pathname) ? path : Pathname.new(path.to_s)
-
end
-
-
# Returns paths search the load path for.
-
2
def search_paths
-
16
paths = [pathname.to_s]
-
-
16
extension = format_extension
-
16
path_without_extension = extension ?
-
pathname.sub(extension, '') :
-
pathname
-
-
# optimization: bower.json can only be nested one level deep
-
16
if !path_without_extension.to_s.index('/')
-
14
paths << path_without_extension.join(".bower.json").to_s
-
14
paths << path_without_extension.join("bower.json").to_s
-
# DEPRECATED bower configuration file
-
14
paths << path_without_extension.join("component.json").to_s
-
end
-
-
16
if pathname.basename(extension.to_s).to_s != 'index'
-
16
paths << path_without_extension.join("index#{extension}").to_s
-
end
-
-
16
paths
-
end
-
-
# Reverse guess logical path for fully expanded path.
-
#
-
# This has some known issues. For an example if a file is
-
# shaddowed in the path, but is required relatively, its logical
-
# path will be incorrect.
-
2
def logical_path
-
848
if root_path = environment.paths.detect { |path| pathname.to_s[path] }
-
88
path = pathname.to_s.sub("#{root_path}/", '')
-
88
path = pathname.relative_path_from(Pathname.new(root_path)).to_s
-
139
path = engine_extensions.inject(path) { |p, ext| p.sub(ext, '') }
-
88
path = "#{path}#{engine_format_extension}" unless format_extension
-
88
path
-
else
-
raise FileOutsidePaths, "#{pathname} isn't in paths: #{environment.paths.join(', ')}"
-
end
-
end
-
-
# Returns `Array` of extension `String`s.
-
#
-
# "foo.js.coffee"
-
# # => [".js", ".coffee"]
-
#
-
2
def extensions
-
885
@extensions ||= @pathname.basename.to_s.scan(/\.[^.]+/)
-
end
-
-
# Returns the format extension.
-
#
-
# "foo.js.coffee"
-
# # => ".js"
-
#
-
2
def format_extension
-
576
extensions.reverse.detect { |ext|
-
662
@environment.mime_types(ext) && !@environment.engines(ext)
-
}
-
end
-
-
# Returns an `Array` of engine extensions.
-
#
-
# "foo.js.coffee.erb"
-
# # => [".coffee", ".erb"]
-
#
-
2
def engine_extensions
-
120
exts = extensions
-
-
120
if offset = extensions.index(format_extension)
-
69
exts = extensions[offset+1..-1]
-
end
-
-
197
exts.select { |ext| @environment.engines(ext) }
-
end
-
-
# Returns engine classes.
-
2
def engines
-
58
engine_extensions.map { |ext| @environment.engines(ext) }
-
end
-
-
# Returns all processors to run on the path.
-
2
def processors
-
environment.preprocessors(content_type) +
-
engines.reverse +
-
6
environment.postprocessors(content_type)
-
end
-
-
# Returns the content type for the pathname. Falls back to `application/octet-stream`.
-
2
def content_type
-
@content_type ||= begin
-
170
if format_extension.nil?
-
1
engine_content_type || 'application/octet-stream'
-
else
-
@environment.mime_types(format_extension) ||
-
169
engine_content_type ||
-
'application/octet-stream'
-
end
-
176
end
-
end
-
-
2
private
-
# Returns implicit engine content type.
-
#
-
# `.coffee` files carry an implicit `application/javascript`
-
# content type.
-
2
def engine_content_type
-
26
engines.reverse.each do |engine|
-
26
if engine.respond_to?(:default_mime_type) && engine.default_mime_type
-
26
return engine.default_mime_type
-
end
-
end
-
nil
-
end
-
-
2
def engine_format_extension
-
25
if content_type = engine_content_type
-
25
environment.extension_for_mime_type(content_type)
-
end
-
end
-
end
-
end
-
2
require 'sprockets/asset_attributes'
-
2
require 'sprockets/bundled_asset'
-
2
require 'sprockets/caching'
-
2
require 'sprockets/errors'
-
2
require 'sprockets/processed_asset'
-
2
require 'sprockets/server'
-
2
require 'sprockets/static_asset'
-
2
require 'multi_json'
-
2
require 'pathname'
-
-
2
module Sprockets
-
# `Base` class for `Environment` and `Index`.
-
2
class Base
-
2
include Caching, Paths, Mime, Processing, Compressing, Engines, Server
-
-
# Returns a `Digest` implementation class.
-
#
-
# Defaults to `Digest::MD5`.
-
2
attr_reader :digest_class
-
-
# Assign a `Digest` implementation class. This may be any Ruby
-
# `Digest::` implementation such as `Digest::MD5` or
-
# `Digest::SHA1`.
-
#
-
# environment.digest_class = Digest::SHA1
-
#
-
2
def digest_class=(klass)
-
expire_index!
-
@digest_class = klass
-
end
-
-
# The `Environment#version` is a custom value used for manually
-
# expiring all asset caches.
-
#
-
# Sprockets is able to track most file and directory changes and
-
# will take care of expiring the cache for you. However, its
-
# impossible to know when any custom helpers change that you mix
-
# into the `Context`.
-
#
-
# It would be wise to increment this value anytime you make a
-
# configuration change to the `Environment` object.
-
2
attr_reader :version
-
-
# Assign an environment version.
-
#
-
# environment.version = '2.0'
-
#
-
2
def version=(version)
-
4
expire_index!
-
4
@version = version
-
end
-
-
# Returns a `Digest` instance for the `Environment`.
-
#
-
# This value serves two purposes. If two `Environment`s have the
-
# same digest value they can be treated as equal. This is more
-
# useful for comparing environment states between processes rather
-
# than in the same. Two equal `Environment`s can share the same
-
# cached assets.
-
#
-
# The value also provides a seed digest for all `Asset`
-
# digests. Any change in the environment digest will affect all of
-
# its assets.
-
2
def digest
-
# Compute the initial digest using the implementation class. The
-
# Sprockets release version and custom environment version are
-
# mixed in. So any new releases will affect all your assets.
-
112
@digest ||= digest_class.new.update(VERSION).update(version.to_s)
-
-
# Returned a dupped copy so the caller can safely mutate it with `.update`
-
112
@digest.dup
-
end
-
-
# Get and set `Logger` instance.
-
2
attr_accessor :logger
-
-
# Get `Context` class.
-
#
-
# This class maybe mutated and mixed in with custom helpers.
-
#
-
# environment.context_class.instance_eval do
-
# include MyHelpers
-
# def asset_url; end
-
# end
-
#
-
2
attr_reader :context_class
-
-
# Get persistent cache store
-
2
attr_reader :cache
-
-
# Set persistent cache store
-
#
-
# The cache store must implement a pair of getters and
-
# setters. Either `get(key)`/`set(key, value)`,
-
# `[key]`/`[key]=value`, `read(key)`/`write(key, value)`.
-
2
def cache=(cache)
-
2
expire_index!
-
2
@cache = cache
-
end
-
-
2
def prepend_path(path)
-
# Overrides the global behavior to expire the index
-
expire_index!
-
super
-
end
-
-
2
def append_path(path)
-
# Overrides the global behavior to expire the index
-
60
expire_index!
-
60
super
-
end
-
-
2
def clear_paths
-
# Overrides the global behavior to expire the index
-
expire_index!
-
super
-
end
-
-
# Finds the expanded real path for a given logical path by
-
# searching the environment's paths.
-
#
-
# resolve("application.js")
-
# # => "/path/to/app/javascripts/application.js.coffee"
-
#
-
# A `FileNotFound` exception is raised if the file does not exist.
-
2
def resolve(logical_path, options = {})
-
# If a block is given, preform an iterable search
-
19
if block_given?
-
16
args = attributes_for(logical_path).search_paths + [options]
-
16
@trail.find(*args) do |path|
-
18
pathname = Pathname.new(path)
-
18
if %w( .bower.json bower.json component.json ).include?(pathname.basename.to_s)
-
bower = json_decode(pathname.read)
-
case bower['main']
-
when String
-
yield pathname.dirname.join(bower['main'])
-
when Array
-
extname = File.extname(logical_path)
-
bower['main'].each do |fn|
-
if extname == "" || extname == File.extname(fn)
-
yield pathname.dirname.join(fn)
-
end
-
end
-
end
-
else
-
18
yield pathname
-
end
-
end
-
else
-
3
resolve(logical_path, options) do |pathname|
-
3
return pathname
-
end
-
raise FileNotFound, "couldn't find file '#{logical_path}'"
-
end
-
end
-
-
# Register a new mime type.
-
2
def register_mime_type(mime_type, ext)
-
# Overrides the global behavior to expire the index
-
expire_index!
-
@trail.append_extension(ext)
-
super
-
end
-
-
# Registers a new Engine `klass` for `ext`.
-
2
def register_engine(ext, klass)
-
# Overrides the global behavior to expire the index
-
expire_index!
-
add_engine_to_trail(ext, klass)
-
super
-
end
-
-
2
def register_preprocessor(mime_type, klass, &block)
-
# Overrides the global behavior to expire the index
-
expire_index!
-
super
-
end
-
-
2
def unregister_preprocessor(mime_type, klass)
-
# Overrides the global behavior to expire the index
-
expire_index!
-
super
-
end
-
-
2
def register_postprocessor(mime_type, klass, &block)
-
# Overrides the global behavior to expire the index
-
expire_index!
-
super
-
end
-
-
2
def unregister_postprocessor(mime_type, klass)
-
# Overrides the global behavior to expire the index
-
expire_index!
-
super
-
end
-
-
2
def register_bundle_processor(mime_type, klass, &block)
-
# Overrides the global behavior to expire the index
-
2
expire_index!
-
2
super
-
end
-
-
2
def unregister_bundle_processor(mime_type, klass)
-
# Overrides the global behavior to expire the index
-
expire_index!
-
super
-
end
-
-
# Return an `Index`. Must be implemented by the subclass.
-
2
def index
-
raise NotImplementedError
-
end
-
-
2
if defined? Encoding.default_external
-
# Define `default_external_encoding` accessor on 1.9.
-
# Defaults to UTF-8.
-
2
attr_accessor :default_external_encoding
-
end
-
-
# Works like `Dir.entries`.
-
#
-
# Subclasses may cache this method.
-
2
def entries(pathname)
-
4
@trail.entries(pathname)
-
end
-
-
# Works like `File.stat`.
-
#
-
# Subclasses may cache this method.
-
2
def stat(path)
-
524
@trail.stat(path)
-
end
-
-
# Read and compute digest of filename.
-
#
-
# Subclasses may cache this method.
-
2
def file_digest(path)
-
5
if stat = self.stat(path)
-
# If its a file, digest the contents
-
5
if stat.file?
-
3
digest.file(path.to_s)
-
-
# If its a directive, digest the list of filenames
-
2
elsif stat.directory?
-
2
contents = self.entries(path).join(',')
-
2
digest.update(contents)
-
end
-
end
-
end
-
-
# Internal. Return a `AssetAttributes` for `path`.
-
2
def attributes_for(path)
-
440
AssetAttributes.new(self, path)
-
end
-
-
# Internal. Return content type of `path`.
-
2
def content_type_of(path)
-
164
attributes_for(path).content_type
-
end
-
-
# Find asset by logical path or expanded path.
-
2
def find_asset(path, options = {})
-
92
logical_path = path
-
92
pathname = Pathname.new(path).cleanpath
-
-
92
if pathname.absolute?
-
89
return unless stat(pathname)
-
88
logical_path = attributes_for(pathname).logical_path
-
else
-
3
begin
-
3
pathname = resolve(logical_path)
-
-
# If logical path is missing a mime type extension, append
-
# the absolute path extname so it has one.
-
#
-
# Ensures some consistency between finding "foo/bar" vs
-
# "foo/bar.js".
-
3
if File.extname(logical_path) == ""
-
expanded_logical_path = attributes_for(pathname).logical_path
-
logical_path += File.extname(expanded_logical_path)
-
end
-
rescue FileNotFound
-
return nil
-
end
-
end
-
-
91
build_asset(logical_path, pathname, options)
-
end
-
-
# Preferred `find_asset` shorthand.
-
#
-
# environment['application.js']
-
#
-
2
def [](*args)
-
39
find_asset(*args)
-
end
-
-
2
def each_entry(root, &block)
-
2
return to_enum(__method__, root) unless block_given?
-
2
root = Pathname.new(root) unless root.is_a?(Pathname)
-
-
2
paths = []
-
2
entries(root).sort.each do |filename|
-
41
path = root.join(filename)
-
41
paths << path
-
-
41
if stat(path).directory?
-
each_entry(path) do |subpath|
-
paths << subpath
-
end
-
end
-
end
-
-
2
paths.sort_by(&:to_s).each(&block)
-
-
nil
-
end
-
-
2
def each_file
-
return to_enum(__method__) unless block_given?
-
paths.each do |root|
-
each_entry(root) do |path|
-
if !stat(path).directory?
-
yield path
-
end
-
end
-
end
-
nil
-
end
-
-
2
def each_logical_path(*args, &block)
-
return to_enum(__method__, *args) unless block_given?
-
filters = args.flatten
-
files = {}
-
each_file do |filename|
-
if logical_path = logical_path_for_filename(filename, filters)
-
unless files[logical_path]
-
if block.arity == 2
-
yield logical_path, filename.to_s
-
else
-
yield logical_path
-
end
-
end
-
-
files[logical_path] = true
-
end
-
end
-
nil
-
end
-
-
# Pretty inspect
-
2
def inspect
-
"#<#{self.class}:0x#{object_id.to_s(16)} " +
-
"root=#{root.to_s.inspect}, " +
-
"paths=#{paths.inspect}, " +
-
"digest=#{digest.to_s.inspect}" +
-
">"
-
end
-
-
2
protected
-
# Clear index after mutating state. Must be implemented by the subclass.
-
2
def expire_index!
-
raise NotImplementedError
-
end
-
-
2
def build_asset(logical_path, pathname, options)
-
4
pathname = Pathname.new(pathname)
-
-
# If there are any processors to run on the pathname, use
-
# `BundledAsset`. Otherwise use `StaticAsset` and treat is as binary.
-
4
if attributes_for(pathname).processors.any?
-
4
if options[:bundle] == false
-
2
circular_call_protection(pathname.to_s) do
-
2
ProcessedAsset.new(index, logical_path, pathname)
-
end
-
else
-
2
BundledAsset.new(index, logical_path, pathname)
-
end
-
else
-
StaticAsset.new(index, logical_path, pathname)
-
end
-
end
-
-
2
def cache_key_for(path, options)
-
546
"#{path}:#{options[:bundle] ? '1' : '0'}"
-
end
-
-
2
def circular_call_protection(path)
-
2
reset = Thread.current[:sprockets_circular_calls].nil?
-
2
calls = Thread.current[:sprockets_circular_calls] ||= Set.new
-
2
if calls.include?(path)
-
raise CircularDependencyError, "#{path} has already been required"
-
end
-
2
calls << path
-
2
yield
-
ensure
-
2
Thread.current[:sprockets_circular_calls] = nil if reset
-
end
-
-
2
def logical_path_for_filename(filename, filters)
-
logical_path = attributes_for(filename).logical_path.to_s
-
-
if matches_filter(filters, logical_path, filename)
-
return logical_path
-
end
-
-
# If filename is an index file, retest with alias
-
if File.basename(logical_path)[/[^\.]+/, 0] == 'index'
-
path = logical_path.sub(/\/index\./, '.')
-
if matches_filter(filters, path, filename)
-
return path
-
end
-
end
-
-
nil
-
end
-
-
2
def matches_filter(filters, logical_path, filename)
-
return true if filters.empty?
-
-
filters.any? do |filter|
-
if filter.is_a?(Regexp)
-
filter.match(logical_path)
-
elsif filter.respond_to?(:call)
-
if filter.arity == 1
-
filter.call(logical_path)
-
else
-
filter.call(logical_path, filename.to_s)
-
end
-
else
-
File.fnmatch(filter.to_s, logical_path)
-
end
-
end
-
end
-
-
# Feature detect newer MultiJson API
-
2
if MultiJson.respond_to?(:dump)
-
2
def json_decode(obj)
-
MultiJson.load(obj)
-
end
-
else
-
def json_decode(obj)
-
MultiJson.decode(obj)
-
end
-
end
-
end
-
end
-
2
require 'sprockets/asset'
-
2
require 'sprockets/errors'
-
2
require 'fileutils'
-
2
require 'set'
-
2
require 'zlib'
-
-
2
module Sprockets
-
# `BundledAsset`s are used for files that need to be processed and
-
# concatenated with other assets. Use for `.js` and `.css` files.
-
2
class BundledAsset < Asset
-
2
attr_reader :source
-
-
2
def initialize(environment, logical_path, pathname)
-
2
super(environment, logical_path, pathname)
-
-
2
@processed_asset = environment.find_asset(pathname, :bundle => false)
-
2
@required_assets = @processed_asset.required_assets
-
2
@dependency_paths = @processed_asset.dependency_paths
-
-
# Explode Asset into parts and gather the dependency bodies
-
90
@source = to_a.map { |dependency| dependency.to_s }.join
-
-
# Run bundle processors on concatenated source
-
2
context = environment.context_class.new(environment, logical_path, pathname)
-
2
@source = context.evaluate(pathname, :data => @source,
-
:processors => environment.bundle_processors(content_type))
-
-
2
@mtime = (to_a + @dependency_paths).map(&:mtime).max
-
2
@length = Rack::Utils.bytesize(source)
-
2
@digest = environment.digest.update(source).hexdigest
-
end
-
-
# Initialize `BundledAsset` from serialized `Hash`.
-
2
def init_with(environment, coder)
-
2
super
-
-
2
@processed_asset = environment.find_asset(pathname, :bundle => false)
-
2
@required_assets = @processed_asset.required_assets
-
-
2
if @processed_asset.dependency_digest != coder['required_assets_digest']
-
2
raise UnserializeError, "processed asset belongs to a stale environment"
-
end
-
-
@source = coder['source']
-
end
-
-
# Serialize custom attributes in `BundledAsset`.
-
2
def encode_with(coder)
-
2
super
-
-
2
coder['source'] = source
-
2
coder['required_assets_digest'] = @processed_asset.dependency_digest
-
end
-
-
# Get asset's own processed contents. Excludes any of its required
-
# dependencies but does run any processors or engines on the
-
# original file.
-
2
def body
-
@processed_asset.source
-
end
-
-
# Return an `Array` of `Asset` files that are declared dependencies.
-
2
def dependencies
-
to_a.reject { |a| a.eql?(@processed_asset) }
-
end
-
-
# Expand asset into an `Array` of parts.
-
2
def to_a
-
4
required_assets
-
end
-
-
# Checks if Asset is stale by comparing the actual mtime and
-
# digest to the inmemory model.
-
2
def fresh?(environment)
-
@processed_asset.fresh?(environment)
-
end
-
end
-
end
-
2
require 'digest/md5'
-
2
require 'fileutils'
-
2
require 'pathname'
-
-
2
module Sprockets
-
2
module Cache
-
# A simple file system cache store.
-
#
-
# environment.cache = Sprockets::Cache::FileStore.new("/tmp")
-
#
-
2
class FileStore
-
2
def initialize(root)
-
2
@root = Pathname.new(root)
-
end
-
-
# Lookup value in cache
-
2
def [](key)
-
91
pathname = @root.join(key)
-
182
pathname.exist? ? pathname.open('rb') { |f| Marshal.load(f) } : nil
-
end
-
-
# Save value to cache
-
2
def []=(key, value)
-
# Ensure directory exists
-
8
FileUtils.mkdir_p @root.join(key).dirname
-
-
16
@root.join(key).open('w') { |f| Marshal.dump(value, f)}
-
8
value
-
end
-
end
-
end
-
end
-
2
module Sprockets
-
# `Caching` is an internal mixin whose public methods are exposed on
-
# the `Environment` and `Index` classes.
-
2
module Caching
-
# Low level cache getter for `key`. Checks a number of supported
-
# cache interfaces.
-
2
def cache_get(key)
-
# `Cache#get(key)` for Memcache
-
91
if cache.respond_to?(:get)
-
cache.get(key)
-
-
# `Cache#[key]` so `Hash` can be used
-
91
elsif cache.respond_to?(:[])
-
91
cache[key]
-
-
# `Cache#read(key)` for `ActiveSupport::Cache` support
-
elsif cache.respond_to?(:read)
-
cache.read(key)
-
-
else
-
nil
-
end
-
end
-
-
# Low level cache setter for `key`. Checks a number of supported
-
# cache interfaces.
-
2
def cache_set(key, value)
-
# `Cache#set(key, value)` for Memcache
-
8
if cache.respond_to?(:set)
-
cache.set(key, value)
-
-
# `Cache#[key]=value` so `Hash` can be used
-
elsif cache.respond_to?(:[]=)
-
8
cache[key] = value
-
-
# `Cache#write(key, value)` for `ActiveSupport::Cache` support
-
elsif cache.respond_to?(:write)
-
cache.write(key, value)
-
end
-
-
8
value
-
end
-
-
2
protected
-
# Cache helper method. Takes a `path` argument which maybe a
-
# logical path or fully expanded path. The `&block` is passed
-
# for finding and building the asset if its not in cache.
-
2
def cache_asset(path)
-
# If `cache` is not set, return fast
-
91
if cache.nil?
-
yield
-
-
# Check cache for `path`
-
91
elsif (asset = Asset.from_hash(self, cache_get_hash(path.to_s))) && asset.fresh?(self)
-
87
asset
-
-
# Otherwise yield block that slowly finds and builds the asset
-
4
elsif asset = yield
-
4
hash = {}
-
4
asset.encode_with(hash)
-
-
# Save the asset to its path
-
4
cache_set_hash(path.to_s, hash)
-
-
# Since path maybe a logical or full pathname, save the
-
# asset its its full path too
-
4
if path.to_s != asset.pathname.to_s
-
4
cache_set_hash(asset.pathname.to_s, hash)
-
end
-
-
4
asset
-
end
-
end
-
-
2
private
-
# Strips `Environment#root` from key to make the key work
-
# consisently across different servers. The key is also hashed
-
# so it does not exceed 250 characters.
-
2
def expand_cache_key(key)
-
99
File.join('sprockets', digest_class.hexdigest(key.sub(root, '')))
-
end
-
-
2
def cache_get_hash(key)
-
91
hash = cache_get(expand_cache_key(key))
-
91
if hash.is_a?(Hash) && digest.hexdigest == hash['_version']
-
91
hash
-
end
-
end
-
-
2
def cache_set_hash(key, hash)
-
8
hash['_version'] = digest.hexdigest
-
8
cache_set(expand_cache_key(key), hash)
-
8
hash
-
end
-
end
-
end
-
2
require 'tilt'
-
-
2
module Sprockets
-
# Some browsers have issues with stylesheets that contain multiple
-
# `@charset` definitions. The issue surfaces while using Sass since
-
# it inserts a `@charset` at the top of each file. Then Sprockets
-
# concatenates them together.
-
#
-
# The `CharsetNormalizer` processor strips out multiple `@charset`
-
# definitions.
-
#
-
# The current implementation is naive. It picks the first `@charset`
-
# it sees and strips the others. This works for most people because
-
# the other definitions are usually `UTF-8`. A more sophisticated
-
# approach would be to re-encode stylesheets with mixed encodings.
-
#
-
# This behavior can be disabled with:
-
#
-
# environment.unregister_bundle_processor 'text/css', Sprockets::CharsetNormalizer
-
#
-
2
class CharsetNormalizer < Tilt::Template
-
2
def prepare
-
end
-
-
2
def evaluate(context, locals, &block)
-
1
charset = nil
-
-
# Find and strip out any `@charset` definitions
-
1
filtered_data = data.gsub(/^@charset "([^"]+)";$/) {
-
1
charset ||= $1; ""
-
}
-
-
1
if charset
-
# If there was a charset, move it to the top
-
1
"@charset \"#{charset}\";#{filtered_data}"
-
else
-
data
-
end
-
end
-
end
-
end
-
2
require 'tilt'
-
-
2
module Sprockets
-
2
class ClosureCompressor < Tilt::Template
-
2
self.default_mime_type = 'application/javascript'
-
-
2
def self.engine_initialized?
-
defined?(::Closure::Compiler)
-
end
-
-
2
def initialize_engine
-
require_template_library 'closure-compiler'
-
end
-
-
2
def prepare
-
end
-
-
2
def evaluate(context, locals, &block)
-
Closure::Compiler.new.compile(data)
-
end
-
end
-
end
-
2
module Sprockets
-
# `Compressing` is an internal mixin whose public methods are exposed on
-
# the `Environment` and `Index` classes.
-
2
module Compressing
-
2
def compressors
-
6
deep_copy_hash(@compressors)
-
end
-
-
2
def register_compressor(mime_type, sym, klass)
-
14
@compressors[mime_type][sym] = klass
-
end
-
-
# Return CSS compressor or nil if none is set
-
2
def css_compressor
-
2
@css_compressor if defined? @css_compressor
-
end
-
-
# Assign a compressor to run on `text/css` assets.
-
#
-
# The compressor object must respond to `compress`.
-
2
def css_compressor=(compressor)
-
2
unregister_bundle_processor 'text/css', css_compressor if css_compressor
-
2
@css_compressor = nil
-
2
return unless compressor
-
-
2
if compressor.is_a?(Symbol)
-
2
compressor = compressors['text/css'][compressor] || raise(Error, "unknown compressor: #{compressor}")
-
end
-
-
2
if compressor.respond_to?(:compress)
-
klass = Class.new(Processor) do
-
@name = "css_compressor"
-
@processor = proc { |context, data| compressor.compress(data) }
-
end
-
@css_compressor = :css_compressor
-
else
-
2
@css_compressor = klass = compressor
-
end
-
-
2
register_bundle_processor 'text/css', klass
-
end
-
-
# Return JS compressor or nil if none is set
-
2
def js_compressor
-
2
@js_compressor if defined? @js_compressor
-
end
-
-
# Assign a compressor to run on `application/javascript` assets.
-
#
-
# The compressor object must respond to `compress`.
-
2
def js_compressor=(compressor)
-
2
unregister_bundle_processor 'application/javascript', js_compressor if js_compressor
-
2
@js_compressor = nil
-
2
return unless compressor
-
-
if compressor.is_a?(Symbol)
-
compressor = compressors['application/javascript'][compressor] || raise(Error, "unknown compressor: #{compressor}")
-
end
-
-
if compressor.respond_to?(:compress)
-
klass = Class.new(Processor) do
-
@name = "js_compressor"
-
@processor = proc { |context, data| compressor.compress(data) }
-
end
-
@js_compressor = :js_compressor
-
else
-
@js_compressor = klass = compressor
-
end
-
-
register_bundle_processor 'application/javascript', klass
-
end
-
end
-
end
-
2
require 'base64'
-
2
require 'rack/utils'
-
2
require 'sprockets/errors'
-
2
require 'sprockets/utils'
-
2
require 'pathname'
-
2
require 'set'
-
-
2
module Sprockets
-
# `Context` provides helper methods to all `Tilt` processors. They
-
# are typically accessed by ERB templates. You can mix in custom
-
# helpers by injecting them into `Environment#context_class`. Do not
-
# mix them into `Context` directly.
-
#
-
# environment.context_class.class_eval do
-
# include MyHelper
-
# def asset_url; end
-
# end
-
#
-
# <%= asset_url "foo.png" %>
-
#
-
# The `Context` also collects dependencies declared by
-
# assets. See `DirectiveProcessor` for an example of this.
-
2
class Context
-
2
attr_reader :environment, :pathname
-
2
attr_reader :_required_paths, :_stubbed_assets
-
2
attr_reader :_dependency_paths, :_dependency_assets
-
2
attr_writer :__LINE__
-
-
2
def initialize(environment, logical_path, pathname)
-
4
@environment = environment
-
4
@logical_path = logical_path
-
4
@pathname = pathname
-
4
@__LINE__ = nil
-
-
4
@_required_paths = []
-
4
@_stubbed_assets = Set.new
-
4
@_dependency_paths = Set.new
-
4
@_dependency_assets = Set.new([pathname.to_s])
-
end
-
-
# Returns the environment path that contains the file.
-
#
-
# If `app/javascripts` and `app/stylesheets` are in your path, and
-
# current file is `app/javascripts/foo/bar.js`, `root_path` would
-
# return `app/javascripts`.
-
2
def root_path
-
environment.paths.detect { |path| pathname.to_s[path] }
-
end
-
-
# Returns logical path without any file extensions.
-
#
-
# 'app/javascripts/application.js'
-
# # => 'application'
-
#
-
2
def logical_path
-
@logical_path.chomp(File.extname(@logical_path))
-
end
-
-
# Returns content type of file
-
#
-
# 'application/javascript'
-
# 'text/css'
-
#
-
2
def content_type
-
106
environment.content_type_of(pathname)
-
end
-
-
# Given a logical path, `resolve` will find and return the fully
-
# expanded path. Relative paths will also be resolved. An optional
-
# `:content_type` restriction can be supplied to restrict the
-
# search.
-
#
-
# resolve("foo.js")
-
# # => "/path/to/app/javascripts/foo.js"
-
#
-
# resolve("./bar.js")
-
# # => "/path/to/app/javascripts/bar.js"
-
#
-
2
def resolve(path, options = {}, &block)
-
164
pathname = Pathname.new(path)
-
164
attributes = environment.attributes_for(pathname)
-
-
164
if pathname.absolute?
-
138
if environment.stat(pathname)
-
138
pathname
-
else
-
raise FileNotFound, "couldn't find file '#{pathname}'"
-
end
-
-
26
elsif content_type = options[:content_type]
-
13
content_type = self.content_type if content_type == :self
-
-
13
if attributes.format_extension
-
if content_type != attributes.content_type
-
raise ContentTypeMismatch, "#{path} is " +
-
"'#{attributes.content_type}', not '#{content_type}'"
-
end
-
end
-
-
13
resolve(path) do |candidate|
-
15
if self.content_type == environment.content_type_of(candidate)
-
13
return candidate
-
end
-
end
-
-
raise FileNotFound, "couldn't find file '#{path}'"
-
else
-
13
environment.resolve(path, {:base_path => self.pathname.dirname}.merge(options), &block)
-
end
-
end
-
-
# `depend_on` allows you to state a dependency on a file without
-
# including it.
-
#
-
# This is used for caching purposes. Any changes made to
-
# the dependency file with invalidate the cache of the
-
# source file.
-
2
def depend_on(path)
-
2
@_dependency_paths << resolve(path).to_s
-
nil
-
end
-
-
# `depend_on_asset` allows you to state an asset dependency
-
# without including it.
-
#
-
# This is used for caching purposes. Any changes that would
-
# invalidate the dependency asset will invalidate the source
-
# file. Unlike `depend_on`, this will include recursively include
-
# the target asset's dependencies.
-
2
def depend_on_asset(path)
-
53
filename = resolve(path).to_s
-
53
@_dependency_assets << filename
-
nil
-
end
-
-
# `require_asset` declares `path` as a dependency of the file. The
-
# dependency will be inserted before the file and will only be
-
# included once.
-
#
-
# If ERB processing is enabled, you can use it to dynamically
-
# require assets.
-
#
-
# <%= require_asset "#{framework}.js" %>
-
#
-
2
def require_asset(path)
-
53
pathname = resolve(path, :content_type => :self)
-
53
depend_on_asset(pathname)
-
53
@_required_paths << pathname.to_s
-
nil
-
end
-
-
# `stub_asset` blacklists `path` from being included in the bundle.
-
# `path` must be an asset which may or may not already be included
-
# in the bundle.
-
2
def stub_asset(path)
-
@_stubbed_assets << resolve(path, :content_type => :self).to_s
-
nil
-
end
-
-
# Tests if target path is able to be safely required into the
-
# current concatenation.
-
2
def asset_requirable?(path)
-
39
pathname = resolve(path)
-
39
content_type = environment.content_type_of(pathname)
-
39
stat = environment.stat(path)
-
39
return false unless stat && stat.file?
-
39
self.content_type.nil? || self.content_type == content_type
-
end
-
-
# Reads `path` and runs processors on the file.
-
#
-
# This allows you to capture the result of an asset and include it
-
# directly in another.
-
#
-
# <%= evaluate "bar.js" %>
-
#
-
2
def evaluate(path, options = {})
-
4
pathname = resolve(path)
-
4
attributes = environment.attributes_for(pathname)
-
4
processors = options[:processors] || attributes.processors
-
-
4
if options[:data]
-
2
result = options[:data]
-
else
-
2
if environment.respond_to?(:default_external_encoding)
-
2
mime_type = environment.mime_types(pathname.extname)
-
2
encoding = environment.encoding_for_mime_type(mime_type)
-
2
result = Sprockets::Utils.read_unicode(pathname, encoding)
-
else
-
result = Sprockets::Utils.read_unicode(pathname)
-
end
-
end
-
-
4
processors.each do |processor|
-
5
begin
-
10
template = processor.new(pathname.to_s) { result }
-
5
result = template.render(self, {})
-
rescue Exception => e
-
annotate_exception! e
-
raise
-
end
-
end
-
-
4
result
-
end
-
-
# Returns a Base64-encoded `data:` URI with the contents of the
-
# asset at the specified path, and marks that path as a dependency
-
# of the current file.
-
#
-
# Use `asset_data_uri` from ERB with CSS or JavaScript assets:
-
#
-
# #logo { background: url(<%= asset_data_uri 'logo.png' %>) }
-
#
-
# $('<img>').attr('src', '<%= asset_data_uri 'avatar.jpg' %>')
-
#
-
2
def asset_data_uri(path)
-
depend_on_asset(path)
-
asset = environment.find_asset(path)
-
base64 = Base64.encode64(asset.to_s).gsub(/\s+/, "")
-
"data:#{asset.content_type};base64,#{Rack::Utils.escape(base64)}"
-
end
-
-
# Expands logical path to full url to asset.
-
#
-
# NOTE: This helper is currently not implemented and should be
-
# customized by the application. Though, in the future, some
-
# basics implemention may be provided with different methods that
-
# are required to be overridden.
-
2
def asset_path(path, options = {})
-
message = <<-EOS
-
Custom asset_path helper is not implemented
-
-
Extend your environment context with a custom method.
-
-
environment.context_class.class_eval do
-
def asset_path(path, options = {})
-
end
-
end
-
EOS
-
raise NotImplementedError, message
-
end
-
-
# Expand logical image asset path.
-
2
def image_path(path)
-
asset_path(path, :type => :image)
-
end
-
-
# Expand logical video asset path.
-
2
def video_path(path)
-
asset_path(path, :type => :video)
-
end
-
-
# Expand logical audio asset path.
-
2
def audio_path(path)
-
asset_path(path, :type => :audio)
-
end
-
-
# Expand logical font asset path.
-
2
def font_path(path)
-
asset_path(path, :type => :font)
-
end
-
-
# Expand logical javascript asset path.
-
2
def javascript_path(path)
-
asset_path(path, :type => :javascript)
-
end
-
-
# Expand logical stylesheet asset path.
-
2
def stylesheet_path(path)
-
asset_path(path, :type => :stylesheet)
-
end
-
-
2
private
-
# Annotates exception backtrace with the original template that
-
# the exception was raised in.
-
2
def annotate_exception!(exception)
-
location = pathname.to_s
-
location << ":#{@__LINE__}" if @__LINE__
-
-
exception.extend(Sprockets::EngineError)
-
exception.sprockets_annotation = " (in #{location})"
-
end
-
-
2
def logger
-
environment.logger
-
end
-
end
-
end
-
2
require 'pathname'
-
2
require 'shellwords'
-
2
require 'tilt'
-
2
require 'yaml'
-
-
2
module Sprockets
-
# The `DirectiveProcessor` is responsible for parsing and evaluating
-
# directive comments in a source file.
-
#
-
# A directive comment starts with a comment prefix, followed by an "=",
-
# then the directive name, then any arguments.
-
#
-
# // JavaScript
-
# //= require "foo"
-
#
-
# # CoffeeScript
-
# #= require "bar"
-
#
-
# /* CSS
-
# *= require "baz"
-
# */
-
#
-
# The Processor is implemented as a `Tilt::Template` and is loosely
-
# coupled to Sprockets. This makes it possible to disable or modify
-
# the processor to do whatever you'd like. You could add your own
-
# custom directives or invent your own directive syntax.
-
#
-
# `Environment#processors` includes `DirectiveProcessor` by default.
-
#
-
# To remove the processor entirely:
-
#
-
# env.unregister_processor('text/css', Sprockets::DirectiveProcessor)
-
# env.unregister_processor('application/javascript', Sprockets::DirectiveProcessor)
-
#
-
# Then inject your own preprocessor:
-
#
-
# env.register_processor('text/css', MyProcessor)
-
#
-
2
class DirectiveProcessor < Tilt::Template
-
# Directives will only be picked up if they are in the header
-
# of the source file. C style (/* */), JavaScript (//), and
-
# Ruby (#) comments are supported.
-
#
-
# Directives in comments after the first non-whitespace line
-
# of code will not be processed.
-
#
-
2
HEADER_PATTERN = /
-
\A (
-
(?m:\s*) (
-
(\/\* (?m:.*?) \*\/) |
-
(\#\#\# (?m:.*?) \#\#\#) |
-
(\/\/ .* \n?)+ |
-
(\# .* \n?)+
-
)
-
)+
-
/x
-
-
# Directives are denoted by a `=` followed by the name, then
-
# argument list.
-
#
-
# A few different styles are allowed:
-
#
-
# // =require foo
-
# //= require foo
-
# //= require "foo"
-
#
-
2
DIRECTIVE_PATTERN = /
-
^ \W* = \s* (\w+.*?) (\*\/)? $
-
/x
-
-
2
attr_reader :pathname
-
2
attr_reader :header, :body
-
-
2
def prepare
-
2
@pathname = Pathname.new(file)
-
-
2
@header = data[HEADER_PATTERN, 0] || ""
-
2
@body = $' || data
-
# Ensure body ends in a new line
-
2
@body += "\n" if @body != "" && @body !~ /\n\Z/m
-
-
2
@included_pathnames = []
-
2
@compat = false
-
end
-
-
# Implemented for Tilt#render.
-
#
-
# `context` is a `Context` instance with methods that allow you to
-
# access the environment and append to the bundle. See `Context`
-
# for the complete API.
-
2
def evaluate(context, locals, &block)
-
2
@context = context
-
-
2
@result = ""
-
2
@result.force_encoding(body.encoding) if body.respond_to?(:encoding)
-
-
2
@has_written_body = false
-
-
2
process_directives
-
2
process_source
-
-
2
@result
-
end
-
-
# Returns the header String with any directives stripped.
-
2
def processed_header
-
4
lineno = 0
-
@processed_header ||= header.lines.map { |line|
-
44
lineno += 1
-
# Replace directive line with a clean break
-
44
directives.assoc(lineno) ? "\n" : line
-
4
}.join.chomp
-
end
-
-
# Returns the source String with any directives stripped.
-
2
def processed_source
-
@processed_source ||= processed_header + body
-
end
-
-
# Returns an Array of directive structures. Each structure
-
# is an Array with the line number as the first element, the
-
# directive name as the second element, followed by any
-
# arguments.
-
#
-
# [[1, "require", "foo"], [2, "require", "bar"]]
-
#
-
2
def directives
-
@directives ||= header.lines.each_with_index.map { |line, index|
-
44
if directive = line[DIRECTIVE_PATTERN, 1]
-
19
name, *args = Shellwords.shellwords(directive)
-
19
if respond_to?("process_#{name}_directive", true)
-
16
[index + 1, name, *args]
-
end
-
end
-
46
}.compact
-
end
-
-
2
protected
-
2
attr_reader :included_pathnames
-
2
attr_reader :context
-
-
# Gathers comment directives in the source and processes them.
-
# Any directive method matching `process_*_directive` will
-
# automatically be available. This makes it easy to extend the
-
# processor.
-
#
-
# To implement a custom directive called `require_glob`, subclass
-
# `Sprockets::DirectiveProcessor`, then add a method called
-
# `process_require_glob_directive`.
-
#
-
# class DirectiveProcessor < Sprockets::DirectiveProcessor
-
# def process_require_glob_directive
-
# Dir["#{pathname.dirname}/#{glob}"].sort.each do |filename|
-
# require(filename)
-
# end
-
# end
-
# end
-
#
-
# Replace the current processor on the environment with your own:
-
#
-
# env.unregister_processor('text/css', Sprockets::DirectiveProcessor)
-
# env.register_processor('text/css', DirectiveProcessor)
-
#
-
2
def process_directives
-
2
directives.each do |line_number, name, *args|
-
16
context.__LINE__ = line_number
-
16
send("process_#{name}_directive", *args)
-
16
context.__LINE__ = nil
-
end
-
end
-
-
2
def process_source
-
3
unless @has_written_body || processed_header.empty?
-
2
@result << processed_header << "\n"
-
end
-
-
3
included_pathnames.each do |pathname|
-
@result << context.evaluate(pathname)
-
end
-
-
3
unless @has_written_body
-
2
@result << body
-
end
-
-
3
if compat? && constants.any?
-
@result.gsub!(/<%=(.*?)%>/) { constants[$1.strip] }
-
end
-
end
-
-
# The `require` directive functions similar to Ruby's own `require`.
-
# It provides a way to declare a dependency on a file in your path
-
# and ensures its only loaded once before the source file.
-
#
-
# `require` works with files in the environment path:
-
#
-
# //= require "foo.js"
-
#
-
# Extensions are optional. If your source file is ".js", it
-
# assumes you are requiring another ".js".
-
#
-
# //= require "foo"
-
#
-
# Relative paths work too. Use a leading `./` to denote a relative
-
# path:
-
#
-
# //= require "./bar"
-
#
-
2
def process_require_directive(path)
-
13
if @compat
-
if path =~ /<([^>]+)>/
-
path = $1
-
else
-
path = "./#{path}" unless relative?(path)
-
end
-
end
-
-
13
context.require_asset(path)
-
end
-
-
# `require_self` causes the body of the current file to be
-
# inserted before any subsequent `require` or `include`
-
# directives. Useful in CSS files, where it's common for the
-
# index file to contain global styles that need to be defined
-
# before other dependencies are loaded.
-
#
-
# /*= require "reset"
-
# *= require_self
-
# *= require_tree .
-
# */
-
#
-
2
def process_require_self_directive
-
1
if @has_written_body
-
raise ArgumentError, "require_self can only be called once per source file"
-
end
-
-
1
context.require_asset(pathname)
-
1
process_source
-
1
included_pathnames.clear
-
1
@has_written_body = true
-
end
-
-
# The `include` directive works similar to `require` but
-
# inserts the contents of the dependency even if it already
-
# has been required.
-
#
-
# //= include "header"
-
#
-
2
def process_include_directive(path)
-
pathname = context.resolve(path)
-
context.depend_on_asset(pathname)
-
included_pathnames << pathname
-
end
-
-
# `require_directory` requires all the files inside a single
-
# directory. It's similar to `path/*` since it does not follow
-
# nested directories.
-
#
-
# //= require_directory "./javascripts"
-
#
-
2
def process_require_directory_directive(path = ".")
-
if relative?(path)
-
root = pathname.dirname.join(path).expand_path
-
-
unless (stats = stat(root)) && stats.directory?
-
raise ArgumentError, "require_directory argument must be a directory"
-
end
-
-
context.depend_on(root)
-
-
entries(root).each do |pathname|
-
pathname = root.join(pathname)
-
if pathname.to_s == self.file
-
next
-
elsif context.asset_requirable?(pathname)
-
context.require_asset(pathname)
-
end
-
end
-
else
-
# The path must be relative and start with a `./`.
-
raise ArgumentError, "require_directory argument must be a relative path"
-
end
-
end
-
-
# `require_tree` requires all the nested files in a directory.
-
# Its glob equivalent is `path/**/*`.
-
#
-
# //= require_tree "./public"
-
#
-
2
def process_require_tree_directive(path = ".")
-
2
if relative?(path)
-
2
root = pathname.dirname.join(path).expand_path
-
-
2
unless (stats = stat(root)) && stats.directory?
-
raise ArgumentError, "require_tree argument must be a directory"
-
end
-
-
2
context.depend_on(root)
-
-
2
each_entry(root) do |pathname|
-
41
if pathname.to_s == self.file
-
2
next
-
elsif stat(pathname).directory?
-
context.depend_on(pathname)
-
elsif context.asset_requirable?(pathname)
-
39
context.require_asset(pathname)
-
end
-
end
-
else
-
# The path must be relative and start with a `./`.
-
raise ArgumentError, "require_tree argument must be a relative path"
-
end
-
end
-
-
# Allows you to state a dependency on a file without
-
# including it.
-
#
-
# This is used for caching purposes. Any changes made to
-
# the dependency file will invalidate the cache of the
-
# source file.
-
#
-
# This is useful if you are using ERB and File.read to pull
-
# in contents from another file.
-
#
-
# //= depend_on "foo.png"
-
#
-
2
def process_depend_on_directive(path)
-
context.depend_on(path)
-
end
-
-
# Allows you to state a dependency on an asset without including
-
# it.
-
#
-
# This is used for caching purposes. Any changes that would
-
# invalid the asset dependency will invalidate the cache our the
-
# source file.
-
#
-
# Unlike `depend_on`, the path must be a requirable asset.
-
#
-
# //= depend_on_asset "bar.js"
-
#
-
2
def process_depend_on_asset_directive(path)
-
context.depend_on_asset(path)
-
end
-
-
# Allows dependency to be excluded from the asset bundle.
-
#
-
# The `path` must be a valid asset and may or may not already
-
# be part of the bundle. Once stubbed, it is blacklisted and
-
# can't be brought back by any other `require`.
-
#
-
# //= stub "jquery"
-
#
-
2
def process_stub_directive(path)
-
context.stub_asset(path)
-
end
-
-
# Enable Sprockets 1.x compat mode.
-
#
-
# Makes it possible to use the same JavaScript source
-
# file in both Sprockets 1 and 2.
-
#
-
# //= compat
-
#
-
2
def process_compat_directive
-
@compat = true
-
end
-
-
# Checks if Sprockets 1.x compat mode enabled
-
2
def compat?
-
3
@compat
-
end
-
-
# Sprockets 1.x allowed for constant interpolation if a
-
# constants.yml was present. This is only available if
-
# compat mode is on.
-
2
def constants
-
if compat?
-
pathname = Pathname.new(context.root_path).join("constants.yml")
-
stat(pathname) ? YAML.load_file(pathname) : {}
-
else
-
{}
-
end
-
end
-
-
# `provide` is stubbed out for Sprockets 1.x compat.
-
# Mutating the path when an asset is being built is
-
# not permitted.
-
2
def process_provide_directive(path)
-
end
-
-
2
private
-
2
def relative?(path)
-
2
path =~ /^\.($|\.?\/)/
-
end
-
-
2
def stat(path)
-
41
context.environment.stat(path)
-
end
-
-
2
def entries(path)
-
context.environment.entries(path)
-
end
-
-
2
def each_entry(root, &block)
-
2
context.environment.each_entry(root, &block)
-
end
-
end
-
end
-
2
require 'tilt'
-
-
2
module Sprockets
-
# Tilt engine class for the Eco compiler. Depends on the `eco` gem.
-
#
-
# For more infomation see:
-
#
-
# https://github.com/sstephenson/ruby-eco
-
# https://github.com/sstephenson/eco
-
#
-
2
class EcoTemplate < Tilt::Template
-
# Check to see if Eco is loaded
-
2
def self.engine_initialized?
-
defined? ::Eco
-
end
-
-
# Autoload eco library. If the library isn't loaded, Tilt will produce
-
# a thread safetly warning. If you intend to use `.eco` files, you
-
# should explicitly require it.
-
2
def initialize_engine
-
require_template_library 'eco'
-
end
-
-
2
def prepare
-
end
-
-
# Compile template data with Eco compiler.
-
#
-
# Returns a JS function definition String. The result should be
-
# assigned to a JS variable.
-
#
-
# # => "function(...) {...}"
-
#
-
2
def evaluate(scope, locals, &block)
-
Eco.compile(data)
-
end
-
end
-
end
-
2
require 'tilt'
-
-
2
module Sprockets
-
# Tilt engine class for the EJS compiler. Depends on the `ejs` gem.
-
#
-
# For more infomation see:
-
#
-
# https://github.com/sstephenson/ruby-ejs
-
#
-
2
class EjsTemplate < Tilt::Template
-
# Check to see if EJS is loaded
-
2
def self.engine_initialized?
-
defined? ::EJS
-
end
-
-
# Autoload ejs library. If the library isn't loaded, Tilt will produce
-
# a thread safetly warning. If you intend to use `.ejs` files, you
-
# should explicitly require it.
-
2
def initialize_engine
-
require_template_library 'ejs'
-
end
-
-
2
def prepare
-
end
-
-
# Compile template data with EJS compiler.
-
#
-
# Returns a JS function definition String. The result should be
-
# assigned to a JS variable.
-
#
-
# # => "function(obj){...}"
-
#
-
2
def evaluate(scope, locals, &block)
-
EJS.compile(data)
-
end
-
end
-
end
-
2
require 'sprockets/eco_template'
-
2
require 'sprockets/ejs_template'
-
2
require 'sprockets/jst_processor'
-
2
require 'sprockets/utils'
-
2
require 'tilt'
-
-
2
module Sprockets
-
# `Engines` provides a global and `Environment` instance registry.
-
#
-
# An engine is a type of processor that is bound to an filename
-
# extension. `application.js.coffee` indicates that the
-
# `CoffeeScriptTemplate` engine will be ran on the file.
-
#
-
# Extensions can be stacked and will be evaulated from right to
-
# left. `application.js.coffee.erb` will first run `ERBTemplate`
-
# then `CoffeeScriptTemplate`.
-
#
-
# All `Engine`s must follow the `Tilt::Template` interface. It is
-
# recommended to subclass `Tilt::Template`.
-
#
-
# Its recommended that you register engine changes on your local
-
# `Environment` instance.
-
#
-
# environment.register_engine '.foo', FooProcessor
-
#
-
# The global registry is exposed for plugins to register themselves.
-
#
-
# Sprockets.register_engine '.sass', SassTemplate
-
#
-
2
module Engines
-
# Returns a `Hash` of `Engine`s registered on the `Environment`.
-
# If an `ext` argument is supplied, the `Engine` associated with
-
# that extension will be returned.
-
#
-
# environment.engines
-
# # => {".coffee" => CoffeeScriptTemplate, ".sass" => SassTemplate, ...}
-
#
-
# environment.engines('.coffee')
-
# # => CoffeeScriptTemplate
-
#
-
2
def engines(ext = nil)
-
580
if ext
-
576
ext = Sprockets::Utils.normalize_extension(ext)
-
576
@engines[ext]
-
else
-
4
@engines.dup
-
end
-
end
-
-
# Returns an `Array` of engine extension `String`s.
-
#
-
# environment.engine_extensions
-
# # => ['.coffee', '.sass', ...]
-
2
def engine_extensions
-
@engines.keys
-
end
-
-
# Registers a new Engine `klass` for `ext`. If the `ext` already
-
# has an engine registered, it will be overridden.
-
#
-
# environment.register_engine '.coffee', CoffeeScriptTemplate
-
#
-
2
def register_engine(ext, klass)
-
18
ext = Sprockets::Utils.normalize_extension(ext)
-
18
@engines[ext] = klass
-
end
-
-
2
private
-
2
def deep_copy_hash(hash)
-
20
initial = Hash.new { |h, k| h[k] = [] }
-
46
hash.inject(initial) { |h, (k, a)| h[k] = a.dup; h }
-
end
-
end
-
end
-
2
require 'sprockets/base'
-
2
require 'sprockets/context'
-
2
require 'sprockets/index'
-
-
2
require 'hike'
-
2
require 'logger'
-
2
require 'pathname'
-
2
require 'tilt'
-
-
2
module Sprockets
-
2
class Environment < Base
-
# `Environment` should initialized with your application's root
-
# directory. This should be the same as your Rails or Rack root.
-
#
-
# env = Environment.new(Rails.root)
-
#
-
2
def initialize(root = ".")
-
2
@trail = Hike::Trail.new(root)
-
-
2
self.logger = Logger.new($stderr)
-
2
self.logger.level = Logger::FATAL
-
-
2
if respond_to?(:default_external_encoding)
-
2
self.default_external_encoding = Encoding::UTF_8
-
end
-
-
# Create a safe `Context` subclass to mutate
-
2
@context_class = Class.new(Context)
-
-
# Set MD5 as the default digest
-
2
require 'digest/md5'
-
2
@digest_class = ::Digest::MD5
-
2
@version = ''
-
-
2
@mime_types = Sprockets.registered_mime_types
-
2
@engines = Sprockets.engines
-
2
@preprocessors = Sprockets.preprocessors
-
2
@postprocessors = Sprockets.postprocessors
-
2
@bundle_processors = Sprockets.bundle_processors
-
2
@compressors = Sprockets.compressors
-
-
2
Sprockets.paths.each do |path|
-
append_path(path)
-
end
-
-
2
@engines.each do |ext, klass|
-
18
add_engine_to_trail(ext, klass)
-
end
-
-
2
@mime_types.each do |ext, type|
-
4
@trail.append_extension(ext)
-
end
-
-
2
expire_index!
-
-
2
yield self if block_given?
-
end
-
-
# Returns a cached version of the environment.
-
#
-
# All its file system calls are cached which makes `index` much
-
# faster. This behavior is ideal in production since the file
-
# system only changes between deploys.
-
2
def index
-
2
Index.new(self)
-
end
-
-
# Cache `find_asset` calls
-
2
def find_asset(path, options = {})
-
options[:bundle] = true unless options.key?(:bundle)
-
-
# Ensure inmemory cached assets are still fresh on every lookup
-
if (asset = @assets[cache_key_for(path, options)]) && asset.fresh?(self)
-
asset
-
elsif asset = index.find_asset(path, options)
-
# Cache is pushed upstream by Index#find_asset
-
asset
-
end
-
end
-
-
2
protected
-
2
def expire_index!
-
# Clear digest to be recomputed
-
70
@digest = nil
-
70
@assets = {}
-
end
-
end
-
end
-
# Define some basic Sprockets error classes
-
2
module Sprockets
-
2
class Error < StandardError; end
-
2
class ArgumentError < Error; end
-
2
class CircularDependencyError < Error; end
-
2
class ContentTypeMismatch < Error; end
-
2
class EncodingError < Error; end
-
2
class FileNotFound < Error; end
-
2
class FileOutsidePaths < Error; end
-
2
class NotImplementedError < Error; end
-
2
class UnserializeError < Error; end
-
-
2
module EngineError
-
2
attr_accessor :sprockets_annotation
-
-
2
def message
-
[super, sprockets_annotation].compact.join("\n")
-
end
-
end
-
end
-
2
require 'sprockets/base'
-
-
2
module Sprockets
-
# `Index` is a special cached version of `Environment`.
-
#
-
# The expection is that all of its file system methods are cached
-
# for the instances lifetime. This makes `Index` much faster. This
-
# behavior is ideal in production environments where the file system
-
# is immutable.
-
#
-
# `Index` should not be initialized directly. Instead use
-
# `Environment#index`.
-
2
class Index < Base
-
2
def initialize(environment)
-
2
@environment = environment
-
-
2
if environment.respond_to?(:default_external_encoding)
-
2
@default_external_encoding = environment.default_external_encoding
-
end
-
-
# Copy environment attributes
-
2
@logger = environment.logger
-
2
@context_class = environment.context_class
-
2
@cache = environment.cache
-
2
@trail = environment.trail.index
-
2
@digest = environment.digest
-
2
@digest_class = environment.digest_class
-
2
@version = environment.version
-
2
@mime_types = environment.mime_types
-
2
@engines = environment.engines
-
2
@preprocessors = environment.preprocessors
-
2
@postprocessors = environment.postprocessors
-
2
@bundle_processors = environment.bundle_processors
-
2
@compressors = environment.compressors
-
-
# Initialize caches
-
2
@assets = {}
-
2
@digests = {}
-
end
-
-
# No-op return self as index
-
2
def index
-
4
self
-
end
-
-
# Cache calls to `file_digest`
-
2
def file_digest(pathname)
-
11
key = pathname.to_s
-
11
if @digests.key?(key)
-
6
@digests[key]
-
else
-
5
@digests[key] = super
-
end
-
end
-
-
# Cache `find_asset` calls
-
2
def find_asset(path, options = {})
-
273
options[:bundle] = true unless options.key?(:bundle)
-
273
if asset = @assets[cache_key_for(path, options)]
-
181
asset
-
92
elsif asset = super
-
91
logical_path_cache_key = cache_key_for(path, options)
-
91
full_path_cache_key = cache_key_for(asset.pathname, options)
-
-
# Cache on Index
-
91
@assets[logical_path_cache_key] = @assets[full_path_cache_key] = asset
-
-
# Push cache upstream to Environment
-
91
@environment.instance_eval do
-
91
@assets[logical_path_cache_key] = @assets[full_path_cache_key] = asset
-
end
-
-
91
asset
-
end
-
end
-
-
2
protected
-
# Index is immutable, any methods that try to clear the cache
-
# should bomb.
-
2
def expire_index!
-
raise TypeError, "can't modify immutable index"
-
end
-
-
# Cache asset building in memory and in persisted cache.
-
2
def build_asset(path, pathname, options)
-
# Memory cache
-
91
key = cache_key_for(pathname, options)
-
91
if @assets.key?(key)
-
@assets[key]
-
else
-
91
@assets[key] = begin
-
# Persisted cache
-
91
cache_asset(key) do
-
4
super
-
end
-
end
-
end
-
end
-
end
-
end
-
2
require 'tilt'
-
-
2
module Sprockets
-
2
class JstProcessor < Tilt::Template
-
2
self.default_mime_type = 'application/javascript'
-
-
2
def self.default_namespace
-
'this.JST'
-
end
-
-
2
def prepare
-
@namespace = self.class.default_namespace
-
end
-
-
2
attr_reader :namespace
-
-
2
def evaluate(scope, locals, &block)
-
<<-JST
-
(function() { #{namespace} || (#{namespace} = {}); #{namespace}[#{scope.logical_path.inspect}] = #{indent(data)};
-
}).call(this);
-
JST
-
end
-
-
2
private
-
2
def indent(string)
-
string.gsub(/$(.)/m, "\\1 ").strip
-
end
-
end
-
end
-
2
require 'multi_json'
-
2
require 'securerandom'
-
2
require 'time'
-
-
2
module Sprockets
-
# The Manifest logs the contents of assets compiled to a single
-
# directory. It records basic attributes about the asset for fast
-
# lookup without having to compile. A pointer from each logical path
-
# indicates with fingerprinted asset is the current one.
-
#
-
# The JSON is part of the public API and should be considered
-
# stable. This should make it easy to read from other programming
-
# languages and processes that don't have sprockets loaded. See
-
# `#assets` and `#files` for more infomation about the structure.
-
2
class Manifest
-
2
attr_reader :environment, :path, :dir
-
-
# Create new Manifest associated with an `environment`. `path` is
-
# a full path to the manifest json file. The file may or may not
-
# already exist. The dirname of the `path` will be used to write
-
# compiled assets to. Otherwise, if the path is a directory, the
-
# filename will default a random "manifest-123.json" file in that
-
# directory.
-
#
-
# Manifest.new(environment, "./public/assets/manifest.json")
-
#
-
2
def initialize(*args)
-
2
if args.first.is_a?(Base) || args.first.nil?
-
2
@environment = args.shift
-
end
-
-
2
@dir, @path = args[0], args[1]
-
-
# Expand paths
-
2
@dir = File.expand_path(@dir) if @dir
-
2
@path = File.expand_path(@path) if @path
-
-
# If path is given as the second arg
-
2
if @dir && File.extname(@dir) != ""
-
@dir, @path = nil, @dir
-
end
-
-
# Default dir to the directory of the path
-
2
@dir ||= File.dirname(@path) if @path
-
-
# If directory is given w/o path, pick a random manifest.json location
-
2
if @dir && @path.nil?
-
# Find the first manifest.json in the directory
-
2
paths = Dir[File.join(@dir, "manifest*.json")]
-
2
if paths.any?
-
@path = paths.first
-
else
-
2
@path = File.join(@dir, "manifest-#{SecureRandom.hex(16)}.json")
-
end
-
end
-
-
2
unless @dir && @path
-
raise ArgumentError, "manifest requires output path"
-
end
-
-
2
data = nil
-
-
2
begin
-
2
if File.exist?(@path)
-
data = json_decode(File.read(@path))
-
end
-
rescue MultiJson::DecodeError => e
-
logger.error "#{@path} is invalid: #{e.class} #{e.message}"
-
end
-
-
2
@data = data.is_a?(Hash) ? data : {}
-
end
-
-
# Returns internal assets mapping. Keys are logical paths which
-
# map to the latest fingerprinted filename.
-
#
-
# Logical path (String): Fingerprint path (String)
-
#
-
# { "application.js" => "application-2e8e9a7c6b0aafa0c9bdeec90ea30213.js",
-
# "jquery.js" => "jquery-ae0908555a245f8266f77df5a8edca2e.js" }
-
#
-
2
def assets
-
39
@data['assets'] ||= {}
-
end
-
-
# Returns internal file directory listing. Keys are filenames
-
# which map to an attributes array.
-
#
-
# Fingerprint path (String):
-
# logical_path: Logical path (String)
-
# mtime: ISO8601 mtime (String)
-
# digest: Base64 hex digest (String)
-
#
-
# { "application-2e8e9a7c6b0aafa0c9bdeec90ea30213.js" =>
-
# { 'logical_path' => "application.js",
-
# 'mtime' => "2011-12-13T21:47:08-06:00",
-
# 'digest' => "2e8e9a7c6b0aafa0c9bdeec90ea30213" } }
-
#
-
2
def files
-
@data['files'] ||= {}
-
end
-
-
# Compile and write asset to directory. The asset is written to a
-
# fingerprinted filename like
-
# `application-2e8e9a7c6b0aafa0c9bdeec90ea30213.js`. An entry is
-
# also inserted into the manifest file.
-
#
-
# compile("application.js")
-
#
-
2
def compile(*args)
-
unless environment
-
raise Error, "manifest requires environment for compilation"
-
end
-
-
paths = environment.each_logical_path(*args).to_a +
-
args.flatten.select { |fn| Pathname.new(fn).absolute? if fn.is_a?(String)}
-
-
paths.each do |path|
-
if asset = find_asset(path)
-
files[asset.digest_path] = {
-
'logical_path' => asset.logical_path,
-
'mtime' => asset.mtime.iso8601,
-
'size' => asset.bytesize,
-
'digest' => asset.digest
-
}
-
assets[asset.logical_path] = asset.digest_path
-
-
target = File.join(dir, asset.digest_path)
-
-
if File.exist?(target)
-
logger.debug "Skipping #{target}, already exists"
-
else
-
logger.info "Writing #{target}"
-
asset.write_to target
-
asset.write_to "#{target}.gz" if asset.is_a?(BundledAsset)
-
end
-
-
end
-
end
-
save
-
paths
-
end
-
-
# Removes file from directory and from manifest. `filename` must
-
# be the name with any directory path.
-
#
-
# manifest.remove("application-2e8e9a7c6b0aafa0c9bdeec90ea30213.js")
-
#
-
2
def remove(filename)
-
path = File.join(dir, filename)
-
gzip = "#{path}.gz"
-
logical_path = files[filename]['logical_path']
-
-
if assets[logical_path] == filename
-
assets.delete(logical_path)
-
end
-
-
files.delete(filename)
-
FileUtils.rm(path) if File.exist?(path)
-
FileUtils.rm(gzip) if File.exist?(gzip)
-
-
save
-
-
logger.info "Removed #{filename}"
-
-
nil
-
end
-
-
# Cleanup old assets in the compile directory. By default it will
-
# keep the latest version plus 2 backups.
-
2
def clean(keep = 2)
-
self.assets.keys.each do |logical_path|
-
# Get assets sorted by ctime, newest first
-
assets = backups_for(logical_path)
-
-
# Keep the last N backups
-
assets = assets[keep..-1] || []
-
-
# Remove old assets
-
assets.each { |path, _| remove(path) }
-
end
-
end
-
-
# Wipe directive
-
2
def clobber
-
FileUtils.rm_r(@dir) if File.exist?(@dir)
-
logger.info "Removed #{@dir}"
-
nil
-
end
-
-
2
protected
-
# Finds all the backup assets for a logical path. The latest
-
# version is always excluded. The return array is sorted by the
-
# assets mtime in descending order (Newest to oldest).
-
2
def backups_for(logical_path)
-
files.select { |filename, attrs|
-
# Matching logical paths
-
attrs['logical_path'] == logical_path &&
-
# Excluding whatever asset is the current
-
assets[logical_path] != filename
-
}.sort_by { |filename, attrs|
-
# Sort by timestamp
-
Time.parse(attrs['mtime'])
-
}.reverse
-
end
-
-
# Basic wrapper around Environment#find_asset. Logs compile time.
-
2
def find_asset(logical_path)
-
asset = nil
-
ms = benchmark do
-
asset = environment.find_asset(logical_path)
-
end
-
logger.debug "Compiled #{logical_path} (#{ms}ms)"
-
asset
-
end
-
-
# Persist manfiest back to FS
-
2
def save
-
FileUtils.mkdir_p File.dirname(path)
-
File.open(path, 'w') do |f|
-
f.write json_encode(@data)
-
end
-
end
-
-
2
private
-
# Feature detect newer MultiJson API
-
2
if MultiJson.respond_to?(:dump)
-
2
def json_decode(obj)
-
MultiJson.load(obj)
-
end
-
-
2
def json_encode(obj)
-
MultiJson.dump(obj)
-
end
-
else
-
def json_decode(obj)
-
MultiJson.decode(obj)
-
end
-
-
def json_encode(obj)
-
MultiJson.encode(obj)
-
end
-
end
-
-
2
def logger
-
if environment
-
environment.logger
-
else
-
logger = Logger.new($stderr)
-
logger.level = Logger::FATAL
-
logger
-
end
-
end
-
-
2
def benchmark
-
start_time = Time.now.to_f
-
yield
-
((Time.now.to_f - start_time) * 1000).to_i
-
end
-
end
-
end
-
2
require 'rack/mime'
-
-
2
module Sprockets
-
2
module Mime
-
# Returns a `Hash` of registered mime types registered on the
-
# environment and those part of `Rack::Mime`.
-
#
-
# If an `ext` is given, it will lookup the mime type for that extension.
-
2
def mime_types(ext = nil)
-
870
if ext.nil?
-
37
Rack::Mime::MIME_TYPES.merge(@mime_types)
-
else
-
833
ext = Sprockets::Utils.normalize_extension(ext)
-
833
@mime_types[ext] || Rack::Mime::MIME_TYPES[ext]
-
end
-
end
-
-
# Returns a `Hash` of explicitly registered mime types.
-
2
def registered_mime_types
-
2
@mime_types.dup
-
end
-
-
2
if {}.respond_to?(:key)
-
2
def extension_for_mime_type(type)
-
35
mime_types.key(type)
-
end
-
else
-
def extension_for_mime_type(type)
-
mime_types.index(type)
-
end
-
end
-
-
# Register a new mime type.
-
2
def register_mime_type(mime_type, ext)
-
4
ext = Sprockets::Utils.normalize_extension(ext)
-
4
@mime_types[ext] = mime_type
-
end
-
-
2
if defined? Encoding
-
# Returns the correct encoding for a given mime type, while falling
-
# back on the default external encoding, if it exists.
-
2
def encoding_for_mime_type(type)
-
2
encoding = Encoding::BINARY if type =~ %r{^(image|audio|video)/}
-
2
encoding ||= default_external_encoding if respond_to?(:default_external_encoding)
-
2
encoding
-
end
-
end
-
end
-
end
-
2
module Sprockets
-
2
module Paths
-
# Returns `Environment` root.
-
#
-
# All relative paths are expanded with root as its base. To be
-
# useful set this to your applications root directory. (`Rails.root`)
-
2
def root
-
194
@trail.root.dup
-
end
-
-
# Returns an `Array` of path `String`s.
-
#
-
# These paths will be used for asset logical path lookups.
-
#
-
# Note that a copy of the `Array` is returned so mutating will
-
# have no affect on the environment. See `append_path`,
-
# `prepend_path`, and `clear_paths`.
-
2
def paths
-
308
@trail.paths.dup
-
end
-
-
# Prepend a `path` to the `paths` list.
-
#
-
# Paths at the end of the `Array` have the least priority.
-
2
def prepend_path(path)
-
@trail.prepend_path(path)
-
end
-
-
# Append a `path` to the `paths` list.
-
#
-
# Paths at the beginning of the `Array` have a higher priority.
-
2
def append_path(path)
-
60
@trail.append_path(path)
-
end
-
-
# Clear all paths and start fresh.
-
#
-
# There is no mechanism for reordering paths, so its best to
-
# completely wipe the paths list and reappend them in the order
-
# you want.
-
2
def clear_paths
-
@trail.paths.dup.each { |path| @trail.remove_path(path) }
-
end
-
-
# Returns an `Array` of extensions.
-
#
-
# These extensions maybe omitted from logical path searches.
-
#
-
# # => [".js", ".css", ".coffee", ".sass", ...]
-
#
-
2
def extensions
-
@trail.extensions.dup
-
end
-
-
2
protected
-
2
attr_reader :trail
-
end
-
end
-
2
require 'sprockets/asset'
-
2
require 'sprockets/utils'
-
-
2
module Sprockets
-
2
class ProcessedAsset < Asset
-
2
def initialize(environment, logical_path, pathname)
-
2
super
-
-
2
start_time = Time.now.to_f
-
-
2
context = environment.context_class.new(environment, logical_path, pathname)
-
2
@source = context.evaluate(pathname)
-
2
@length = Rack::Utils.bytesize(source)
-
2
@digest = environment.digest.update(source).hexdigest
-
-
2
build_required_assets(environment, context)
-
2
build_dependency_paths(environment, context)
-
-
2
@dependency_digest = compute_dependency_digest(environment)
-
-
2
elapsed_time = ((Time.now.to_f - start_time) * 1000).to_i
-
2
environment.logger.debug "Compiled #{logical_path} (#{elapsed_time}ms) (pid #{Process.pid})"
-
end
-
-
# Interal: Used to check equality
-
2
attr_reader :dependency_digest
-
-
2
attr_reader :source
-
-
# Initialize `BundledAsset` from serialized `Hash`.
-
2
def init_with(environment, coder)
-
88
super
-
-
88
@source = coder['source']
-
88
@dependency_digest = coder['dependency_digest']
-
-
88
@required_assets = coder['required_paths'].map { |p|
-
218
p = expand_root_path(p)
-
-
2367
unless environment.paths.detect { |path| p[path] }
-
raise UnserializeError, "#{p} isn't in paths"
-
end
-
-
218
p == pathname.to_s ? self : environment.find_asset(p, :bundle => false)
-
}
-
88
@dependency_paths = coder['dependency_paths'].map { |h|
-
266
DependencyFile.new(expand_root_path(h['path']), h['mtime'], h['digest'])
-
}
-
end
-
-
# Serialize custom attributes in `BundledAsset`.
-
2
def encode_with(coder)
-
2
super
-
-
2
coder['source'] = source
-
2
coder['dependency_digest'] = dependency_digest
-
-
2
coder['required_paths'] = required_assets.map { |a|
-
88
relativize_root_path(a.pathname).to_s
-
}
-
2
coder['dependency_paths'] = dependency_paths.map { |d|
-
{ 'path' => relativize_root_path(d.pathname).to_s,
-
'mtime' => d.mtime.iso8601,
-
110
'digest' => d.digest }
-
}
-
end
-
-
# Checks if Asset is stale by comparing the actual mtime and
-
# digest to the inmemory model.
-
2
def fresh?(environment)
-
# Check freshness of all declared dependencies
-
246
@dependency_paths.all? { |dep| dependency_fresh?(environment, dep) }
-
end
-
-
2
protected
-
2
class DependencyFile < Struct.new(:pathname, :mtime, :digest)
-
2
def initialize(pathname, mtime, digest)
-
270
pathname = Pathname.new(pathname) unless pathname.is_a?(Pathname)
-
270
mtime = Time.parse(mtime) if mtime.is_a?(String)
-
270
super
-
end
-
-
2
def eql?(other)
-
other.is_a?(DependencyFile) &&
-
pathname.eql?(other.pathname) &&
-
mtime.eql?(other.mtime) &&
-
digest.eql?(other.digest)
-
end
-
-
2
def hash
-
110
pathname.to_s.hash
-
end
-
end
-
-
2
private
-
2
def build_required_assets(environment, context)
-
2
@required_assets = resolve_dependencies(environment, context._required_paths + [pathname.to_s]) -
-
resolve_dependencies(environment, context._stubbed_assets.to_a)
-
end
-
-
2
def resolve_dependencies(environment, paths)
-
4
assets = []
-
4
cache = {}
-
-
4
paths.each do |path|
-
55
if path == self.pathname.to_s
-
3
unless cache[self]
-
2
cache[self] = true
-
2
assets << self
-
end
-
elsif asset = environment.find_asset(path, :bundle => false)
-
52
asset.required_assets.each do |asset_dependency|
-
90
unless cache[asset_dependency]
-
86
cache[asset_dependency] = true
-
86
assets << asset_dependency
-
end
-
end
-
end
-
end
-
-
4
assets
-
end
-
-
2
def build_dependency_paths(environment, context)
-
2
dependency_paths = {}
-
-
2
context._dependency_paths.each do |path|
-
2
dep = DependencyFile.new(path, environment.stat(path).mtime, environment.file_digest(path).hexdigest)
-
2
dependency_paths[dep] = true
-
end
-
-
2
context._dependency_assets.each do |path|
-
50
if path == self.pathname.to_s
-
2
dep = DependencyFile.new(pathname, environment.stat(path).mtime, environment.file_digest(path).hexdigest)
-
2
dependency_paths[dep] = true
-
elsif asset = environment.find_asset(path, :bundle => false)
-
48
asset.dependency_paths.each do |d|
-
106
dependency_paths[d] = true
-
end
-
end
-
end
-
-
2
@dependency_paths = dependency_paths.keys
-
end
-
-
2
def compute_dependency_digest(environment)
-
required_assets.inject(environment.digest) { |digest, asset|
-
88
digest.update asset.digest
-
2
}.hexdigest
-
end
-
end
-
end
-
2
require 'sprockets/engines'
-
2
require 'sprockets/mime'
-
2
require 'sprockets/processor'
-
2
require 'sprockets/utils'
-
-
2
module Sprockets
-
# `Processing` is an internal mixin whose public methods are exposed on
-
# the `Environment` and `Index` classes.
-
2
module Processing
-
# Returns an `Array` of format extension `String`s.
-
#
-
# format_extensions
-
# # => ['.js', '.css']
-
#
-
2
def format_extensions
-
@trail.extensions - @engines.keys
-
end
-
-
# Deprecated alias for `preprocessors`.
-
2
def processors(*args)
-
preprocessors(*args)
-
end
-
-
# Returns an `Array` of `Processor` classes. If a `mime_type`
-
# argument is supplied, the processors registered under that
-
# extension will be returned.
-
#
-
# Preprocessors are ran before Postprocessors and Engine
-
# processors.
-
#
-
# All `Processor`s must follow the `Tilt::Template` interface. It is
-
# recommended to subclass `Tilt::Template`.
-
2
def preprocessors(mime_type = nil)
-
10
if mime_type
-
6
@preprocessors[mime_type].dup
-
else
-
4
deep_copy_hash(@preprocessors)
-
end
-
end
-
-
# Returns an `Array` of `Processor` classes. If a `mime_type`
-
# argument is supplied, the processors registered under that
-
# extension will be returned.
-
#
-
# Postprocessors are ran after Preprocessors and Engine processors.
-
#
-
# All `Processor`s must follow the `Tilt::Template` interface. It is
-
# recommended to subclass `Tilt::Template`.
-
2
def postprocessors(mime_type = nil)
-
10
if mime_type
-
6
@postprocessors[mime_type].dup
-
else
-
4
deep_copy_hash(@postprocessors)
-
end
-
end
-
-
# Deprecated alias for `register_preprocessor`.
-
2
def register_processor(*args, &block)
-
register_preprocessor(*args, &block)
-
end
-
-
# Registers a new Preprocessor `klass` for `mime_type`.
-
#
-
# register_preprocessor 'text/css', Sprockets::DirectiveProcessor
-
#
-
# A block can be passed for to create a shorthand processor.
-
#
-
# register_preprocessor 'text/css', :my_processor do |context, data|
-
# data.gsub(...)
-
# end
-
#
-
2
def register_preprocessor(mime_type, klass, &block)
-
4
if block_given?
-
name = klass.to_s
-
klass = Class.new(Processor) do
-
@name = name
-
@processor = block
-
end
-
end
-
-
4
@preprocessors[mime_type].push(klass)
-
end
-
-
# Registers a new Postprocessor `klass` for `mime_type`.
-
#
-
# register_postprocessor 'text/css', Sprockets::CharsetNormalizer
-
#
-
# A block can be passed for to create a shorthand processor.
-
#
-
# register_postprocessor 'text/css', :my_processor do |context, data|
-
# data.gsub(...)
-
# end
-
#
-
2
def register_postprocessor(mime_type, klass, &block)
-
2
if block_given?
-
name = klass.to_s
-
klass = Class.new(Processor) do
-
@name = name
-
@processor = block
-
end
-
end
-
-
2
@postprocessors[mime_type].push(klass)
-
end
-
-
# Deprecated alias for `unregister_preprocessor`.
-
2
def unregister_processor(*args)
-
unregister_preprocessor(*args)
-
end
-
-
# Remove Preprocessor `klass` for `mime_type`.
-
#
-
# unregister_preprocessor 'text/css', Sprockets::DirectiveProcessor
-
#
-
2
def unregister_preprocessor(mime_type, klass)
-
if klass.is_a?(String) || klass.is_a?(Symbol)
-
klass = @preprocessors[mime_type].detect { |cls|
-
cls.respond_to?(:name) &&
-
cls.name == "Sprockets::Processor (#{klass})"
-
}
-
end
-
-
@preprocessors[mime_type].delete(klass)
-
end
-
-
# Remove Postprocessor `klass` for `mime_type`.
-
#
-
# unregister_postprocessor 'text/css', Sprockets::DirectiveProcessor
-
#
-
2
def unregister_postprocessor(mime_type, klass)
-
if klass.is_a?(String) || klass.is_a?(Symbol)
-
klass = @postprocessors[mime_type].detect { |cls|
-
cls.respond_to?(:name) &&
-
cls.name == "Sprockets::Processor (#{klass})"
-
}
-
end
-
-
@postprocessors[mime_type].delete(klass)
-
end
-
-
# Returns an `Array` of `Processor` classes. If a `mime_type`
-
# argument is supplied, the processors registered under that
-
# extension will be returned.
-
#
-
# Bundle Processors are ran on concatenated assets rather than
-
# individual files.
-
#
-
# All `Processor`s must follow the `Tilt::Template` interface. It is
-
# recommended to subclass `Tilt::Template`.
-
2
def bundle_processors(mime_type = nil)
-
6
if mime_type
-
2
@bundle_processors[mime_type].dup
-
else
-
4
deep_copy_hash(@bundle_processors)
-
end
-
end
-
-
# Registers a new Bundle Processor `klass` for `mime_type`.
-
#
-
# register_bundle_processor 'text/css', Sprockets::CharsetNormalizer
-
#
-
# A block can be passed for to create a shorthand processor.
-
#
-
# register_bundle_processor 'text/css', :my_processor do |context, data|
-
# data.gsub(...)
-
# end
-
#
-
2
def register_bundle_processor(mime_type, klass, &block)
-
4
if block_given?
-
name = klass.to_s
-
klass = Class.new(Processor) do
-
@name = name
-
@processor = block
-
end
-
end
-
-
4
@bundle_processors[mime_type].push(klass)
-
end
-
-
# Remove Bundle Processor `klass` for `mime_type`.
-
#
-
# unregister_bundle_processor 'text/css', Sprockets::CharsetNormalizer
-
#
-
2
def unregister_bundle_processor(mime_type, klass)
-
if klass.is_a?(String) || klass.is_a?(Symbol)
-
klass = @bundle_processors[mime_type].detect { |cls|
-
cls.respond_to?(:name) &&
-
cls.name == "Sprockets::Processor (#{klass})"
-
}
-
end
-
-
@bundle_processors[mime_type].delete(klass)
-
end
-
-
2
private
-
2
def add_engine_to_trail(ext, klass)
-
18
@trail.append_extension(ext.to_s)
-
-
18
if klass.respond_to?(:default_mime_type) && klass.default_mime_type
-
10
if format_ext = extension_for_mime_type(klass.default_mime_type)
-
10
@trail.alias_extension(ext.to_s, format_ext)
-
end
-
end
-
end
-
end
-
end
-
2
require 'tilt'
-
-
2
module Sprockets
-
# `Processor` creates an anonymous processor class from a block.
-
#
-
# register_preprocessor 'text/css', :my_processor do |context, data|
-
# # ...
-
# end
-
#
-
2
class Processor < Tilt::Template
-
# `processor` is a lambda or block
-
2
def self.processor
-
@processor
-
end
-
-
2
def self.name
-
"Sprockets::Processor (#{@name})"
-
end
-
-
2
def self.to_s
-
name
-
end
-
-
2
def prepare
-
end
-
-
# Call processor block with `context` and `data`.
-
2
def evaluate(context, locals)
-
self.class.processor.call(context, data)
-
end
-
end
-
end
-
2
require 'tilt'
-
-
2
module Sprockets
-
# For JS developers who are colonfobic, concatenating JS files using
-
# the module pattern usually leads to syntax errors.
-
#
-
# The `SafetyColons` processor will insert missing semicolons to the
-
# end of the file.
-
#
-
# This behavior can be disabled with:
-
#
-
# environment.unregister_postprocessor 'application/javascript', Sprockets::SafetyColons
-
#
-
2
class SafetyColons < Tilt::Template
-
2
def prepare
-
end
-
-
2
def evaluate(context, locals, &block)
-
# If the file is blank or ends in a semicolon, leave it as is
-
1
if data =~ /\A\s*\Z/m || data =~ /;\s*\Z/m
-
data
-
else
-
# Otherwise, append a semicolon and newline
-
1
"#{data};\n"
-
end
-
end
-
end
-
end
-
2
require 'tilt'
-
-
2
module Sprockets
-
2
class SassCompressor < Tilt::Template
-
2
self.default_mime_type = 'text/css'
-
-
2
def self.engine_initialized?
-
1
defined?(::Sass::Engine)
-
end
-
-
2
def initialize_engine
-
require_template_library 'sass'
-
end
-
-
2
def prepare
-
end
-
-
2
def evaluate(context, locals, &block)
-
::Sass::Engine.new(data, {
-
:syntax => :scss,
-
:cache => false,
-
:read_cache => false,
-
:style => :compressed
-
1
}).render
-
end
-
end
-
end
-
2
require 'sass'
-
-
2
module Sprockets
-
2
module SassFunctions
-
2
def asset_path(path)
-
::Sass::Script::String.new(sprockets_context.asset_path(path.value), :string)
-
end
-
-
2
def asset_url(path)
-
::Sass::Script::String.new("url(" + sprockets_context.asset_path(path.value) + ")")
-
end
-
-
2
def image_path(path)
-
::Sass::Script::String.new(sprockets_context.image_path(path.value), :string)
-
end
-
-
2
def image_url(path)
-
::Sass::Script::String.new("url(" + sprockets_context.image_path(path.value) + ")")
-
end
-
-
2
def video_path(path)
-
::Sass::Script::String.new(sprockets_context.video_path(path.value), :string)
-
end
-
-
2
def video_url(path)
-
::Sass::Script::String.new("url(" + sprockets_context.video_path(path.value) + ")")
-
end
-
-
2
def audio_path(path)
-
::Sass::Script::String.new(sprockets_context.audio_path(path.value), :string)
-
end
-
-
2
def audio_url(path)
-
::Sass::Script::String.new("url(" + sprockets_context.audio_path(path.value) + ")")
-
end
-
-
2
def font_path(path)
-
::Sass::Script::String.new(sprockets_context.font_path(path.value), :string)
-
end
-
-
2
def font_url(path)
-
::Sass::Script::String.new("url(" + sprockets_context.font_path(path.value) + ")")
-
end
-
-
2
def javascript_path(path)
-
::Sass::Script::String.new(sprockets_context.javascript_path(path.value), :string)
-
end
-
-
2
def javascript_url(path)
-
::Sass::Script::String.new("url(" + sprockets_context.javascript_path(path.value) + ")")
-
end
-
-
2
def stylesheet_path(path)
-
::Sass::Script::String.new(sprockets_context.stylesheet_path(path.value), :string)
-
end
-
-
2
def stylesheet_url(path)
-
::Sass::Script::String.new("url(" + sprockets_context.stylesheet_path(path.value) + ")")
-
end
-
-
2
protected
-
2
def sprockets_context
-
options[:sprockets][:context]
-
end
-
-
2
def sprockets_environment
-
options[:sprockets][:environment]
-
end
-
end
-
end
-
2
require 'sass'
-
-
2
module Sprockets
-
# This custom importer that tracks all imported filenames during
-
# compile.
-
2
class SassImporter < ::Sass::Importers::Filesystem
-
2
attr_reader :imported_filenames
-
-
2
def initialize(*args)
-
@imported_filenames = []
-
super
-
end
-
-
2
def find_relative(*args)
-
engine = super
-
if engine && (filename = engine.options[:filename])
-
@imported_filenames << filename
-
end
-
engine
-
end
-
-
2
def find(*args)
-
engine = super
-
if engine && (filename = engine.options[:filename])
-
@imported_filenames << filename
-
end
-
engine
-
end
-
end
-
end
-
2
require 'tilt'
-
-
2
module Sprockets
-
# This custom Tilt handler replaces the one built into Tilt. The
-
# main difference is that it uses a custom importer that plays nice
-
# with sprocket's caching system.
-
#
-
# See `SassImporter` for more infomation.
-
2
class SassTemplate < Tilt::Template
-
2
self.default_mime_type = 'text/css'
-
-
2
def self.engine_initialized?
-
defined?(::Sass::Engine) && defined?(::Sass::Script::Functions) &&
-
::Sass::Script::Functions < Sprockets::SassFunctions
-
end
-
-
2
def initialize_engine
-
# Double check constant to avoid tilt warning
-
unless defined? ::Sass
-
require_template_library 'sass'
-
end
-
-
# Install custom functions. It'd be great if this didn't need to
-
# be installed globally, but could be passed into Engine as an
-
# option.
-
::Sass::Script::Functions.send :include, Sprockets::SassFunctions
-
end
-
-
2
def prepare
-
end
-
-
2
def syntax
-
:sass
-
end
-
-
2
def evaluate(context, locals, &block)
-
# Use custom importer that knows about Sprockets Caching
-
cache_store = SassCacheStore.new(context.environment)
-
-
options = {
-
:filename => eval_file,
-
:line => line,
-
:syntax => syntax,
-
:cache_store => cache_store,
-
:importer => SassImporter.new(context.pathname.to_s),
-
:load_paths => context.environment.paths.map { |path| SassImporter.new(path.to_s) },
-
:sprockets => {
-
:context => context,
-
:environment => context.environment
-
}
-
}
-
-
result = ::Sass::Engine.new(data, options).render
-
-
# Track all imported files
-
filenames = ([options[:importer].imported_filenames] + options[:load_paths].map(&:imported_filenames)).flatten.uniq
-
filenames.each { |filename| context.depend_on(filename) }
-
-
result
-
rescue ::Sass::SyntaxError => e
-
# Annotates exception message with parse line number
-
context.__LINE__ = e.sass_backtrace.first[:line]
-
raise e
-
end
-
end
-
end
-
2
require 'sprockets/sass_template'
-
-
2
module Sprockets
-
# Scss handler to replace Tilt's builtin one. See `SassTemplate` and
-
# `SassImporter` for more infomation.
-
2
class ScssTemplate < SassTemplate
-
2
self.default_mime_type = 'text/css'
-
-
2
def syntax
-
:scss
-
end
-
end
-
end
-
2
require 'time'
-
2
require 'uri'
-
-
2
module Sprockets
-
# `Server` is a concern mixed into `Environment` and
-
# `Index` that provides a Rack compatible `call`
-
# interface and url generation helpers.
-
2
module Server
-
# `call` implements the Rack 1.x specification which accepts an
-
# `env` Hash and returns a three item tuple with the status code,
-
# headers, and body.
-
#
-
# Mapping your environment at a url prefix will serve all assets
-
# in the path.
-
#
-
# map "/assets" do
-
# run Sprockets::Environment.new
-
# end
-
#
-
# A request for `"/assets/foo/bar.js"` will search your
-
# environment for `"foo/bar.js"`.
-
2
def call(env)
-
start_time = Time.now.to_f
-
time_elapsed = lambda { ((Time.now.to_f - start_time) * 1000).to_i }
-
-
msg = "Served asset #{env['PATH_INFO']} -"
-
-
# Mark session as "skipped" so no `Set-Cookie` header is set
-
env['rack.session.options'] ||= {}
-
env['rack.session.options'][:defer] = true
-
env['rack.session.options'][:skip] = true
-
-
# Extract the path from everything after the leading slash
-
path = unescape(env['PATH_INFO'].to_s.sub(/^\//, ''))
-
-
# Strip fingerprint
-
if fingerprint = path_fingerprint(path)
-
path = path.sub("-#{fingerprint}", '')
-
end
-
-
# URLs containing a `".."` are rejected for security reasons.
-
if forbidden_request?(path)
-
return forbidden_response
-
end
-
-
# Look up the asset.
-
asset = find_asset(path, :bundle => !body_only?(env))
-
-
# `find_asset` returns nil if the asset doesn't exist
-
if asset.nil?
-
logger.info "#{msg} 404 Not Found (#{time_elapsed.call}ms)"
-
-
# Return a 404 Not Found
-
not_found_response
-
-
# Check request headers `HTTP_IF_NONE_MATCH` against the asset digest
-
elsif etag_match?(asset, env)
-
logger.info "#{msg} 304 Not Modified (#{time_elapsed.call}ms)"
-
-
# Return a 304 Not Modified
-
not_modified_response(asset, env)
-
-
else
-
logger.info "#{msg} 200 OK (#{time_elapsed.call}ms)"
-
-
# Return a 200 with the asset contents
-
ok_response(asset, env)
-
end
-
rescue Exception => e
-
logger.error "Error compiling asset #{path}:"
-
logger.error "#{e.class.name}: #{e.message}"
-
-
case content_type_of(path)
-
when "application/javascript"
-
# Re-throw JavaScript asset exceptions to the browser
-
logger.info "#{msg} 500 Internal Server Error\n\n"
-
return javascript_exception_response(e)
-
when "text/css"
-
# Display CSS asset exceptions in the browser
-
logger.info "#{msg} 500 Internal Server Error\n\n"
-
return css_exception_response(e)
-
else
-
raise
-
end
-
end
-
-
2
private
-
2
def forbidden_request?(path)
-
# Prevent access to files elsewhere on the file system
-
#
-
# http://example.org/assets/../../../etc/passwd
-
#
-
path.include?("..") || Pathname.new(path).absolute?
-
end
-
-
# Returns a 403 Forbidden response tuple
-
2
def forbidden_response
-
[ 403, { "Content-Type" => "text/plain", "Content-Length" => "9" }, [ "Forbidden" ] ]
-
end
-
-
# Returns a 404 Not Found response tuple
-
2
def not_found_response
-
[ 404, { "Content-Type" => "text/plain", "Content-Length" => "9", "X-Cascade" => "pass" }, [ "Not found" ] ]
-
end
-
-
# Returns a JavaScript response that re-throws a Ruby exception
-
# in the browser
-
2
def javascript_exception_response(exception)
-
err = "#{exception.class.name}: #{exception.message}"
-
body = "throw Error(#{err.inspect})"
-
[ 200, { "Content-Type" => "application/javascript", "Content-Length" => Rack::Utils.bytesize(body).to_s }, [ body ] ]
-
end
-
-
# Returns a CSS response that hides all elements on the page and
-
# displays the exception
-
2
def css_exception_response(exception)
-
message = "\n#{exception.class.name}: #{exception.message}"
-
backtrace = "\n #{exception.backtrace.first}"
-
-
body = <<-CSS
-
html {
-
padding: 18px 36px;
-
}
-
-
head {
-
display: block;
-
}
-
-
body {
-
margin: 0;
-
padding: 0;
-
}
-
-
body > * {
-
display: none !important;
-
}
-
-
head:after, body:before, body:after {
-
display: block !important;
-
}
-
-
head:after {
-
font-family: sans-serif;
-
font-size: large;
-
font-weight: bold;
-
content: "Error compiling CSS asset";
-
}
-
-
body:before, body:after {
-
font-family: monospace;
-
white-space: pre-wrap;
-
}
-
-
body:before {
-
font-weight: bold;
-
content: "#{escape_css_content(message)}";
-
}
-
-
body:after {
-
content: "#{escape_css_content(backtrace)}";
-
}
-
CSS
-
-
[ 200, { "Content-Type" => "text/css;charset=utf-8", "Content-Length" => Rack::Utils.bytesize(body).to_s }, [ body ] ]
-
end
-
-
# Escape special characters for use inside a CSS content("...") string
-
2
def escape_css_content(content)
-
content.
-
gsub('\\', '\\\\005c ').
-
gsub("\n", '\\\\000a ').
-
gsub('"', '\\\\0022 ').
-
gsub('/', '\\\\002f ')
-
end
-
-
# Compare the requests `HTTP_IF_NONE_MATCH` against the assets digest
-
2
def etag_match?(asset, env)
-
env["HTTP_IF_NONE_MATCH"] == etag(asset)
-
end
-
-
# Test if `?body=1` or `body=true` query param is set
-
2
def body_only?(env)
-
env["QUERY_STRING"].to_s =~ /body=(1|t)/
-
end
-
-
# Returns a 304 Not Modified response tuple
-
2
def not_modified_response(asset, env)
-
[ 304, {}, [] ]
-
end
-
-
# Returns a 200 OK response tuple
-
2
def ok_response(asset, env)
-
[ 200, headers(env, asset, asset.length), asset ]
-
end
-
-
2
def headers(env, asset, length)
-
Hash.new.tap do |headers|
-
# Set content type and length headers
-
headers["Content-Type"] = asset.content_type
-
headers["Content-Length"] = length.to_s
-
-
# Set caching headers
-
headers["Cache-Control"] = "public"
-
headers["Last-Modified"] = asset.mtime.httpdate
-
headers["ETag"] = etag(asset)
-
-
# If the request url contains a fingerprint, set a long
-
# expires on the response
-
if path_fingerprint(env["PATH_INFO"])
-
headers["Cache-Control"] << ", max-age=31536000"
-
-
# Otherwise set `must-revalidate` since the asset could be modified.
-
else
-
headers["Cache-Control"] << ", must-revalidate"
-
end
-
end
-
end
-
-
# Gets digest fingerprint.
-
#
-
# "foo-0aa2105d29558f3eb790d411d7d8fb66.js"
-
# # => "0aa2105d29558f3eb790d411d7d8fb66"
-
#
-
2
def path_fingerprint(path)
-
path[/-([0-9a-f]{7,40})\.[^.]+\z/, 1]
-
end
-
-
# URI.unescape is deprecated on 1.9. We need to use URI::Parser
-
# if its available.
-
2
if defined? URI::DEFAULT_PARSER
-
2
def unescape(str)
-
str = URI::DEFAULT_PARSER.unescape(str)
-
str.force_encoding(Encoding.default_internal) if Encoding.default_internal
-
str
-
end
-
else
-
def unescape(str)
-
URI.unescape(str)
-
end
-
end
-
-
# Helper to quote the assets digest for use as an ETag.
-
2
def etag(asset)
-
%("#{asset.digest}")
-
end
-
end
-
end
-
2
require 'sprockets/asset'
-
2
require 'fileutils'
-
2
require 'zlib'
-
-
2
module Sprockets
-
# `StaticAsset`s are used for files that are served verbatim without
-
# any processing or concatenation. These are typical images and
-
# other binary files.
-
2
class StaticAsset < Asset
-
# Returns file contents as its `source`.
-
2
def source
-
# File is read everytime to avoid memory bloat of large binary files
-
pathname.open('rb') { |f| f.read }
-
end
-
-
# Implemented for Rack SendFile support.
-
2
def to_path
-
pathname.to_s
-
end
-
-
# Save asset to disk.
-
2
def write_to(filename, options = {})
-
# Gzip contents if filename has '.gz'
-
unless options.key?(:compress)
-
options[:compress] = File.extname(filename) == '.gz' && File.extname(logical_path) != '.gz'
-
end
-
-
FileUtils.mkdir_p File.dirname(filename)
-
-
if options[:compress]
-
# Open file and run it through `Zlib`
-
pathname.open('rb') do |rd|
-
File.open("#{filename}+", 'wb') do |wr|
-
gz = Zlib::GzipWriter.new(wr, Zlib::BEST_COMPRESSION)
-
gz.mtime = mtime.to_i
-
buf = ""
-
while rd.read(16384, buf)
-
gz.write(buf)
-
end
-
gz.close
-
end
-
end
-
else
-
# If no compression needs to be done, we can just copy it into place.
-
FileUtils.cp(pathname, "#{filename}+")
-
end
-
-
# Atomic write
-
FileUtils.mv("#{filename}+", filename)
-
-
# Set mtime correctly
-
File.utime(mtime, mtime, filename)
-
-
nil
-
ensure
-
# Ensure tmp file gets cleaned up
-
FileUtils.rm("#{filename}+") if File.exist?("#{filename}+")
-
end
-
end
-
end
-
2
require 'tilt'
-
-
2
module Sprockets
-
2
class UglifierCompressor < Tilt::Template
-
2
self.default_mime_type = 'application/javascript'
-
-
2
def self.engine_initialized?
-
defined?(::Uglifier)
-
end
-
-
2
def initialize_engine
-
require_template_library 'uglifier'
-
end
-
-
2
def prepare
-
end
-
-
2
def evaluate(context, locals, &block)
-
# Feature detect Uglifier 2.0 option support
-
if Uglifier::DEFAULTS[:copyright]
-
# Uglifier < 2.x
-
Uglifier.new(:copyright => false).compile(data)
-
else
-
# Uglifier >= 2.x
-
Uglifier.new(:comments => :none).compile(data)
-
end
-
end
-
end
-
end
-
2
module Sprockets
-
# `Utils`, we didn't know where else to put it!
-
2
module Utils
-
# If theres encoding support (aka Ruby 1.9)
-
2
if "".respond_to?(:valid_encoding?)
-
# Define UTF-8 BOM pattern matcher.
-
# Avoid using a Regexp literal because it inheirts the files
-
# encoding and we want to avoid syntax errors in other interpreters.
-
2
UTF8_BOM_PATTERN = Regexp.new("\\A\uFEFF".encode('utf-8'))
-
-
2
def self.read_unicode(pathname, external_encoding = Encoding.default_external)
-
2
pathname.open("r:#{external_encoding}") do |f|
-
2
f.read.tap do |data|
-
# Eager validate the file's encoding. In most cases we
-
# expect it to be UTF-8 unless `default_external` is set to
-
# something else. An error is usually raised if the file is
-
# saved as UTF-16 when we expected UTF-8.
-
2
if !data.valid_encoding?
-
raise EncodingError, "#{pathname} has a invalid " +
-
"#{data.encoding} byte sequence"
-
-
# If the file is UTF-8 and theres a BOM, strip it for safe concatenation.
-
elsif data.encoding.name == "UTF-8" && data =~ UTF8_BOM_PATTERN
-
data.sub!(UTF8_BOM_PATTERN, "")
-
end
-
end
-
end
-
end
-
-
else
-
# Define UTF-8 and UTF-16 BOM pattern matchers.
-
# Avoid using a Regexp literal to prevent syntax errors in other interpreters.
-
UTF8_BOM_PATTERN = Regexp.new("\\A\\xEF\\xBB\\xBF")
-
UTF16_BOM_PATTERN = Regexp.new("\\A(\\xFE\\xFF|\\xFF\\xFE)")
-
-
def self.read_unicode(pathname)
-
pathname.read.tap do |data|
-
# If the file is UTF-8 and theres a BOM, strip it for safe concatenation.
-
if data =~ UTF8_BOM_PATTERN
-
data.sub!(UTF8_BOM_PATTERN, "")
-
-
# If we find a UTF-16 BOM, theres nothing we can do on
-
# 1.8. Only UTF-8 is supported.
-
elsif data =~ UTF16_BOM_PATTERN
-
raise EncodingError, "#{pathname} has a UTF-16 BOM. " +
-
"Resave the file as UTF-8 or upgrade to Ruby 1.9."
-
end
-
end
-
end
-
end
-
-
# Prepends a leading "." to an extension if its missing.
-
#
-
# normalize_extension("js")
-
# # => ".js"
-
#
-
# normalize_extension(".css")
-
# # => ".css"
-
#
-
2
def self.normalize_extension(extension)
-
1431
extension = extension.to_s
-
1431
if extension[/^\./]
-
1431
extension
-
else
-
".#{extension}"
-
end
-
end
-
end
-
end
-
2
module Sprockets
-
2
VERSION = "2.12.4"
-
end
-
2
require 'tilt'
-
-
2
module Sprockets
-
2
class YUICompressor < Tilt::Template
-
2
def self.engine_initialized?
-
defined?(::YUI)
-
end
-
-
2
def initialize_engine
-
require_template_library 'yui/compressor'
-
end
-
-
2
def prepare
-
end
-
-
2
def evaluate(context, locals, &block)
-
case context.content_type
-
when 'application/javascript'
-
YUI::JavaScriptCompressor.new.compress(data)
-
when 'text/css'
-
YUI::CssCompressor.new.compress(data)
-
else
-
data
-
end
-
end
-
end
-
end
-
2
require 'action_view'
-
2
require 'sprockets'
-
2
require 'active_support/core_ext/class/attribute'
-
-
2
module Sprockets
-
2
module Rails
-
2
module Helper
-
2
class << self
-
2
attr_accessor :precompile, :assets, :raise_runtime_errors
-
end
-
-
2
def precompile
-
Sprockets::Rails::Helper.precompile
-
end
-
-
2
def assets
-
Sprockets::Rails::Helper.assets
-
end
-
-
2
def raise_runtime_errors
-
39
Sprockets::Rails::Helper.raise_runtime_errors
-
end
-
-
2
class AssetFilteredError < StandardError
-
2
def initialize(source)
-
msg = "Asset filtered out and will not be served: " <<
-
"add `Rails.application.config.assets.precompile += %w( #{source} )` " <<
-
"to `config/initializers/assets.rb` and restart your server"
-
super(msg)
-
end
-
end
-
-
2
class AbsoluteAssetPathError < ArgumentError
-
2
def initialize(bad_path, good_path, prefix)
-
msg = "Asset names passed to helpers should not include the #{prefix.inspect} prefix. " <<
-
"Instead of #{bad_path.inspect}, use #{good_path.inspect}"
-
super(msg)
-
end
-
end
-
-
2
if defined? ActionView::Helpers::AssetUrlHelper
-
2
include ActionView::Helpers::AssetUrlHelper
-
2
include ActionView::Helpers::AssetTagHelper
-
else
-
require 'sprockets/rails/legacy_asset_tag_helper'
-
require 'sprockets/rails/legacy_asset_url_helper'
-
include LegacyAssetTagHelper
-
include LegacyAssetUrlHelper
-
end
-
-
2
VIEW_ACCESSORS = [:assets_environment, :assets_manifest,
-
:assets_prefix, :digest_assets, :debug_assets]
-
-
2
def self.included(klass)
-
4
if klass < Sprockets::Context
-
2
klass.class_eval do
-
2
alias_method :assets_environment, :environment
-
2
def assets_manifest; end
-
2
class_attribute :config, :assets_prefix, :digest_assets, :debug_assets
-
end
-
else
-
2
klass.class_attribute(*VIEW_ACCESSORS)
-
end
-
end
-
-
2
def self.extended(obj)
-
obj.class_eval do
-
attr_accessor(*VIEW_ACCESSORS)
-
end
-
end
-
-
2
def compute_asset_path(path, options = {})
-
# Check if we are inside Sprockets context before calling check_dependencies!.
-
39
check_dependencies!(path) if defined?(depend_on)
-
-
39
if digest_path = asset_digest_path(path)
-
39
path = digest_path if digest_assets
-
39
path += "?body=1" if options[:debug]
-
39
File.join(assets_prefix || "/", path)
-
else
-
super
-
end
-
end
-
-
# Computes the full URL to a asset in the public directory. This
-
# method checks for errors before returning path.
-
2
def asset_path(source, options = {})
-
39
unless options[:debug]
-
39
check_errors_for(source, options)
-
end
-
39
super(source, options)
-
end
-
2
alias :path_to_asset :asset_path
-
-
# Get digest for asset path.
-
#
-
# path - String path
-
# options - Hash options
-
#
-
# Returns String Hex digest or nil if digests are disabled.
-
2
def asset_digest(path, options = {})
-
return unless digest_assets
-
-
if digest_path = asset_digest_path(path, options)
-
digest_path[/-(.+)\./, 1]
-
end
-
end
-
-
# Expand asset path to digested form.
-
#
-
# path - String path
-
# options - Hash options
-
#
-
# Returns String path or nil if no asset was found.
-
2
def asset_digest_path(path, options = {})
-
39
if manifest = assets_manifest
-
39
if digest_path = manifest.assets[path]
-
return digest_path
-
end
-
end
-
-
39
if environment = assets_environment
-
39
if asset = environment[path]
-
39
return asset.digest_path
-
end
-
end
-
end
-
-
# Override javascript tag helper to provide debugging support.
-
#
-
# Eventually will be deprecated and replaced by source maps.
-
2
def javascript_include_tag(*sources)
-
13
options = sources.extract_options!.stringify_keys
-
-
13
if options["debug"] != false && request_debug_assets?
-
sources.map { |source|
-
check_errors_for(source, :type => :javascript)
-
if asset = lookup_asset_for_path(source, :type => :javascript)
-
asset.to_a.map do |a|
-
super(path_to_javascript(a.logical_path, :debug => true), options)
-
end
-
else
-
super(source, options)
-
end
-
}.flatten.uniq.join("\n").html_safe
-
else
-
13
sources.push(options)
-
13
super(*sources)
-
end
-
end
-
-
# Override stylesheet tag helper to provide debugging support.
-
#
-
# Eventually will be deprecated and replaced by source maps.
-
2
def stylesheet_link_tag(*sources)
-
13
options = sources.extract_options!.stringify_keys
-
13
if options["debug"] != false && request_debug_assets?
-
sources.map { |source|
-
check_errors_for(source, :type => :stylesheet)
-
if asset = lookup_asset_for_path(source, :type => :stylesheet)
-
asset.to_a.map do |a|
-
super(path_to_stylesheet(a.logical_path, :debug => true), options)
-
end
-
else
-
super(source, options)
-
end
-
}.flatten.uniq.join("\n").html_safe
-
else
-
13
sources.push(options)
-
13
super(*sources)
-
end
-
end
-
-
2
protected
-
# Ensures the asset is included in the dependencies list.
-
2
def check_dependencies!(dep)
-
depend_on(dep)
-
depend_on_asset(dep)
-
rescue Sprockets::FileNotFound
-
end
-
-
# Raise errors when source is not in the precompiled list, or
-
# incorrectly contains the assets_prefix.
-
2
def check_errors_for(source, options)
-
39
return unless self.raise_runtime_errors
-
-
source = source.to_s
-
return if source.blank? || source =~ URI_REGEXP
-
-
asset = lookup_asset_for_path(source, options)
-
-
if asset && asset_needs_precompile?(asset.logical_path, asset.pathname.to_s)
-
raise AssetFilteredError.new(asset.logical_path)
-
end
-
-
full_prefix = File.join(self.assets_prefix || "/", '')
-
if !asset && source.start_with?(full_prefix)
-
short_path = source[full_prefix.size, source.size]
-
if lookup_asset_for_path(short_path, options)
-
raise AbsoluteAssetPathError.new(source, short_path, full_prefix)
-
end
-
end
-
end
-
-
# Returns true when an asset will not be available after precompile is run
-
2
def asset_needs_precompile?(source, filename)
-
if assets_environment && assets_environment.send(:matches_filter, precompile || [], source, filename)
-
false
-
else
-
true
-
end
-
end
-
-
# Enable split asset debugging. Eventually will be deprecated
-
# and replaced by source maps in Sprockets 3.x.
-
2
def request_debug_assets?
-
26
debug_assets || (defined?(controller) && controller && params[:debug_assets])
-
rescue
-
return false
-
end
-
-
# Internal method to support multifile debugging. Will
-
# eventually be removed w/ Sprockets 3.x.
-
2
def lookup_asset_for_path(path, options = {})
-
return unless env = assets_environment
-
path = path.to_s
-
if extname = compute_asset_extname(path, options)
-
path = "#{path}#{extname}"
-
end
-
env[path]
-
end
-
end
-
end
-
end
-
2
module Sprockets
-
2
module Rails
-
2
VERSION = "2.3.3"
-
end
-
end
-
2
require 'rails'
-
2
require 'rails/railtie'
-
2
require 'action_controller/railtie'
-
2
require 'active_support/core_ext/module/remove_method'
-
2
require 'sprockets'
-
2
require 'sprockets/rails/helper'
-
2
require 'sprockets/rails/version'
-
-
2
module Rails
-
2
class Application
-
# Hack: We need to remove Rails' built in config.assets so we can
-
# do our own thing.
-
2
class Configuration
-
2
remove_possible_method :assets
-
end
-
-
# Undefine Rails' assets method before redefining it, to avoid warnings.
-
2
remove_possible_method :assets
-
2
remove_possible_method :assets=
-
-
# Returns Sprockets::Environment for app config.
-
2
def assets
-
@assets ||= Sprockets::Environment.new(root.to_s) do |env|
-
2
env.version = ::Rails.env
-
-
2
path = "#{config.root}/tmp/cache/assets/#{::Rails.env}"
-
2
env.cache = Sprockets::Cache::FileStore.new(path)
-
-
2
env.context_class.class_eval do
-
2
include ::Sprockets::Rails::Helper
-
end
-
86
end
-
end
-
2
attr_writer :assets
-
-
# Returns Sprockets::Manifest for app config.
-
2
attr_accessor :assets_manifest
-
end
-
-
2
class Engine < Railtie
-
# Skip defining append_assets_path on Rails <= 4.2
-
16
unless initializers.find { |init| init.name == :append_assets_path }
-
initializer :append_assets_path, :group => :all do |app|
-
if paths["app/assets"].respond_to?(:existent_directories)
-
app.config.assets.paths.unshift(*paths["vendor/assets"].existent_directories)
-
app.config.assets.paths.unshift(*paths["lib/assets"].existent_directories)
-
app.config.assets.paths.unshift(*paths["app/assets"].existent_directories)
-
else
-
app.config.assets.paths.unshift(*paths["vendor/assets"].paths.select { |d| File.directory?(d) })
-
app.config.assets.paths.unshift(*paths["lib/assets"].paths.select { |d| File.directory?(d) })
-
app.config.assets.paths.unshift(*paths["app/assets"].paths.select { |d| File.directory?(d) })
-
end
-
end
-
end
-
end
-
end
-
-
2
module Sprockets
-
2
class Railtie < ::Rails::Railtie
-
2
LOOSE_APP_ASSETS = lambda do |filename, path|
-
path =~ /app\/assets/ && !%w(.js .css).include?(File.extname(filename))
-
end
-
-
2
class OrderedOptions < ActiveSupport::OrderedOptions
-
2
def configure(&block)
-
self._blocks << block
-
end
-
end
-
-
2
config.assets = OrderedOptions.new
-
2
config.assets._blocks = []
-
2
config.assets.paths = []
-
2
config.assets.prefix = "/assets"
-
2
config.assets.manifest = nil
-
2
config.assets.precompile = [LOOSE_APP_ASSETS, /(?:\/|\\|\A)application\.(css|js)$/]
-
2
config.assets.version = ""
-
2
config.assets.debug = false
-
2
config.assets.compile = true
-
2
config.assets.digest = false
-
-
2
rake_tasks do |app|
-
require 'sprockets/rails/task'
-
Sprockets::Rails::Task.new(app)
-
end
-
-
2
config.after_initialize do |app|
-
2
config = app.config
-
-
# Configuration options that should invalidate
-
# the Sprockets cache when changed.
-
2
app.assets.version = [
-
app.assets.version,
-
config.assets.version,
-
config.action_controller.relative_url_root,
-
2
(config.action_controller.asset_host unless config.action_controller.asset_host.respond_to?(:call)),
-
Sprockets::Rails::VERSION
-
].compact.join('-')
-
-
# Copy config.assets.paths to Sprockets
-
2
config.assets.paths.each do |path|
-
60
app.assets.append_path path
-
end
-
-
# Run app.assets.configure blocks
-
2
config.assets._blocks.each do |block|
-
block.call app.assets
-
end
-
-
# Set compressors after the configure blocks since they can
-
# define new compressors and we only accept existent compressors.
-
2
app.assets.js_compressor = config.assets.js_compressor
-
2
app.assets.css_compressor = config.assets.css_compressor
-
-
# No more configuration changes at this point.
-
# With cache classes on, Sprockets won't check the FS when files
-
# change. Preferable in production when the FS only changes on
-
# deploys when the app restarts.
-
2
if config.cache_classes
-
2
app.assets = app.assets.index
-
end
-
-
2
manifest_assets_path = File.join(config.paths['public'].first, config.assets.prefix)
-
2
if config.assets.compile
-
2
app.assets_manifest = Sprockets::Manifest.new(app.assets, manifest_assets_path, config.assets.manifest)
-
else
-
app.assets_manifest = Sprockets::Manifest.new(manifest_assets_path, config.assets.manifest)
-
end
-
-
2
ActiveSupport.on_load(:action_view) do
-
2
include Sprockets::Rails::Helper
-
-
# Copy relevant config to AV context
-
2
self.debug_assets = config.assets.debug
-
2
self.digest_assets = config.assets.digest
-
2
self.assets_prefix = config.assets.prefix
-
-
# Copy over to Sprockets as well
-
2
context = app.assets.context_class
-
2
context.assets_prefix = config.assets.prefix
-
2
context.digest_assets = config.assets.digest
-
2
context.config = config.action_controller
-
-
2
self.assets_environment = app.assets if config.assets.compile
-
2
self.assets_manifest = app.assets_manifest
-
end
-
-
2
Sprockets::Rails::Helper.precompile ||= app.config.assets.precompile
-
2
Sprockets::Rails::Helper.assets ||= app.assets
-
2
Sprockets::Rails::Helper.raise_runtime_errors = app.config.assets.raise_runtime_errors
-
-
2
if config.assets.compile
-
2
if app.routes.respond_to?(:prepend)
-
2
app.routes.prepend do
-
2
mount app.assets => config.assets.prefix
-
end
-
end
-
end
-
end
-
end
-
end
-
# support multiple ruby version (fat binaries under windows)
-
2
begin
-
2
RUBY_VERSION =~ /(\d+\.\d+)/
-
2
require "sqlite3/#{$1}/sqlite3_native"
-
rescue LoadError
-
2
require 'sqlite3/sqlite3_native'
-
end
-
-
2
require 'sqlite3/database'
-
2
require 'sqlite3/version'
-
4
module SQLite3 ; module Constants
-
-
2
module TextRep
-
2
UTF8 = 1
-
2
UTF16LE = 2
-
2
UTF16BE = 3
-
2
UTF16 = 4
-
2
ANY = 5
-
end
-
-
2
module ColumnType
-
2
INTEGER = 1
-
2
FLOAT = 2
-
2
TEXT = 3
-
2
BLOB = 4
-
2
NULL = 5
-
end
-
-
2
module ErrorCode
-
2
OK = 0 # Successful result
-
2
ERROR = 1 # SQL error or missing database
-
2
INTERNAL = 2 # An internal logic error in SQLite
-
2
PERM = 3 # Access permission denied
-
2
ABORT = 4 # Callback routine requested an abort
-
2
BUSY = 5 # The database file is locked
-
2
LOCKED = 6 # A table in the database is locked
-
2
NOMEM = 7 # A malloc() failed
-
2
READONLY = 8 # Attempt to write a readonly database
-
2
INTERRUPT = 9 # Operation terminated by sqlite_interrupt()
-
2
IOERR = 10 # Some kind of disk I/O error occurred
-
2
CORRUPT = 11 # The database disk image is malformed
-
2
NOTFOUND = 12 # (Internal Only) Table or record not found
-
2
FULL = 13 # Insertion failed because database is full
-
2
CANTOPEN = 14 # Unable to open the database file
-
2
PROTOCOL = 15 # Database lock protocol error
-
2
EMPTY = 16 # (Internal Only) Database table is empty
-
2
SCHEMA = 17 # The database schema changed
-
2
TOOBIG = 18 # Too much data for one row of a table
-
2
CONSTRAINT = 19 # Abort due to contraint violation
-
2
MISMATCH = 20 # Data type mismatch
-
2
MISUSE = 21 # Library used incorrectly
-
2
NOLFS = 22 # Uses OS features not supported on host
-
2
AUTH = 23 # Authorization denied
-
-
2
ROW = 100 # sqlite_step() has another row ready
-
2
DONE = 101 # sqlite_step() has finished executing
-
end
-
-
end ; end
-
2
require 'sqlite3/constants'
-
2
require 'sqlite3/errors'
-
2
require 'sqlite3/pragmas'
-
2
require 'sqlite3/statement'
-
2
require 'sqlite3/translator'
-
2
require 'sqlite3/value'
-
-
2
module SQLite3
-
-
# The Database class encapsulates a single connection to a SQLite3 database.
-
# Its usage is very straightforward:
-
#
-
# require 'sqlite3'
-
#
-
# SQLite3::Database.new( "data.db" ) do |db|
-
# db.execute( "select * from table" ) do |row|
-
# p row
-
# end
-
# end
-
#
-
# It wraps the lower-level methods provides by the selected driver, and
-
# includes the Pragmas module for access to various pragma convenience
-
# methods.
-
#
-
# The Database class provides type translation services as well, by which
-
# the SQLite3 data types (which are all represented as strings) may be
-
# converted into their corresponding types (as defined in the schemas
-
# for their tables). This translation only occurs when querying data from
-
# the database--insertions and updates are all still typeless.
-
#
-
# Furthermore, the Database class has been designed to work well with the
-
# ArrayFields module from Ara Howard. If you require the ArrayFields
-
# module before performing a query, and if you have not enabled results as
-
# hashes, then the results will all be indexible by field name.
-
2
class Database
-
2
attr_reader :collations
-
-
2
include Pragmas
-
-
2
class << self
-
-
2
alias :open :new
-
-
# Quotes the given string, making it safe to use in an SQL statement.
-
# It replaces all instances of the single-quote character with two
-
# single-quote characters. The modified string is returned.
-
2
def quote( string )
-
197
string.gsub( /'/, "''" )
-
end
-
-
end
-
-
# A boolean that indicates whether rows in result sets should be returned
-
# as hashes or not. By default, rows are returned as arrays.
-
2
attr_accessor :results_as_hash
-
-
2
def type_translation= value # :nodoc:
-
warn(<<-eowarn) if $VERBOSE
-
#{caller[0]} is calling SQLite3::Database#type_translation=
-
SQLite3::Database#type_translation= is deprecated and will be removed
-
in version 2.0.0.
-
eowarn
-
@type_translation = value
-
end
-
2
attr_reader :type_translation # :nodoc:
-
-
# Return the type translator employed by this database instance. Each
-
# database instance has its own type translator; this allows for different
-
# type handlers to be installed in each instance without affecting other
-
# instances. Furthermore, the translators are instantiated lazily, so that
-
# if a database does not use type translation, it will not be burdened by
-
# the overhead of a useless type translator. (See the Translator class.)
-
2
def translator
-
@translator ||= Translator.new
-
end
-
-
# Installs (or removes) a block that will be invoked for every access
-
# to the database. If the block returns 0 (or +nil+), the statement
-
# is allowed to proceed. Returning 1 causes an authorization error to
-
# occur, and returning 2 causes the access to be silently denied.
-
2
def authorizer( &block )
-
self.authorizer = block
-
end
-
-
# Returns a Statement object representing the given SQL. This does not
-
# execute the statement; it merely prepares the statement for execution.
-
#
-
# The Statement can then be executed using Statement#execute.
-
#
-
2
def prepare sql
-
705
stmt = SQLite3::Statement.new( self, sql )
-
705
return stmt unless block_given?
-
-
460
begin
-
460
yield stmt
-
ensure
-
460
stmt.close unless stmt.closed?
-
end
-
end
-
-
# Executes the given SQL statement. If additional parameters are given,
-
# they are treated as bind variables, and are bound to the placeholders in
-
# the query.
-
#
-
# Note that if any of the values passed to this are hashes, then the
-
# key/value pairs are each bound separately, with the key being used as
-
# the name of the placeholder to bind the value to.
-
#
-
# The block is optional. If given, it will be invoked for each row returned
-
# by the query. Otherwise, any results are accumulated into an array and
-
# returned wholesale.
-
#
-
# See also #execute2, #query, and #execute_batch for additional ways of
-
# executing statements.
-
2
def execute sql, bind_vars = [], *args, &block
-
# FIXME: This is a terrible hack and should be removed but is required
-
# for older versions of rails
-
460
hack = Object.const_defined?(:ActiveRecord) && sql =~ /^PRAGMA index_list/
-
-
460
if bind_vars.nil? || !args.empty?
-
if args.empty?
-
bind_vars = []
-
else
-
bind_vars = [bind_vars] + args
-
end
-
-
warn(<<-eowarn) if $VERBOSE
-
#{caller[0]} is calling SQLite3::Database#execute with nil or multiple bind params
-
without using an array. Please switch to passing bind parameters as an array.
-
Support for bind parameters as *args will be removed in 2.0.0.
-
eowarn
-
end
-
-
460
prepare( sql ) do |stmt|
-
460
stmt.bind_params(bind_vars)
-
460
columns = stmt.columns
-
460
stmt = ResultSet.new(self, stmt).to_a if type_translation
-
-
460
if block_given?
-
stmt.each do |row|
-
if @results_as_hash
-
yield type_translation ? row : ordered_map_for(columns, row)
-
else
-
yield row
-
end
-
end
-
else
-
460
if @results_as_hash
-
460
stmt.map { |row|
-
h = type_translation ? row : ordered_map_for(columns, row)
-
-
# FIXME UGH TERRIBLE HACK!
-
h['unique'] = h['unique'].to_s if hack
-
-
h
-
}
-
else
-
stmt.to_a
-
end
-
end
-
end
-
end
-
-
# Executes the given SQL statement, exactly as with #execute. However, the
-
# first row returned (either via the block, or in the returned array) is
-
# always the names of the columns. Subsequent rows correspond to the data
-
# from the result set.
-
#
-
# Thus, even if the query itself returns no rows, this method will always
-
# return at least one row--the names of the columns.
-
#
-
# See also #execute, #query, and #execute_batch for additional ways of
-
# executing statements.
-
2
def execute2( sql, *bind_vars )
-
prepare( sql ) do |stmt|
-
result = stmt.execute( *bind_vars )
-
if block_given?
-
yield stmt.columns
-
result.each { |row| yield row }
-
else
-
return result.inject( [ stmt.columns ] ) { |arr,row|
-
arr << row; arr }
-
end
-
end
-
end
-
-
# Executes all SQL statements in the given string. By contrast, the other
-
# means of executing queries will only execute the first statement in the
-
# string, ignoring all subsequent statements. This will execute each one
-
# in turn. The same bind parameters, if given, will be applied to each
-
# statement.
-
#
-
# This always returns +nil+, making it unsuitable for queries that return
-
# rows.
-
2
def execute_batch( sql, bind_vars = [], *args )
-
# FIXME: remove this stuff later
-
unless [Array, Hash].include?(bind_vars.class)
-
bind_vars = [bind_vars]
-
warn(<<-eowarn) if $VERBOSE
-
#{caller[0]} is calling SQLite3::Database#execute_batch with bind parameters
-
that are not a list of a hash. Please switch to passing bind parameters as an
-
array or hash. Support for this behavior will be removed in version 2.0.0.
-
eowarn
-
end
-
-
# FIXME: remove this stuff later
-
if bind_vars.nil? || !args.empty?
-
if args.empty?
-
bind_vars = []
-
else
-
bind_vars = [nil] + args
-
end
-
-
warn(<<-eowarn) if $VERBOSE
-
#{caller[0]} is calling SQLite3::Database#execute_batch with nil or multiple bind params
-
without using an array. Please switch to passing bind parameters as an array.
-
Support for this behavior will be removed in version 2.0.0.
-
eowarn
-
end
-
-
sql = sql.strip
-
until sql.empty? do
-
prepare( sql ) do |stmt|
-
unless stmt.closed?
-
# FIXME: this should probably use sqlite3's api for batch execution
-
# This implementation requires stepping over the results.
-
if bind_vars.length == stmt.bind_parameter_count
-
stmt.bind_params(bind_vars)
-
end
-
stmt.step
-
end
-
sql = stmt.remainder.strip
-
end
-
end
-
# FIXME: we should not return `nil` as a success return value
-
nil
-
end
-
-
# This is a convenience method for creating a statement, binding
-
# paramters to it, and calling execute:
-
#
-
# result = db.query( "select * from foo where a=?", [5])
-
# # is the same as
-
# result = db.prepare( "select * from foo where a=?" ).execute( 5 )
-
#
-
# You must be sure to call +close+ on the ResultSet instance that is
-
# returned, or you could have problems with locks on the table. If called
-
# with a block, +close+ will be invoked implicitly when the block
-
# terminates.
-
2
def query( sql, bind_vars = [], *args )
-
-
if bind_vars.nil? || !args.empty?
-
if args.empty?
-
bind_vars = []
-
else
-
bind_vars = [bind_vars] + args
-
end
-
-
warn(<<-eowarn) if $VERBOSE
-
#{caller[0]} is calling SQLite3::Database#query with nil or multiple bind params
-
without using an array. Please switch to passing bind parameters as an array.
-
Support for this will be removed in version 2.0.0.
-
eowarn
-
end
-
-
result = prepare( sql ).execute( bind_vars )
-
if block_given?
-
begin
-
yield result
-
ensure
-
result.close
-
end
-
else
-
return result
-
end
-
end
-
-
# A convenience method for obtaining the first row of a result set, and
-
# discarding all others. It is otherwise identical to #execute.
-
#
-
# See also #get_first_value.
-
2
def get_first_row( sql, *bind_vars )
-
execute( sql, *bind_vars ).first
-
end
-
-
# A convenience method for obtaining the first value of the first row of a
-
# result set, and discarding all other values and rows. It is otherwise
-
# identical to #execute.
-
#
-
# See also #get_first_row.
-
2
def get_first_value( sql, *bind_vars )
-
execute( sql, *bind_vars ) { |row| return row[0] }
-
nil
-
end
-
-
2
alias :busy_timeout :busy_timeout=
-
-
# Creates a new function for use in SQL statements. It will be added as
-
# +name+, with the given +arity+. (For variable arity functions, use
-
# -1 for the arity.)
-
#
-
# The block should accept at least one parameter--the FunctionProxy
-
# instance that wraps this function invocation--and any other
-
# arguments it needs (up to its arity).
-
#
-
# The block does not return a value directly. Instead, it will invoke
-
# the FunctionProxy#result= method on the +func+ parameter and
-
# indicate the return value that way.
-
#
-
# Example:
-
#
-
# db.create_function( "maim", 1 ) do |func, value|
-
# if value.nil?
-
# func.result = nil
-
# else
-
# func.result = value.split(//).sort.join
-
# end
-
# end
-
#
-
# puts db.get_first_value( "select maim(name) from table" )
-
2
def create_function name, arity, text_rep=Constants::TextRep::ANY, &block
-
define_function(name) do |*args|
-
fp = FunctionProxy.new
-
block.call(fp, *args)
-
fp.result
-
end
-
self
-
end
-
-
# Creates a new aggregate function for use in SQL statements. Aggregate
-
# functions are functions that apply over every row in the result set,
-
# instead of over just a single row. (A very common aggregate function
-
# is the "count" function, for determining the number of rows that match
-
# a query.)
-
#
-
# The new function will be added as +name+, with the given +arity+. (For
-
# variable arity functions, use -1 for the arity.)
-
#
-
# The +step+ parameter must be a proc object that accepts as its first
-
# parameter a FunctionProxy instance (representing the function
-
# invocation), with any subsequent parameters (up to the function's arity).
-
# The +step+ callback will be invoked once for each row of the result set.
-
#
-
# The +finalize+ parameter must be a +proc+ object that accepts only a
-
# single parameter, the FunctionProxy instance representing the current
-
# function invocation. It should invoke FunctionProxy#result= to
-
# store the result of the function.
-
#
-
# Example:
-
#
-
# db.create_aggregate( "lengths", 1 ) do
-
# step do |func, value|
-
# func[ :total ] ||= 0
-
# func[ :total ] += ( value ? value.length : 0 )
-
# end
-
#
-
# finalize do |func|
-
# func.result = func[ :total ] || 0
-
# end
-
# end
-
#
-
# puts db.get_first_value( "select lengths(name) from table" )
-
#
-
# See also #create_aggregate_handler for a more object-oriented approach to
-
# aggregate functions.
-
2
def create_aggregate( name, arity, step=nil, finalize=nil,
-
text_rep=Constants::TextRep::ANY, &block )
-
-
factory = Class.new do
-
def self.step( &block )
-
define_method(:step, &block)
-
end
-
-
def self.finalize( &block )
-
define_method(:finalize, &block)
-
end
-
end
-
-
if block_given?
-
factory.instance_eval(&block)
-
else
-
factory.class_eval do
-
define_method(:step, step)
-
define_method(:finalize, finalize)
-
end
-
end
-
-
proxy = factory.new
-
proxy.extend(Module.new {
-
attr_accessor :ctx
-
-
def step( *args )
-
super(@ctx, *args)
-
end
-
-
def finalize
-
super(@ctx)
-
end
-
})
-
proxy.ctx = FunctionProxy.new
-
define_aggregator(name, proxy)
-
end
-
-
# This is another approach to creating an aggregate function (see
-
# #create_aggregate). Instead of explicitly specifying the name,
-
# callbacks, arity, and type, you specify a factory object
-
# (the "handler") that knows how to obtain all of that information. The
-
# handler should respond to the following messages:
-
#
-
# +arity+:: corresponds to the +arity+ parameter of #create_aggregate. This
-
# message is optional, and if the handler does not respond to it,
-
# the function will have an arity of -1.
-
# +name+:: this is the name of the function. The handler _must_ implement
-
# this message.
-
# +new+:: this must be implemented by the handler. It should return a new
-
# instance of the object that will handle a specific invocation of
-
# the function.
-
#
-
# The handler instance (the object returned by the +new+ message, described
-
# above), must respond to the following messages:
-
#
-
# +step+:: this is the method that will be called for each step of the
-
# aggregate function's evaluation. It should implement the same
-
# signature as the +step+ callback for #create_aggregate.
-
# +finalize+:: this is the method that will be called to finalize the
-
# aggregate function's evaluation. It should implement the
-
# same signature as the +finalize+ callback for
-
# #create_aggregate.
-
#
-
# Example:
-
#
-
# class LengthsAggregateHandler
-
# def self.arity; 1; end
-
# def self.name; 'lengths'; end
-
#
-
# def initialize
-
# @total = 0
-
# end
-
#
-
# def step( ctx, name )
-
# @total += ( name ? name.length : 0 )
-
# end
-
#
-
# def finalize( ctx )
-
# ctx.result = @total
-
# end
-
# end
-
#
-
# db.create_aggregate_handler( LengthsAggregateHandler )
-
# puts db.get_first_value( "select lengths(name) from A" )
-
2
def create_aggregate_handler( handler )
-
proxy = Class.new do
-
def initialize klass
-
@klass = klass
-
@fp = FunctionProxy.new
-
end
-
-
def step( *args )
-
instance.step(@fp, *args)
-
end
-
-
def finalize
-
instance.finalize @fp
-
@instance = nil
-
@fp.result
-
end
-
-
private
-
-
def instance
-
@instance ||= @klass.new
-
end
-
end
-
define_aggregator(handler.name, proxy.new(handler))
-
self
-
end
-
-
# Begins a new transaction. Note that nested transactions are not allowed
-
# by SQLite, so attempting to nest a transaction will result in a runtime
-
# exception.
-
#
-
# The +mode+ parameter may be either <tt>:deferred</tt> (the default),
-
# <tt>:immediate</tt>, or <tt>:exclusive</tt>.
-
#
-
# If a block is given, the database instance is yielded to it, and the
-
# transaction is committed when the block terminates. If the block
-
# raises an exception, a rollback will be performed instead. Note that if
-
# a block is given, #commit and #rollback should never be called
-
# explicitly or you'll get an error when the block terminates.
-
#
-
# If a block is not given, it is the caller's responsibility to end the
-
# transaction explicitly, either by calling #commit, or by calling
-
# #rollback.
-
2
def transaction( mode = :deferred )
-
33
execute "begin #{mode.to_s} transaction"
-
-
33
if block_given?
-
abort = false
-
begin
-
yield self
-
rescue ::Object
-
abort = true
-
raise
-
ensure
-
abort and rollback or commit
-
end
-
end
-
-
33
true
-
end
-
-
# Commits the current transaction. If there is no current transaction,
-
# this will cause an error to be raised. This returns +true+, in order
-
# to allow it to be used in idioms like
-
# <tt>abort? and rollback or commit</tt>.
-
2
def commit
-
6
execute "commit transaction"
-
6
true
-
end
-
-
# Rolls the current transaction back. If there is no current transaction,
-
# this will cause an error to be raised. This returns +true+, in order
-
# to allow it to be used in idioms like
-
# <tt>abort? and rollback or commit</tt>.
-
2
def rollback
-
27
execute "rollback transaction"
-
27
true
-
end
-
-
# Returns +true+ if the database has been open in readonly mode
-
# A helper to check before performing any operation
-
2
def readonly?
-
@readonly
-
end
-
-
# A helper class for dealing with custom functions (see #create_function,
-
# #create_aggregate, and #create_aggregate_handler). It encapsulates the
-
# opaque function object that represents the current invocation. It also
-
# provides more convenient access to the API functions that operate on
-
# the function object.
-
#
-
# This class will almost _always_ be instantiated indirectly, by working
-
# with the create methods mentioned above.
-
2
class FunctionProxy
-
2
attr_accessor :result
-
-
# Create a new FunctionProxy that encapsulates the given +func+ object.
-
# If context is non-nil, the functions context will be set to that. If
-
# it is non-nil, it must quack like a Hash. If it is nil, then none of
-
# the context functions will be available.
-
2
def initialize
-
@result = nil
-
@context = {}
-
end
-
-
# Set the result of the function to the given error message.
-
# The function will then return that error.
-
2
def set_error( error )
-
@driver.result_error( @func, error.to_s, -1 )
-
end
-
-
# (Only available to aggregate functions.) Returns the number of rows
-
# that the aggregate has processed so far. This will include the current
-
# row, and so will always return at least 1.
-
2
def count
-
@driver.aggregate_count( @func )
-
end
-
-
# Returns the value with the given key from the context. This is only
-
# available to aggregate functions.
-
2
def []( key )
-
@context[ key ]
-
end
-
-
# Sets the value with the given key in the context. This is only
-
# available to aggregate functions.
-
2
def []=( key, value )
-
@context[ key ] = value
-
end
-
end
-
-
2
private
-
-
2
def ordered_map_for columns, row
-
h = Hash[*columns.zip(row).flatten]
-
row.each_with_index { |r, i| h[i] = r }
-
h
-
end
-
end
-
end
-
2
require 'sqlite3/constants'
-
-
2
module SQLite3
-
2
class Exception < ::StandardError
-
2
@code = 0
-
-
# The numeric error code that this exception represents.
-
2
def self.code
-
@code
-
end
-
-
# A convenience for accessing the error code for this exception.
-
2
def code
-
self.class.code
-
end
-
end
-
-
2
class SQLException < Exception; end
-
2
class InternalException < Exception; end
-
2
class PermissionException < Exception; end
-
2
class AbortException < Exception; end
-
2
class BusyException < Exception; end
-
2
class LockedException < Exception; end
-
2
class MemoryException < Exception; end
-
2
class ReadOnlyException < Exception; end
-
2
class InterruptException < Exception; end
-
2
class IOException < Exception; end
-
2
class CorruptException < Exception; end
-
2
class NotFoundException < Exception; end
-
2
class FullException < Exception; end
-
2
class CantOpenException < Exception; end
-
2
class ProtocolException < Exception; end
-
2
class EmptyException < Exception; end
-
2
class SchemaChangedException < Exception; end
-
2
class TooBigException < Exception; end
-
2
class ConstraintException < Exception; end
-
2
class MismatchException < Exception; end
-
2
class MisuseException < Exception; end
-
2
class UnsupportedException < Exception; end
-
2
class AuthorizationException < Exception; end
-
2
class FormatException < Exception; end
-
2
class RangeException < Exception; end
-
2
class NotADatabaseException < Exception; end
-
end
-
2
require 'sqlite3/errors'
-
-
2
module SQLite3
-
-
# This module is intended for inclusion solely by the Database class. It
-
# defines convenience methods for the various pragmas supported by SQLite3.
-
#
-
# For a detailed description of these pragmas, see the SQLite3 documentation
-
# at http://sqlite.org/pragma.html.
-
2
module Pragmas
-
-
# Returns +true+ or +false+ depending on the value of the named pragma.
-
2
def get_boolean_pragma( name )
-
get_first_value( "PRAGMA #{name}" ) != "0"
-
end
-
2
private :get_boolean_pragma
-
-
# Sets the given pragma to the given boolean value. The value itself
-
# may be +true+ or +false+, or any other commonly used string or
-
# integer that represents truth.
-
2
def set_boolean_pragma( name, mode )
-
case mode
-
when String
-
case mode.downcase
-
when "on", "yes", "true", "y", "t"; mode = "'ON'"
-
when "off", "no", "false", "n", "f"; mode = "'OFF'"
-
else
-
raise Exception,
-
"unrecognized pragma parameter #{mode.inspect}"
-
end
-
when true, 1
-
mode = "ON"
-
when false, 0, nil
-
mode = "OFF"
-
else
-
raise Exception,
-
"unrecognized pragma parameter #{mode.inspect}"
-
end
-
-
execute( "PRAGMA #{name}=#{mode}" )
-
end
-
2
private :set_boolean_pragma
-
-
# Requests the given pragma (and parameters), and if the block is given,
-
# each row of the result set will be yielded to it. Otherwise, the results
-
# are returned as an array.
-
2
def get_query_pragma( name, *parms, &block ) # :yields: row
-
if parms.empty?
-
execute( "PRAGMA #{name}", &block )
-
else
-
args = "'" + parms.join("','") + "'"
-
execute( "PRAGMA #{name}( #{args} )", &block )
-
end
-
end
-
2
private :get_query_pragma
-
-
# Return the value of the given pragma.
-
2
def get_enum_pragma( name )
-
get_first_value( "PRAGMA #{name}" )
-
end
-
2
private :get_enum_pragma
-
-
# Set the value of the given pragma to +mode+. The +mode+ parameter must
-
# conform to one of the values in the given +enum+ array. Each entry in
-
# the array is another array comprised of elements in the enumeration that
-
# have duplicate values. See #synchronous, #default_synchronous,
-
# #temp_store, and #default_temp_store for usage examples.
-
2
def set_enum_pragma( name, mode, enums )
-
match = enums.find { |p| p.find { |i| i.to_s.downcase == mode.to_s.downcase } }
-
raise Exception,
-
"unrecognized #{name} #{mode.inspect}" unless match
-
execute( "PRAGMA #{name}='#{match.first.upcase}'" )
-
end
-
2
private :set_enum_pragma
-
-
# Returns the value of the given pragma as an integer.
-
2
def get_int_pragma( name )
-
get_first_value( "PRAGMA #{name}" ).to_i
-
end
-
2
private :get_int_pragma
-
-
# Set the value of the given pragma to the integer value of the +value+
-
# parameter.
-
2
def set_int_pragma( name, value )
-
execute( "PRAGMA #{name}=#{value.to_i}" )
-
end
-
2
private :set_int_pragma
-
-
# The enumeration of valid synchronous modes.
-
2
SYNCHRONOUS_MODES = [ [ 'full', 2 ], [ 'normal', 1 ], [ 'off', 0 ] ]
-
-
# The enumeration of valid temp store modes.
-
2
TEMP_STORE_MODES = [ [ 'default', 0 ], [ 'file', 1 ], [ 'memory', 2 ] ]
-
-
# Does an integrity check on the database. If the check fails, a
-
# SQLite3::Exception will be raised. Otherwise it
-
# returns silently.
-
2
def integrity_check
-
execute( "PRAGMA integrity_check" ) do |row|
-
raise Exception, row[0] if row[0] != "ok"
-
end
-
end
-
-
2
def auto_vacuum
-
get_boolean_pragma "auto_vacuum"
-
end
-
-
2
def auto_vacuum=( mode )
-
set_boolean_pragma "auto_vacuum", mode
-
end
-
-
2
def schema_cookie
-
get_int_pragma "schema_cookie"
-
end
-
-
2
def schema_cookie=( cookie )
-
set_int_pragma "schema_cookie", cookie
-
end
-
-
2
def user_cookie
-
get_int_pragma "user_cookie"
-
end
-
-
2
def user_cookie=( cookie )
-
set_int_pragma "user_cookie", cookie
-
end
-
-
2
def cache_size
-
get_int_pragma "cache_size"
-
end
-
-
2
def cache_size=( size )
-
set_int_pragma "cache_size", size
-
end
-
-
2
def default_cache_size
-
get_int_pragma "default_cache_size"
-
end
-
-
2
def default_cache_size=( size )
-
set_int_pragma "default_cache_size", size
-
end
-
-
2
def default_synchronous
-
get_enum_pragma "default_synchronous"
-
end
-
-
2
def default_synchronous=( mode )
-
set_enum_pragma "default_synchronous", mode, SYNCHRONOUS_MODES
-
end
-
-
2
def synchronous
-
get_enum_pragma "synchronous"
-
end
-
-
2
def synchronous=( mode )
-
set_enum_pragma "synchronous", mode, SYNCHRONOUS_MODES
-
end
-
-
2
def default_temp_store
-
get_enum_pragma "default_temp_store"
-
end
-
-
2
def default_temp_store=( mode )
-
set_enum_pragma "default_temp_store", mode, TEMP_STORE_MODES
-
end
-
-
2
def temp_store
-
get_enum_pragma "temp_store"
-
end
-
-
2
def temp_store=( mode )
-
set_enum_pragma "temp_store", mode, TEMP_STORE_MODES
-
end
-
-
2
def full_column_names
-
get_boolean_pragma "full_column_names"
-
end
-
-
2
def full_column_names=( mode )
-
set_boolean_pragma "full_column_names", mode
-
end
-
-
2
def parser_trace
-
get_boolean_pragma "parser_trace"
-
end
-
-
2
def parser_trace=( mode )
-
set_boolean_pragma "parser_trace", mode
-
end
-
-
2
def vdbe_trace
-
get_boolean_pragma "vdbe_trace"
-
end
-
-
2
def vdbe_trace=( mode )
-
set_boolean_pragma "vdbe_trace", mode
-
end
-
-
2
def database_list( &block ) # :yields: row
-
get_query_pragma "database_list", &block
-
end
-
-
2
def foreign_key_list( table, &block ) # :yields: row
-
get_query_pragma "foreign_key_list", table, &block
-
end
-
-
2
def index_info( index, &block ) # :yields: row
-
get_query_pragma "index_info", index, &block
-
end
-
-
2
def index_list( table, &block ) # :yields: row
-
get_query_pragma "index_list", table, &block
-
end
-
-
###
-
# Returns information about +table+. Yields each row of table information
-
# if a block is provided.
-
2
def table_info table
-
stmt = prepare "PRAGMA table_info(#{table})"
-
columns = stmt.columns
-
-
needs_tweak_default =
-
version_compare(SQLite3.libversion.to_s, "3.3.7") > 0
-
-
result = [] unless block_given?
-
stmt.each do |row|
-
new_row = Hash[columns.zip(row)]
-
-
# FIXME: This should be removed but is required for older versions
-
# of rails
-
if(Object.const_defined?(:ActiveRecord))
-
new_row['notnull'] = new_row['notnull'].to_s
-
end
-
-
tweak_default(new_row) if needs_tweak_default
-
-
if block_given?
-
yield new_row
-
else
-
result << new_row
-
end
-
end
-
stmt.close
-
-
result
-
end
-
-
2
private
-
-
# Compares two version strings
-
2
def version_compare(v1, v2)
-
v1 = v1.split(".").map { |i| i.to_i }
-
v2 = v2.split(".").map { |i| i.to_i }
-
parts = [v1.length, v2.length].max
-
v1.push 0 while v1.length < parts
-
v2.push 0 while v2.length < parts
-
v1.zip(v2).each do |a,b|
-
return -1 if a < b
-
return 1 if a > b
-
end
-
return 0
-
end
-
-
# Since SQLite 3.3.8, the table_info pragma has returned the default
-
# value of the row as a quoted SQL value. This method essentially
-
# unquotes those values.
-
2
def tweak_default(hash)
-
case hash["dflt_value"]
-
when /^null$/i
-
hash["dflt_value"] = nil
-
when /^'(.*)'$/m
-
hash["dflt_value"] = $1.gsub(/''/, "'")
-
when /^"(.*)"$/m
-
hash["dflt_value"] = $1.gsub(/""/, '"')
-
end
-
end
-
end
-
-
end
-
2
require 'sqlite3/constants'
-
2
require 'sqlite3/errors'
-
-
2
module SQLite3
-
-
# The ResultSet object encapsulates the enumerability of a query's output.
-
# It is a simple cursor over the data that the query returns. It will
-
# very rarely (if ever) be instantiated directly. Instead, clients should
-
# obtain a ResultSet instance via Statement#execute.
-
2
class ResultSet
-
2
include Enumerable
-
-
2
class ArrayWithTypes < Array # :nodoc:
-
2
attr_accessor :types
-
end
-
-
2
class ArrayWithTypesAndFields < Array # :nodoc:
-
2
attr_writer :types
-
2
attr_writer :fields
-
-
2
def types
-
warn(<<-eowarn) if $VERBOSE
-
#{caller[0]} is calling #{self.class}#types. This method will be removed in
-
sqlite3 version 2.0.0, please call the `types` method on the SQLite3::ResultSet
-
object that created this object
-
eowarn
-
@types
-
end
-
-
2
def fields
-
warn(<<-eowarn) if $VERBOSE
-
#{caller[0]} is calling #{self.class}#fields. This method will be removed in
-
sqlite3 version 2.0.0, please call the `columns` method on the SQLite3::ResultSet
-
object that created this object
-
eowarn
-
@fields
-
end
-
end
-
-
# The class of which we return an object in case we want a Hash as
-
# result.
-
2
class HashWithTypesAndFields < Hash # :nodoc:
-
2
attr_writer :types
-
2
attr_writer :fields
-
-
2
def types
-
warn(<<-eowarn) if $VERBOSE
-
#{caller[0]} is calling #{self.class}#types. This method will be removed in
-
sqlite3 version 2.0.0, please call the `types` method on the SQLite3::ResultSet
-
object that created this object
-
eowarn
-
@types
-
end
-
-
2
def fields
-
warn(<<-eowarn) if $VERBOSE
-
#{caller[0]} is calling #{self.class}#fields. This method will be removed in
-
sqlite3 version 2.0.0, please call the `columns` method on the SQLite3::ResultSet
-
object that created this object
-
eowarn
-
@fields
-
end
-
-
2
def [] key
-
key = fields[key] if key.is_a? Numeric
-
super key
-
end
-
end
-
-
# Create a new ResultSet attached to the given database, using the
-
# given sql text.
-
2
def initialize db, stmt
-
@db = db
-
@stmt = stmt
-
end
-
-
# Reset the cursor, so that a result set which has reached end-of-file
-
# can be rewound and reiterated.
-
2
def reset( *bind_params )
-
@stmt.reset!
-
@stmt.bind_params( *bind_params )
-
@eof = false
-
end
-
-
# Query whether the cursor has reached the end of the result set or not.
-
2
def eof?
-
@stmt.done?
-
end
-
-
# Obtain the next row from the cursor. If there are no more rows to be
-
# had, this will return +nil+. If type translation is active on the
-
# corresponding database, the values in the row will be translated
-
# according to their types.
-
#
-
# The returned value will be an array, unless Database#results_as_hash has
-
# been set to +true+, in which case the returned value will be a hash.
-
#
-
# For arrays, the column names are accessible via the +fields+ property,
-
# and the column types are accessible via the +types+ property.
-
#
-
# For hashes, the column names are the keys of the hash, and the column
-
# types are accessible via the +types+ property.
-
2
def next
-
if @db.results_as_hash
-
return next_hash
-
end
-
-
row = @stmt.step
-
return nil if @stmt.done?
-
-
if @db.type_translation
-
row = @stmt.types.zip(row).map do |type, value|
-
@db.translator.translate( type, value )
-
end
-
end
-
-
if row.respond_to?(:fields)
-
# FIXME: this can only happen if the translator returns something
-
# that responds to `fields`. Since we're removing the translator
-
# in 2.0, we can remove this branch in 2.0.
-
row = ArrayWithTypes.new(row)
-
else
-
# FIXME: the `fields` and `types` methods are deprecated on this
-
# object for version 2.0, so we can safely remove this branch
-
# as well.
-
row = ArrayWithTypesAndFields.new(row)
-
end
-
-
row.fields = @stmt.columns
-
row.types = @stmt.types
-
row
-
end
-
-
# Required by the Enumerable mixin. Provides an internal iterator over the
-
# rows of the result set.
-
2
def each
-
while node = self.next
-
yield node
-
end
-
end
-
-
# Provides an internal iterator over the rows of the result set where
-
# each row is yielded as a hash.
-
2
def each_hash
-
while node = next_hash
-
yield node
-
end
-
end
-
-
# Closes the statement that spawned this result set.
-
# <em>Use with caution!</em> Closing a result set will automatically
-
# close any other result sets that were spawned from the same statement.
-
2
def close
-
@stmt.close
-
end
-
-
# Queries whether the underlying statement has been closed or not.
-
2
def closed?
-
@stmt.closed?
-
end
-
-
# Returns the types of the columns returned by this result set.
-
2
def types
-
@stmt.types
-
end
-
-
# Returns the names of the columns returned by this result set.
-
2
def columns
-
@stmt.columns
-
end
-
-
# Return the next row as a hash
-
2
def next_hash
-
row = @stmt.step
-
return nil if @stmt.done?
-
-
# FIXME: type translation is deprecated, so this can be removed
-
# in 2.0
-
if @db.type_translation
-
row = @stmt.types.zip(row).map do |type, value|
-
@db.translator.translate( type, value )
-
end
-
end
-
-
# FIXME: this can be switched to a regular hash in 2.0
-
row = HashWithTypesAndFields[*@stmt.columns.zip(row).flatten]
-
-
# FIXME: these methods are deprecated for version 2.0, so we can remove
-
# this code in 2.0
-
row.fields = @stmt.columns
-
row.types = @stmt.types
-
row
-
end
-
end
-
end
-
2
require 'sqlite3/errors'
-
2
require 'sqlite3/resultset'
-
-
2
class String
-
2
def to_blob
-
SQLite3::Blob.new( self )
-
end
-
end
-
-
2
module SQLite3
-
# A statement represents a prepared-but-unexecuted SQL query. It will rarely
-
# (if ever) be instantiated directly by a client, and is most often obtained
-
# via the Database#prepare method.
-
2
class Statement
-
2
include Enumerable
-
-
# This is any text that followed the first valid SQL statement in the text
-
# with which the statement was initialized. If there was no trailing text,
-
# this will be the empty string.
-
2
attr_reader :remainder
-
-
# Binds the given variables to the corresponding placeholders in the SQL
-
# text.
-
#
-
# See Database#execute for a description of the valid placeholder
-
# syntaxes.
-
#
-
# Example:
-
#
-
# stmt = db.prepare( "select * from table where a=? and b=?" )
-
# stmt.bind_params( 15, "hello" )
-
#
-
# See also #execute, #bind_param, Statement#bind_param, and
-
# Statement#bind_params.
-
2
def bind_params( *bind_vars )
-
727
index = 1
-
727
bind_vars.flatten.each do |var|
-
1405
if Hash === var
-
var.each { |key, val| bind_param key, val }
-
else
-
1405
bind_param index, var
-
1405
index += 1
-
end
-
end
-
end
-
-
# Execute the statement. This creates a new ResultSet object for the
-
# statement's virtual machine. If a block was given, the new ResultSet will
-
# be yielded to it; otherwise, the ResultSet will be returned.
-
#
-
# Any parameters will be bound to the statement using #bind_params.
-
#
-
# Example:
-
#
-
# stmt = db.prepare( "select * from table" )
-
# stmt.execute do |result|
-
# ...
-
# end
-
#
-
# See also #bind_params, #execute!.
-
2
def execute( *bind_vars )
-
reset! if active? || done?
-
-
bind_params(*bind_vars) unless bind_vars.empty?
-
@results = ResultSet.new(@connection, self)
-
-
step if 0 == column_count
-
-
yield @results if block_given?
-
@results
-
end
-
-
# Execute the statement. If no block was given, this returns an array of
-
# rows returned by executing the statement. Otherwise, each row will be
-
# yielded to the block.
-
#
-
# Any parameters will be bound to the statement using #bind_params.
-
#
-
# Example:
-
#
-
# stmt = db.prepare( "select * from table" )
-
# stmt.execute! do |row|
-
# ...
-
# end
-
#
-
# See also #bind_params, #execute.
-
2
def execute!( *bind_vars, &block )
-
execute(*bind_vars)
-
block_given? ? each(&block) : to_a
-
end
-
-
# Returns true if the statement is currently active, meaning it has an
-
# open result set.
-
2
def active?
-
!done?
-
end
-
-
# Return an array of the column names for this statement. Note that this
-
# may execute the statement in order to obtain the metadata; this makes it
-
# a (potentially) expensive operation.
-
2
def columns
-
705
get_metadata unless @columns
-
705
return @columns
-
end
-
-
2
def each
-
967
loop do
-
1208
val = step
-
1208
break self if done?
-
241
yield val
-
end
-
end
-
-
# Return an array of the data types for each column in this statement. Note
-
# that this may execute the statement in order to obtain the metadata; this
-
# makes it a (potentially) expensive operation.
-
2
def types
-
must_be_open!
-
get_metadata unless @types
-
@types
-
end
-
-
# Performs a sanity check to ensure that the statement is not
-
# closed. If it is, an exception is raised.
-
2
def must_be_open! # :nodoc:
-
if closed?
-
raise SQLite3::Exception, "cannot use a closed statement"
-
end
-
end
-
-
2
private
-
# A convenience method for obtaining the metadata about the query. Note
-
# that this will actually execute the SQL, which means it can be a
-
# (potentially) expensive operation.
-
2
def get_metadata
-
705
@columns = Array.new(column_count) do |column|
-
590
column_name column
-
end
-
705
@types = Array.new(column_count) do |column|
-
590
column_decltype column
-
end
-
end
-
end
-
end
-
2
require 'time'
-
2
require 'date'
-
-
2
module SQLite3
-
-
# The Translator class encapsulates the logic and callbacks necessary for
-
# converting string data to a value of some specified type. Every Database
-
# instance may have a Translator instance, in order to assist in type
-
# translation (Database#type_translation).
-
#
-
# Further, applications may define their own custom type translation logic
-
# by registering translator blocks with the corresponding database's
-
# translator instance (Database#translator).
-
2
class Translator
-
-
# Create a new Translator instance. It will be preinitialized with default
-
# translators for most SQL data types.
-
2
def initialize
-
@translators = Hash.new( proc { |type,value| value } )
-
@type_name_cache = {}
-
register_default_translators
-
end
-
-
# Add a new translator block, which will be invoked to process type
-
# translations to the given type. The type should be an SQL datatype, and
-
# may include parentheses (i.e., "VARCHAR(30)"). However, any parenthetical
-
# information is stripped off and discarded, so type translation decisions
-
# are made solely on the "base" type name.
-
#
-
# The translator block itself should accept two parameters, "type" and
-
# "value". In this case, the "type" is the full type name (including
-
# parentheses), so the block itself may include logic for changing how a
-
# type is translated based on the additional data. The "value" parameter
-
# is the (string) data to convert.
-
#
-
# The block should return the translated value.
-
2
def add_translator( type, &block ) # :yields: type, value
-
warn(<<-eowarn) if $VERBOSE
-
#{caller[0]} is calling `add_translator`.
-
Built in translators are deprecated and will be removed in version 2.0.0
-
eowarn
-
@translators[ type_name( type ) ] = block
-
end
-
-
# Translate the given string value to a value of the given type. In the
-
# absense of an installed translator block for the given type, the value
-
# itself is always returned. Further, +nil+ values are never translated,
-
# and are always passed straight through regardless of the type parameter.
-
2
def translate( type, value )
-
unless value.nil?
-
# FIXME: this is a hack to support Sequel
-
if type && %w{ datetime timestamp }.include?(type.downcase)
-
@translators[ type_name( type ) ].call( type, value.to_s )
-
else
-
@translators[ type_name( type ) ].call( type, value )
-
end
-
end
-
end
-
-
# A convenience method for working with type names. This returns the "base"
-
# type name, without any parenthetical data.
-
2
def type_name( type )
-
@type_name_cache[type] ||= begin
-
type = "" if type.nil?
-
type = $1 if type =~ /^(.*?)\(/
-
type.upcase
-
end
-
end
-
2
private :type_name
-
-
# Register the default translators for the current Translator instance.
-
# This includes translators for most major SQL data types.
-
2
def register_default_translators
-
[ "time",
-
"timestamp" ].each { |type| add_translator( type ) { |t, v| Time.parse( v ) } }
-
-
add_translator( "date" ) { |t,v| Date.parse(v) }
-
add_translator( "datetime" ) { |t,v| DateTime.parse(v) }
-
-
[ "decimal",
-
"float",
-
"numeric",
-
"double",
-
"real",
-
"dec",
-
"fixed" ].each { |type| add_translator( type ) { |t,v| v.to_f } }
-
-
[ "integer",
-
"smallint",
-
"mediumint",
-
"int",
-
"bigint" ].each { |type| add_translator( type ) { |t,v| v.to_i } }
-
-
[ "bit",
-
"bool",
-
"boolean" ].each do |type|
-
add_translator( type ) do |t,v|
-
!( v.strip.gsub(/00+/,"0") == "0" ||
-
v.downcase == "false" ||
-
v.downcase == "f" ||
-
v.downcase == "no" ||
-
v.downcase == "n" )
-
end
-
end
-
-
add_translator( "tinyint" ) do |type, value|
-
if type =~ /\(\s*1\s*\)/
-
value.to_i == 1
-
else
-
value.to_i
-
end
-
end
-
end
-
2
private :register_default_translators
-
-
end
-
-
end
-
2
require 'sqlite3/constants'
-
-
2
module SQLite3
-
-
2
class Value
-
2
attr_reader :handle
-
-
2
def initialize( db, handle )
-
@driver = db.driver
-
@handle = handle
-
end
-
-
2
def null?
-
type == :null
-
end
-
-
2
def to_blob
-
@driver.value_blob( @handle )
-
end
-
-
2
def length( utf16=false )
-
if utf16
-
@driver.value_bytes16( @handle )
-
else
-
@driver.value_bytes( @handle )
-
end
-
end
-
-
2
def to_f
-
@driver.value_double( @handle )
-
end
-
-
2
def to_i
-
@driver.value_int( @handle )
-
end
-
-
2
def to_int64
-
@driver.value_int64( @handle )
-
end
-
-
2
def to_s( utf16=false )
-
@driver.value_text( @handle, utf16 )
-
end
-
-
2
def type
-
case @driver.value_type( @handle )
-
when Constants::ColumnType::INTEGER then :int
-
when Constants::ColumnType::FLOAT then :float
-
when Constants::ColumnType::TEXT then :text
-
when Constants::ColumnType::BLOB then :blob
-
when Constants::ColumnType::NULL then :null
-
end
-
end
-
-
end
-
-
end
-
2
module SQLite3
-
-
2
VERSION = '1.3.11'
-
-
2
module VersionProxy
-
-
2
MAJOR = 1
-
2
MINOR = 3
-
2
TINY = 11
-
2
BUILD = nil
-
-
2
STRING = [ MAJOR, MINOR, TINY, BUILD ].compact.join( "." )
-
#:beta-tag:
-
-
2
VERSION = ::SQLite3::VERSION
-
end
-
-
2
def self.const_missing(name)
-
return super unless name == :Version
-
warn(<<-eowarn) if $VERBOSE
-
#{caller[0]}: SQLite::Version will be removed in sqlite3-ruby version 2.0.0
-
eowarn
-
VersionProxy
-
end
-
end
-
1
require "thor/command"
-
1
require "thor/core_ext/hash_with_indifferent_access"
-
1
require "thor/core_ext/ordered_hash"
-
1
require "thor/error"
-
1
require "thor/invocation"
-
1
require "thor/parser"
-
1
require "thor/shell"
-
1
require "thor/line_editor"
-
1
require "thor/util"
-
-
1
class Thor
-
1
autoload :Actions, "thor/actions"
-
1
autoload :RakeCompat, "thor/rake_compat"
-
1
autoload :Group, "thor/group"
-
-
# Shortcuts for help.
-
1
HELP_MAPPINGS = %w[-h -? --help -D]
-
-
# Thor methods that should not be overwritten by the user.
-
1
THOR_RESERVED_WORDS = %w[invoke shell options behavior root destination_root relative_root
-
action add_file create_file in_root inside run run_ruby_script]
-
-
1
TEMPLATE_EXTNAME = ".tt"
-
-
1
module Base
-
1
attr_accessor :options, :parent_options, :args
-
-
# It receives arguments in an Array and two hashes, one for options and
-
# other for configuration.
-
#
-
# Notice that it does not check if all required arguments were supplied.
-
# It should be done by the parser.
-
#
-
# ==== Parameters
-
# args<Array[Object]>:: An array of objects. The objects are applied to their
-
# respective accessors declared with <tt>argument</tt>.
-
#
-
# options<Hash>:: An options hash that will be available as self.options.
-
# The hash given is converted to a hash with indifferent
-
# access, magic predicates (options.skip?) and then frozen.
-
#
-
# config<Hash>:: Configuration for this Thor class.
-
#
-
1
def initialize(args = [], local_options = {}, config = {}) # rubocop:disable MethodLength
-
parse_options = self.class.class_options
-
-
# The start method splits inbound arguments at the first argument
-
# that looks like an option (starts with - or --). It then calls
-
# new, passing in the two halves of the arguments Array as the
-
# first two parameters.
-
-
command_options = config.delete(:command_options) # hook for start
-
parse_options = parse_options.merge(command_options) if command_options
-
if local_options.is_a?(Array)
-
array_options, hash_options = local_options, {}
-
else
-
# Handle the case where the class was explicitly instantiated
-
# with pre-parsed options.
-
array_options, hash_options = [], local_options
-
end
-
-
# Let Thor::Options parse the options first, so it can remove
-
# declared options from the array. This will leave us with
-
# a list of arguments that weren't declared.
-
stop_on_unknown = self.class.stop_on_unknown_option? config[:current_command]
-
opts = Thor::Options.new(parse_options, hash_options, stop_on_unknown)
-
self.options = opts.parse(array_options)
-
self.options = config[:class_options].merge(options) if config[:class_options]
-
-
# If unknown options are disallowed, make sure that none of the
-
# remaining arguments looks like an option.
-
opts.check_unknown! if self.class.check_unknown_options?(config)
-
-
# Add the remaining arguments from the options parser to the
-
# arguments passed in to initialize. Then remove any positional
-
# arguments declared using #argument (this is primarily used
-
# by Thor::Group). Tis will leave us with the remaining
-
# positional arguments.
-
to_parse = args
-
to_parse += opts.remaining unless self.class.strict_args_position?(config)
-
-
thor_args = Thor::Arguments.new(self.class.arguments)
-
thor_args.parse(to_parse).each { |k, v| __send__("#{k}=", v) }
-
@args = thor_args.remaining
-
end
-
-
1
class << self
-
1
def included(base) #:nodoc:
-
1
base.extend ClassMethods
-
1
base.send :include, Invocation
-
1
base.send :include, Shell
-
end
-
-
# Returns the classes that inherits from Thor or Thor::Group.
-
#
-
# ==== Returns
-
# Array[Class]
-
#
-
1
def subclasses
-
@subclasses ||= []
-
end
-
-
# Returns the files where the subclasses are kept.
-
#
-
# ==== Returns
-
# Hash[path<String> => Class]
-
#
-
1
def subclass_files
-
@subclass_files ||= Hash.new { |h, k| h[k] = [] }
-
end
-
-
# Whenever a class inherits from Thor or Thor::Group, we should track the
-
# class and the file on Thor::Base. This is the method responsable for it.
-
#
-
1
def register_klass_file(klass) #:nodoc:
-
file = caller[1].match(/(.*):\d+/)[1]
-
Thor::Base.subclasses << klass unless Thor::Base.subclasses.include?(klass)
-
-
file_subclasses = Thor::Base.subclass_files[File.expand_path(file)]
-
file_subclasses << klass unless file_subclasses.include?(klass)
-
end
-
end
-
-
1
module ClassMethods
-
1
def attr_reader(*) #:nodoc:
-
no_commands { super }
-
end
-
-
1
def attr_writer(*) #:nodoc:
-
no_commands { super }
-
end
-
-
1
def attr_accessor(*) #:nodoc:
-
no_commands { super }
-
end
-
-
# If you want to raise an error for unknown options, call check_unknown_options!
-
# This is disabled by default to allow dynamic invocations.
-
1
def check_unknown_options!
-
@check_unknown_options = true
-
end
-
-
1
def check_unknown_options #:nodoc:
-
@check_unknown_options ||= from_superclass(:check_unknown_options, false)
-
end
-
-
1
def check_unknown_options?(config) #:nodoc:
-
!!check_unknown_options
-
end
-
-
# If true, option parsing is suspended as soon as an unknown option or a
-
# regular argument is encountered. All remaining arguments are passed to
-
# the command as regular arguments.
-
1
def stop_on_unknown_option?(command_name) #:nodoc:
-
false
-
end
-
-
# If you want only strict string args (useful when cascading thor classes),
-
# call strict_args_position! This is disabled by default to allow dynamic
-
# invocations.
-
1
def strict_args_position!
-
@strict_args_position = true
-
end
-
-
1
def strict_args_position #:nodoc:
-
@strict_args_position ||= from_superclass(:strict_args_position, false)
-
end
-
-
1
def strict_args_position?(config) #:nodoc:
-
!!strict_args_position
-
end
-
-
# Adds an argument to the class and creates an attr_accessor for it.
-
#
-
# Arguments are different from options in several aspects. The first one
-
# is how they are parsed from the command line, arguments are retrieved
-
# from position:
-
#
-
# thor command NAME
-
#
-
# Instead of:
-
#
-
# thor command --name=NAME
-
#
-
# Besides, arguments are used inside your code as an accessor (self.argument),
-
# while options are all kept in a hash (self.options).
-
#
-
# Finally, arguments cannot have type :default or :boolean but can be
-
# optional (supplying :optional => :true or :required => false), although
-
# you cannot have a required argument after a non-required argument. If you
-
# try it, an error is raised.
-
#
-
# ==== Parameters
-
# name<Symbol>:: The name of the argument.
-
# options<Hash>:: Described below.
-
#
-
# ==== Options
-
# :desc - Description for the argument.
-
# :required - If the argument is required or not.
-
# :optional - If the argument is optional or not.
-
# :type - The type of the argument, can be :string, :hash, :array, :numeric.
-
# :default - Default value for this argument. It cannot be required and have default values.
-
# :banner - String to show on usage notes.
-
#
-
# ==== Errors
-
# ArgumentError:: Raised if you supply a required argument after a non required one.
-
#
-
1
def argument(name, options = {}) # rubocop:disable MethodLength
-
is_thor_reserved_word?(name, :argument)
-
no_commands { attr_accessor name }
-
-
required = if options.key?(:optional)
-
!options[:optional]
-
elsif options.key?(:required)
-
options[:required]
-
else
-
options[:default].nil?
-
end
-
-
remove_argument name
-
-
arguments.each do |argument|
-
next if argument.required?
-
fail ArgumentError, "You cannot have #{name.to_s.inspect} as required argument after " <<
-
"the non-required argument #{argument.human_name.inspect}."
-
end if required
-
-
options[:required] = required
-
-
arguments << Thor::Argument.new(name, options)
-
end
-
-
# Returns this class arguments, looking up in the ancestors chain.
-
#
-
# ==== Returns
-
# Array[Thor::Argument]
-
#
-
1
def arguments
-
@arguments ||= from_superclass(:arguments, [])
-
end
-
-
# Adds a bunch of options to the set of class options.
-
#
-
# class_options :foo => false, :bar => :required, :baz => :string
-
#
-
# If you prefer more detailed declaration, check class_option.
-
#
-
# ==== Parameters
-
# Hash[Symbol => Object]
-
#
-
1
def class_options(options = nil)
-
@class_options ||= from_superclass(:class_options, {})
-
build_options(options, @class_options) if options
-
@class_options
-
end
-
-
# Adds an option to the set of class options
-
#
-
# ==== Parameters
-
# name<Symbol>:: The name of the argument.
-
# options<Hash>:: Described below.
-
#
-
# ==== Options
-
# :desc:: -- Description for the argument.
-
# :required:: -- If the argument is required or not.
-
# :default:: -- Default value for this argument.
-
# :group:: -- The group for this options. Use by class options to output options in different levels.
-
# :aliases:: -- Aliases for this option. <b>Note:</b> Thor follows a convention of one-dash-one-letter options. Thus aliases like "-something" wouldn't be parsed; use either "\--something" or "-s" instead.
-
# :type:: -- The type of the argument, can be :string, :hash, :array, :numeric or :boolean.
-
# :banner:: -- String to show on usage notes.
-
# :hide:: -- If you want to hide this option from the help.
-
#
-
1
def class_option(name, options = {})
-
build_option(name, options, class_options)
-
end
-
-
# Removes a previous defined argument. If :undefine is given, undefine
-
# accessors as well.
-
#
-
# ==== Parameters
-
# names<Array>:: Arguments to be removed
-
#
-
# ==== Examples
-
#
-
# remove_argument :foo
-
# remove_argument :foo, :bar, :baz, :undefine => true
-
#
-
1
def remove_argument(*names)
-
options = names.last.is_a?(Hash) ? names.pop : {}
-
-
names.each do |name|
-
arguments.delete_if { |a| a.name == name.to_s }
-
undef_method name, "#{name}=" if options[:undefine]
-
end
-
end
-
-
# Removes a previous defined class option.
-
#
-
# ==== Parameters
-
# names<Array>:: Class options to be removed
-
#
-
# ==== Examples
-
#
-
# remove_class_option :foo
-
# remove_class_option :foo, :bar, :baz
-
#
-
1
def remove_class_option(*names)
-
names.each do |name|
-
class_options.delete(name)
-
end
-
end
-
-
# Defines the group. This is used when thor list is invoked so you can specify
-
# that only commands from a pre-defined group will be shown. Defaults to standard.
-
#
-
# ==== Parameters
-
# name<String|Symbol>
-
#
-
1
def group(name = nil)
-
if name
-
@group = name.to_s
-
else
-
@group ||= from_superclass(:group, "standard")
-
end
-
end
-
-
# Returns the commands for this Thor class.
-
#
-
# ==== Returns
-
# OrderedHash:: An ordered hash with commands names as keys and Thor::Command
-
# objects as values.
-
#
-
1
def commands
-
@commands ||= Thor::CoreExt::OrderedHash.new
-
end
-
1
alias_method :tasks, :commands
-
-
# Returns the commands for this Thor class and all subclasses.
-
#
-
# ==== Returns
-
# OrderedHash:: An ordered hash with commands names as keys and Thor::Command
-
# objects as values.
-
#
-
1
def all_commands
-
@all_commands ||= from_superclass(:all_commands, Thor::CoreExt::OrderedHash.new)
-
@all_commands.merge(commands)
-
end
-
1
alias_method :all_tasks, :all_commands
-
-
# Removes a given command from this Thor class. This is usually done if you
-
# are inheriting from another class and don't want it to be available
-
# anymore.
-
#
-
# By default it only remove the mapping to the command. But you can supply
-
# :undefine => true to undefine the method from the class as well.
-
#
-
# ==== Parameters
-
# name<Symbol|String>:: The name of the command to be removed
-
# options<Hash>:: You can give :undefine => true if you want commands the method
-
# to be undefined from the class as well.
-
#
-
1
def remove_command(*names)
-
options = names.last.is_a?(Hash) ? names.pop : {}
-
-
names.each do |name|
-
commands.delete(name.to_s)
-
all_commands.delete(name.to_s)
-
undef_method name if options[:undefine]
-
end
-
end
-
1
alias_method :remove_task, :remove_command
-
-
# All methods defined inside the given block are not added as commands.
-
#
-
# So you can do:
-
#
-
# class MyScript < Thor
-
# no_commands do
-
# def this_is_not_a_command
-
# end
-
# end
-
# end
-
#
-
# You can also add the method and remove it from the command list:
-
#
-
# class MyScript < Thor
-
# def this_is_not_a_command
-
# end
-
# remove_command :this_is_not_a_command
-
# end
-
#
-
1
def no_commands
-
@no_commands = true
-
yield
-
ensure
-
@no_commands = false
-
end
-
1
alias_method :no_tasks, :no_commands
-
-
# Sets the namespace for the Thor or Thor::Group class. By default the
-
# namespace is retrieved from the class name. If your Thor class is named
-
# Scripts::MyScript, the help method, for example, will be called as:
-
#
-
# thor scripts:my_script -h
-
#
-
# If you change the namespace:
-
#
-
# namespace :my_scripts
-
#
-
# You change how your commands are invoked:
-
#
-
# thor my_scripts -h
-
#
-
# Finally, if you change your namespace to default:
-
#
-
# namespace :default
-
#
-
# Your commands can be invoked with a shortcut. Instead of:
-
#
-
# thor :my_command
-
#
-
1
def namespace(name = nil)
-
if name
-
@namespace = name.to_s
-
else
-
@namespace ||= Thor::Util.namespace_from_thor_class(self)
-
end
-
end
-
-
# Parses the command and options from the given args, instantiate the class
-
# and invoke the command. This method is used when the arguments must be parsed
-
# from an array. If you are inside Ruby and want to use a Thor class, you
-
# can simply initialize it:
-
#
-
# script = MyScript.new(args, options, config)
-
# script.invoke(:command, first_arg, second_arg, third_arg)
-
#
-
1
def start(given_args = ARGV, config = {})
-
config[:shell] ||= Thor::Base.shell.new
-
dispatch(nil, given_args.dup, nil, config)
-
rescue Thor::Error => e
-
config[:debug] || ENV["THOR_DEBUG"] == "1" ? (raise e) : config[:shell].error(e.message)
-
exit(1) if exit_on_failure?
-
rescue Errno::EPIPE
-
# This happens if a thor command is piped to something like `head`,
-
# which closes the pipe when it's done reading. This will also
-
# mean that if the pipe is closed, further unnecessary
-
# computation will not occur.
-
exit(0)
-
end
-
-
# Allows to use private methods from parent in child classes as commands.
-
#
-
# ==== Parameters
-
# names<Array>:: Method names to be used as commands
-
#
-
# ==== Examples
-
#
-
# public_command :foo
-
# public_command :foo, :bar, :baz
-
#
-
1
def public_command(*names)
-
names.each do |name|
-
class_eval "def #{name}(*); super end"
-
end
-
end
-
1
alias_method :public_task, :public_command
-
-
1
def handle_no_command_error(command, has_namespace = $thor_runner) #:nodoc:
-
if has_namespace
-
fail UndefinedCommandError, "Could not find command #{command.inspect} in #{namespace.inspect} namespace."
-
else
-
fail UndefinedCommandError, "Could not find command #{command.inspect}."
-
end
-
end
-
1
alias_method :handle_no_task_error, :handle_no_command_error
-
-
1
def handle_argument_error(command, error, args, arity) #:nodoc:
-
msg = "ERROR: \"#{basename} #{command.name}\" was called with "
-
msg << "no arguments" if args.empty?
-
msg << "arguments " << args.inspect unless args.empty?
-
msg << "\nUsage: #{banner(command).inspect}"
-
fail InvocationError, msg
-
end
-
-
1
protected
-
-
# Prints the class options per group. If an option does not belong to
-
# any group, it's printed as Class option.
-
#
-
1
def class_options_help(shell, groups = {}) #:nodoc:
-
# Group options by group
-
class_options.each do |_, value|
-
groups[value.group] ||= []
-
groups[value.group] << value
-
end
-
-
# Deal with default group
-
global_options = groups.delete(nil) || []
-
print_options(shell, global_options)
-
-
# Print all others
-
groups.each do |group_name, options|
-
print_options(shell, options, group_name)
-
end
-
end
-
-
# Receives a set of options and print them.
-
1
def print_options(shell, options, group_name = nil)
-
return if options.empty?
-
-
list = []
-
padding = options.map { |o| o.aliases.size }.max.to_i * 4
-
-
options.each do |option|
-
unless option.hide
-
item = [option.usage(padding)]
-
item.push(option.description ? "# #{option.description}" : "")
-
-
list << item
-
list << ["", "# Default: #{option.default}"] if option.show_default?
-
list << ["", "# Possible values: #{option.enum.join(', ')}"] if option.enum
-
end
-
end
-
-
shell.say(group_name ? "#{group_name} options:" : "Options:")
-
shell.print_table(list, :indent => 2)
-
shell.say ""
-
end
-
-
# Raises an error if the word given is a Thor reserved word.
-
1
def is_thor_reserved_word?(word, type) #:nodoc:
-
return false unless THOR_RESERVED_WORDS.include?(word.to_s)
-
fail "#{word.inspect} is a Thor reserved word and cannot be defined as #{type}"
-
end
-
-
# Build an option and adds it to the given scope.
-
#
-
# ==== Parameters
-
# name<Symbol>:: The name of the argument.
-
# options<Hash>:: Described in both class_option and method_option.
-
# scope<Hash>:: Options hash that is being built up
-
1
def build_option(name, options, scope) #:nodoc:
-
scope[name] = Thor::Option.new(name, options)
-
end
-
-
# Receives a hash of options, parse them and add to the scope. This is a
-
# fast way to set a bunch of options:
-
#
-
# build_options :foo => true, :bar => :required, :baz => :string
-
#
-
# ==== Parameters
-
# Hash[Symbol => Object]
-
1
def build_options(options, scope) #:nodoc:
-
options.each do |key, value|
-
scope[key] = Thor::Option.parse(key, value)
-
end
-
end
-
-
# Finds a command with the given name. If the command belongs to the current
-
# class, just return it, otherwise dup it and add the fresh copy to the
-
# current command hash.
-
1
def find_and_refresh_command(name) #:nodoc:
-
if commands[name.to_s]
-
commands[name.to_s]
-
elsif command = all_commands[name.to_s] # rubocop:disable AssignmentInCondition
-
commands[name.to_s] = command.clone
-
else
-
fail ArgumentError, "You supplied :for => #{name.inspect}, but the command #{name.inspect} could not be found."
-
end
-
end
-
1
alias_method :find_and_refresh_task, :find_and_refresh_command
-
-
# Everytime someone inherits from a Thor class, register the klass
-
# and file into baseclass.
-
1
def inherited(klass)
-
Thor::Base.register_klass_file(klass)
-
klass.instance_variable_set(:@no_commands, false)
-
end
-
-
# Fire this callback whenever a method is added. Added methods are
-
# tracked as commands by invoking the create_command method.
-
1
def method_added(meth)
-
1
meth = meth.to_s
-
-
1
if meth == "initialize"
-
initialize_added
-
return
-
end
-
-
# Return if it's not a public instance method
-
1
return unless public_method_defined?(meth.to_sym)
-
-
@no_commands ||= false
-
return if @no_commands || !create_command(meth)
-
-
is_thor_reserved_word?(meth, :command)
-
Thor::Base.register_klass_file(self)
-
end
-
-
# Retrieves a value from superclass. If it reaches the baseclass,
-
# returns default.
-
1
def from_superclass(method, default = nil)
-
if self == baseclass || !superclass.respond_to?(method, true)
-
default
-
else
-
value = superclass.send(method)
-
-
# Ruby implements `dup` on Object, but raises a `TypeError`
-
# if the method is called on immediates. As a result, we
-
# don't have a good way to check whether dup will succeed
-
# without calling it and rescuing the TypeError.
-
begin
-
value.dup
-
rescue TypeError
-
value
-
end
-
-
end
-
end
-
-
# A flag that makes the process exit with status 1 if any error happens.
-
1
def exit_on_failure?
-
false
-
end
-
-
#
-
# The basename of the program invoking the thor class.
-
#
-
1
def basename
-
File.basename($PROGRAM_NAME).split(" ").first
-
end
-
-
# SIGNATURE: Sets the baseclass. This is where the superclass lookup
-
# finishes.
-
1
def baseclass #:nodoc:
-
end
-
-
# SIGNATURE: Creates a new command if valid_command? is true. This method is
-
# called when a new method is added to the class.
-
1
def create_command(meth) #:nodoc:
-
end
-
1
alias_method :create_task, :create_command
-
-
# SIGNATURE: Defines behavior when the initialize method is added to the
-
# class.
-
1
def initialize_added #:nodoc:
-
end
-
-
# SIGNATURE: The hook invoked by start.
-
1
def dispatch(command, given_args, given_opts, config) #:nodoc:
-
fail NotImplementedError
-
end
-
end
-
end
-
end
-
1
class Thor
-
1
class Command < Struct.new(:name, :description, :long_description, :usage, :options)
-
1
FILE_REGEXP = /^#{Regexp.escape(File.dirname(__FILE__))}/
-
-
1
def initialize(name, description, long_description, usage, options = nil)
-
super(name.to_s, description, long_description, usage, options || {})
-
end
-
-
1
def initialize_copy(other) #:nodoc:
-
super(other)
-
self.options = other.options.dup if other.options
-
end
-
-
1
def hidden?
-
false
-
end
-
-
# By default, a command invokes a method in the thor class. You can change this
-
# implementation to create custom commands.
-
1
def run(instance, args = [])
-
arity = nil
-
-
if private_method?(instance)
-
instance.class.handle_no_command_error(name)
-
elsif public_method?(instance)
-
arity = instance.method(name).arity
-
instance.__send__(name, *args)
-
elsif local_method?(instance, :method_missing)
-
instance.__send__(:method_missing, name.to_sym, *args)
-
else
-
instance.class.handle_no_command_error(name)
-
end
-
rescue ArgumentError => e
-
handle_argument_error?(instance, e, caller) ? instance.class.handle_argument_error(self, e, args, arity) : (raise e)
-
rescue NoMethodError => e
-
handle_no_method_error?(instance, e, caller) ? instance.class.handle_no_command_error(name) : (fail e)
-
end
-
-
# Returns the formatted usage by injecting given required arguments
-
# and required options into the given usage.
-
1
def formatted_usage(klass, namespace = true, subcommand = false)
-
if namespace
-
namespace = klass.namespace
-
formatted = "#{namespace.gsub(/^(default)/, '')}:"
-
end
-
formatted = "#{klass.namespace.split(':').last} " if subcommand
-
-
formatted ||= ""
-
-
# Add usage with required arguments
-
formatted << if klass && !klass.arguments.empty?
-
usage.to_s.gsub(/^#{name}/) do |match|
-
match << " " << klass.arguments.map { |a| a.usage }.compact.join(" ")
-
end
-
else
-
usage.to_s
-
end
-
-
# Add required options
-
formatted << " #{required_options}"
-
-
# Strip and go!
-
formatted.strip
-
end
-
-
1
protected
-
-
1
def not_debugging?(instance)
-
!(instance.class.respond_to?(:debugging) && instance.class.debugging)
-
end
-
-
1
def required_options
-
@required_options ||= options.map { |_, o| o.usage if o.required? }.compact.sort.join(" ")
-
end
-
-
# Given a target, checks if this class name is a public method.
-
1
def public_method?(instance) #:nodoc:
-
!(instance.public_methods & [name.to_s, name.to_sym]).empty?
-
end
-
-
1
def private_method?(instance)
-
!(instance.private_methods & [name.to_s, name.to_sym]).empty?
-
end
-
-
1
def local_method?(instance, name)
-
methods = instance.public_methods(false) + instance.private_methods(false) + instance.protected_methods(false)
-
!(methods & [name.to_s, name.to_sym]).empty?
-
end
-
-
1
def sans_backtrace(backtrace, caller) #:nodoc:
-
saned = backtrace.reject { |frame| frame =~ FILE_REGEXP || (frame =~ /\.java:/ && RUBY_PLATFORM =~ /java/) || (frame =~ /^kernel\// && RUBY_ENGINE =~ /rbx/) }
-
saned - caller
-
end
-
-
1
def handle_argument_error?(instance, error, caller)
-
not_debugging?(instance) && (error.message =~ /wrong number of arguments/ || error.message =~ /given \d*, expected \d*/) && begin
-
saned = sans_backtrace(error.backtrace, caller)
-
# Ruby 1.9 always include the called method in the backtrace
-
saned.empty? || (saned.size == 1 && RUBY_VERSION >= "1.9")
-
end
-
end
-
-
1
def handle_no_method_error?(instance, error, caller)
-
not_debugging?(instance) &&
-
error.message =~ /^undefined method `#{name}' for #{Regexp.escape(instance.to_s)}$/
-
end
-
end
-
1
Task = Command # rubocop:disable ConstantName
-
-
# A command that is hidden in help messages but still invocable.
-
1
class HiddenCommand < Command
-
1
def hidden?
-
true
-
end
-
end
-
1
HiddenTask = HiddenCommand # rubocop:disable ConstantName
-
-
# A dynamic command that handles method missing scenarios.
-
1
class DynamicCommand < Command
-
1
def initialize(name, options = nil)
-
super(name.to_s, "A dynamically-generated command", name.to_s, name.to_s, options)
-
end
-
-
1
def run(instance, args = [])
-
if (instance.methods & [name.to_s, name.to_sym]).empty?
-
super
-
else
-
instance.class.handle_no_command_error(name)
-
end
-
end
-
end
-
1
DynamicTask = DynamicCommand # rubocop:disable ConstantName
-
end
-
2
class Thor
-
2
module CoreExt #:nodoc:
-
# A hash with indifferent access and magic predicates.
-
#
-
# hash = Thor::CoreExt::HashWithIndifferentAccess.new 'foo' => 'bar', 'baz' => 'bee', 'force' => true
-
#
-
# hash[:foo] #=> 'bar'
-
# hash['foo'] #=> 'bar'
-
# hash.foo? #=> true
-
#
-
2
class HashWithIndifferentAccess < ::Hash #:nodoc:
-
2
def initialize(hash = {})
-
super()
-
hash.each do |key, value|
-
self[convert_key(key)] = value
-
end
-
end
-
-
2
def [](key)
-
super(convert_key(key))
-
end
-
-
2
def []=(key, value)
-
super(convert_key(key), value)
-
end
-
-
2
def delete(key)
-
super(convert_key(key))
-
end
-
-
2
def values_at(*indices)
-
indices.map { |key| self[convert_key(key)] }
-
end
-
-
2
def merge(other)
-
dup.merge!(other)
-
end
-
-
2
def merge!(other)
-
other.each do |key, value|
-
self[convert_key(key)] = value
-
end
-
self
-
end
-
-
# Convert to a Hash with String keys.
-
2
def to_hash
-
Hash.new(default).merge!(self)
-
end
-
-
2
protected
-
-
2
def convert_key(key)
-
key.is_a?(Symbol) ? key.to_s : key
-
end
-
-
# Magic predicates. For instance:
-
#
-
# options.force? # => !!options['force']
-
# options.shebang # => "/usr/lib/local/ruby"
-
# options.test_framework?(:rspec) # => options[:test_framework] == :rspec
-
#
-
2
def method_missing(method, *args, &block)
-
method = method.to_s
-
if method =~ /^(\w+)\?$/
-
if args.empty?
-
!!self[$1]
-
else
-
self[$1] == args.first
-
end
-
else
-
self[method]
-
end
-
end
-
end
-
end
-
end
-
1
class Thor
-
1
module CoreExt #:nodoc:
-
1
if RUBY_VERSION >= "1.9"
-
1
class OrderedHash < ::Hash
-
end
-
else
-
# This class is based on the Ruby 1.9 ordered hashes.
-
#
-
# It keeps the semantics and most of the efficiency of normal hashes
-
# while also keeping track of the order in which elements were set.
-
#
-
class OrderedHash #:nodoc:
-
include Enumerable
-
-
Node = Struct.new(:key, :value, :next, :prev)
-
-
def initialize
-
@hash = {}
-
end
-
-
def [](key)
-
@hash[key] && @hash[key].value
-
end
-
-
def []=(key, value)
-
if node = @hash[key] # rubocop:disable AssignmentInCondition
-
node.value = value
-
else
-
node = Node.new(key, value)
-
-
if !defined?(@first) || @first.nil?
-
@first = @last = node
-
else
-
node.prev = @last
-
@last.next = node
-
@last = node
-
end
-
end
-
-
@hash[key] = node
-
value
-
end
-
-
def delete(key)
-
if node = @hash[key] # rubocop:disable AssignmentInCondition
-
prev_node = node.prev
-
next_node = node.next
-
-
next_node.prev = prev_node if next_node
-
prev_node.next = next_node if prev_node
-
-
@first = next_node if @first == node
-
@last = prev_node if @last == node
-
-
value = node.value
-
end
-
-
@hash.delete(key)
-
value
-
end
-
-
def keys
-
map { |k, v| k }
-
end
-
-
def values
-
map { |k, v| v }
-
end
-
-
def each
-
return unless defined?(@first) && @first
-
yield [@first.key, @first.value]
-
node = @first
-
yield [node.key, node.value] while node = node.next # rubocop:disable AssignmentInCondition
-
self
-
end
-
-
def merge(other)
-
hash = self.class.new
-
-
each do |key, value|
-
hash[key] = value
-
end
-
-
other.each do |key, value|
-
hash[key] = value
-
end
-
-
hash
-
end
-
-
def empty?
-
@hash.empty?
-
end
-
end
-
end
-
end
-
end
-
1
class Thor
-
# Thor::Error is raised when it's caused by wrong usage of thor classes. Those
-
# errors have their backtrace suppressed and are nicely shown to the user.
-
#
-
# Errors that are caused by the developer, like declaring a method which
-
# overwrites a thor keyword, it SHOULD NOT raise a Thor::Error. This way, we
-
# ensure that developer errors are shown with full backtrace.
-
1
class Error < StandardError
-
end
-
-
# Raised when a command was not found.
-
1
class UndefinedCommandError < Error
-
end
-
1
UndefinedTaskError = UndefinedCommandError # rubocop:disable ConstantName
-
-
1
class AmbiguousCommandError < Error
-
end
-
1
AmbiguousTaskError = AmbiguousCommandError # rubocop:disable ConstantName
-
-
# Raised when a command was found, but not invoked properly.
-
1
class InvocationError < Error
-
end
-
-
1
class UnknownArgumentError < Error
-
end
-
-
1
class RequiredArgumentMissingError < InvocationError
-
end
-
-
1
class MalformattedArgumentError < InvocationError
-
end
-
end
-
1
require "thor/base"
-
-
# Thor has a special class called Thor::Group. The main difference to Thor class
-
# is that it invokes all commands at once. It also include some methods that allows
-
# invocations to be done at the class method, which are not available to Thor
-
# commands.
-
1
class Thor::Group # rubocop:disable ClassLength
-
1
class << self
-
# The description for this Thor::Group. If none is provided, but a source root
-
# exists, tries to find the USAGE one folder above it, otherwise searches
-
# in the superclass.
-
#
-
# ==== Parameters
-
# description<String>:: The description for this Thor::Group.
-
#
-
1
def desc(description = nil)
-
if description
-
@desc = description
-
else
-
@desc ||= from_superclass(:desc, nil)
-
end
-
end
-
-
# Prints help information.
-
#
-
# ==== Options
-
# short:: When true, shows only usage.
-
#
-
1
def help(shell)
-
shell.say "Usage:"
-
shell.say " #{banner}\n"
-
shell.say
-
class_options_help(shell)
-
shell.say desc if desc
-
end
-
-
# Stores invocations for this class merging with superclass values.
-
#
-
1
def invocations #:nodoc:
-
@invocations ||= from_superclass(:invocations, {})
-
end
-
-
# Stores invocation blocks used on invoke_from_option.
-
#
-
1
def invocation_blocks #:nodoc:
-
@invocation_blocks ||= from_superclass(:invocation_blocks, {})
-
end
-
-
# Invoke the given namespace or class given. It adds an instance
-
# method that will invoke the klass and command. You can give a block to
-
# configure how it will be invoked.
-
#
-
# The namespace/class given will have its options showed on the help
-
# usage. Check invoke_from_option for more information.
-
#
-
1
def invoke(*names, &block) # rubocop:disable MethodLength
-
options = names.last.is_a?(Hash) ? names.pop : {}
-
verbose = options.fetch(:verbose, true)
-
-
names.each do |name|
-
invocations[name] = false
-
invocation_blocks[name] = block if block_given?
-
-
class_eval <<-METHOD, __FILE__, __LINE__
-
def _invoke_#{name.to_s.gsub(/\W/, "_")}
-
klass, command = self.class.prepare_for_invocation(nil, #{name.inspect})
-
-
if klass
-
say_status :invoke, #{name.inspect}, #{verbose.inspect}
-
block = self.class.invocation_blocks[#{name.inspect}]
-
_invoke_for_class_method klass, command, &block
-
else
-
say_status :error, %(#{name.inspect} [not found]), :red
-
end
-
end
-
METHOD
-
end
-
end
-
-
# Invoke a thor class based on the value supplied by the user to the
-
# given option named "name". A class option must be created before this
-
# method is invoked for each name given.
-
#
-
# ==== Examples
-
#
-
# class GemGenerator < Thor::Group
-
# class_option :test_framework, :type => :string
-
# invoke_from_option :test_framework
-
# end
-
#
-
# ==== Boolean options
-
#
-
# In some cases, you want to invoke a thor class if some option is true or
-
# false. This is automatically handled by invoke_from_option. Then the
-
# option name is used to invoke the generator.
-
#
-
# ==== Preparing for invocation
-
#
-
# In some cases you want to customize how a specified hook is going to be
-
# invoked. You can do that by overwriting the class method
-
# prepare_for_invocation. The class method must necessarily return a klass
-
# and an optional command.
-
#
-
# ==== Custom invocations
-
#
-
# You can also supply a block to customize how the option is going to be
-
# invoked. The block receives two parameters, an instance of the current
-
# class and the klass to be invoked.
-
#
-
1
def invoke_from_option(*names, &block) # rubocop:disable MethodLength
-
options = names.last.is_a?(Hash) ? names.pop : {}
-
verbose = options.fetch(:verbose, :white)
-
-
names.each do |name|
-
unless class_options.key?(name)
-
fail ArgumentError, "You have to define the option #{name.inspect} " <<
-
"before setting invoke_from_option."
-
end
-
-
invocations[name] = true
-
invocation_blocks[name] = block if block_given?
-
-
class_eval <<-METHOD, __FILE__, __LINE__
-
def _invoke_from_option_#{name.to_s.gsub(/\W/, "_")}
-
return unless options[#{name.inspect}]
-
-
value = options[#{name.inspect}]
-
value = #{name.inspect} if TrueClass === value
-
klass, command = self.class.prepare_for_invocation(#{name.inspect}, value)
-
-
if klass
-
say_status :invoke, value, #{verbose.inspect}
-
block = self.class.invocation_blocks[#{name.inspect}]
-
_invoke_for_class_method klass, command, &block
-
else
-
say_status :error, %(\#{value} [not found]), :red
-
end
-
end
-
METHOD
-
end
-
end
-
-
# Remove a previously added invocation.
-
#
-
# ==== Examples
-
#
-
# remove_invocation :test_framework
-
#
-
1
def remove_invocation(*names)
-
names.each do |name|
-
remove_command(name)
-
remove_class_option(name)
-
invocations.delete(name)
-
invocation_blocks.delete(name)
-
end
-
end
-
-
# Overwrite class options help to allow invoked generators options to be
-
# shown recursively when invoking a generator.
-
#
-
1
def class_options_help(shell, groups = {}) #:nodoc:
-
get_options_from_invocations(groups, class_options) do |klass|
-
klass.send(:get_options_from_invocations, groups, class_options)
-
end
-
super(shell, groups)
-
end
-
-
# Get invocations array and merge options from invocations. Those
-
# options are added to group_options hash. Options that already exists
-
# in base_options are not added twice.
-
#
-
1
def get_options_from_invocations(group_options, base_options) #:nodoc: # rubocop:disable MethodLength
-
invocations.each do |name, from_option|
-
value = if from_option
-
option = class_options[name]
-
option.type == :boolean ? name : option.default
-
else
-
name
-
end
-
next unless value
-
-
klass, _ = prepare_for_invocation(name, value)
-
next unless klass && klass.respond_to?(:class_options)
-
-
value = value.to_s
-
human_name = value.respond_to?(:classify) ? value.classify : value
-
-
group_options[human_name] ||= []
-
group_options[human_name] += klass.class_options.values.select do |class_option|
-
base_options[class_option.name.to_sym].nil? && class_option.group.nil? &&
-
!group_options.values.flatten.any? { |i| i.name == class_option.name }
-
end
-
-
yield klass if block_given?
-
end
-
end
-
-
# Returns commands ready to be printed.
-
1
def printable_commands(*)
-
item = []
-
item << banner
-
item << (desc ? "# #{desc.gsub(/\s+/m, ' ')}" : "")
-
[item]
-
end
-
1
alias_method :printable_tasks, :printable_commands
-
-
1
def handle_argument_error(command, error, args, arity) #:nodoc:
-
msg = "#{basename} #{command.name} takes #{arity} argument"
-
msg << "s" if arity > 1
-
msg << ", but it should not."
-
fail error, msg
-
end
-
-
1
protected
-
-
# The method responsible for dispatching given the args.
-
1
def dispatch(command, given_args, given_opts, config) #:nodoc:
-
if Thor::HELP_MAPPINGS.include?(given_args.first)
-
help(config[:shell])
-
return
-
end
-
-
args, opts = Thor::Options.split(given_args)
-
opts = given_opts || opts
-
-
instance = new(args, opts, config)
-
yield instance if block_given?
-
-
if command
-
instance.invoke_command(all_commands[command])
-
else
-
instance.invoke_all
-
end
-
end
-
-
# The banner for this class. You can customize it if you are invoking the
-
# thor class by another ways which is not the Thor::Runner.
-
1
def banner
-
"#{basename} #{self_command.formatted_usage(self, false)}"
-
end
-
-
# Represents the whole class as a command.
-
1
def self_command #:nodoc:
-
Thor::DynamicCommand.new(namespace, class_options)
-
end
-
1
alias_method :self_task, :self_command
-
-
1
def baseclass #:nodoc:
-
Thor::Group
-
end
-
-
1
def create_command(meth) #:nodoc:
-
commands[meth.to_s] = Thor::Command.new(meth, nil, nil, nil, nil)
-
true
-
end
-
1
alias_method :create_task, :create_command
-
end
-
-
1
include Thor::Base
-
-
1
protected
-
-
# Shortcut to invoke with padding and block handling. Use internally by
-
# invoke and invoke_from_option class methods.
-
1
def _invoke_for_class_method(klass, command = nil, *args, &block) #:nodoc:
-
with_padding do
-
if block
-
case block.arity
-
when 3
-
block.call(self, klass, command)
-
when 2
-
block.call(self, klass)
-
when 1
-
instance_exec(klass, &block)
-
end
-
else
-
invoke klass, command, *args
-
end
-
end
-
end
-
end
-
1
class Thor
-
1
module Invocation
-
1
def self.included(base) #:nodoc:
-
1
base.extend ClassMethods
-
end
-
-
1
module ClassMethods
-
# This method is responsible for receiving a name and find the proper
-
# class and command for it. The key is an optional parameter which is
-
# available only in class methods invocations (i.e. in Thor::Group).
-
1
def prepare_for_invocation(key, name) #:nodoc:
-
case name
-
when Symbol, String
-
Thor::Util.find_class_and_command_by_namespace(name.to_s, !key)
-
else
-
name
-
end
-
end
-
end
-
-
# Make initializer aware of invocations and the initialization args.
-
1
def initialize(args = [], options = {}, config = {}, &block) #:nodoc:
-
@_invocations = config[:invocations] || Hash.new { |h, k| h[k] = [] }
-
@_initializer = [args, options, config]
-
super
-
end
-
-
# Make the current command chain accessible with in a Thor-(sub)command
-
1
def current_command_chain
-
@_invocations.values.flatten.map(&:to_sym)
-
end
-
-
# Receives a name and invokes it. The name can be a string (either "command" or
-
# "namespace:command"), a Thor::Command, a Class or a Thor instance. If the
-
# command cannot be guessed by name, it can also be supplied as second argument.
-
#
-
# You can also supply the arguments, options and configuration values for
-
# the command to be invoked, if none is given, the same values used to
-
# initialize the invoker are used to initialize the invoked.
-
#
-
# When no name is given, it will invoke the default command of the current class.
-
#
-
# ==== Examples
-
#
-
# class A < Thor
-
# def foo
-
# invoke :bar
-
# invoke "b:hello", ["Erik"]
-
# end
-
#
-
# def bar
-
# invoke "b:hello", ["Erik"]
-
# end
-
# end
-
#
-
# class B < Thor
-
# def hello(name)
-
# puts "hello #{name}"
-
# end
-
# end
-
#
-
# You can notice that the method "foo" above invokes two commands: "bar",
-
# which belongs to the same class and "hello" which belongs to the class B.
-
#
-
# By using an invocation system you ensure that a command is invoked only once.
-
# In the example above, invoking "foo" will invoke "b:hello" just once, even
-
# if it's invoked later by "bar" method.
-
#
-
# When class A invokes class B, all arguments used on A initialization are
-
# supplied to B. This allows lazy parse of options. Let's suppose you have
-
# some rspec commands:
-
#
-
# class Rspec < Thor::Group
-
# class_option :mock_framework, :type => :string, :default => :rr
-
#
-
# def invoke_mock_framework
-
# invoke "rspec:#{options[:mock_framework]}"
-
# end
-
# end
-
#
-
# As you noticed, it invokes the given mock framework, which might have its
-
# own options:
-
#
-
# class Rspec::RR < Thor::Group
-
# class_option :style, :type => :string, :default => :mock
-
# end
-
#
-
# Since it's not rspec concern to parse mock framework options, when RR
-
# is invoked all options are parsed again, so RR can extract only the options
-
# that it's going to use.
-
#
-
# If you want Rspec::RR to be initialized with its own set of options, you
-
# have to do that explicitly:
-
#
-
# invoke "rspec:rr", [], :style => :foo
-
#
-
# Besides giving an instance, you can also give a class to invoke:
-
#
-
# invoke Rspec::RR, [], :style => :foo
-
#
-
1
def invoke(name = nil, *args)
-
if name.nil?
-
warn "[Thor] Calling invoke() without argument is deprecated. Please use invoke_all instead.\n#{caller.join("\n")}"
-
return invoke_all
-
end
-
-
args.unshift(nil) if args.first.is_a?(Array) || args.first.nil?
-
command, args, opts, config = args
-
-
klass, command = _retrieve_class_and_command(name, command)
-
fail "Missing Thor class for invoke #{name}" unless klass
-
fail "Expected Thor class, got #{klass}" unless klass <= Thor::Base
-
-
args, opts, config = _parse_initialization_options(args, opts, config)
-
klass.send(:dispatch, command, args, opts, config) do |instance|
-
instance.parent_options = options
-
end
-
end
-
-
# Invoke the given command if the given args.
-
1
def invoke_command(command, *args) #:nodoc:
-
current = @_invocations[self.class]
-
-
unless current.include?(command.name)
-
current << command.name
-
command.run(self, *args)
-
end
-
end
-
1
alias_method :invoke_task, :invoke_command
-
-
# Invoke all commands for the current instance.
-
1
def invoke_all #:nodoc:
-
self.class.all_commands.map { |_, command| invoke_command(command) }
-
end
-
-
# Invokes using shell padding.
-
1
def invoke_with_padding(*args)
-
with_padding { invoke(*args) }
-
end
-
-
1
protected
-
-
# Configuration values that are shared between invocations.
-
1
def _shared_configuration #:nodoc:
-
{:invocations => @_invocations}
-
end
-
-
# This method simply retrieves the class and command to be invoked.
-
# If the name is nil or the given name is a command in the current class,
-
# use the given name and return self as class. Otherwise, call
-
# prepare_for_invocation in the current class.
-
1
def _retrieve_class_and_command(name, sent_command = nil) #:nodoc:
-
case
-
when name.nil?
-
[self.class, nil]
-
when self.class.all_commands[name.to_s]
-
[self.class, name.to_s]
-
else
-
klass, command = self.class.prepare_for_invocation(nil, name)
-
[klass, command || sent_command]
-
end
-
end
-
1
alias_method :_retrieve_class_and_task, :_retrieve_class_and_command
-
-
# Initialize klass using values stored in the @_initializer.
-
1
def _parse_initialization_options(args, opts, config) #:nodoc:
-
stored_args, stored_opts, stored_config = @_initializer
-
-
args ||= stored_args.dup
-
opts ||= stored_opts.dup
-
-
config ||= {}
-
config = stored_config.merge(_shared_configuration).merge!(config)
-
-
[args, opts, config]
-
end
-
end
-
end
-
1
require "thor/line_editor/basic"
-
1
require "thor/line_editor/readline"
-
-
1
class Thor
-
1
module LineEditor
-
1
def self.readline(prompt, options = {})
-
best_available.new(prompt, options).readline
-
end
-
-
1
def self.best_available
-
[
-
Thor::LineEditor::Readline,
-
Thor::LineEditor::Basic
-
].detect(&:available?)
-
end
-
end
-
end
-
1
class Thor
-
1
module LineEditor
-
1
class Basic
-
1
attr_reader :prompt, :options
-
-
1
def self.available?
-
true
-
end
-
-
1
def initialize(prompt, options)
-
@prompt = prompt
-
@options = options
-
end
-
-
1
def readline
-
$stdout.print(prompt)
-
get_input
-
end
-
-
1
private
-
-
1
def get_input
-
if echo?
-
$stdin.gets
-
else
-
$stdin.noecho(&:gets)
-
end
-
end
-
-
1
def echo?
-
options.fetch(:echo, true)
-
end
-
end
-
end
-
end
-
1
begin
-
1
require "readline"
-
rescue LoadError
-
end
-
-
1
class Thor
-
1
module LineEditor
-
1
class Readline < Basic
-
1
def self.available?
-
Object.const_defined?(:Readline)
-
end
-
-
1
def readline
-
if echo?
-
::Readline.completion_append_character = nil
-
# Ruby 1.8.7 does not allow Readline.completion_proc= to receive nil.
-
if complete = completion_proc
-
::Readline.completion_proc = complete
-
end
-
::Readline.readline(prompt, add_to_history?)
-
else
-
super
-
end
-
end
-
-
1
private
-
-
1
def add_to_history?
-
options.fetch(:add_to_history, true)
-
end
-
-
1
def completion_proc
-
if use_path_completion?
-
proc { |text| PathCompletion.new(text).matches }
-
elsif completion_options.any?
-
proc do |text|
-
completion_options.select { |option| option.start_with?(text) }
-
end
-
end
-
end
-
-
1
def completion_options
-
options.fetch(:limited_to, [])
-
end
-
-
1
def use_path_completion?
-
options.fetch(:path, false)
-
end
-
-
1
class PathCompletion
-
1
attr_reader :text
-
1
private :text
-
-
1
def initialize(text)
-
@text = text
-
end
-
-
1
def matches
-
relative_matches
-
end
-
-
1
private
-
-
1
def relative_matches
-
absolute_matches.map { |path| path.sub(base_path, "") }
-
end
-
-
1
def absolute_matches
-
Dir[glob_pattern].map do |path|
-
if File.directory?(path)
-
"#{path}/"
-
else
-
path
-
end
-
end
-
end
-
-
1
def glob_pattern
-
"#{base_path}#{text}*"
-
end
-
-
1
def base_path
-
"#{Dir.pwd}/"
-
end
-
end
-
end
-
end
-
end
-
1
require "thor/parser/argument"
-
1
require "thor/parser/arguments"
-
1
require "thor/parser/option"
-
1
require "thor/parser/options"
-
1
class Thor
-
1
class Argument #:nodoc:
-
1
VALID_TYPES = [:numeric, :hash, :array, :string]
-
-
1
attr_reader :name, :description, :enum, :required, :type, :default, :banner
-
1
alias_method :human_name, :name
-
-
1
def initialize(name, options = {})
-
class_name = self.class.name.split("::").last
-
-
type = options[:type]
-
-
fail ArgumentError, "#{class_name} name can't be nil." if name.nil?
-
fail ArgumentError, "Type :#{type} is not valid for #{class_name.downcase}s." if type && !valid_type?(type)
-
-
@name = name.to_s
-
@description = options[:desc]
-
@required = options.key?(:required) ? options[:required] : true
-
@type = (type || :string).to_sym
-
@default = options[:default]
-
@banner = options[:banner] || default_banner
-
@enum = options[:enum]
-
-
validate! # Trigger specific validations
-
end
-
-
1
def usage
-
required? ? banner : "[#{banner}]"
-
end
-
-
1
def required?
-
required
-
end
-
-
1
def show_default?
-
case default
-
when Array, String, Hash
-
!default.empty?
-
else
-
default
-
end
-
end
-
-
1
protected
-
-
1
def validate!
-
if required? && !default.nil?
-
fail ArgumentError, "An argument cannot be required and have default value."
-
elsif @enum && !@enum.is_a?(Array)
-
fail ArgumentError, "An argument cannot have an enum other than an array."
-
end
-
end
-
-
1
def valid_type?(type)
-
self.class::VALID_TYPES.include?(type.to_sym)
-
end
-
-
1
def default_banner
-
case type
-
when :boolean
-
nil
-
when :string, :default
-
human_name.upcase
-
when :numeric
-
"N"
-
when :hash
-
"key:value"
-
when :array
-
"one two three"
-
end
-
end
-
end
-
end
-
1
class Thor
-
1
class Arguments #:nodoc: # rubocop:disable ClassLength
-
1
NUMERIC = /(\d*\.\d+|\d+)/
-
-
# Receives an array of args and returns two arrays, one with arguments
-
# and one with switches.
-
#
-
1
def self.split(args)
-
arguments = []
-
-
args.each do |item|
-
break if item =~ /^-/
-
arguments << item
-
end
-
-
[arguments, args[Range.new(arguments.size, -1)]]
-
end
-
-
1
def self.parse(*args)
-
to_parse = args.pop
-
new(*args).parse(to_parse)
-
end
-
-
# Takes an array of Thor::Argument objects.
-
#
-
1
def initialize(arguments = [])
-
@assigns, @non_assigned_required = {}, []
-
@switches = arguments
-
-
arguments.each do |argument|
-
if !argument.default.nil?
-
@assigns[argument.human_name] = argument.default
-
elsif argument.required?
-
@non_assigned_required << argument
-
end
-
end
-
end
-
-
1
def parse(args)
-
@pile = args.dup
-
-
@switches.each do |argument|
-
break unless peek
-
@non_assigned_required.delete(argument)
-
@assigns[argument.human_name] = send(:"parse_#{argument.type}", argument.human_name)
-
end
-
-
check_requirement!
-
@assigns
-
end
-
-
1
def remaining # rubocop:disable TrivialAccessors
-
@pile
-
end
-
-
1
private
-
-
1
def no_or_skip?(arg)
-
arg =~ /^--(no|skip)-([-\w]+)$/
-
$2
-
end
-
-
1
def last?
-
@pile.empty?
-
end
-
-
1
def peek
-
@pile.first
-
end
-
-
1
def shift
-
@pile.shift
-
end
-
-
1
def unshift(arg)
-
if arg.kind_of?(Array)
-
@pile = arg + @pile
-
else
-
@pile.unshift(arg)
-
end
-
end
-
-
1
def current_is_value?
-
peek && peek.to_s !~ /^-/
-
end
-
-
# Runs through the argument array getting strings that contains ":" and
-
# mark it as a hash:
-
#
-
# [ "name:string", "age:integer" ]
-
#
-
# Becomes:
-
#
-
# { "name" => "string", "age" => "integer" }
-
#
-
1
def parse_hash(name)
-
return shift if peek.is_a?(Hash)
-
hash = {}
-
-
while current_is_value? && peek.include?(":")
-
key, value = shift.split(":", 2)
-
hash[key] = value
-
end
-
hash
-
end
-
-
# Runs through the argument array getting all strings until no string is
-
# found or a switch is found.
-
#
-
# ["a", "b", "c"]
-
#
-
# And returns it as an array:
-
#
-
# ["a", "b", "c"]
-
#
-
1
def parse_array(name)
-
return shift if peek.is_a?(Array)
-
array = []
-
array << shift while current_is_value?
-
array
-
end
-
-
# Check if the peek is numeric format and return a Float or Integer.
-
# Check if the peek is included in enum if enum is provided.
-
# Otherwise raises an error.
-
#
-
1
def parse_numeric(name)
-
return shift if peek.is_a?(Numeric)
-
-
unless peek =~ NUMERIC && $& == peek
-
fail MalformattedArgumentError, "Expected numeric value for '#{name}'; got #{peek.inspect}"
-
end
-
-
value = $&.index(".") ? shift.to_f : shift.to_i
-
if @switches.is_a?(Hash) && switch = @switches[name]
-
if switch.enum && !switch.enum.include?(value)
-
fail MalformattedArgumentError, "Expected '#{name}' to be one of #{switch.enum.join(', ')}; got #{value}"
-
end
-
end
-
value
-
end
-
-
# Parse string:
-
# for --string-arg, just return the current value in the pile
-
# for --no-string-arg, nil
-
# Check if the peek is included in enum if enum is provided. Otherwise raises an error.
-
#
-
1
def parse_string(name)
-
if no_or_skip?(name)
-
nil
-
else
-
value = shift
-
if @switches.is_a?(Hash) && switch = @switches[name] # rubocop:disable AssignmentInCondition
-
if switch.enum && !switch.enum.include?(value)
-
fail MalformattedArgumentError, "Expected '#{name}' to be one of #{switch.enum.join(', ')}; got #{value}"
-
end
-
end
-
value
-
end
-
end
-
-
# Raises an error if @non_assigned_required array is not empty.
-
#
-
1
def check_requirement!
-
unless @non_assigned_required.empty?
-
names = @non_assigned_required.map do |o|
-
o.respond_to?(:switch_name) ? o.switch_name : o.human_name
-
end.join("', '")
-
-
class_name = self.class.name.split("::").last.downcase
-
fail RequiredArgumentMissingError, "No value provided for required #{class_name} '#{names}'"
-
end
-
end
-
end
-
end
-
1
class Thor
-
1
class Option < Argument #:nodoc:
-
1
attr_reader :aliases, :group, :lazy_default, :hide
-
-
1
VALID_TYPES = [:boolean, :numeric, :hash, :array, :string]
-
-
1
def initialize(name, options = {})
-
options[:required] = false unless options.key?(:required)
-
super
-
@lazy_default = options[:lazy_default]
-
@group = options[:group].to_s.capitalize if options[:group]
-
@aliases = Array(options[:aliases])
-
@hide = options[:hide]
-
end
-
-
# This parse quick options given as method_options. It makes several
-
# assumptions, but you can be more specific using the option method.
-
#
-
# parse :foo => "bar"
-
# #=> Option foo with default value bar
-
#
-
# parse [:foo, :baz] => "bar"
-
# #=> Option foo with default value bar and alias :baz
-
#
-
# parse :foo => :required
-
# #=> Required option foo without default value
-
#
-
# parse :foo => 2
-
# #=> Option foo with default value 2 and type numeric
-
#
-
# parse :foo => :numeric
-
# #=> Option foo without default value and type numeric
-
#
-
# parse :foo => true
-
# #=> Option foo with default value true and type boolean
-
#
-
# The valid types are :boolean, :numeric, :hash, :array and :string. If none
-
# is given a default type is assumed. This default type accepts arguments as
-
# string (--foo=value) or booleans (just --foo).
-
#
-
# By default all options are optional, unless :required is given.
-
#
-
1
def self.parse(key, value) # rubocop:disable MethodLength
-
if key.is_a?(Array)
-
name, *aliases = key
-
else
-
name, aliases = key, []
-
end
-
-
name = name.to_s
-
default = value
-
-
type = case value
-
when Symbol
-
default = nil
-
if VALID_TYPES.include?(value)
-
value
-
elsif required = (value == :required) # rubocop:disable AssignmentInCondition
-
:string
-
end
-
when TrueClass, FalseClass
-
:boolean
-
when Numeric
-
:numeric
-
when Hash, Array, String
-
value.class.name.downcase.to_sym
-
end
-
new(name.to_s, :required => required, :type => type, :default => default, :aliases => aliases)
-
end
-
-
1
def switch_name
-
@switch_name ||= dasherized? ? name : dasherize(name)
-
end
-
-
1
def human_name
-
@human_name ||= dasherized? ? undasherize(name) : name
-
end
-
-
1
def usage(padding = 0)
-
sample = if banner && !banner.to_s.empty?
-
"#{switch_name}=#{banner}"
-
else
-
switch_name
-
end
-
-
sample = "[#{sample}]" unless required?
-
-
if boolean?
-
sample << ", [#{dasherize("no-" + human_name)}]" unless name == "force"
-
end
-
-
if aliases.empty?
-
(" " * padding) << sample
-
else
-
"#{aliases.join(', ')}, #{sample}"
-
end
-
end
-
-
1
VALID_TYPES.each do |type|
-
5
class_eval <<-RUBY, __FILE__, __LINE__ + 1
-
def #{type}?
-
self.type == #{type.inspect}
-
end
-
RUBY
-
end
-
-
1
protected
-
-
1
def validate!
-
fail ArgumentError, "An option cannot be boolean and required." if boolean? && required?
-
end
-
-
1
def dasherized?
-
name.index("-") == 0
-
end
-
-
1
def undasherize(str)
-
str.sub(/^-{1,2}/, "")
-
end
-
-
1
def dasherize(str)
-
(str.length > 1 ? "--" : "-") + str.gsub("_", "-")
-
end
-
end
-
end
-
1
class Thor
-
1
class Options < Arguments #:nodoc: # rubocop:disable ClassLength
-
1
LONG_RE = /^(--\w+(?:-\w+)*)$/
-
1
SHORT_RE = /^(-[a-z])$/i
-
1
EQ_RE = /^(--\w+(?:-\w+)*|-[a-z])=(.*)$/i
-
1
SHORT_SQ_RE = /^-([a-z]{2,})$/i # Allow either -x -v or -xv style for single char args
-
1
SHORT_NUM = /^(-[a-z])#{NUMERIC}$/i
-
1
OPTS_END = "--".freeze
-
-
# Receives a hash and makes it switches.
-
1
def self.to_switches(options)
-
options.map do |key, value|
-
case value
-
when true
-
"--#{key}"
-
when Array
-
"--#{key} #{value.map { |v| v.inspect }.join(' ')}"
-
when Hash
-
"--#{key} #{value.map { |k, v| "#{k}:#{v}" }.join(' ')}"
-
when nil, false
-
""
-
else
-
"--#{key} #{value.inspect}"
-
end
-
end.join(" ")
-
end
-
-
# Takes a hash of Thor::Option and a hash with defaults.
-
#
-
# If +stop_on_unknown+ is true, #parse will stop as soon as it encounters
-
# an unknown option or a regular argument.
-
1
def initialize(hash_options = {}, defaults = {}, stop_on_unknown = false)
-
@stop_on_unknown = stop_on_unknown
-
options = hash_options.values
-
super(options)
-
-
# Add defaults
-
defaults.each do |key, value|
-
@assigns[key.to_s] = value
-
@non_assigned_required.delete(hash_options[key])
-
end
-
-
@shorts, @switches, @extra = {}, {}, []
-
-
options.each do |option|
-
@switches[option.switch_name] = option
-
-
option.aliases.each do |short|
-
name = short.to_s.sub(/^(?!\-)/, "-")
-
@shorts[name] ||= option.switch_name
-
end
-
end
-
end
-
-
1
def remaining # rubocop:disable TrivialAccessors
-
@extra
-
end
-
-
1
def peek
-
return super unless @parsing_options
-
-
result = super
-
if result == OPTS_END
-
shift
-
@parsing_options = false
-
super
-
else
-
result
-
end
-
end
-
-
1
def parse(args) # rubocop:disable MethodLength
-
@pile = args.dup
-
@parsing_options = true
-
-
while peek
-
if parsing_options?
-
match, is_switch = current_is_switch?
-
shifted = shift
-
-
if is_switch
-
case shifted
-
when SHORT_SQ_RE
-
unshift($1.split("").map { |f| "-#{f}" })
-
next
-
when EQ_RE, SHORT_NUM
-
unshift($2)
-
switch = $1
-
when LONG_RE, SHORT_RE
-
switch = $1
-
end
-
-
switch = normalize_switch(switch)
-
option = switch_option(switch)
-
@assigns[option.human_name] = parse_peek(switch, option)
-
elsif @stop_on_unknown
-
@parsing_options = false
-
@extra << shifted
-
@extra << shift while peek
-
break
-
elsif match
-
@extra << shifted
-
@extra << shift while peek && peek !~ /^-/
-
else
-
@extra << shifted
-
end
-
else
-
@extra << shift
-
end
-
end
-
-
check_requirement!
-
-
assigns = Thor::CoreExt::HashWithIndifferentAccess.new(@assigns)
-
assigns.freeze
-
assigns
-
end
-
-
1
def check_unknown!
-
# an unknown option starts with - or -- and has no more --'s afterward.
-
unknown = @extra.select { |str| str =~ /^--?(?:(?!--).)*$/ }
-
fail UnknownArgumentError, "Unknown switches '#{unknown.join(', ')}'" unless unknown.empty?
-
end
-
-
1
protected
-
-
# Check if the current value in peek is a registered switch.
-
#
-
# Two booleans are returned. The first is true if the current value
-
# starts with a hyphen; the second is true if it is a registered switch.
-
1
def current_is_switch?
-
case peek
-
when LONG_RE, SHORT_RE, EQ_RE, SHORT_NUM
-
[true, switch?($1)]
-
when SHORT_SQ_RE
-
[true, $1.split("").any? { |f| switch?("-#{f}") }]
-
else
-
[false, false]
-
end
-
end
-
-
1
def current_is_switch_formatted?
-
case peek
-
when LONG_RE, SHORT_RE, EQ_RE, SHORT_NUM, SHORT_SQ_RE
-
true
-
else
-
false
-
end
-
end
-
-
1
def current_is_value?
-
peek && (!parsing_options? || super)
-
end
-
-
1
def switch?(arg)
-
switch_option(normalize_switch(arg))
-
end
-
-
1
def switch_option(arg)
-
if match = no_or_skip?(arg) # rubocop:disable AssignmentInCondition
-
@switches[arg] || @switches["--#{match}"]
-
else
-
@switches[arg]
-
end
-
end
-
-
# Check if the given argument is actually a shortcut.
-
#
-
1
def normalize_switch(arg)
-
(@shorts[arg] || arg).tr("_", "-")
-
end
-
-
1
def parsing_options?
-
peek
-
@parsing_options
-
end
-
-
# Parse boolean values which can be given as --foo=true, --foo or --no-foo.
-
#
-
1
def parse_boolean(switch)
-
if current_is_value?
-
if ["true", "TRUE", "t", "T", true].include?(peek)
-
shift
-
true
-
elsif ["false", "FALSE", "f", "F", false].include?(peek)
-
shift
-
false
-
else
-
true
-
end
-
else
-
@switches.key?(switch) || !no_or_skip?(switch)
-
end
-
end
-
-
# Parse the value at the peek analyzing if it requires an input or not.
-
#
-
1
def parse_peek(switch, option)
-
if parsing_options? && (current_is_switch_formatted? || last?)
-
if option.boolean?
-
# No problem for boolean types
-
elsif no_or_skip?(switch)
-
return nil # User set value to nil
-
elsif option.string? && !option.required?
-
# Return the default if there is one, else the human name
-
return option.lazy_default || option.default || option.human_name
-
elsif option.lazy_default
-
return option.lazy_default
-
else
-
fail MalformattedArgumentError, "No value provided for option '#{switch}'"
-
end
-
end
-
-
@non_assigned_required.delete(option)
-
send(:"parse_#{option.type}", switch)
-
end
-
end
-
end
-
1
require "rbconfig"
-
-
1
class Thor
-
1
module Base
-
1
class << self
-
1
attr_writer :shell
-
-
# Returns the shell used in all Thor classes. If you are in a Unix platform
-
# it will use a colored log, otherwise it will use a basic one without color.
-
#
-
1
def shell
-
@shell ||= if ENV["THOR_SHELL"] && ENV["THOR_SHELL"].size > 0
-
Thor::Shell.const_get(ENV["THOR_SHELL"])
-
elsif RbConfig::CONFIG["host_os"] =~ /mswin|mingw/ && !ENV["ANSICON"]
-
Thor::Shell::Basic
-
else
-
Thor::Shell::Color
-
end
-
end
-
end
-
end
-
-
1
module Shell
-
1
SHELL_DELEGATED_METHODS = [:ask, :error, :set_color, :yes?, :no?, :say, :say_status, :print_in_columns, :print_table, :print_wrapped, :file_collision, :terminal_width]
-
1
attr_writer :shell
-
-
1
autoload :Basic, "thor/shell/basic"
-
1
autoload :Color, "thor/shell/color"
-
1
autoload :HTML, "thor/shell/html"
-
-
# Add shell to initialize config values.
-
#
-
# ==== Configuration
-
# shell<Object>:: An instance of the shell to be used.
-
#
-
# ==== Examples
-
#
-
# class MyScript < Thor
-
# argument :first, :type => :numeric
-
# end
-
#
-
# MyScript.new [1.0], { :foo => :bar }, :shell => Thor::Shell::Basic.new
-
#
-
1
def initialize(args = [], options = {}, config = {})
-
super
-
self.shell = config[:shell]
-
shell.base ||= self if shell.respond_to?(:base)
-
end
-
-
# Holds the shell for the given Thor instance. If no shell is given,
-
# it gets a default shell from Thor::Base.shell.
-
1
def shell
-
@shell ||= Thor::Base.shell.new
-
end
-
-
# Common methods that are delegated to the shell.
-
1
SHELL_DELEGATED_METHODS.each do |method|
-
12
module_eval <<-METHOD, __FILE__, __LINE__
-
def #{method}(*args,&block)
-
shell.#{method}(*args,&block)
-
end
-
METHOD
-
end
-
-
# Yields the given block with padding.
-
1
def with_padding
-
shell.padding += 1
-
yield
-
ensure
-
shell.padding -= 1
-
end
-
-
1
protected
-
-
# Allow shell to be shared between invocations.
-
#
-
1
def _shared_configuration #:nodoc:
-
super.merge!(:shell => shell)
-
end
-
end
-
end
-
1
require "tempfile"
-
1
require "io/console" if RUBY_VERSION > "1.9.2"
-
-
1
class Thor
-
1
module Shell
-
1
class Basic # rubocop:disable ClassLength
-
1
attr_accessor :base
-
1
attr_reader :padding
-
-
# Initialize base, mute and padding to nil.
-
#
-
1
def initialize #:nodoc:
-
@base, @mute, @padding, @always_force = nil, false, 0, false
-
end
-
-
# Mute everything that's inside given block
-
#
-
1
def mute
-
@mute = true
-
yield
-
ensure
-
@mute = false
-
end
-
-
# Check if base is muted
-
#
-
1
def mute? # rubocop:disable TrivialAccessors
-
@mute
-
end
-
-
# Sets the output padding, not allowing less than zero values.
-
#
-
1
def padding=(value)
-
@padding = [0, value].max
-
end
-
-
# Asks something to the user and receives a response.
-
#
-
# If asked to limit the correct responses, you can pass in an
-
# array of acceptable answers. If one of those is not supplied,
-
# they will be shown a message stating that one of those answers
-
# must be given and re-asked the question.
-
#
-
# If asking for sensitive information, the :echo option can be set
-
# to false to mask user input from $stdin.
-
#
-
# If the required input is a path, then set the path option to
-
# true. This will enable tab completion for file paths relative
-
# to the current working directory on systems that support
-
# Readline.
-
#
-
# ==== Example
-
# ask("What is your name?")
-
#
-
# ask("What is your favorite Neopolitan flavor?", :limited_to => ["strawberry", "chocolate", "vanilla"])
-
#
-
# ask("What is your password?", :echo => false)
-
#
-
# ask("Where should the file be saved?", :path => true)
-
#
-
1
def ask(statement, *args)
-
options = args.last.is_a?(Hash) ? args.pop : {}
-
color = args.first
-
-
if options[:limited_to]
-
ask_filtered(statement, color, options)
-
else
-
ask_simply(statement, color, options)
-
end
-
end
-
-
# Say (print) something to the user. If the sentence ends with a whitespace
-
# or tab character, a new line is not appended (print + flush). Otherwise
-
# are passed straight to puts (behavior got from Highline).
-
#
-
# ==== Example
-
# say("I know you knew that.")
-
#
-
1
def say(message = "", color = nil, force_new_line = (message.to_s !~ /( |\t)\Z/))
-
buffer = prepare_message(message, *color)
-
buffer << "\n" if force_new_line && !message.to_s.end_with?("\n")
-
-
stdout.print(buffer)
-
stdout.flush
-
end
-
-
# Say a status with the given color and appends the message. Since this
-
# method is used frequently by actions, it allows nil or false to be given
-
# in log_status, avoiding the message from being shown. If a Symbol is
-
# given in log_status, it's used as the color.
-
#
-
1
def say_status(status, message, log_status = true)
-
return if quiet? || log_status == false
-
spaces = " " * (padding + 1)
-
color = log_status.is_a?(Symbol) ? log_status : :green
-
-
status = status.to_s.rjust(12)
-
status = set_color status, color, true if color
-
-
buffer = "#{status}#{spaces}#{message}"
-
buffer << "\n" unless buffer.end_with?("\n")
-
-
stdout.print(buffer)
-
stdout.flush
-
end
-
-
# Make a question the to user and returns true if the user replies "y" or
-
# "yes".
-
#
-
1
def yes?(statement, color = nil)
-
!!(ask(statement, color, :add_to_history => false) =~ is?(:yes))
-
end
-
-
# Make a question the to user and returns true if the user replies "n" or
-
# "no".
-
#
-
1
def no?(statement, color = nil)
-
!!(ask(statement, color, :add_to_history => false) =~ is?(:no))
-
end
-
-
# Prints values in columns
-
#
-
# ==== Parameters
-
# Array[String, String, ...]
-
#
-
1
def print_in_columns(array)
-
return if array.empty?
-
colwidth = (array.map { |el| el.to_s.size }.max || 0) + 2
-
array.each_with_index do |value, index|
-
# Don't output trailing spaces when printing the last column
-
if ((((index + 1) % (terminal_width / colwidth))).zero? && !index.zero?) || index + 1 == array.length
-
stdout.puts value
-
else
-
stdout.printf("%-#{colwidth}s", value)
-
end
-
end
-
end
-
-
# Prints a table.
-
#
-
# ==== Parameters
-
# Array[Array[String, String, ...]]
-
#
-
# ==== Options
-
# indent<Integer>:: Indent the first column by indent value.
-
# colwidth<Integer>:: Force the first column to colwidth spaces wide.
-
#
-
1
def print_table(array, options = {}) # rubocop:disable MethodLength
-
return if array.empty?
-
-
formats, indent, colwidth = [], options[:indent].to_i, options[:colwidth]
-
options[:truncate] = terminal_width if options[:truncate] == true
-
-
formats << "%-#{colwidth + 2}s" if colwidth
-
start = colwidth ? 1 : 0
-
-
colcount = array.max { |a, b| a.size <=> b.size }.size
-
-
maximas = []
-
-
start.upto(colcount - 1) do |index|
-
maxima = array.map { |row| row[index] ? row[index].to_s.size : 0 }.max
-
maximas << maxima
-
if index == colcount - 1
-
# Don't output 2 trailing spaces when printing the last column
-
formats << "%-s"
-
else
-
formats << "%-#{maxima + 2}s"
-
end
-
end
-
-
formats[0] = formats[0].insert(0, " " * indent)
-
formats << "%s"
-
-
array.each do |row|
-
sentence = ""
-
-
row.each_with_index do |column, index|
-
maxima = maximas[index]
-
-
if column.is_a?(Numeric)
-
if index == row.size - 1
-
# Don't output 2 trailing spaces when printing the last column
-
f = "%#{maxima}s"
-
else
-
f = "%#{maxima}s "
-
end
-
else
-
f = formats[index]
-
end
-
sentence << f % column.to_s
-
end
-
-
sentence = truncate(sentence, options[:truncate]) if options[:truncate]
-
stdout.puts sentence
-
end
-
end
-
-
# Prints a long string, word-wrapping the text to the current width of the
-
# terminal display. Ideal for printing heredocs.
-
#
-
# ==== Parameters
-
# String
-
#
-
# ==== Options
-
# indent<Integer>:: Indent each line of the printed paragraph by indent value.
-
#
-
1
def print_wrapped(message, options = {})
-
indent = options[:indent] || 0
-
width = terminal_width - indent
-
paras = message.split("\n\n")
-
-
paras.map! do |unwrapped|
-
unwrapped.strip.gsub(/\n/, " ").squeeze(" ").gsub(/.{1,#{width}}(?:\s|\Z)/) { ($& + 5.chr).gsub(/\n\005/, "\n").gsub(/\005/, "\n") }
-
end
-
-
paras.each do |para|
-
para.split("\n").each do |line|
-
stdout.puts line.insert(0, " " * indent)
-
end
-
stdout.puts unless para == paras.last
-
end
-
end
-
-
# Deals with file collision and returns true if the file should be
-
# overwritten and false otherwise. If a block is given, it uses the block
-
# response as the content for the diff.
-
#
-
# ==== Parameters
-
# destination<String>:: the destination file to solve conflicts
-
# block<Proc>:: an optional block that returns the value to be used in diff
-
#
-
1
def file_collision(destination) # rubocop:disable MethodLength
-
return true if @always_force
-
options = block_given? ? "[Ynaqdh]" : "[Ynaqh]"
-
-
loop do
-
answer = ask(
-
%[Overwrite #{destination}? (enter "h" for help) #{options}],
-
:add_to_history => false
-
)
-
-
case answer
-
when is?(:yes), is?(:force), ""
-
return true
-
when is?(:no), is?(:skip)
-
return false
-
when is?(:always)
-
return @always_force = true
-
when is?(:quit)
-
say "Aborting..."
-
fail SystemExit
-
when is?(:diff)
-
show_diff(destination, yield) if block_given?
-
say "Retrying..."
-
else
-
say file_collision_help
-
end
-
end
-
end
-
-
# This code was copied from Rake, available under MIT-LICENSE
-
# Copyright (c) 2003, 2004 Jim Weirich
-
1
def terminal_width
-
if ENV["THOR_COLUMNS"]
-
result = ENV["THOR_COLUMNS"].to_i
-
else
-
result = unix? ? dynamic_width : 80
-
end
-
result < 10 ? 80 : result
-
rescue
-
80
-
end
-
-
# Called if something goes wrong during the execution. This is used by Thor
-
# internally and should not be used inside your scripts. If something went
-
# wrong, you can always raise an exception. If you raise a Thor::Error, it
-
# will be rescued and wrapped in the method below.
-
#
-
1
def error(statement)
-
stderr.puts statement
-
end
-
-
# Apply color to the given string with optional bold. Disabled in the
-
# Thor::Shell::Basic class.
-
#
-
1
def set_color(string, *args) #:nodoc:
-
string
-
end
-
-
1
protected
-
-
1
def prepare_message(message, *color)
-
spaces = " " * padding
-
spaces + set_color(message.to_s, *color)
-
end
-
-
1
def can_display_colors?
-
false
-
end
-
-
1
def lookup_color(color)
-
return color unless color.is_a?(Symbol)
-
self.class.const_get(color.to_s.upcase)
-
end
-
-
1
def stdout
-
$stdout
-
end
-
-
1
def stderr
-
$stderr
-
end
-
-
1
def is?(value) #:nodoc:
-
value = value.to_s
-
-
if value.size == 1
-
/\A#{value}\z/i
-
else
-
/\A(#{value}|#{value[0, 1]})\z/i
-
end
-
end
-
-
1
def file_collision_help #:nodoc:
-
<<-HELP
-
Y - yes, overwrite
-
n - no, do not overwrite
-
a - all, overwrite this and all others
-
q - quit, abort
-
d - diff, show the differences between the old and the new
-
h - help, show this help
-
HELP
-
end
-
-
1
def show_diff(destination, content) #:nodoc:
-
diff_cmd = ENV["THOR_DIFF"] || ENV["RAILS_DIFF"] || "diff -u"
-
-
Tempfile.open(File.basename(destination), File.dirname(destination)) do |temp|
-
temp.write content
-
temp.rewind
-
system %(#{diff_cmd} "#{destination}" "#{temp.path}")
-
end
-
end
-
-
1
def quiet? #:nodoc:
-
mute? || (base && base.options[:quiet])
-
end
-
-
# Calculate the dynamic width of the terminal
-
1
def dynamic_width
-
@dynamic_width ||= (dynamic_width_stty.nonzero? || dynamic_width_tput)
-
end
-
-
1
def dynamic_width_stty
-
%x(stty size 2>/dev/null).split[1].to_i
-
end
-
-
1
def dynamic_width_tput
-
%x(tput cols 2>/dev/null).to_i
-
end
-
-
1
def unix?
-
RUBY_PLATFORM =~ /(aix|darwin|linux|(net|free|open)bsd|cygwin|solaris|irix|hpux)/i
-
end
-
-
1
def truncate(string, width)
-
as_unicode do
-
chars = string.chars.to_a
-
if chars.length <= width
-
chars.join
-
else
-
( chars[0, width - 3].join) + "..."
-
end
-
end
-
end
-
-
1
if "".respond_to?(:encode)
-
1
def as_unicode
-
yield
-
end
-
else
-
def as_unicode
-
old, $KCODE = $KCODE, "U"
-
yield
-
ensure
-
$KCODE = old
-
end
-
end
-
-
1
def ask_simply(statement, color, options)
-
default = options[:default]
-
message = [statement, ("(#{default})" if default), nil].uniq.join(" ")
-
message = prepare_message(message, color)
-
result = Thor::LineEditor.readline(message, options)
-
-
return unless result
-
-
result.strip!
-
-
if default && result == ""
-
default
-
else
-
result
-
end
-
end
-
-
1
def ask_filtered(statement, color, options)
-
answer_set = options[:limited_to]
-
correct_answer = nil
-
until correct_answer
-
answers = answer_set.join(", ")
-
answer = ask_simply("#{statement} [#{answers}]", color, options)
-
correct_answer = answer_set.include?(answer) ? answer : nil
-
say("Your response must be one of: [#{answers}]. Please try again.") unless correct_answer
-
end
-
correct_answer
-
end
-
end
-
end
-
end
-
1
require "rbconfig"
-
-
1
class Thor
-
1
module Sandbox #:nodoc:
-
end
-
-
# This module holds several utilities:
-
#
-
# 1) Methods to convert thor namespaces to constants and vice-versa.
-
#
-
# Thor::Util.namespace_from_thor_class(Foo::Bar::Baz) #=> "foo:bar:baz"
-
#
-
# 2) Loading thor files and sandboxing:
-
#
-
# Thor::Util.load_thorfile("~/.thor/foo")
-
#
-
1
module Util
-
1
class << self
-
# Receives a namespace and search for it in the Thor::Base subclasses.
-
#
-
# ==== Parameters
-
# namespace<String>:: The namespace to search for.
-
#
-
1
def find_by_namespace(namespace)
-
namespace = "default#{namespace}" if namespace.empty? || namespace =~ /^:/
-
Thor::Base.subclasses.detect { |klass| klass.namespace == namespace }
-
end
-
-
# Receives a constant and converts it to a Thor namespace. Since Thor
-
# commands can be added to a sandbox, this method is also responsable for
-
# removing the sandbox namespace.
-
#
-
# This method should not be used in general because it's used to deal with
-
# older versions of Thor. On current versions, if you need to get the
-
# namespace from a class, just call namespace on it.
-
#
-
# ==== Parameters
-
# constant<Object>:: The constant to be converted to the thor path.
-
#
-
# ==== Returns
-
# String:: If we receive Foo::Bar::Baz it returns "foo:bar:baz"
-
#
-
1
def namespace_from_thor_class(constant)
-
constant = constant.to_s.gsub(/^Thor::Sandbox::/, "")
-
constant = snake_case(constant).squeeze(":")
-
constant
-
end
-
-
# Given the contents, evaluate it inside the sandbox and returns the
-
# namespaces defined in the sandbox.
-
#
-
# ==== Parameters
-
# contents<String>
-
#
-
# ==== Returns
-
# Array[Object]
-
#
-
1
def namespaces_in_content(contents, file = __FILE__)
-
old_constants = Thor::Base.subclasses.dup
-
Thor::Base.subclasses.clear
-
-
load_thorfile(file, contents)
-
-
new_constants = Thor::Base.subclasses.dup
-
Thor::Base.subclasses.replace(old_constants)
-
-
new_constants.map! { |c| c.namespace }
-
new_constants.compact!
-
new_constants
-
end
-
-
# Returns the thor classes declared inside the given class.
-
#
-
1
def thor_classes_in(klass)
-
stringfied_constants = klass.constants.map { |c| c.to_s }
-
Thor::Base.subclasses.select do |subclass|
-
next unless subclass.name
-
stringfied_constants.include?(subclass.name.gsub("#{klass.name}::", ""))
-
end
-
end
-
-
# Receives a string and convert it to snake case. SnakeCase returns snake_case.
-
#
-
# ==== Parameters
-
# String
-
#
-
# ==== Returns
-
# String
-
#
-
1
def snake_case(str)
-
return str.downcase if str =~ /^[A-Z_]+$/
-
str.gsub(/\B[A-Z]/, '_\&').squeeze("_") =~ /_*(.*)/
-
$+.downcase
-
end
-
-
# Receives a string and convert it to camel case. camel_case returns CamelCase.
-
#
-
# ==== Parameters
-
# String
-
#
-
# ==== Returns
-
# String
-
#
-
1
def camel_case(str)
-
return str if str !~ /_/ && str =~ /[A-Z]+.*/
-
str.split("_").map { |i| i.capitalize }.join
-
end
-
-
# Receives a namespace and tries to retrieve a Thor or Thor::Group class
-
# from it. It first searches for a class using the all the given namespace,
-
# if it's not found, removes the highest entry and searches for the class
-
# again. If found, returns the highest entry as the class name.
-
#
-
# ==== Examples
-
#
-
# class Foo::Bar < Thor
-
# def baz
-
# end
-
# end
-
#
-
# class Baz::Foo < Thor::Group
-
# end
-
#
-
# Thor::Util.namespace_to_thor_class("foo:bar") #=> Foo::Bar, nil # will invoke default command
-
# Thor::Util.namespace_to_thor_class("baz:foo") #=> Baz::Foo, nil
-
# Thor::Util.namespace_to_thor_class("foo:bar:baz") #=> Foo::Bar, "baz"
-
#
-
# ==== Parameters
-
# namespace<String>
-
#
-
1
def find_class_and_command_by_namespace(namespace, fallback = true)
-
if namespace.include?(":") # look for a namespaced command
-
pieces = namespace.split(":")
-
command = pieces.pop
-
klass = Thor::Util.find_by_namespace(pieces.join(":"))
-
end
-
unless klass # look for a Thor::Group with the right name
-
klass, command = Thor::Util.find_by_namespace(namespace), nil
-
end
-
if !klass && fallback # try a command in the default namespace
-
command = namespace
-
klass = Thor::Util.find_by_namespace("")
-
end
-
[klass, command]
-
end
-
1
alias_method :find_class_and_task_by_namespace, :find_class_and_command_by_namespace
-
-
# Receives a path and load the thor file in the path. The file is evaluated
-
# inside the sandbox to avoid namespacing conflicts.
-
#
-
1
def load_thorfile(path, content = nil, debug = false)
-
content ||= File.binread(path)
-
-
begin
-
Thor::Sandbox.class_eval(content, path)
-
rescue StandardError => e
-
$stderr.puts("WARNING: unable to load thorfile #{path.inspect}: #{e.message}")
-
if debug
-
$stderr.puts(*e.backtrace)
-
else
-
$stderr.puts(e.backtrace.first)
-
end
-
end
-
end
-
-
1
def user_home # rubocop:disable MethodLength
-
@@user_home ||= if ENV["HOME"]
-
ENV["HOME"]
-
elsif ENV["USERPROFILE"]
-
ENV["USERPROFILE"]
-
elsif ENV["HOMEDRIVE"] && ENV["HOMEPATH"]
-
File.join(ENV["HOMEDRIVE"], ENV["HOMEPATH"])
-
elsif ENV["APPDATA"]
-
ENV["APPDATA"]
-
else
-
begin
-
File.expand_path("~")
-
rescue
-
if File::ALT_SEPARATOR
-
"C:/"
-
else
-
"/"
-
end
-
end
-
end
-
end
-
-
# Returns the root where thor files are located, depending on the OS.
-
#
-
1
def thor_root
-
File.join(user_home, ".thor").gsub(/\\/, "/")
-
end
-
-
# Returns the files in the thor root. On Windows thor_root will be something
-
# like this:
-
#
-
# C:\Documents and Settings\james\.thor
-
#
-
# If we don't #gsub the \ character, Dir.glob will fail.
-
#
-
1
def thor_root_glob
-
files = Dir["#{escape_globs(thor_root)}/*"]
-
-
files.map! do |file|
-
File.directory?(file) ? File.join(file, "main.thor") : file
-
end
-
end
-
-
# Where to look for Thor files.
-
#
-
1
def globs_for(path)
-
path = escape_globs(path)
-
["#{path}/Thorfile", "#{path}/*.thor", "#{path}/tasks/*.thor", "#{path}/lib/tasks/*.thor"]
-
end
-
-
# Return the path to the ruby interpreter taking into account multiple
-
# installations and windows extensions.
-
#
-
1
def ruby_command # rubocop:disable MethodLength
-
@ruby_command ||= begin
-
ruby_name = RbConfig::CONFIG["ruby_install_name"]
-
ruby = File.join(RbConfig::CONFIG["bindir"], ruby_name)
-
ruby << RbConfig::CONFIG["EXEEXT"]
-
-
# avoid using different name than ruby (on platforms supporting links)
-
if ruby_name != "ruby" && File.respond_to?(:readlink)
-
begin
-
alternate_ruby = File.join(RbConfig::CONFIG["bindir"], "ruby")
-
alternate_ruby << RbConfig::CONFIG["EXEEXT"]
-
-
# ruby is a symlink
-
if File.symlink? alternate_ruby
-
linked_ruby = File.readlink alternate_ruby
-
-
# symlink points to 'ruby_install_name'
-
ruby = alternate_ruby if linked_ruby == ruby_name || linked_ruby == ruby
-
end
-
rescue NotImplementedError # rubocop:disable HandleExceptions
-
# just ignore on windows
-
end
-
end
-
-
# escape string in case path to ruby executable contain spaces.
-
ruby.sub!(/.*\s.*/m, '"\&"')
-
ruby
-
end
-
end
-
-
# Returns a string that has had any glob characters escaped.
-
# The glob characters are `* ? { } [ ]`.
-
#
-
# ==== Examples
-
#
-
# Thor::Util.escape_globs('[apps]') # => '\[apps\]'
-
#
-
# ==== Parameters
-
# String
-
#
-
# ==== Returns
-
# String
-
#
-
1
def escape_globs(path)
-
path.to_s.gsub(/[*?{}\[\]]/, '\\\\\\&')
-
end
-
end
-
end
-
end
-
2
require 'thread_safe/version'
-
2
require 'thread_safe/synchronized_delegator'
-
-
2
module ThreadSafe
-
2
autoload :Cache, 'thread_safe/cache'
-
2
autoload :Util, 'thread_safe/util'
-
-
# Various classes within allows for +nil+ values to be stored, so a special +NULL+ token is required to indicate the "nil-ness".
-
2
NULL = Object.new
-
-
2
if defined?(JRUBY_VERSION)
-
require 'jruby/synchronized'
-
-
# A thread-safe subclass of Array. This version locks
-
# against the object itself for every method call,
-
# ensuring only one thread can be reading or writing
-
# at a time. This includes iteration methods like
-
# #each.
-
class Array < ::Array
-
include JRuby::Synchronized
-
end
-
-
# A thread-safe subclass of Hash. This version locks
-
# against the object itself for every method call,
-
# ensuring only one thread can be reading or writing
-
# at a time. This includes iteration methods like
-
# #each.
-
class Hash < ::Hash
-
include JRuby::Synchronized
-
end
-
elsif !defined?(RUBY_ENGINE) || RUBY_ENGINE == 'ruby'
-
# Because MRI never runs code in parallel, the existing
-
# non-thread-safe structures should usually work fine.
-
2
Array = ::Array
-
2
Hash = ::Hash
-
elsif defined?(RUBY_ENGINE) && RUBY_ENGINE == 'rbx'
-
require 'monitor'
-
-
class Hash < ::Hash; end
-
class Array < ::Array; end
-
-
[Hash, Array].each do |klass|
-
klass.class_eval do
-
private
-
def _mon_initialize
-
@_monitor = Monitor.new unless @_monitor # avoid double initialisation
-
end
-
-
def self.allocate
-
obj = super
-
obj.send(:_mon_initialize)
-
obj
-
end
-
end
-
-
klass.superclass.instance_methods(false).each do |method|
-
klass.class_eval <<-RUBY_EVAL, __FILE__, __LINE__ + 1
-
def #{method}(*args)
-
@_monitor.synchronize { super }
-
end
-
RUBY_EVAL
-
end
-
end
-
end
-
end
-
2
require 'thread'
-
-
2
module ThreadSafe
-
2
autoload :JRubyCacheBackend, 'thread_safe/jruby_cache_backend'
-
2
autoload :MriCacheBackend, 'thread_safe/mri_cache_backend'
-
2
autoload :NonConcurrentCacheBackend, 'thread_safe/non_concurrent_cache_backend'
-
2
autoload :AtomicReferenceCacheBackend, 'thread_safe/atomic_reference_cache_backend'
-
2
autoload :SynchronizedCacheBackend, 'thread_safe/synchronized_cache_backend'
-
-
2
ConcurrentCacheBackend = if defined?(RUBY_ENGINE)
-
2
case RUBY_ENGINE
-
when 'jruby'; JRubyCacheBackend
-
2
when 'ruby'; MriCacheBackend
-
when 'rbx'; AtomicReferenceCacheBackend
-
else
-
warn 'ThreadSafe: unsupported Ruby engine, using a fully synchronized ThreadSafe::Cache implementation' if $VERBOSE
-
SynchronizedCacheBackend
-
end
-
else
-
MriCacheBackend
-
end
-
-
2
class Cache < ConcurrentCacheBackend
-
2
KEY_ERROR = defined?(KeyError) ? KeyError : IndexError # there is no KeyError in 1.8 mode
-
-
2
def initialize(options = nil, &block)
-
460
if options.kind_of?(::Hash)
-
167
validate_options_hash!(options)
-
else
-
293
options = nil
-
end
-
-
460
super(options)
-
460
@default_proc = block
-
end
-
-
2
def [](key)
-
51426
if value = super # non-falsy value is an existing mapping, return it right away
-
50951
value
-
# re-check is done with get_or_default(key, NULL) instead of a simple !key?(key) in order to avoid a race condition, whereby by the time the current thread gets to the key?(key) call
-
# a key => value mapping might have already been created by a different thread (key?(key) would then return true, this elsif branch wouldn't be taken and an incorrent +nil+ value
-
# would be returned)
-
# note: nil == value check is not technically necessary
-
475
elsif @default_proc && nil == value && NULL == (value = get_or_default(key, NULL))
-
146
@default_proc.call(self, key)
-
else
-
329
value
-
end
-
end
-
-
2
alias_method :get, :[]
-
2
alias_method :put, :[]=
-
-
2
def fetch(key, default_value = NULL)
-
27
if NULL != (value = get_or_default(key, NULL))
-
15
value
-
12
elsif block_given?
-
12
yield key
-
elsif NULL != default_value
-
default_value
-
else
-
raise_fetch_no_key
-
end
-
end
-
-
2
def fetch_or_store(key, default_value = NULL)
-
fetch(key) do
-
put(key, block_given? ? yield(key) : (NULL == default_value ? raise_fetch_no_key : default_value))
-
end
-
end
-
-
def put_if_absent(key, value)
-
computed = false
-
result = compute_if_absent(key) do
-
computed = true
-
value
-
end
-
computed ? nil : result
-
2
end unless method_defined?(:put_if_absent)
-
-
def value?(value)
-
each_value do |v|
-
return true if value.equal?(v)
-
end
-
false
-
2
end unless method_defined?(:value?)
-
-
def keys
-
21
arr = []
-
21
each_pair {|k, v| arr << k}
-
21
arr
-
2
end unless method_defined?(:keys)
-
-
def values
-
54
arr = []
-
344
each_pair {|k, v| arr << v}
-
54
arr
-
2
end unless method_defined?(:values)
-
-
def each_key
-
each_pair {|k, v| yield k}
-
2
end unless method_defined?(:each_key)
-
-
def each_value
-
each_pair {|k, v| yield v}
-
2
end unless method_defined?(:each_value)
-
-
def key(value)
-
each_pair {|k, v| return k if v == value}
-
nil
-
2
end unless method_defined?(:key)
-
2
alias_method :index, :key if RUBY_VERSION < '1.9'
-
-
def empty?
-
each_pair {|k, v| return false}
-
true
-
2
end unless method_defined?(:empty?)
-
-
def size
-
count = 0
-
each_pair {|k, v| count += 1}
-
count
-
2
end unless method_defined?(:size)
-
-
2
def marshal_dump
-
raise TypeError, "can't dump hash with default proc" if @default_proc
-
h = {}
-
each_pair {|k, v| h[k] = v}
-
h
-
end
-
-
2
def marshal_load(hash)
-
initialize
-
populate_from(hash)
-
end
-
-
2
undef :freeze
-
-
2
private
-
2
def raise_fetch_no_key
-
raise KEY_ERROR, 'key not found'
-
end
-
-
2
def initialize_copy(other)
-
super
-
populate_from(other)
-
end
-
-
2
def populate_from(hash)
-
hash.each_pair {|k, v| self[k] = v}
-
self
-
end
-
-
2
def validate_options_hash!(options)
-
167
if (initial_capacity = options[:initial_capacity]) && (!initial_capacity.kind_of?(Fixnum) || initial_capacity < 0)
-
raise ArgumentError, ":initial_capacity must be a positive Fixnum"
-
end
-
167
if (load_factor = options[:load_factor]) && (!load_factor.kind_of?(Numeric) || load_factor <= 0 || load_factor > 1)
-
raise ArgumentError, ":load_factor must be a number between 0 and 1"
-
end
-
end
-
end
-
end
-
2
module ThreadSafe
-
2
class MriCacheBackend < NonConcurrentCacheBackend
-
# We can get away with a single global write lock (instead of a per-instance
-
# one) because of the GVL/green threads.
-
#
-
# The previous implementation used `Thread.critical` on 1.8 MRI to implement
-
# the 4 composed atomic operations (`put_if_absent`, `replace_pair`,
-
# `replace_if_exists`, `delete_pair`) this however doesn't work for
-
# `compute_if_absent` because on 1.8 the Mutex class is itself implemented
-
# via `Thread.critical` and a call to `Mutex#lock` does not restore the
-
# previous `Thread.critical` value (thus any synchronisation clears the
-
# `Thread.critical` flag and we loose control). This poses a problem as the
-
# provided block might use synchronisation on its own.
-
#
-
# NOTE: a neat idea of writing a c-ext to manually perform atomic
-
# put_if_absent, while relying on Ruby not releasing a GVL while calling a
-
# c-ext will not work because of the potentially Ruby implemented `#hash`
-
# and `#eql?` key methods.
-
2
WRITE_LOCK = Mutex.new
-
-
2
def []=(key, value)
-
734
WRITE_LOCK.synchronize { super }
-
end
-
-
2
def compute_if_absent(key)
-
732
if stored_value = _get(key) # fast non-blocking path for the most likely case
-
616
stored_value
-
else
-
232
WRITE_LOCK.synchronize { super }
-
end
-
end
-
-
2
def compute_if_present(key)
-
WRITE_LOCK.synchronize { super }
-
end
-
-
2
def compute(key)
-
WRITE_LOCK.synchronize { super }
-
end
-
-
2
def merge_pair(key, value)
-
WRITE_LOCK.synchronize { super }
-
end
-
-
2
def replace_pair(key, old_value, new_value)
-
WRITE_LOCK.synchronize { super }
-
end
-
-
2
def replace_if_exists(key, new_value)
-
WRITE_LOCK.synchronize { super }
-
end
-
-
2
def get_and_set(key, value)
-
WRITE_LOCK.synchronize { super }
-
end
-
-
2
def delete(key)
-
46
WRITE_LOCK.synchronize { super }
-
end
-
-
2
def delete_pair(key, value)
-
WRITE_LOCK.synchronize { super }
-
end
-
-
2
def clear
-
488
WRITE_LOCK.synchronize { super }
-
end
-
end
-
end
-
2
module ThreadSafe
-
2
class NonConcurrentCacheBackend
-
# WARNING: all public methods of the class must operate on the @backend
-
# directly without calling each other. This is important because of the
-
# SynchronizedCacheBackend which uses a non-reentrant mutex for perfomance
-
# reasons.
-
2
def initialize(options = nil)
-
460
@backend = {}
-
end
-
-
2
def [](key)
-
52158
@backend[key]
-
end
-
-
2
def []=(key, value)
-
367
@backend[key] = value
-
end
-
-
2
def compute_if_absent(key)
-
116
if NULL != (stored_value = @backend.fetch(key, NULL))
-
stored_value
-
else
-
116
@backend[key] = yield
-
end
-
end
-
-
2
def replace_pair(key, old_value, new_value)
-
if pair?(key, old_value)
-
@backend[key] = new_value
-
true
-
else
-
false
-
end
-
end
-
-
2
def replace_if_exists(key, new_value)
-
if NULL != (stored_value = @backend.fetch(key, NULL))
-
@backend[key] = new_value
-
stored_value
-
end
-
end
-
-
2
def compute_if_present(key)
-
if NULL != (stored_value = @backend.fetch(key, NULL))
-
store_computed_value(key, yield(stored_value))
-
end
-
end
-
-
2
def compute(key)
-
store_computed_value(key, yield(@backend[key]))
-
end
-
-
2
def merge_pair(key, value)
-
if NULL == (stored_value = @backend.fetch(key, NULL))
-
@backend[key] = value
-
else
-
store_computed_value(key, yield(stored_value))
-
end
-
end
-
-
2
def get_and_set(key, value)
-
stored_value = @backend[key]
-
@backend[key] = value
-
stored_value
-
end
-
-
2
def key?(key)
-
@backend.key?(key)
-
end
-
-
2
def value?(value)
-
@backend.value?(value)
-
end
-
-
2
def delete(key)
-
23
@backend.delete(key)
-
end
-
-
2
def delete_pair(key, value)
-
if pair?(key, value)
-
@backend.delete(key)
-
true
-
else
-
false
-
end
-
end
-
-
2
def clear
-
244
@backend.clear
-
244
self
-
end
-
-
2
def each_pair
-
75
dupped_backend.each_pair do |k, v|
-
290
yield k, v
-
end
-
75
self
-
end
-
-
2
def size
-
@backend.size
-
end
-
-
2
def get_or_default(key, default_value)
-
173
@backend.fetch(key, default_value)
-
end
-
-
2
alias_method :_get, :[]
-
2
alias_method :_set, :[]=
-
2
private :_get, :_set
-
2
private
-
2
def initialize_copy(other)
-
super
-
@backend = {}
-
self
-
end
-
-
2
def dupped_backend
-
75
@backend.dup
-
end
-
-
2
def pair?(key, expected_value)
-
NULL != (stored_value = @backend.fetch(key, NULL)) && expected_value.equal?(stored_value)
-
end
-
-
2
def store_computed_value(key, new_value)
-
if new_value.nil?
-
@backend.delete(key)
-
nil
-
else
-
@backend[key] = new_value
-
end
-
end
-
end
-
end
-
2
require 'delegate'
-
2
require 'monitor'
-
-
# This class provides a trivial way to synchronize all calls to a given object
-
# by wrapping it with a `Delegator` that performs `Monitor#enter/exit` calls
-
# around the delegated `#send`. Example:
-
#
-
# array = [] # not thread-safe on many impls
-
# array = SynchronizedDelegator.new([]) # thread-safe
-
#
-
# A simple `Monitor` provides a very coarse-grained way to synchronize a given
-
# object, in that it will cause synchronization for methods that have no need
-
# for it, but this is a trivial way to get thread-safety where none may exist
-
# currently on some implementations.
-
#
-
# This class is currently being considered for inclusion into stdlib, via
-
# https://bugs.ruby-lang.org/issues/8556
-
class SynchronizedDelegator < SimpleDelegator
-
2
def setup
-
@old_abort = Thread.abort_on_exception
-
Thread.abort_on_exception = true
-
end
-
-
2
def teardown
-
Thread.abort_on_exception = @old_abort
-
end
-
-
2
def initialize(obj)
-
__setobj__(obj)
-
@monitor = Monitor.new
-
end
-
-
2
def method_missing(method, *args, &block)
-
monitor = @monitor
-
begin
-
monitor.enter
-
super
-
ensure
-
monitor.exit
-
end
-
end
-
-
# Work-around for 1.8 std-lib not passing block around to delegate.
-
# @private
-
def method_missing(method, *args, &block)
-
monitor = @monitor
-
begin
-
monitor.enter
-
target = self.__getobj__
-
if target.respond_to?(method)
-
target.__send__(method, *args, &block)
-
else
-
super(method, *args, &block)
-
end
-
ensure
-
monitor.exit
-
end
-
2
end if RUBY_VERSION[0, 3] == '1.8'
-
-
2
end unless defined?(SynchronizedDelegator)
-
2
module ThreadSafe
-
2
VERSION = "0.3.5"
-
end
-
-
# NOTE: <= 0.2.0 used Threadsafe::VERSION
-
# @private
-
2
module Threadsafe
-
-
# @private
-
2
def self.const_missing(name)
-
name = name.to_sym
-
if ThreadSafe.const_defined?(name)
-
warn "[DEPRECATION] `Threadsafe::#{name}' is deprecated, use `ThreadSafe::#{name}' instead."
-
ThreadSafe.const_get(name)
-
else
-
warn "[DEPRECATION] the `Threadsafe' module is deprecated, please use `ThreadSafe` instead."
-
super
-
end
-
end
-
-
end
-
2
module Tilt
-
2
VERSION = '1.4.1'
-
-
2
@preferred_mappings = Hash.new
-
64
@template_mappings = Hash.new { |h, k| h[k] = [] }
-
-
# Hash of template path pattern => template implementation class mappings.
-
2
def self.mappings
-
104
@template_mappings
-
end
-
-
2
def self.normalize(ext)
-
104
ext.to_s.downcase.sub(/^\./, '')
-
end
-
-
# Register a template implementation by file extension.
-
2
def self.register(template_class, *extensions)
-
58
if template_class.respond_to?(:to_str)
-
# Support register(ext, template_class) too
-
extensions, template_class = [template_class], extensions[0]
-
end
-
-
58
extensions.each do |ext|
-
104
ext = normalize(ext)
-
104
mappings[ext].unshift(template_class).uniq!
-
end
-
end
-
-
# Makes a template class preferred for the given file extensions. If you
-
# don't provide any extensions, it will be preferred for all its already
-
# registered extensions:
-
#
-
# # Prefer RDiscount for its registered file extensions:
-
# Tilt.prefer(Tilt::RDiscountTemplate)
-
#
-
# # Prefer RDiscount only for the .md extensions:
-
# Tilt.prefer(Tilt::RDiscountTemplate, '.md')
-
2
def self.prefer(template_class, *extensions)
-
if extensions.empty?
-
mappings.each do |ext, klasses|
-
@preferred_mappings[ext] = template_class if klasses.include? template_class
-
end
-
else
-
extensions.each do |ext|
-
ext = normalize(ext)
-
register(template_class, ext)
-
@preferred_mappings[ext] = template_class
-
end
-
end
-
end
-
-
# Returns true when a template exists on an exact match of the provided file extension
-
2
def self.registered?(ext)
-
mappings.key?(ext.downcase) && !mappings[ext.downcase].empty?
-
end
-
-
# Create a new template for the given file using the file's extension
-
# to determine the the template mapping.
-
2
def self.new(file, line=nil, options={}, &block)
-
if template_class = self[file]
-
template_class.new(file, line, options, &block)
-
else
-
fail "No template engine registered for #{File.basename(file)}"
-
end
-
end
-
-
# Lookup a template class for the given filename or file
-
# extension. Return nil when no implementation is found.
-
2
def self.[](file)
-
pattern = file.to_s.downcase
-
until pattern.empty? || registered?(pattern)
-
pattern = File.basename(pattern)
-
pattern.sub!(/^[^.]*\.?/, '')
-
end
-
-
# Try to find a preferred engine.
-
preferred_klass = @preferred_mappings[pattern]
-
return preferred_klass if preferred_klass
-
-
# Fall back to the general list of mappings.
-
klasses = @template_mappings[pattern]
-
-
# Try to find an engine which is already loaded.
-
template = klasses.detect do |klass|
-
if klass.respond_to?(:engine_initialized?)
-
klass.engine_initialized?
-
end
-
end
-
-
return template if template
-
-
# Try each of the classes until one succeeds. If all of them fails,
-
# we'll raise the error of the first class.
-
first_failure = nil
-
-
klasses.each do |klass|
-
begin
-
klass.new { '' }
-
rescue Exception => ex
-
first_failure ||= ex
-
next
-
else
-
return klass
-
end
-
end
-
-
raise first_failure if first_failure
-
end
-
-
# Deprecated module.
-
2
module CompileSite
-
end
-
-
# Extremely simple template cache implementation. Calling applications
-
# create a Tilt::Cache instance and use #fetch with any set of hashable
-
# arguments (such as those to Tilt.new):
-
# cache = Tilt::Cache.new
-
# cache.fetch(path, line, options) { Tilt.new(path, line, options) }
-
#
-
# Subsequent invocations return the already loaded template object.
-
2
class Cache
-
2
def initialize
-
@cache = {}
-
end
-
-
2
def fetch(*key)
-
@cache[key] ||= yield
-
end
-
-
2
def clear
-
@cache = {}
-
end
-
end
-
-
-
# Template Implementations ================================================
-
-
2
require 'tilt/string'
-
2
register StringTemplate, 'str'
-
-
2
require 'tilt/erb'
-
2
register ERBTemplate, 'erb', 'rhtml'
-
2
register ErubisTemplate, 'erb', 'rhtml', 'erubis'
-
-
2
require 'tilt/etanni'
-
2
register EtanniTemplate, 'etn', 'etanni'
-
-
2
require 'tilt/haml'
-
2
register HamlTemplate, 'haml'
-
-
2
require 'tilt/css'
-
2
register SassTemplate, 'sass'
-
2
register ScssTemplate, 'scss'
-
2
register LessTemplate, 'less'
-
-
2
require 'tilt/csv'
-
2
register CSVTemplate, 'rcsv'
-
-
2
require 'tilt/coffee'
-
2
register CoffeeScriptTemplate, 'coffee'
-
-
2
require 'tilt/nokogiri'
-
2
register NokogiriTemplate, 'nokogiri'
-
-
2
require 'tilt/builder'
-
2
register BuilderTemplate, 'builder'
-
-
2
require 'tilt/markaby'
-
2
register MarkabyTemplate, 'mab'
-
-
2
require 'tilt/liquid'
-
2
register LiquidTemplate, 'liquid'
-
-
2
require 'tilt/radius'
-
2
register RadiusTemplate, 'radius'
-
-
2
require 'tilt/markdown'
-
2
register MarukuTemplate, 'markdown', 'mkd', 'md'
-
2
register KramdownTemplate, 'markdown', 'mkd', 'md'
-
2
register BlueClothTemplate, 'markdown', 'mkd', 'md'
-
2
register RDiscountTemplate, 'markdown', 'mkd', 'md'
-
2
register RedcarpetTemplate::Redcarpet1, 'markdown', 'mkd', 'md'
-
2
register RedcarpetTemplate::Redcarpet2, 'markdown', 'mkd', 'md'
-
2
register RedcarpetTemplate, 'markdown', 'mkd', 'md'
-
-
2
require 'tilt/textile'
-
2
register RedClothTemplate, 'textile'
-
-
2
require 'tilt/rdoc'
-
2
register RDocTemplate, 'rdoc'
-
-
2
require 'tilt/wiki'
-
2
register CreoleTemplate, 'wiki', 'creole'
-
2
register WikiClothTemplate, 'wiki', 'mediawiki', 'mw'
-
-
2
require 'tilt/yajl'
-
2
register YajlTemplate, 'yajl'
-
-
2
require 'tilt/asciidoc'
-
2
register AsciidoctorTemplate, 'ad', 'adoc', 'asciidoc'
-
-
2
require 'tilt/plain'
-
2
register PlainTemplate, 'html'
-
end
-
2
require 'tilt/template'
-
-
# AsciiDoc see: http://asciidoc.org/
-
2
module Tilt
-
# Asciidoctor implementation for AsciiDoc see:
-
# http://asciidoctor.github.com/
-
#
-
# Asciidoctor is an open source, pure-Ruby processor for
-
# converting AsciiDoc documents or strings into HTML 5,
-
# DocBook 4.5 and other formats.
-
2
class AsciidoctorTemplate < Template
-
2
self.default_mime_type = 'text/html'
-
-
2
def self.engine_initialized?
-
defined? ::Asciidoctor::Document
-
end
-
-
2
def initialize_engine
-
require_template_library 'asciidoctor'
-
end
-
-
2
def prepare
-
options[:header_footer] = false if options[:header_footer].nil?
-
end
-
-
2
def evaluate(scope, locals, &block)
-
@output ||= Asciidoctor.render(data, options, &block)
-
end
-
-
2
def allows_script?
-
false
-
end
-
end
-
end
-
2
require 'tilt/template'
-
-
2
module Tilt
-
# Builder template implementation. See:
-
# http://builder.rubyforge.org/
-
2
class BuilderTemplate < Template
-
2
self.default_mime_type = 'text/xml'
-
-
2
def self.engine_initialized?
-
defined? ::Builder
-
end
-
-
2
def initialize_engine
-
require_template_library 'builder'
-
end
-
-
2
def prepare; end
-
-
2
def evaluate(scope, locals, &block)
-
return super(scope, locals, &block) if data.respond_to?(:to_str)
-
xml = ::Builder::XmlMarkup.new(:indent => 2)
-
data.call(xml)
-
xml.target!
-
end
-
-
2
def precompiled_preamble(locals)
-
return super if locals.include? :xml
-
"xml = ::Builder::XmlMarkup.new(:indent => 2)\n#{super}"
-
end
-
-
2
def precompiled_postamble(locals)
-
"xml.target!"
-
end
-
-
2
def precompiled_template(locals)
-
data.to_str
-
end
-
end
-
end
-
-
2
require 'tilt/template'
-
-
2
module Tilt
-
# CoffeeScript template implementation. See:
-
# http://coffeescript.org/
-
#
-
# CoffeeScript templates do not support object scopes, locals, or yield.
-
2
class CoffeeScriptTemplate < Template
-
2
self.default_mime_type = 'application/javascript'
-
-
2
@@default_bare = false
-
-
2
def self.default_bare
-
@@default_bare
-
end
-
-
2
def self.default_bare=(value)
-
@@default_bare = value
-
end
-
-
# DEPRECATED
-
2
def self.default_no_wrap
-
@@default_bare
-
end
-
-
# DEPRECATED
-
2
def self.default_no_wrap=(value)
-
@@default_bare = value
-
end
-
-
2
def self.engine_initialized?
-
defined? ::CoffeeScript
-
end
-
-
2
def initialize_engine
-
require_template_library 'coffee_script'
-
end
-
-
2
def prepare
-
if !options.key?(:bare) and !options.key?(:no_wrap)
-
options[:bare] = self.class.default_bare
-
end
-
end
-
-
2
def evaluate(scope, locals, &block)
-
@output ||= CoffeeScript.compile(data, options)
-
end
-
-
2
def allows_script?
-
false
-
end
-
end
-
end
-
-
2
require 'tilt/template'
-
-
2
module Tilt
-
# Sass template implementation. See:
-
# http://haml.hamptoncatlin.com/
-
#
-
# Sass templates do not support object scopes, locals, or yield.
-
2
class SassTemplate < Template
-
2
self.default_mime_type = 'text/css'
-
-
2
def self.engine_initialized?
-
defined? ::Sass::Engine
-
end
-
-
2
def initialize_engine
-
require_template_library 'sass'
-
end
-
-
2
def prepare
-
@engine = ::Sass::Engine.new(data, sass_options)
-
end
-
-
2
def evaluate(scope, locals, &block)
-
@output ||= @engine.render
-
end
-
-
2
def allows_script?
-
false
-
end
-
-
2
private
-
2
def sass_options
-
options.merge(:filename => eval_file, :line => line, :syntax => :sass)
-
end
-
end
-
-
# Sass's new .scss type template implementation.
-
2
class ScssTemplate < SassTemplate
-
2
self.default_mime_type = 'text/css'
-
-
2
private
-
2
def sass_options
-
options.merge(:filename => eval_file, :line => line, :syntax => :scss)
-
end
-
end
-
-
# Lessscss template implementation. See:
-
# http://lesscss.org/
-
#
-
# Less templates do not support object scopes, locals, or yield.
-
2
class LessTemplate < Template
-
2
self.default_mime_type = 'text/css'
-
-
2
def self.engine_initialized?
-
defined? ::Less
-
end
-
-
2
def initialize_engine
-
require_template_library 'less'
-
end
-
-
2
def prepare
-
if ::Less.const_defined? :Engine
-
@engine = ::Less::Engine.new(data)
-
else
-
parser = ::Less::Parser.new(options.merge :filename => eval_file, :line => line)
-
@engine = parser.parse(data)
-
end
-
end
-
-
2
def evaluate(scope, locals, &block)
-
@output ||= @engine.to_css(options)
-
end
-
-
2
def allows_script?
-
false
-
end
-
end
-
end
-
-
2
require 'tilt/template'
-
-
2
module Tilt
-
-
# CSV Template implementation. See:
-
# http://ruby-doc.org/stdlib/libdoc/csv/rdoc/CSV.html
-
#
-
# == Example
-
#
-
# # Example of csv template
-
# tpl = <<-EOS
-
# # header
-
# csv << ['NAME', 'ID']
-
#
-
# # data rows
-
# @people.each do |person|
-
# csv << [person[:name], person[:id]]
-
# end
-
# EOS
-
#
-
# @people = [
-
# {:name => "Joshua Peek", :id => 1},
-
# {:name => "Ryan Tomayko", :id => 2},
-
# {:name => "Simone Carletti", :id => 3}
-
# ]
-
#
-
# template = Tilt::CSVTemplate.new { tpl }
-
# template.render(self)
-
#
-
2
class CSVTemplate < Template
-
2
self.default_mime_type = 'text/csv'
-
-
2
def self.engine_initialized?
-
engine
-
end
-
-
2
def self.engine
-
if RUBY_VERSION >= '1.9.0' && defined? ::CSV
-
::CSV
-
elsif defined? ::FasterCSV
-
::FasterCSV
-
end
-
end
-
-
2
def initialize_engine
-
if RUBY_VERSION >= '1.9.0'
-
require_template_library 'csv'
-
else
-
require_template_library 'fastercsv'
-
end
-
end
-
-
2
def prepare
-
@code =<<-RUBY
-
#{self.class.engine}.generate do |csv|
-
#{data}
-
end
-
RUBY
-
end
-
-
2
def precompiled_template(locals)
-
@code
-
end
-
-
2
def precompiled(locals)
-
source, offset = super
-
[source, offset + 1]
-
end
-
-
end
-
end
-
2
require 'tilt/template'
-
-
2
module Tilt
-
# ERB template implementation. See:
-
# http://www.ruby-doc.org/stdlib/libdoc/erb/rdoc/classes/ERB.html
-
2
class ERBTemplate < Template
-
2
@@default_output_variable = '_erbout'
-
-
2
def self.default_output_variable
-
@@default_output_variable
-
end
-
-
2
def self.default_output_variable=(name)
-
@@default_output_variable = name
-
end
-
-
2
def self.engine_initialized?
-
defined? ::ERB
-
end
-
-
2
def initialize_engine
-
require_template_library 'erb'
-
end
-
-
2
def prepare
-
@outvar = options[:outvar] || self.class.default_output_variable
-
options[:trim] = '<>' if !(options[:trim] == false) && (options[:trim].nil? || options[:trim] == true)
-
@engine = ::ERB.new(data, options[:safe], options[:trim], @outvar)
-
end
-
-
2
def precompiled_template(locals)
-
source = @engine.src
-
source
-
end
-
-
2
def precompiled_preamble(locals)
-
<<-RUBY
-
begin
-
__original_outvar = #{@outvar} if defined?(#{@outvar})
-
#{super}
-
RUBY
-
end
-
-
2
def precompiled_postamble(locals)
-
<<-RUBY
-
#{super}
-
ensure
-
#{@outvar} = __original_outvar
-
end
-
RUBY
-
end
-
-
# ERB generates a line to specify the character coding of the generated
-
# source in 1.9. Account for this in the line offset.
-
2
if RUBY_VERSION >= '1.9.0'
-
2
def precompiled(locals)
-
source, offset = super
-
[source, offset + 1]
-
end
-
end
-
end
-
-
# Erubis template implementation. See:
-
# http://www.kuwata-lab.com/erubis/
-
#
-
# ErubisTemplate supports the following additional options, which are not
-
# passed down to the Erubis engine:
-
#
-
# :engine_class allows you to specify a custom engine class to use
-
# instead of the default (which is ::Erubis::Eruby).
-
#
-
# :escape_html when true, ::Erubis::EscapedEruby will be used as
-
# the engine class instead of the default. All content
-
# within <%= %> blocks will be automatically html escaped.
-
2
class ErubisTemplate < ERBTemplate
-
2
def self.engine_initialized?
-
defined? ::Erubis::Eruby
-
end
-
-
2
def initialize_engine
-
require_template_library 'erubis'
-
end
-
-
2
def prepare
-
@outvar = options.delete(:outvar) || self.class.default_output_variable
-
@options.merge!(:preamble => false, :postamble => false, :bufvar => @outvar)
-
engine_class = options.delete(:engine_class)
-
engine_class = ::Erubis::EscapedEruby if options.delete(:escape_html)
-
@engine = (engine_class || ::Erubis::Eruby).new(data, options)
-
end
-
-
2
def precompiled_preamble(locals)
-
[super, "#{@outvar} = _buf = ''"].join("\n")
-
end
-
-
2
def precompiled_postamble(locals)
-
[@outvar, super].join("\n")
-
end
-
-
# Erubis doesn't have ERB's line-off-by-one under 1.9 problem.
-
# Override and adjust back.
-
2
if RUBY_VERSION >= '1.9.0'
-
2
def precompiled(locals)
-
source, offset = super
-
[source, offset - 1]
-
end
-
end
-
end
-
end
-
-
2
require 'tilt/template'
-
-
2
module Tilt
-
2
class EtanniTemplate < Template
-
2
def prepare
-
separator = data.hash.abs
-
chomp = "<<#{separator}.chomp!"
-
start = "\n_out_ << #{chomp}\n"
-
stop = "\n#{separator}\n"
-
replacement = "#{stop}\\1#{start}"
-
-
temp = data.strip
-
temp.gsub!(/<\?r\s+(.*?)\s+\?>/m, replacement)
-
-
@code = "_out_ = [<<#{separator}.chomp!]\n#{temp}#{stop}_out_.join"
-
end
-
-
2
def precompiled_template(locals)
-
@code
-
end
-
-
2
def precompiled(locals)
-
source, offset = super
-
[source, offset + 1]
-
end
-
end
-
end
-
2
require 'tilt/template'
-
-
2
module Tilt
-
# Haml template implementation. See:
-
# http://haml.hamptoncatlin.com/
-
2
class HamlTemplate < Template
-
2
self.default_mime_type = 'text/html'
-
-
2
def self.engine_initialized?
-
defined? ::Haml::Engine
-
end
-
-
2
def initialize_engine
-
require_template_library 'haml'
-
end
-
-
2
def prepare
-
options = @options.merge(:filename => eval_file, :line => line)
-
@engine = ::Haml::Engine.new(data, options)
-
end
-
-
2
def evaluate(scope, locals, &block)
-
if @engine.respond_to?(:precompiled_method_return_value, true)
-
super
-
else
-
@engine.render(scope, locals, &block)
-
end
-
end
-
-
# Precompiled Haml source. Taken from the precompiled_with_ambles
-
# method in Haml::Precompiler:
-
# http://github.com/nex3/haml/blob/master/lib/haml/precompiler.rb#L111-126
-
2
def precompiled_template(locals)
-
@engine.precompiled
-
end
-
-
2
def precompiled_preamble(locals)
-
local_assigns = super
-
@engine.instance_eval do
-
<<-RUBY
-
begin
-
extend Haml::Helpers
-
_hamlout = @haml_buffer = Haml::Buffer.new(@haml_buffer, #{options_for_buffer.inspect})
-
_erbout = _hamlout.buffer
-
__in_erb_template = true
-
_haml_locals = locals
-
#{local_assigns}
-
RUBY
-
end
-
end
-
-
2
def precompiled_postamble(locals)
-
@engine.instance_eval do
-
<<-RUBY
-
#{precompiled_method_return_value}
-
ensure
-
@haml_buffer = @haml_buffer.upper
-
end
-
RUBY
-
end
-
end
-
end
-
end
-
-
2
require 'tilt/template'
-
-
2
module Tilt
-
# Liquid template implementation. See:
-
# http://liquid.rubyforge.org/
-
#
-
# Liquid is designed to be a *safe* template system and threfore
-
# does not provide direct access to execuatable scopes. In order to
-
# support a +scope+, the +scope+ must be able to represent itself
-
# as a hash by responding to #to_h. If the +scope+ does not respond
-
# to #to_h it will be ignored.
-
#
-
# LiquidTemplate does not support yield blocks.
-
#
-
# It's suggested that your program require 'liquid' at load
-
# time when using this template engine.
-
2
class LiquidTemplate < Template
-
2
def self.engine_initialized?
-
defined? ::Liquid::Template
-
end
-
-
2
def initialize_engine
-
require_template_library 'liquid'
-
end
-
-
2
def prepare
-
@engine = ::Liquid::Template.parse(data)
-
end
-
-
2
def evaluate(scope, locals, &block)
-
locals = locals.inject({}){ |h,(k,v)| h[k.to_s] = v ; h }
-
if scope.respond_to?(:to_h)
-
scope = scope.to_h.inject({}){ |h,(k,v)| h[k.to_s] = v ; h }
-
locals = scope.merge(locals)
-
end
-
locals['yield'] = block.nil? ? '' : yield
-
locals['content'] = locals['yield']
-
@engine.render(locals)
-
end
-
-
2
def allows_script?
-
false
-
end
-
end
-
end
-
2
require 'tilt/template'
-
-
2
module Tilt
-
# Markaby
-
# http://github.com/markaby/markaby
-
2
class MarkabyTemplate < Template
-
2
def self.builder_class
-
@builder_class ||= Class.new(Markaby::Builder) do
-
def __capture_markaby_tilt__(&block)
-
__run_markaby_tilt__ do
-
text capture(&block)
-
end
-
end
-
end
-
end
-
-
2
def self.engine_initialized?
-
defined? ::Markaby
-
end
-
-
2
def initialize_engine
-
require_template_library 'markaby'
-
end
-
-
2
def prepare
-
end
-
-
2
def evaluate(scope, locals, &block)
-
builder = self.class.builder_class.new({}, scope)
-
builder.locals = locals
-
-
if data.kind_of? Proc
-
(class << builder; self end).send(:define_method, :__run_markaby_tilt__, &data)
-
else
-
builder.instance_eval <<-CODE, __FILE__, __LINE__
-
def __run_markaby_tilt__
-
#{data}
-
end
-
CODE
-
end
-
-
if block
-
builder.__capture_markaby_tilt__(&block)
-
else
-
builder.__run_markaby_tilt__
-
end
-
-
builder.to_s
-
end
-
end
-
end
-
-
2
require 'tilt/template'
-
-
2
module Tilt
-
# Discount Markdown implementation. See:
-
# http://github.com/rtomayko/rdiscount
-
#
-
# RDiscount is a simple text filter. It does not support +scope+ or
-
# +locals+. The +:smart+ and +:filter_html+ options may be set true
-
# to enable those flags on the underlying RDiscount object.
-
2
class RDiscountTemplate < Template
-
2
self.default_mime_type = 'text/html'
-
-
2
ALIAS = {
-
:escape_html => :filter_html,
-
:smartypants => :smart
-
}
-
-
2
FLAGS = [:smart, :filter_html, :smartypants, :escape_html]
-
-
2
def flags
-
FLAGS.select { |flag| options[flag] }.map { |flag| ALIAS[flag] || flag }
-
end
-
-
2
def self.engine_initialized?
-
defined? ::RDiscount
-
end
-
-
2
def initialize_engine
-
require_template_library 'rdiscount'
-
end
-
-
2
def prepare
-
@engine = RDiscount.new(data, *flags)
-
@output = nil
-
end
-
-
2
def evaluate(scope, locals, &block)
-
@output ||= @engine.to_html
-
end
-
-
2
def allows_script?
-
false
-
end
-
end
-
-
# Upskirt Markdown implementation. See:
-
# https://github.com/tanoku/redcarpet
-
#
-
# Supports both Redcarpet 1.x and 2.x
-
2
class RedcarpetTemplate < Template
-
2
def self.engine_initialized?
-
defined? ::Redcarpet
-
end
-
-
2
def initialize_engine
-
require_template_library 'redcarpet'
-
end
-
-
2
def prepare
-
klass = [Redcarpet2, Redcarpet1].detect { |e| e.engine_initialized? }
-
@engine = klass.new(file, line, options) { data }
-
end
-
-
2
def evaluate(scope, locals, &block)
-
@engine.evaluate(scope, locals, &block)
-
end
-
-
2
def allows_script?
-
false
-
end
-
-
# Compatibility mode for Redcarpet 1.x
-
2
class Redcarpet1 < RDiscountTemplate
-
2
self.default_mime_type = 'text/html'
-
-
2
def self.engine_initialized?
-
defined? ::RedcarpetCompat
-
end
-
-
2
def prepare
-
@engine = RedcarpetCompat.new(data, *flags)
-
@output = nil
-
end
-
end
-
-
# Future proof mode for Redcarpet 2.x (not yet released)
-
2
class Redcarpet2 < Template
-
2
self.default_mime_type = 'text/html'
-
-
2
def self.engine_initialized?
-
defined? ::Redcarpet::Render and defined? ::Redcarpet::Markdown
-
end
-
-
2
def generate_renderer
-
renderer = options.delete(:renderer) || ::Redcarpet::Render::HTML
-
return renderer unless options.delete(:smartypants)
-
return renderer if renderer.is_a?(Class) && renderer <= ::Redcarpet::Render::SmartyPants
-
-
if renderer == ::Redcarpet::Render::XHTML
-
::Redcarpet::Render::SmartyHTML.new(:xhtml => true)
-
elsif renderer == ::Redcarpet::Render::HTML
-
::Redcarpet::Render::SmartyHTML
-
elsif renderer.is_a? Class
-
Class.new(renderer) { include ::Redcarpet::Render::SmartyPants }
-
else
-
renderer.extend ::Redcarpet::Render::SmartyPants
-
end
-
end
-
-
2
def prepare
-
# try to support the same aliases
-
RDiscountTemplate::ALIAS.each do |opt, aka|
-
next if options.key? opt or not options.key? aka
-
options[opt] = options.delete(aka)
-
end
-
-
# only raise an exception if someone is trying to enable :escape_html
-
options.delete(:escape_html) unless options[:escape_html]
-
-
@engine = ::Redcarpet::Markdown.new(generate_renderer, options)
-
@output = nil
-
end
-
-
2
def evaluate(scope, locals, &block)
-
@output ||= @engine.render(data)
-
end
-
-
2
def allows_script?
-
false
-
end
-
end
-
end
-
-
# BlueCloth Markdown implementation. See:
-
# http://deveiate.org/projects/BlueCloth/
-
2
class BlueClothTemplate < Template
-
2
self.default_mime_type = 'text/html'
-
-
2
def self.engine_initialized?
-
defined? ::BlueCloth
-
end
-
-
2
def initialize_engine
-
require_template_library 'bluecloth'
-
end
-
-
2
def prepare
-
@engine = BlueCloth.new(data, options)
-
@output = nil
-
end
-
-
2
def evaluate(scope, locals, &block)
-
@output ||= @engine.to_html
-
end
-
-
2
def allows_script?
-
false
-
end
-
end
-
-
# Maruku markdown implementation. See:
-
# http://maruku.rubyforge.org/
-
2
class MarukuTemplate < Template
-
2
def self.engine_initialized?
-
defined? ::Maruku
-
end
-
-
2
def initialize_engine
-
require_template_library 'maruku'
-
end
-
-
2
def prepare
-
@engine = Maruku.new(data, options)
-
@output = nil
-
end
-
-
2
def evaluate(scope, locals, &block)
-
@output ||= @engine.to_html
-
end
-
-
2
def allows_script?
-
false
-
end
-
end
-
-
# Kramdown Markdown implementation. See:
-
# http://kramdown.rubyforge.org/
-
2
class KramdownTemplate < Template
-
2
DUMB_QUOTES = [39, 39, 34, 34]
-
-
2
def self.engine_initialized?
-
defined? ::Kramdown
-
end
-
-
2
def initialize_engine
-
require_template_library 'kramdown'
-
end
-
-
2
def prepare
-
options[:smart_quotes] = DUMB_QUOTES unless options[:smartypants]
-
@engine = Kramdown::Document.new(data, options)
-
@output = nil
-
end
-
-
2
def evaluate(scope, locals, &block)
-
@output ||= @engine.to_html
-
end
-
-
2
def allows_script?
-
false
-
end
-
end
-
end
-
-
2
require 'tilt/template'
-
-
2
module Tilt
-
# Nokogiri template implementation. See:
-
# http://nokogiri.org/
-
2
class NokogiriTemplate < Template
-
2
DOCUMENT_HEADER = /^<\?xml version=\"1\.0\"\?>\n?/
-
2
self.default_mime_type = 'text/xml'
-
-
2
def self.engine_initialized?
-
defined? ::Nokogiri
-
end
-
-
2
def initialize_engine
-
require_template_library 'nokogiri'
-
end
-
-
2
def prepare; end
-
-
2
def evaluate(scope, locals)
-
if data.respond_to?(:to_str)
-
wrapper = proc { yield.sub(DOCUMENT_HEADER, "") } if block_given?
-
super(scope, locals, &wrapper)
-
else
-
::Nokogiri::XML::Builder.new.tap(&data).to_xml
-
end
-
end
-
-
2
def precompiled_preamble(locals)
-
return super if locals.include? :xml
-
"xml = ::Nokogiri::XML::Builder.new { |xml| }\n#{super}"
-
end
-
-
2
def precompiled_postamble(locals)
-
"xml.to_xml"
-
end
-
-
2
def precompiled_template(locals)
-
data.to_str
-
end
-
end
-
end
-
-
2
require 'tilt/template'
-
-
-
2
module Tilt
-
# Raw text (no template functionality).
-
2
class PlainTemplate < Template
-
2
self.default_mime_type = 'text/html'
-
-
2
def self.engine_initialized?
-
true
-
end
-
-
2
def prepare
-
end
-
-
2
def evaluate(scope, locals, &block)
-
@output ||= data
-
end
-
end
-
end
-
2
require 'tilt/template'
-
-
2
module Tilt
-
# Radius Template
-
# http://github.com/jlong/radius/
-
2
class RadiusTemplate < Template
-
2
def self.engine_initialized?
-
defined? ::Radius
-
end
-
-
2
def self.context_class
-
@context_class ||= Class.new(Radius::Context) do
-
attr_accessor :tilt_scope
-
-
def tag_missing(name, attributes)
-
tilt_scope.__send__(name)
-
end
-
-
def dup
-
i = super
-
i.tilt_scope = tilt_scope
-
i
-
end
-
end
-
end
-
-
2
def initialize_engine
-
require_template_library 'radius'
-
end
-
-
2
def prepare
-
end
-
-
2
def evaluate(scope, locals, &block)
-
context = self.class.context_class.new
-
context.tilt_scope = scope
-
context.define_tag("yield") do
-
block.call
-
end
-
locals.each do |tag, value|
-
context.define_tag(tag) do
-
value
-
end
-
end
-
-
options = {:tag_prefix => 'r'}.merge(@options)
-
parser = Radius::Parser.new(context, options)
-
parser.parse(data)
-
end
-
-
2
def allows_script?
-
false
-
end
-
end
-
end
-
2
require 'tilt/template'
-
-
2
module Tilt
-
# RDoc template. See:
-
# http://rdoc.rubyforge.org/
-
#
-
# It's suggested that your program `require 'rdoc/markup'` and
-
# `require 'rdoc/markup/to_html'` at load time when using this template
-
# engine in a threaded environment.
-
2
class RDocTemplate < Template
-
2
self.default_mime_type = 'text/html'
-
-
2
def self.engine_initialized?
-
defined? ::RDoc::Markup::ToHtml
-
end
-
-
2
def initialize_engine
-
require_template_library 'rdoc'
-
require_template_library 'rdoc/markup'
-
require_template_library 'rdoc/markup/to_html'
-
end
-
-
2
def markup
-
begin
-
# RDoc 4.0
-
require 'rdoc/options'
-
RDoc::Markup::ToHtml.new(RDoc::Options.new, nil)
-
rescue ArgumentError
-
# RDoc < 4.0
-
RDoc::Markup::ToHtml.new
-
end
-
end
-
-
2
def prepare
-
@engine = markup.convert(data)
-
@output = nil
-
end
-
-
2
def evaluate(scope, locals, &block)
-
@output ||= @engine.to_s
-
end
-
-
2
def allows_script?
-
false
-
end
-
end
-
end
-
2
require 'tilt/template'
-
-
2
module Tilt
-
# The template source is evaluated as a Ruby string. The #{} interpolation
-
# syntax can be used to generated dynamic output.
-
2
class StringTemplate < Template
-
2
def prepare
-
hash = "TILT#{data.hash.abs}"
-
@code = "<<#{hash}.chomp\n#{data}\n#{hash}"
-
end
-
-
2
def precompiled_template(locals)
-
@code
-
end
-
-
2
def precompiled(locals)
-
source, offset = super
-
[source, offset + 1]
-
end
-
end
-
end
-
2
module Tilt
-
2
TOPOBJECT = Object.superclass || Object
-
-
# Base class for template implementations. Subclasses must implement
-
# the #prepare method and one of the #evaluate or #precompiled_template
-
# methods.
-
2
class Template
-
# Template source; loaded from a file or given directly.
-
2
attr_reader :data
-
-
# The name of the file where the template data was loaded from.
-
2
attr_reader :file
-
-
# The line number in #file where template data was loaded from.
-
2
attr_reader :line
-
-
# A Hash of template engine specific options. This is passed directly
-
# to the underlying engine and is not used by the generic template
-
# interface.
-
2
attr_reader :options
-
-
# Used to determine if this class's initialize_engine method has
-
# been called yet.
-
2
@engine_initialized = false
-
2
class << self
-
2
attr_accessor :engine_initialized
-
2
alias engine_initialized? engine_initialized
-
-
2
attr_accessor :default_mime_type
-
end
-
-
# Create a new template with the file, line, and options specified. By
-
# default, template data is read from the file. When a block is given,
-
# it should read template data and return as a String. When file is nil,
-
# a block is required.
-
#
-
# All arguments are optional.
-
2
def initialize(file=nil, line=1, options={}, &block)
-
5
@file, @line, @options = nil, 1, {}
-
-
5
[options, line, file].compact.each do |arg|
-
case
-
5
when arg.respond_to?(:to_str) ; @file = arg.to_str
-
5
when arg.respond_to?(:to_int) ; @line = arg.to_int
-
5
when arg.respond_to?(:to_hash) ; @options = arg.to_hash.dup
-
when arg.respond_to?(:path) ; @file = arg.path
-
else raise TypeError
-
15
end
-
end
-
-
5
raise ArgumentError, "file or block required" if (@file || block).nil?
-
-
# call the initialize_engine method if this is the very first time
-
# an instance of this class has been created.
-
5
if !self.class.engine_initialized?
-
3
initialize_engine
-
3
self.class.engine_initialized = true
-
end
-
-
# used to hold compiled template methods
-
5
@compiled_method = {}
-
-
# used on 1.9 to set the encoding if it is not set elsewhere (like a magic comment)
-
# currently only used if template compiles to ruby
-
5
@default_encoding = @options.delete :default_encoding
-
-
# load template data and prepare (uses binread to avoid encoding issues)
-
5
@reader = block || lambda { |t| read_template_file }
-
5
@data = @reader.call(self)
-
-
5
if @data.respond_to?(:force_encoding)
-
5
@data.force_encoding(default_encoding) if default_encoding
-
-
5
if !@data.valid_encoding?
-
raise Encoding::InvalidByteSequenceError, "#{eval_file} is not valid #{@data.encoding}"
-
end
-
end
-
-
5
prepare
-
end
-
-
# The encoding of the source data. Defaults to the
-
# default_encoding-option if present. You may override this method
-
# in your template class if you have a better hint of the data's
-
# encoding.
-
2
def default_encoding
-
5
@default_encoding
-
end
-
-
2
def read_template_file
-
data = File.open(file, 'rb') { |io| io.read }
-
if data.respond_to?(:force_encoding)
-
# Set it to the default external (without verifying)
-
data.force_encoding(Encoding.default_external) if Encoding.default_external
-
end
-
data
-
end
-
-
# Render the template in the given scope with the locals specified. If a
-
# block is given, it is typically available within the template via
-
# +yield+.
-
2
def render(scope=Object.new, locals={}, &block)
-
5
evaluate scope, locals || {}, &block
-
end
-
-
# The basename of the template file.
-
2
def basename(suffix='')
-
File.basename(file, suffix) if file
-
end
-
-
# The template file's basename with all extensions chomped off.
-
2
def name
-
basename.split('.', 2).first if basename
-
end
-
-
# The filename used in backtraces to describe the template.
-
2
def eval_file
-
file || '(__TEMPLATE__)'
-
end
-
-
# Whether or not this template engine allows executing Ruby script
-
# within the template. If this is false, +scope+ and +locals+ will
-
# generally not be used, nor will the provided block be avaiable
-
# via +yield+.
-
# This should be overridden by template subclasses.
-
2
def allows_script?
-
true
-
end
-
-
2
protected
-
# Called once and only once for each template subclass the first time
-
# the template class is initialized. This should be used to require the
-
# underlying template library and perform any initial setup.
-
2
def initialize_engine
-
end
-
-
# Like Kernel#require but issues a warning urging a manual require when
-
# running under a threaded environment.
-
2
def require_template_library(name)
-
if Thread.list.size > 1
-
warn "WARN: tilt autoloading '#{name}' in a non thread-safe way; " +
-
"explicit require '#{name}' suggested."
-
end
-
require name
-
end
-
-
# Do whatever preparation is necessary to setup the underlying template
-
# engine. Called immediately after template data is loaded. Instance
-
# variables set in this method are available when #evaluate is called.
-
#
-
# Subclasses must provide an implementation of this method.
-
2
def prepare
-
if respond_to?(:compile!)
-
# backward compat with tilt < 0.6; just in case
-
warn 'Tilt::Template#compile! is deprecated; implement #prepare instead.'
-
compile!
-
else
-
raise NotImplementedError
-
end
-
end
-
-
# Execute the compiled template and return the result string. Template
-
# evaluation is guaranteed to be performed in the scope object with the
-
# locals specified and with support for yielding to the block.
-
#
-
# This method is only used by source generating templates. Subclasses that
-
# override render() may not support all features.
-
2
def evaluate(scope, locals, &block)
-
method = compiled_method(locals.keys)
-
method.bind(scope).call(locals, &block)
-
end
-
-
# Generates all template source by combining the preamble, template, and
-
# postamble and returns a two-tuple of the form: [source, offset], where
-
# source is the string containing (Ruby) source code for the template and
-
# offset is the integer line offset where line reporting should begin.
-
#
-
# Template subclasses may override this method when they need complete
-
# control over source generation or want to adjust the default line
-
# offset. In most cases, overriding the #precompiled_template method is
-
# easier and more appropriate.
-
2
def precompiled(locals)
-
preamble = precompiled_preamble(locals)
-
template = precompiled_template(locals)
-
postamble = precompiled_postamble(locals)
-
source = ''
-
-
# Ensure that our generated source code has the same encoding as the
-
# the source code generated by the template engine.
-
if source.respond_to?(:force_encoding)
-
template_encoding = extract_encoding(template)
-
-
source.force_encoding(template_encoding)
-
template.force_encoding(template_encoding)
-
end
-
-
# https://github.com/rtomayko/tilt/issues/193
-
warn "precompiled_preamble should return String (not Array)" if preamble.is_a?(Array)
-
warn "precompiled_postamble should return String (not Array)" if postamble.is_a?(Array)
-
source << [preamble, template, postamble].join("\n")
-
-
[source, preamble.count("\n")+1]
-
end
-
-
# A string containing the (Ruby) source code for the template. The
-
# default Template#evaluate implementation requires either this
-
# method or the #precompiled method be overridden. When defined,
-
# the base Template guarantees correct file/line handling, locals
-
# support, custom scopes, proper encoding, and support for template
-
# compilation.
-
2
def precompiled_template(locals)
-
raise NotImplementedError
-
end
-
-
# Generates preamble code for initializing template state, and performing
-
# locals assignment. The default implementation performs locals
-
# assignment only. Lines included in the preamble are subtracted from the
-
# source line offset, so adding code to the preamble does not effect line
-
# reporting in Kernel::caller and backtraces.
-
2
def precompiled_preamble(locals)
-
locals.map do |k,v|
-
if k.to_s =~ /\A[a-z_][a-zA-Z_0-9]*\z/
-
"#{k} = locals[#{k.inspect}]"
-
else
-
raise "invalid locals key: #{k.inspect} (keys must be variable names)"
-
end
-
end.join("\n")
-
end
-
-
# Generates postamble code for the precompiled template source. The
-
# string returned from this method is appended to the precompiled
-
# template source.
-
2
def precompiled_postamble(locals)
-
''
-
end
-
-
# The compiled method for the locals keys provided.
-
2
def compiled_method(locals_keys)
-
@compiled_method[locals_keys] ||=
-
compile_template_method(locals_keys)
-
end
-
-
2
private
-
2
def compile_template_method(locals)
-
source, offset = precompiled(locals)
-
method_name = "__tilt_#{Thread.current.object_id.abs}"
-
method_source = ""
-
-
if method_source.respond_to?(:force_encoding)
-
method_source.force_encoding(source.encoding)
-
end
-
-
method_source << <<-RUBY
-
TOPOBJECT.class_eval do
-
def #{method_name}(locals)
-
Thread.current[:tilt_vars] = [self, locals]
-
class << self
-
this, locals = Thread.current[:tilt_vars]
-
this.instance_eval do
-
RUBY
-
offset += method_source.count("\n")
-
method_source << source
-
method_source << "\nend;end;end;end"
-
Object.class_eval method_source, eval_file, line - offset
-
unbind_compiled_method(method_name)
-
end
-
-
2
def unbind_compiled_method(method_name)
-
method = TOPOBJECT.instance_method(method_name)
-
TOPOBJECT.class_eval { remove_method(method_name) }
-
method
-
end
-
-
2
def extract_encoding(script)
-
extract_magic_comment(script) || script.encoding
-
end
-
-
2
def extract_magic_comment(script)
-
binary script do
-
script[/\A[ \t]*\#.*coding\s*[=:]\s*([[:alnum:]\-_]+).*$/n, 1]
-
end
-
end
-
-
2
def binary(string)
-
original_encoding = string.encoding
-
string.force_encoding(Encoding::BINARY)
-
yield
-
ensure
-
string.force_encoding(original_encoding)
-
end
-
end
-
end
-
2
require 'tilt/template'
-
-
2
module Tilt
-
# RedCloth implementation. See:
-
# http://redcloth.org/
-
2
class RedClothTemplate < Template
-
2
def self.engine_initialized?
-
defined? ::RedCloth
-
end
-
-
2
def initialize_engine
-
require_template_library 'redcloth'
-
end
-
-
2
def prepare
-
@engine = RedCloth.new(data)
-
options.each {|k, v| @engine.send("#{k}=", v) if @engine.respond_to? "#{k}="}
-
@output = nil
-
end
-
-
2
def evaluate(scope, locals, &block)
-
@output ||= @engine.to_html
-
end
-
-
2
def allows_script?
-
false
-
end
-
end
-
end
-
-
2
require 'tilt/template'
-
-
2
module Tilt
-
# Creole implementation. See:
-
# http://www.wikicreole.org/
-
2
class CreoleTemplate < Template
-
2
def self.engine_initialized?
-
defined? ::Creole
-
end
-
-
2
def initialize_engine
-
require_template_library 'creole'
-
end
-
-
2
def prepare
-
opts = {}
-
[:allowed_schemes, :extensions, :no_escape].each do |k|
-
opts[k] = options[k] if options[k]
-
end
-
@engine = Creole::Parser.new(data, opts)
-
@output = nil
-
end
-
-
2
def evaluate(scope, locals, &block)
-
@output ||= @engine.to_html
-
end
-
-
2
def allows_script?
-
false
-
end
-
end
-
-
# WikiCloth implementation. See:
-
# http://redcloth.org/
-
2
class WikiClothTemplate < Template
-
2
def self.engine_initialized?
-
defined? ::WikiCloth::Parser
-
end
-
-
2
def initialize_engine
-
require_template_library 'wikicloth'
-
end
-
-
2
def prepare
-
@parser = options.delete(:parser) || WikiCloth::Parser
-
@engine = @parser.new options.merge(:data => data)
-
@output = nil
-
end
-
-
2
def evaluate(scope, locals, &block)
-
@output ||= @engine.to_html
-
end
-
-
2
def allows_script?
-
false
-
end
-
end
-
end
-
2
require 'tilt/template'
-
-
2
module Tilt
-
-
# Yajl Template implementation
-
#
-
# Yajl is a fast JSON parsing and encoding library for Ruby
-
# See https://github.com/brianmario/yajl-ruby
-
#
-
# The template source is evaluated as a Ruby string,
-
# and the result is converted #to_json.
-
#
-
# == Example
-
#
-
# # This is a template example.
-
# # The template can contain any Ruby statement.
-
# tpl <<-EOS
-
# @counter = 0
-
#
-
# # The json variable represents the buffer
-
# # and holds the data to be serialized into json.
-
# # It defaults to an empty hash, but you can override it at any time.
-
# json = {
-
# :"user#{@counter += 1}" => { :name => "Joshua Peek", :id => @counter },
-
# :"user#{@counter += 1}" => { :name => "Ryan Tomayko", :id => @counter },
-
# :"user#{@counter += 1}" => { :name => "Simone Carletti", :id => @counter },
-
# }
-
#
-
# # Since the json variable is a Hash,
-
# # you can use conditional statements or any other Ruby statement
-
# # to populate it.
-
# json[:"user#{@counter += 1}"] = { :name => "Unknown" } if 1 == 2
-
#
-
# # The last line doesn't affect the returned value.
-
# nil
-
# EOS
-
#
-
# template = Tilt::YajlTemplate.new { tpl }
-
# template.render(self)
-
#
-
2
class YajlTemplate < Template
-
-
2
self.default_mime_type = 'application/json'
-
-
2
def self.engine_initialized?
-
defined? ::Yajl
-
end
-
-
2
def initialize_engine
-
require_template_library 'yajl'
-
end
-
-
2
def prepare
-
end
-
-
2
def evaluate(scope, locals, &block)
-
decorate super(scope, locals, &block)
-
end
-
-
2
def precompiled_preamble(locals)
-
return super if locals.include? :json
-
"json = {}\n#{super}"
-
end
-
-
2
def precompiled_postamble(locals)
-
"Yajl::Encoder.new.encode(json)"
-
end
-
-
2
def precompiled_template(locals)
-
data.to_str
-
end
-
-
-
# Decorates the +json+ input according to given +options+.
-
#
-
# json - The json String to decorate.
-
# options - The option Hash to customize the behavior.
-
#
-
# Returns the decorated String.
-
2
def decorate(json)
-
callback, variable = options[:callback], options[:variable]
-
if callback && variable
-
"var #{variable} = #{json}; #{callback}(#{variable});"
-
elsif variable
-
"var #{variable} = #{json};"
-
elsif callback
-
"#{callback}(#{json});"
-
else
-
json
-
end
-
end
-
end
-
-
end
-
2
require 'turbolinks/version'
-
2
require 'turbolinks/xhr_headers'
-
2
require 'turbolinks/xhr_url_for'
-
2
require 'turbolinks/cookies'
-
2
require 'turbolinks/x_domain_blocker'
-
2
require 'turbolinks/redirection'
-
-
2
module Turbolinks
-
2
class Engine < ::Rails::Engine
-
2
initializer :turbolinks do |config|
-
2
ActiveSupport.on_load(:action_controller) do
-
2
ActionController::Base.class_eval do
-
2
include XHRHeaders, Cookies, XDomainBlocker, Redirection
-
2
before_filter :set_xhr_redirected_to, :set_request_method_cookie
-
2
after_filter :abort_xdomain_redirect
-
end
-
-
2
ActionDispatch::Request.class_eval do
-
2
def referer
-
self.headers['X-XHR-Referer'] || super
-
end
-
2
alias referrer referer
-
end
-
end
-
-
ActiveSupport.on_load(:action_view) do
-
2
(ActionView::RoutingUrlFor rescue ActionView::Helpers::UrlHelper).module_eval do
-
2
include XHRUrlFor
-
end
-
2
end unless RUBY_VERSION =~ /^1\.8/
-
end
-
end
-
end
-
2
module Turbolinks
-
# For non-GET requests, sets a request_method cookie containing
-
# the request method of the current request. The Turbolinks script
-
# will not initialize if this cookie is set.
-
2
module Cookies
-
2
private
-
2
def set_request_method_cookie
-
24
if request.get?
-
20
cookies.delete(:request_method)
-
else
-
4
cookies[:request_method] = request.request_method
-
end
-
end
-
end
-
end
-
2
module Turbolinks
-
# Provides a means of using Turbolinks to perform redirects. The server
-
# will respond with a JavaScript call to Turbolinks.visit(url).
-
2
module Redirection
-
2
extend ActiveSupport::Concern
-
-
2
def redirect_via_turbolinks_to(url = {}, response_status = {})
-
redirect_to(url, response_status)
-
-
self.status = 200
-
self.response_body = "Turbolinks.visit('#{location}');"
-
response.content_type = Mime::JS
-
end
-
end
-
end
-
2
module Turbolinks
-
2
VERSION = '2.5.3'
-
end
-
2
module Turbolinks
-
# Changes the response status to 403 Forbidden if all of these conditions are true:
-
# - The current request originated from Turbolinks
-
# - The request is being redirected to a different domain
-
2
module XDomainBlocker
-
2
private
-
2
def same_origin?(a, b)
-
a = URI.parse URI.escape(a)
-
b = URI.parse URI.escape(b)
-
[a.scheme, a.host, a.port] == [b.scheme, b.host, b.port]
-
end
-
-
2
def abort_xdomain_redirect
-
24
to_uri = response.headers['Location'] || ""
-
24
current = request.headers['X-XHR-Referer'] || ""
-
24
unless to_uri.blank? || current.blank? || same_origin?(current, to_uri)
-
self.status = 403
-
end
-
end
-
end
-
end
-
2
module Turbolinks
-
# Intercepts calls to _compute_redirect_to_location (used by redirect_to) for two purposes.
-
#
-
# 1. Corrects the behavior of redirect_to with the :back option by using the X-XHR-Referer
-
# request header instead of the standard Referer request header.
-
#
-
# 2. Stores the return value (the redirect target url) to persist through to the redirect
-
# request, where it will be used to set the X-XHR-Redirected-To response header. The
-
# Turbolinks script will detect the header and use replaceState to reflect the redirected
-
# url.
-
2
module XHRHeaders
-
2
extend ActiveSupport::Concern
-
-
2
def _compute_redirect_to_location(*args)
-
options, request = _normalize_redirect_params(args)
-
-
store_for_turbolinks begin
-
if options == :back && request.headers["X-XHR-Referer"]
-
super(*[(request if args.length == 2), request.headers["X-XHR-Referer"]].compact)
-
else
-
super(*args)
-
end
-
end
-
end
-
-
2
private
-
2
def store_for_turbolinks(url)
-
session[:_turbolinks_redirect_to] = url if session && request.headers["X-XHR-Referer"]
-
url
-
end
-
-
2
def set_xhr_redirected_to
-
24
if session && session[:_turbolinks_redirect_to]
-
response.headers['X-XHR-Redirected-To'] = session.delete :_turbolinks_redirect_to
-
end
-
end
-
-
# Ensure backwards compatibility
-
# Rails < 4.2: _compute_redirect_to_location(options)
-
# Rails >= 4.2: _compute_redirect_to_location(request, options)
-
2
def _normalize_redirect_params(args)
-
options, req = args.reverse
-
[options, req || request]
-
end
-
end
-
end
-
2
module Turbolinks
-
# Corrects the behavior of url_for (and link_to, which uses url_for) with the :back
-
# option by using the X-XHR-Referer request header instead of the standard Referer
-
# request header.
-
2
module XHRUrlFor
-
2
def self.included(base)
-
2
base.alias_method_chain :url_for, :xhr_referer
-
end
-
-
2
def url_for_with_xhr_referer(options = {})
-
65
options = (controller.request.headers["X-XHR-Referer"] || options) if options == :back
-
65
url_for_without_xhr_referer options
-
end
-
end
-
end
-
2
module BadgeLabelHelper
-
2
def badge(*args)
-
badge_label(:badge, *args)
-
end
-
-
2
def tag_label(*args)
-
badge_label(:label, *args)
-
end
-
-
2
private
-
2
def badge_label(what, value, type = nil)
-
klass = [what]
-
klass << "#{what}-#{type}" if type.present?
-
content_tag :span, value, :class => "#{klass.join(' ')}"
-
end
-
end
-
2
module BootstrapFlashHelper
-
2
ALERT_TYPES = [:success, :info, :warning, :danger] unless const_defined?(:ALERT_TYPES)
-
-
2
def bootstrap_flash(options = {})
-
flash_messages = []
-
flash.each do |type, message|
-
# Skip empty messages, e.g. for devise messages set to nothing in a locale file.
-
next if message.blank?
-
-
type = type.to_sym
-
type = :success if type == :notice
-
type = :danger if type == :alert
-
type = :danger if type == :error
-
next unless ALERT_TYPES.include?(type)
-
-
tag_class = options.extract!(:class)[:class]
-
tag_options = {
-
class: "alert fade in alert-#{type} #{tag_class}"
-
}.merge(options)
-
-
close_button = content_tag(:button, raw("×"), type: "button", class: "close", "data-dismiss" => "alert")
-
-
Array(message).each do |msg|
-
text = content_tag(:div, close_button + msg, tag_options)
-
flash_messages << text if msg
-
end
-
end
-
flash_messages.join("\n").html_safe
-
end
-
end
-
2
module FlashBlockHelper
-
2
def flash_block
-
output = ''
-
flash.each do |type, message|
-
output += flash_container(type, message)
-
end
-
-
raw(output)
-
end
-
-
2
def flash_container(type, message)
-
raw(content_tag(:div, :class => "alert alert-#{type}") do
-
content_tag(:a, raw("×"),:class => 'close', :data => {:dismiss => 'alert'}) +
-
message
-
end)
-
end
-
end
-
2
module FormErrorsHelper
-
2
include ActionView::Helpers::FormTagHelper
-
-
2
def error_span(attribute, options = {})
-
options[:span_class] ||= 'help-block'
-
options[:error_class] ||= 'has-error'
-
-
if errors_on?(attribute)
-
@template.content_tag( :div, :class => options[:error_class] ) do
-
content_tag( :span, errors_for(attribute), :class => options[:span_class] )
-
end
-
end
-
end
-
-
2
def errors_on?(attribute)
-
object.errors[attribute].present? if object.respond_to?(:errors)
-
end
-
-
2
def errors_for(attribute)
-
object.errors[attribute].try(:join, ', ') || object.errors[attribute].try(:to_s)
-
end
-
end
-
2
module GlyphHelper
-
# ==== Examples
-
# glyph(:share_alt)
-
# # => <span class="icon-share-alt"></span>
-
# glyph(:lock, :white)
-
# # => <span class="icon-lock icon-white"></span>
-
# glyph(:thumbs_up, :pull_left)
-
# # => <i class="icon-thumbs-up pull-left"></i>
-
# glyph(:lock, {tag: :span})
-
# # => <span class="icon-lock"></span>
-
2
def glyph(*names)
-
options = (names.last.kind_of?(Hash)) ? names.pop : {}
-
names.map! { |name| name.to_s.gsub('_','-') }
-
names.map! do |name|
-
name =~ /pull-(?:left|right)/ ? name : "glyphicon glyphicon-#{name}"
-
end
-
options[:tag] = options[:tag] ||= :i
-
content_tag options[:tag], nil, :class => names
-
end
-
end
-
2
module ModalHelper
-
-
#modals have a header, a body, a footer for options.
-
2
def modal_dialog(options = {}, &block)
-
options = {:id => 'modal', :size => '', :show_close => true, :dismiss => true}.merge options
-
content_tag :div, :class => "bootstrap-modal modal fade", :id => options[:id] do
-
content_tag :div, :class => "modal-dialog #{options['size']}" do
-
content_tag :div, :class => "modal-content" do
-
modal_header(options[:header], &block) +
-
modal_body(options[:body], &block) +
-
modal_footer(options[:footer], &block)
-
end
-
end
-
end
-
end
-
-
2
def modal_header(options, &block)
-
content_tag :div, :class => 'modal-header' do
-
if options[:show_close]
-
close_button(options[:dismiss]) +
-
content_tag(:h4, options[:title], :class => 'modal-title', &block)
-
else
-
content_tag(:h4, options[:title], :class => 'modal-title', &block)
-
end
-
end
-
end
-
-
2
def modal_body(options, &block)
-
content_tag :div, options[:content], :class => 'modal-body', :style => options[:style], &block
-
end
-
-
2
def modal_footer(options, &block)
-
content_tag :div, options[:content], :class => 'modal-footer', &block
-
end
-
-
2
def close_button(dismiss)
-
#It doesn't seem to like content_tag, so we do this instead.
-
raw("<button class=\"close\" data-dismiss=\"#{dismiss}\" aria-hidden=\"true\">×</button>")
-
end
-
-
2
def modal_toggle(content_or_options = nil, options, &block)
-
if block_given?
-
options = content_or_options if content_or_options.is_a?(Hash)
-
default_options = { :class => 'btn btn-default', "data-toggle" => "modal", "href" => options[:dialog] }.merge(options)
-
-
content_tag :a, nil, default_options, true, &block
-
else
-
default_options = { :class => 'btn btn-default', "data-toggle" => "modal", "href" => options[:dialog] }.merge(options)
-
content_tag :a, content_or_options, default_options, true
-
end
-
end
-
-
2
def modal_cancel_button(content, options)
-
default_opts = { :class => "btn bootstrap-modal-cancel-button" }
-
-
content_tag_string "a", content, default_opts.merge(options)
-
end
-
-
end
-
#Credit for this goes to https://github.com/julescopeland/Rails-Bootstrap-Navbar
-
2
module NavbarHelper
-
2
def nav_bar(options={}, &block)
-
nav_bar_nav(options) do
-
container_div(options[:brand], options[:brand_link], options[:responsive], options[:fluid], options[:no_turbolink]) do
-
yield if block_given?
-
end
-
end
-
end
-
-
2
def menu_group(options={}, &block)
-
pull_class = "navbar-#{options[:pull].to_s}" if options[:pull].present?
-
content_tag(:ul, :class => "nav navbar-nav #{pull_class}", &block)
-
end
-
-
2
def menu_item(name=nil, path="#", *args, &block)
-
path = name || path if block_given?
-
options = args.extract_options!
-
content_tag :li, :class => is_active?(path, options) do
-
if block_given?
-
link_to path, options, &block
-
else
-
link_to name, path, options, &block
-
end
-
end
-
end
-
-
2
def drop_down(name)
-
content_tag :li, :class => "dropdown" do
-
drop_down_link(name) + drop_down_list { yield }
-
end
-
end
-
-
2
def drop_down_with_submenu(name, &block)
-
content_tag :li, :class => "dropdown" do
-
drop_down_link(name) + drop_down_sublist(&block)
-
end
-
end
-
-
2
def drop_down_sublist(&block)
-
content_tag :ul, :class => "dropdown-menu", &block
-
end
-
-
2
def drop_down_submenu(name, &block)
-
content_tag :li, :class => "dropdown-submenu" do
-
link_to(name, "") + drop_down_list(&block)
-
end
-
end
-
-
2
def drop_down_divider
-
content_tag :li, "", :class => "divider"
-
end
-
-
2
def drop_down_header(text)
-
content_tag :li, text, :class => "nav-header"
-
end
-
-
2
def menu_divider
-
content_tag :li, "", :class => "divider-vertical"
-
end
-
-
2
def menu_text(text=nil, options={}, &block)
-
pull = options.delete(:pull)
-
pull_class = pull.present? ? "pull-#{pull.to_s}" : nil
-
options.append_merge!(:class, pull_class)
-
options.append_merge!(:class, "navbar-text")
-
content_tag :p, options do
-
text || yield
-
end
-
end
-
-
# Returns current url or path state (useful for buttons).
-
# Example:
-
# # Assume we'r currently at blog/categories/test
-
# uri_state('/blog/categories/test', {}) # :active
-
# uri_state('/blog/categories', {}) # :chosen
-
# uri_state('/blog/categories/test', {method: delete}) # :inactive
-
# uri_state('/blog/categories/test/3', {}) # :inactive
-
2
def uri_state(uri, options={})
-
return options[:status] if options.key?(:status)
-
-
root_url = request.host_with_port + '/'
-
root = uri == '/' || uri == root_url
-
-
request_uri = if uri.start_with?(root_url)
-
request.url
-
else
-
request.path
-
end
-
-
if !options[:method].nil? || !options["data-method"].nil?
-
:inactive
-
elsif uri == request_uri || (options[:root] && (request_uri == '/') || (request_uri == root_url))
-
:active
-
else
-
if request_uri.start_with?(uri) and not(root)
-
:chosen
-
else
-
:inactive
-
end
-
end
-
end
-
-
2
private
-
-
2
def nav_bar_nav(options, &block)
-
-
position = "static-#{options[:static].to_s}" if options[:static]
-
position = "fixed-#{options[:fixed].to_s}" if options[:fixed]
-
inverse = (options[:inverse].present? && options[:inverse] == true) ? true : false
-
-
content_tag :nav, :class => nav_bar_css_class(position, inverse), :role => "navigation" do
-
yield
-
end
-
end
-
-
2
def container_div(brand, brand_link, responsive, fluid, no_turbolink, &block)
-
div_container_class = fluid ? "container-fluid" : "container"
-
no_turbolink ||= false
-
-
content_tag :div, :class => div_container_class do
-
container_div_with_block(brand, brand_link, responsive, no_turbolink, &block)
-
end
-
end
-
-
2
def container_div_with_block(brand, brand_link, responsive, no_turbolink, &block)
-
output = []
-
if responsive == true
-
output << responsive_nav_header(brand, brand_link, no_turbolink)
-
output << responsive_div { capture(&block) }
-
else
-
output << brand_link(brand, brand_link, no_turbolink)
-
output << capture(&block)
-
end
-
output.join("\n").html_safe
-
end
-
-
2
def responsive_nav_header(brand, brand_link, no_turbolink)
-
content_tag(:div, :class => "navbar-header") do
-
output = []
-
output << responsive_button
-
output << brand_link(brand, brand_link, no_turbolink)
-
output.join("\n").html_safe
-
end
-
end
-
-
2
def nav_bar_css_class(position, inverse = false)
-
css_class = ["navbar", "navbar-default"]
-
css_class << "navbar-#{position}" if position.present?
-
css_class << "navbar-inverse" if inverse
-
css_class.join(" ")
-
end
-
-
2
def brand_link(name, url, no_turbolink)
-
return "" if name.blank?
-
url ||= root_url
-
-
if no_turbolink
-
link_to(name, url, :class => "navbar-brand", :data => { :no_turbolink => true})
-
else
-
link_to(name, url, :class => "navbar-brand")
-
end
-
end
-
-
2
def responsive_button
-
%{<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
-
<span class="sr-only">Toggle navigation</span>
-
<span class="icon-bar"></span>
-
<span class="icon-bar"></span>
-
<span class="icon-bar"></span>
-
</button>}
-
end
-
-
2
def responsive_div(&block)
-
content_tag(:div, :class => "navbar-collapse collapse", &block)
-
end
-
-
2
def is_active?(path, options={})
-
state = uri_state(path, options)
-
"active" if state.in?([:active, :chosen]) || state === true
-
end
-
-
2
def name_and_caret(name)
-
"#{name} #{content_tag(:b, :class => "caret") {}}".html_safe
-
end
-
-
2
def drop_down_link(name)
-
link_to(name_and_caret(name), "#", :class => "dropdown-toggle", "data-toggle" => "dropdown")
-
end
-
-
2
def drop_down_list(&block)
-
content_tag :ul, :class => "dropdown-menu", &block
-
end
-
end
-
-
2
class Hash
-
# appends a string to a hash key's value after a space character (Good for merging CSS classes in options hashes)
-
2
def append_merge!(key, value)
-
# just return self if value is blank
-
return self if value.blank?
-
-
current_value = self[key]
-
# just merge if it doesn't already have that key
-
self[key] = value and return if current_value.blank?
-
# raise error if we're trying to merge into something that isn't a string
-
raise ArgumentError, "Can only merge strings" unless current_value.is_a?(String)
-
self[key] = [current_value, value].compact.join(" ")
-
end
-
end
-
2
module TwitterBreadcrumbsHelper
-
2
def render_bootstrap_breadcrumbs(divider = '/', options={}, &block)
-
default_options = { :class => '', :item_class => '', :divider_class => '', :active_class => 'active' }.merge(options)
-
content = render :partial => 'twitter-bootstrap/breadcrumbs', :layout => false, :locals => { :divider => divider, options: options }
-
if block_given?
-
capture(content, &block)
-
else
-
content
-
end
-
end
-
-
# Add backward compatible alias unless BC on rails present
-
2
alias_method :render_breadcrumbs, :render_bootstrap_breadcrumbs unless defined?(::BreadcrumbsOnRails)
-
end
-
2
module Twitter
-
2
module Bootstrap
-
2
module Rails
-
2
require 'twitter/bootstrap/rails/engine' if defined?(Rails)
-
end
-
end
-
end
-
-
#require 'less-rails'
-
2
require 'twitter/bootstrap/rails/bootstrap' if defined?(Rails)
-
2
require "twitter/bootstrap/rails/engine"
-
2
require "twitter/bootstrap/rails/version"
-
2
module Twitter
-
2
module Bootstrap
-
-
# Keep current method calls as is using aliases
-
2
module Breadcrumbs
-
2
extend ActiveSupport::Concern
-
2
included do
-
# Used to provide compatibility with breadcrumbs-on-rails gem, if detected
-
# breadcrumbs controller methods won't be overridden.
-
2
if defined?(::BreadcrumbsOnRails)
-
::Rails.logger.info <<-EOT.squish
-
BreadcrumbsOnRails detected it won't be overridden. To use methods from this gem you need to call them
-
using bootstrap prefix i.e. add_bootstrap_breadcrumb and render_bootstrap_breadcrumbs.
-
EOT
-
else
-
# Provide backward compatibility with existing code
-
2
alias_method :add_breadcrumb, :add_bootstrap_breadcrumb
-
2
class << self
-
2
alias_method :add_breadcrumb, :add_bootstrap_breadcrumb
-
end
-
end
-
end
-
-
2
module ClassMethods
-
2
def add_bootstrap_breadcrumb(name, url = '', options = {})
-
options.merge! :klass => self.name
-
before_filter options do |controller|
-
controller.send :add_bootstrap_breadcrumb, name, url, options
-
end
-
end
-
end
-
-
2
protected
-
-
2
def add_bootstrap_breadcrumb(name, url = '', options = {})
-
@__bs_breadcrumbs ||= []
-
-
class_name = options.delete(:klass) || self.class.name
-
-
if name.is_a? Symbol
-
if url.blank?
-
url_helper = :"#{name}_path"
-
url = url_helper if respond_to?(url_helper)
-
end
-
-
name = translate_breadcrumb name, class_name
-
end
-
-
unless name.is_a? String
-
url = polymorphic_path name if url.blank?
-
name = name.to_s
-
end
-
-
url = eval(url.to_s) if url.is_a?(Symbol) && url =~ /_path|_url|@/
-
-
@__bs_breadcrumbs << {:name => name, :url => url, :options => options}
-
end
-
-
2
def translate_breadcrumb(name, class_name)
-
scope = [:breadcrumbs]
-
namespace = class_name.underscore.split('/')
-
namespace.last.sub!('_controller', '')
-
scope += namespace
-
-
I18n.t name, :scope => scope
-
end
-
end
-
end
-
end
-
2
require 'rails'
-
-
2
require_relative 'breadcrumbs.rb'
-
2
require_relative '../../../../app/helpers/flash_block_helper.rb'
-
2
require_relative '../../../../app/helpers/modal_helper.rb'
-
2
require_relative '../../../../app/helpers/navbar_helper.rb'
-
2
require_relative '../../../../app/helpers/bootstrap_flash_helper.rb'
-
2
require_relative '../../../../app/helpers/form_errors_helper.rb'
-
-
2
module Twitter
-
2
module Bootstrap
-
2
module Rails
-
2
class Engine < ::Rails::Engine
-
2
initializer 'twitter-bootstrap-rails.setup',
-
:after => 'less-rails.after.load_config_initializers',
-
:group => :all do |app|
-
2
if defined?(Less)
-
app.config.less.paths << File.join(config.root, 'vendor', 'toolkit')
-
end
-
end
-
-
2
initializer 'twitter-bootstrap-rails.setup_helpers' do |app|
-
2
app.config.to_prepare do
-
2
ActionController::Base.send :include, Breadcrumbs
-
end
-
[FlashBlockHelper,
-
BootstrapFlashHelper,
-
ModalHelper,
-
NavbarHelper,
-
2
BadgeLabelHelper].each do |h|
-
10
app.config.to_prepare do
-
10
ActionController::Base.send :helper, h
-
end
-
end
-
2
ActionView::Helpers::FormBuilder.send :include, FormErrorsHelper
-
end
-
end
-
end
-
end
-
end
-
2
module Twitter
-
2
module Bootstrap
-
2
module Rails
-
2
VERSION = "3.2.2"
-
end
-
end
-
end
-
# Top level module for TZInfo.
-
2
module TZInfo
-
end
-
-
2
require 'tzinfo/ruby_core_support'
-
2
require 'tzinfo/offset_rationals'
-
2
require 'tzinfo/time_or_datetime'
-
-
2
require 'tzinfo/timezone_definition'
-
-
2
require 'tzinfo/timezone_offset'
-
2
require 'tzinfo/timezone_transition'
-
2
require 'tzinfo/timezone_transition_definition'
-
-
2
require 'tzinfo/timezone_index_definition'
-
-
2
require 'tzinfo/timezone_info'
-
2
require 'tzinfo/data_timezone_info'
-
2
require 'tzinfo/linked_timezone_info'
-
2
require 'tzinfo/transition_data_timezone_info'
-
2
require 'tzinfo/zoneinfo_timezone_info'
-
-
2
require 'tzinfo/data_source'
-
2
require 'tzinfo/ruby_data_source'
-
2
require 'tzinfo/zoneinfo_data_source'
-
-
2
require 'tzinfo/timezone_period'
-
2
require 'tzinfo/timezone'
-
2
require 'tzinfo/info_timezone'
-
2
require 'tzinfo/data_timezone'
-
2
require 'tzinfo/linked_timezone'
-
2
require 'tzinfo/timezone_proxy'
-
-
2
require 'tzinfo/country_index_definition'
-
2
require 'tzinfo/country_info'
-
2
require 'tzinfo/ruby_country_info'
-
2
require 'tzinfo/zoneinfo_country_info'
-
-
2
require 'tzinfo/country'
-
2
require 'tzinfo/country_timezone'
-
2
require 'thread_safe'
-
-
2
module TZInfo
-
# Raised by Country#get if the code given is not valid.
-
2
class InvalidCountryCode < StandardError
-
end
-
-
# The Country class represents an ISO 3166-1 country. It can be used to
-
# obtain a list of Timezones for a country. For example:
-
#
-
# us = Country.get('US')
-
# us.zone_identifiers
-
# us.zones
-
# us.zone_info
-
#
-
# The Country class is thread-safe. It is safe to use class and instance
-
# methods of Country in concurrently executing threads. Instances of Country
-
# can be shared across thread boundaries.
-
#
-
# Country information available through TZInfo is intended as an aid for
-
# users, to help them select time zone data appropriate for their practical
-
# needs. It is not intended to take or endorse any position on legal or
-
# territorial claims.
-
2
class Country
-
2
include Comparable
-
-
# Defined countries.
-
#
-
# @!visibility private
-
2
@@countries = nil
-
-
# Whether the countries index has been loaded yet.
-
#
-
# @!visibility private
-
2
@@index_loaded = false
-
-
# Gets a Country by its ISO 3166-1 alpha-2 code. Raises an
-
# InvalidCountryCode exception if it couldn't be found.
-
2
def self.get(identifier)
-
instance = @@countries[identifier]
-
-
unless instance
-
# Thread-safety: It is possible that multiple equivalent Country
-
# instances could be created here in concurrently executing threads.
-
# The consequences of this are that the data may be loaded more than
-
# once (depending on the data source) and memoized calculations could
-
# be discarded. The performance benefit of ensuring that only a single
-
# instance is created is unlikely to be worth the overhead of only
-
# allowing one Country to be loaded at a time.
-
info = data_source.load_country_info(identifier)
-
instance = Country.new(info)
-
@@countries[identifier] = instance
-
end
-
-
instance
-
end
-
-
# If identifier is a CountryInfo object, initializes the Country instance,
-
# otherwise calls get(identifier).
-
2
def self.new(identifier)
-
if identifier.kind_of?(CountryInfo)
-
instance = super()
-
instance.send :setup, identifier
-
instance
-
else
-
get(identifier)
-
end
-
end
-
-
# Returns an Array of all the valid country codes.
-
2
def self.all_codes
-
data_source.country_codes
-
end
-
-
# Returns an Array of all the defined Countries.
-
2
def self.all
-
data_source.country_codes.collect {|code| get(code)}
-
end
-
-
# The ISO 3166-1 alpha-2 country code.
-
2
def code
-
@info.code
-
end
-
-
# The name of the country.
-
2
def name
-
@info.name
-
end
-
-
# Alias for name.
-
2
def to_s
-
name
-
end
-
-
# Returns internal object state as a programmer-readable string.
-
2
def inspect
-
"#<#{self.class}: #{@info.code}>"
-
end
-
-
# Returns a frozen array of all the zone identifiers for the country. These
-
# are in an order that
-
#
-
# 1. makes some geographical sense, and
-
# 2. puts the most populous zones first, where that does not contradict 1.
-
#
-
# Returned zone identifiers may refer to cities and regions outside of the
-
# country. This will occur if the zone covers multiple countries. Any zones
-
# referring to a city or region in a different country will be listed after
-
# those relating to this country.
-
2
def zone_identifiers
-
@info.zone_identifiers
-
end
-
2
alias zone_names zone_identifiers
-
-
# An array of all the Timezones for this country. Returns TimezoneProxy
-
# objects to avoid the overhead of loading Timezone definitions until
-
# a conversion is actually required. The Timezones are returned in an order
-
# that
-
#
-
# 1. makes some geographical sense, and
-
# 2. puts the most populous zones first, where that does not contradict 1.
-
#
-
# Identifiers of the zones returned may refer to cities and regions outside
-
# of the country. This will occur if the zone covers multiple countries. Any
-
# zones referring to a city or region in a different country will be listed
-
# after those relating to this country.
-
2
def zones
-
zone_identifiers.collect {|id|
-
Timezone.get_proxy(id)
-
}
-
end
-
-
# Returns a frozen array of all the timezones for the for the country as
-
# CountryTimezone instances (containing extra information about each zone).
-
# These are in an order that
-
#
-
# 1. makes some geographical sense, and
-
# 2. puts the most populous zones first, where that does not contradict 1.
-
#
-
# Identifiers and descriptions of the zones returned may refer to cities and
-
# regions outside of the country. This will occur if the zone covers
-
# multiple countries. Any zones referring to a city or region in a different
-
# country will be listed after those relating to this country.
-
2
def zone_info
-
@info.zones
-
end
-
-
# Compare two Countries based on their code. Returns -1 if c is less
-
# than self, 0 if c is equal to self and +1 if c is greater than self.
-
#
-
# Returns nil if c is not comparable with Country instances.
-
2
def <=>(c)
-
return nil unless c.is_a?(Country)
-
code <=> c.code
-
end
-
-
# Returns true if and only if the code of c is equal to the code of this
-
# Country.
-
2
def eql?(c)
-
self == c
-
end
-
-
# Returns a hash value for this Country.
-
2
def hash
-
code.hash
-
end
-
-
# Dumps this Country for marshalling.
-
2
def _dump(limit)
-
code
-
end
-
-
# Loads a marshalled Country.
-
2
def self._load(data)
-
Country.get(data)
-
end
-
-
2
private
-
# Called by Country.new to initialize a new Country instance. The info
-
# parameter is a CountryInfo that defines the country.
-
2
def setup(info)
-
@info = info
-
end
-
-
# Initializes @@countries.
-
2
def self.init_countries
-
2
@@countries = ThreadSafe::Cache.new
-
end
-
2
init_countries
-
-
# Returns the current DataSource
-
2
def self.data_source
-
DataSource.get
-
end
-
end
-
end
-
2
module TZInfo
-
# The country index file includes CountryIndexDefinition which provides
-
# a country method used to define each country in the index.
-
#
-
# @private
-
2
module CountryIndexDefinition #:nodoc:
-
2
def self.append_features(base)
-
super
-
base.extend(ClassMethods)
-
base.instance_eval { @countries = {} }
-
end
-
-
# Class methods for inclusion.
-
#
-
# @private
-
2
module ClassMethods #:nodoc:
-
# Defines a country with an ISO 3166 country code, name and block. The
-
# block will be evaluated to obtain all the timezones for the country.
-
# Calls Country.country_defined with the definition of each country.
-
2
def country(code, name, &block)
-
@countries[code] = RubyCountryInfo.new(code, name, &block)
-
end
-
-
# Returns a frozen hash of all the countries that have been defined in
-
# the index.
-
2
def countries
-
@countries.freeze
-
end
-
end
-
end
-
end
-
2
module TZInfo
-
# Represents a country and references to its timezones as returned by a
-
# DataSource.
-
2
class CountryInfo
-
# The ISO 3166 country code.
-
2
attr_reader :code
-
-
# The name of the country.
-
2
attr_reader :name
-
-
# Constructs a new CountryInfo with an ISO 3166 country code and name
-
2
def initialize(code, name)
-
498
@code = code
-
498
@name = name
-
end
-
-
# Returns internal object state as a programmer-readable string.
-
2
def inspect
-
"#<#{self.class}: #@code>"
-
end
-
-
# Returns a frozen array of all the zone identifiers for the country.
-
# The identifiers are ordered by importance according to the DataSource.
-
2
def zone_identifiers
-
raise_not_implemented('zone_identifiers')
-
end
-
-
# Returns a frozen array of all the timezones for the for the country as
-
# CountryTimezone instances.
-
#
-
# The timezones are ordered by importance according to the DataSource.
-
2
def zones
-
raise_not_implemented('zones')
-
end
-
-
2
private
-
-
2
def raise_not_implemented(method_name)
-
raise NotImplementedError, "Subclasses must override #{method_name}"
-
end
-
end
-
end
-
2
module TZInfo
-
# A Timezone within a Country. This contains extra information about the
-
# Timezone that is specific to the Country (a Timezone could be used by
-
# multiple countries).
-
2
class CountryTimezone
-
# The zone identifier.
-
2
attr_reader :identifier
-
-
# A description of this timezone in relation to the country, e.g.
-
# "Eastern Time". This is usually nil for countries having only a single
-
# Timezone.
-
2
attr_reader :description
-
-
2
class << self
-
# Creates a new CountryTimezone with a timezone identifier, latitude,
-
# longitude and description. The latitude and longitude are specified as
-
# rationals - a numerator and denominator. For performance reasons, the
-
# numerators and denominators must be specified in their lowest form.
-
#
-
# For use internally within TZInfo.
-
#
-
# @!visibility private
-
2
alias :new! :new
-
-
# Creates a new CountryTimezone with a timezone identifier, latitude,
-
# longitude and description. The latitude and longitude must be specified
-
# as instances of Rational.
-
#
-
# CountryTimezone instances should normally only be constructed when
-
# creating new DataSource implementations.
-
2
def new(identifier, latitude, longitude, description = nil)
-
834
super(identifier, latitude, nil, longitude, nil, description)
-
end
-
end
-
-
# Creates a new CountryTimezone with a timezone identifier, latitude,
-
# longitude and description. The latitude and longitude are specified as
-
# rationals - a numerator and denominator. For performance reasons, the
-
# numerators and denominators must be specified in their lowest form.
-
#
-
# @!visibility private
-
2
def initialize(identifier, latitude_numerator, latitude_denominator,
-
longitude_numerator, longitude_denominator, description = nil) #:nodoc:
-
834
@identifier = identifier
-
-
834
if latitude_numerator.kind_of?(Rational)
-
834
@latitude = latitude_numerator
-
else
-
@latitude = nil
-
@latitude_numerator = latitude_numerator
-
@latitude_denominator = latitude_denominator
-
end
-
-
834
if longitude_numerator.kind_of?(Rational)
-
834
@longitude = longitude_numerator
-
else
-
@longitude = nil
-
@longitude_numerator = longitude_numerator
-
@longitude_denominator = longitude_denominator
-
end
-
-
834
@description = description
-
end
-
-
# The Timezone (actually a TimezoneProxy for performance reasons).
-
2
def timezone
-
Timezone.get_proxy(@identifier)
-
end
-
-
# if description is not nil, this method returns description; otherwise it
-
# returns timezone.friendly_identifier(true).
-
2
def description_or_friendly_identifier
-
description || timezone.friendly_identifier(true)
-
end
-
-
# The latitude of this timezone in degrees as a Rational.
-
2
def latitude
-
# Thread-safety: It is possible that the value of @latitude may be
-
# calculated multiple times in concurrently executing threads. It is not
-
# worth the overhead of locking to ensure that @latitude is only
-
# calculated once.
-
@latitude ||= RubyCoreSupport.rational_new!(@latitude_numerator, @latitude_denominator)
-
end
-
-
# The longitude of this timezone in degrees as a Rational.
-
2
def longitude
-
# Thread-safety: It is possible that the value of @longitude may be
-
# calculated multiple times in concurrently executing threads. It is not
-
# worth the overhead of locking to ensure that @longitude is only
-
# calculated once.
-
@longitude ||= RubyCoreSupport.rational_new!(@longitude_numerator, @longitude_denominator)
-
end
-
-
# Returns true if and only if the given CountryTimezone is equal to the
-
# current CountryTimezone (has the same identifer, latitude, longitude
-
# and description).
-
2
def ==(ct)
-
ct.kind_of?(CountryTimezone) &&
-
identifier == ct.identifier && latitude == ct.latitude &&
-
longitude == ct.longitude && description == ct.description
-
end
-
-
# Returns true if and only if the given CountryTimezone is equal to the
-
# current CountryTimezone (has the same identifer, latitude, longitude
-
# and description).
-
2
def eql?(ct)
-
self == ct
-
end
-
-
# Returns a hash of this CountryTimezone.
-
2
def hash
-
@identifier.hash ^
-
(@latitude ? @latitude.numerator.hash ^ @latitude.denominator.hash : @latitude_numerator.hash ^ @latitude_denominator.hash) ^
-
(@longitude ? @longitude.numerator.hash ^ @longitude.denominator.hash : @longitude_numerator.hash ^ @longitude_denominator.hash) ^
-
@description.hash
-
end
-
-
# Returns internal object state as a programmer-readable string.
-
2
def inspect
-
"#<#{self.class}: #@identifier>"
-
end
-
end
-
end
-
2
require 'thread'
-
-
2
module TZInfo
-
# InvalidDataSource is raised if the DataSource is used doesn't implement one
-
# of the required methods.
-
2
class InvalidDataSource < StandardError
-
end
-
-
# DataSourceNotFound is raised if no data source could be found (i.e.
-
# if 'tzinfo/data' cannot be found on the load path and no valid zoneinfo
-
# directory can be found on the system).
-
2
class DataSourceNotFound < StandardError
-
end
-
-
# The base class for data sources of timezone and country data.
-
#
-
# Use DataSource.set to change the data source being used.
-
2
class DataSource
-
# The currently selected data source.
-
2
@@instance = nil
-
-
# Mutex used to ensure the default data source is only created once.
-
2
@@default_mutex = Mutex.new
-
-
# Returns the currently selected DataSource instance.
-
2
def self.get
-
# If a DataSource hasn't been manually set when the first request is
-
# made to obtain a DataSource, then a Default data source is created.
-
-
# This is done at the first request rather than when TZInfo is loaded to
-
# avoid unnecessary (or in some cases potentially harmful) attempts to
-
# find a suitable DataSource.
-
-
# A Mutex is used to ensure that only a single default instance is
-
# created (having two different DataSources in use simultaneously could
-
# cause unexpected results).
-
-
2
unless @@instance
-
2
@@default_mutex.synchronize do
-
2
set(create_default_data_source) unless @@instance
-
end
-
end
-
-
2
@@instance
-
end
-
-
# Sets the currently selected data source for Timezone and Country data.
-
#
-
# This should usually be set to one of the two standard data source types:
-
#
-
# * +:ruby+ - read data from the Ruby modules included in the TZInfo::Data
-
# library (tzinfo-data gem).
-
# * +:zoneinfo+ - read data from the zoneinfo files included with most
-
# Unix-like operating sytems (e.g. in /usr/share/zoneinfo).
-
#
-
# To set TZInfo to use one of the standard data source types, call
-
# \TZInfo::DataSource.set in one of the following ways:
-
#
-
# TZInfo::DataSource.set(:ruby)
-
# TZInfo::DataSource.set(:zoneinfo)
-
# TZInfo::DataSource.set(:zoneinfo, zoneinfo_dir)
-
# TZInfo::DataSource.set(:zoneinfo, zoneinfo_dir, iso3166_tab_file)
-
#
-
# \DataSource.set(:zoneinfo) will automatically search for the zoneinfo
-
# directory by checking the paths specified in
-
# ZoneinfoDataSource.search_paths. ZoneinfoDirectoryNotFound will be raised
-
# if no valid zoneinfo directory could be found.
-
#
-
# \DataSource.set(:zoneinfo, zoneinfo_dir) uses the specified zoneinfo
-
# directory as the data source. If the directory is not a valid zoneinfo
-
# directory, an InvalidZoneinfoDirectory exception will be raised.
-
#
-
# \DataSource.set(:zoneinfo, zoneinfo_dir, iso3166_tab_file) uses the
-
# specified zoneinfo directory as the data source, but loads the iso3166.tab
-
# file from an alternate path. If the directory is not a valid zoneinfo
-
# directory, an InvalidZoneinfoDirectory exception will be raised.
-
#
-
# Custom data sources can be created by subclassing TZInfo::DataSource and
-
# implementing the following methods:
-
#
-
# * \load_timezone_info
-
# * \timezone_identifiers
-
# * \data_timezone_identifiers
-
# * \linked_timezone_identifiers
-
# * \load_country_info
-
# * \country_codes
-
#
-
# To have TZInfo use the custom data source, call \DataSource.set
-
# as follows:
-
#
-
# TZInfo::DataSource.set(CustomDataSource.new)
-
#
-
# To avoid inconsistent data, \DataSource.set should be called before
-
# accessing any Timezone or Country data.
-
#
-
# If \DataSource.set is not called, TZInfo will by default use TZInfo::Data
-
# as the data source. If TZInfo::Data is not available (i.e. if require
-
# 'tzinfo/data' fails), then TZInfo will search for a zoneinfo directory
-
# instead (using the search path specified by
-
# TZInfo::ZoneinfoDataSource::DEFAULT_SEARCH_PATH).
-
2
def self.set(data_source_or_type, *args)
-
2
if data_source_or_type.kind_of?(DataSource)
-
2
@@instance = data_source_or_type
-
elsif data_source_or_type == :ruby
-
@@instance = RubyDataSource.new
-
elsif data_source_or_type == :zoneinfo
-
@@instance = ZoneinfoDataSource.new(*args)
-
else
-
raise ArgumentError, 'data_source_or_type must be a DataSource instance or a data source type (:ruby)'
-
end
-
end
-
-
# Returns a TimezoneInfo instance for a given identifier. The TimezoneInfo
-
# instance should derive from either DataTimzoneInfo for timezones that
-
# define their own data or LinkedTimezoneInfo for links or aliases to
-
# other timezones.
-
#
-
# Raises InvalidTimezoneIdentifier if the timezone is not found or the
-
# identifier is invalid.
-
2
def load_timezone_info(identifier)
-
raise_invalid_data_source('load_timezone_info')
-
end
-
-
# Returns an array of all the available timezone identifiers.
-
2
def timezone_identifiers
-
raise_invalid_data_source('timezone_identifiers')
-
end
-
-
# Returns an array of all the available timezone identifiers for
-
# data timezones (i.e. those that actually contain definitions).
-
2
def data_timezone_identifiers
-
raise_invalid_data_source('data_timezone_identifiers')
-
end
-
-
# Returns an array of all the available timezone identifiers that
-
# are links to other timezones.
-
2
def linked_timezone_identifiers
-
raise_invalid_data_source('linked_timezone_identifiers')
-
end
-
-
# Returns a CountryInfo instance for the given ISO 3166-1 alpha-2
-
# country code. Raises InvalidCountryCode if the country could not be found
-
# or the code is invalid.
-
2
def load_country_info(code)
-
raise_invalid_data_source('load_country_info')
-
end
-
-
# Returns an array of all the available ISO 3166-1 alpha-2
-
# country codes.
-
2
def country_codes
-
raise_invalid_data_source('country_codes')
-
end
-
-
# Returns the name of this DataSource.
-
2
def to_s
-
"Default DataSource"
-
end
-
-
# Returns internal object state as a programmer-readable string.
-
2
def inspect
-
"#<#{self.class}>"
-
end
-
-
2
private
-
-
# Creates a DataSource instance for use as the default. Used if
-
# no preference has been specified manually.
-
2
def self.create_default_data_source
-
2
has_tzinfo_data = false
-
-
2
begin
-
2
require 'tzinfo/data'
-
has_tzinfo_data = true
-
rescue LoadError
-
end
-
-
2
return RubyDataSource.new if has_tzinfo_data
-
-
2
begin
-
2
return ZoneinfoDataSource.new
-
rescue ZoneinfoDirectoryNotFound
-
raise DataSourceNotFound, "No source of timezone data could be found.\nPlease refer to http://tzinfo.github.io/datasourcenotfound for help resolving this error."
-
end
-
end
-
-
2
def raise_invalid_data_source(method_name)
-
raise InvalidDataSource, "#{method_name} not defined"
-
end
-
end
-
end
-
2
module TZInfo
-
-
# A Timezone based on a DataTimezoneInfo.
-
#
-
# @private
-
2
class DataTimezone < InfoTimezone #:nodoc:
-
-
# Returns the TimezonePeriod for the given UTC time. utc can either be
-
# a DateTime, Time or integer timestamp (Time.to_i). Any timezone
-
# information in utc is ignored (it is treated as a UTC time).
-
#
-
# If no TimezonePeriod could be found, PeriodNotFound is raised.
-
2
def period_for_utc(utc)
-
536
info.period_for_utc(utc)
-
end
-
-
# Returns the set of TimezonePeriod instances that are valid for the given
-
# local time as an array. If you just want a single period, use
-
# period_for_local instead and specify how abiguities should be resolved.
-
# Raises PeriodNotFound if no periods are found for the given time.
-
2
def periods_for_local(local)
-
info.periods_for_local(local)
-
end
-
-
# Returns an Array of TimezoneTransition instances representing the times
-
# where the UTC offset of the timezone changes.
-
#
-
# Transitions are returned up to a given date and time up to a given date
-
# and time, specified in UTC (utc_to).
-
#
-
# A from date and time may also be supplied using the utc_from parameter
-
# (also specified in UTC). If utc_from is not nil, only transitions from
-
# that date and time onwards will be returned.
-
#
-
# Comparisons with utc_to are exclusive. Comparisons with utc_from are
-
# inclusive. If a transition falls precisely on utc_to, it will be excluded.
-
# If a transition falls on utc_from, it will be included.
-
#
-
# Transitions returned are ordered by when they occur, from earliest to
-
# latest.
-
#
-
# utc_to and utc_from can be specified using either DateTime, Time or
-
# integer timestamps (Time.to_i).
-
#
-
# If utc_from is specified and utc_to is not greater than utc_from, then
-
# transitions_up_to raises an ArgumentError exception.
-
2
def transitions_up_to(utc_to, utc_from = nil)
-
info.transitions_up_to(utc_to, utc_from)
-
end
-
-
# Returns the canonical zone for this Timezone.
-
#
-
# For a DataTimezone, this is always self.
-
2
def canonical_zone
-
self
-
end
-
end
-
end
-
2
module TZInfo
-
# Represents a defined timezone containing transition data.
-
2
class DataTimezoneInfo < TimezoneInfo
-
-
# Returns the TimezonePeriod for the given UTC time.
-
2
def period_for_utc(utc)
-
raise_not_implemented('period_for_utc')
-
end
-
-
# Returns the set of TimezonePeriods for the given local time as an array.
-
# Results returned are ordered by increasing UTC start date.
-
# Returns an empty array if no periods are found for the given time.
-
2
def periods_for_local(local)
-
raise_not_implemented('periods_for_local')
-
end
-
-
# Returns an Array of TimezoneTransition instances representing the times
-
# where the UTC offset of the timezone changes.
-
#
-
# Transitions are returned up to a given date and time up to a given date
-
# and time, specified in UTC (utc_to).
-
#
-
# A from date and time may also be supplied using the utc_from parameter
-
# (also specified in UTC). If utc_from is not nil, only transitions from
-
# that date and time onwards will be returned.
-
#
-
# Comparisons with utc_to are exclusive. Comparisons with utc_from are
-
# inclusive. If a transition falls precisely on utc_to, it will be excluded.
-
# If a transition falls on utc_from, it will be included.
-
#
-
# Transitions returned are ordered by when they occur, from earliest to
-
# latest.
-
#
-
# utc_to and utc_from can be specified using either DateTime, Time or
-
# integer timestamps (Time.to_i).
-
#
-
# If utc_from is specified and utc_to is not greater than utc_from, then
-
# transitions_up_to raises an ArgumentError exception.
-
2
def transitions_up_to(utc_to, utc_from = nil)
-
raise_not_implemented('transitions_up_to')
-
end
-
-
# Constructs a Timezone instance for the timezone represented by this
-
# DataTimezoneInfo.
-
2
def create_timezone
-
2
DataTimezone.new(self)
-
end
-
-
2
private
-
-
2
def raise_not_implemented(method_name)
-
raise NotImplementedError, "Subclasses must override #{method_name}"
-
end
-
end
-
end
-
2
module TZInfo
-
-
# A Timezone based on a TimezoneInfo.
-
#
-
# @private
-
2
class InfoTimezone < Timezone #:nodoc:
-
-
# Constructs a new InfoTimezone with a TimezoneInfo instance.
-
2
def self.new(info)
-
2
tz = super()
-
2
tz.send(:setup, info)
-
2
tz
-
end
-
-
# The identifier of the timezone, e.g. "Europe/Paris".
-
2
def identifier
-
2
@info.identifier
-
end
-
-
2
protected
-
# The TimezoneInfo for this Timezone.
-
2
def info
-
536
@info
-
end
-
-
2
def setup(info)
-
2
@info = info
-
end
-
end
-
end
-
2
module TZInfo
-
-
# A Timezone based on a LinkedTimezoneInfo.
-
#
-
# @private
-
2
class LinkedTimezone < InfoTimezone #:nodoc:
-
# Returns the TimezonePeriod for the given UTC time. utc can either be
-
# a DateTime, Time or integer timestamp (Time.to_i). Any timezone
-
# information in utc is ignored (it is treated as a UTC time).
-
#
-
# If no TimezonePeriod could be found, PeriodNotFound is raised.
-
2
def period_for_utc(utc)
-
@linked_timezone.period_for_utc(utc)
-
end
-
-
# Returns the set of TimezonePeriod instances that are valid for the given
-
# local time as an array. If you just want a single period, use
-
# period_for_local instead and specify how abiguities should be resolved.
-
# Raises PeriodNotFound if no periods are found for the given time.
-
2
def periods_for_local(local)
-
@linked_timezone.periods_for_local(local)
-
end
-
-
# Returns an Array of TimezoneTransition instances representing the times
-
# where the UTC offset of the timezone changes.
-
#
-
# Transitions are returned up to a given date and time up to a given date
-
# and time, specified in UTC (utc_to).
-
#
-
# A from date and time may also be supplied using the utc_from parameter
-
# (also specified in UTC). If utc_from is not nil, only transitions from
-
# that date and time onwards will be returned.
-
#
-
# Comparisons with utc_to are exclusive. Comparisons with utc_from are
-
# inclusive. If a transition falls precisely on utc_to, it will be excluded.
-
# If a transition falls on utc_from, it will be included.
-
#
-
# Transitions returned are ordered by when they occur, from earliest to
-
# latest.
-
#
-
# utc_to and utc_from can be specified using either DateTime, Time or
-
# integer timestamps (Time.to_i).
-
#
-
# If utc_from is specified and utc_to is not greater than utc_from, then
-
# transitions_up_to raises an ArgumentError exception.
-
2
def transitions_up_to(utc_to, utc_from = nil)
-
@linked_timezone.transitions_up_to(utc_to, utc_from)
-
end
-
-
# Returns the canonical zone for this Timezone.
-
#
-
# For a LinkedTimezone, this is the canonical zone of the link target.
-
2
def canonical_zone
-
@linked_timezone.canonical_zone
-
end
-
-
2
protected
-
2
def setup(info)
-
super(info)
-
@linked_timezone = Timezone.get(info.link_to_identifier)
-
end
-
end
-
end
-
2
module TZInfo
-
# Represents a timezone that is defined as a link or alias to another zone.
-
2
class LinkedTimezoneInfo < TimezoneInfo
-
-
# The zone that provides the data (that this zone is an alias for).
-
2
attr_reader :link_to_identifier
-
-
# Constructs a new LinkedTimezoneInfo with an identifier and the identifier
-
# of the zone linked to.
-
2
def initialize(identifier, link_to_identifier)
-
super(identifier)
-
@link_to_identifier = link_to_identifier
-
end
-
-
# Returns internal object state as a programmer-readable string.
-
2
def inspect
-
"#<#{self.class}: #@identifier,#@link_to_identifier>"
-
end
-
-
# Constructs a Timezone instance for the timezone represented by this
-
# DataTimezoneInfo.
-
2
def create_timezone
-
LinkedTimezone.new(self)
-
end
-
end
-
end
-
2
require 'rational' unless defined?(Rational)
-
-
2
module TZInfo
-
-
# Provides a method for getting Rationals for a timezone offset in seconds.
-
# Pre-reduced rationals are returned for all the half-hour intervals between
-
# -14 and +14 hours to avoid having to call gcd at runtime.
-
#
-
# @private
-
2
module OffsetRationals #:nodoc:
-
2
@@rational_cache = {
-
-50400 => RubyCoreSupport.rational_new!(-7,12),
-
-48600 => RubyCoreSupport.rational_new!(-9,16),
-
-46800 => RubyCoreSupport.rational_new!(-13,24),
-
-45000 => RubyCoreSupport.rational_new!(-25,48),
-
-43200 => RubyCoreSupport.rational_new!(-1,2),
-
-41400 => RubyCoreSupport.rational_new!(-23,48),
-
-39600 => RubyCoreSupport.rational_new!(-11,24),
-
-37800 => RubyCoreSupport.rational_new!(-7,16),
-
-36000 => RubyCoreSupport.rational_new!(-5,12),
-
-34200 => RubyCoreSupport.rational_new!(-19,48),
-
-32400 => RubyCoreSupport.rational_new!(-3,8),
-
-30600 => RubyCoreSupport.rational_new!(-17,48),
-
-28800 => RubyCoreSupport.rational_new!(-1,3),
-
-27000 => RubyCoreSupport.rational_new!(-5,16),
-
-25200 => RubyCoreSupport.rational_new!(-7,24),
-
-23400 => RubyCoreSupport.rational_new!(-13,48),
-
-21600 => RubyCoreSupport.rational_new!(-1,4),
-
-19800 => RubyCoreSupport.rational_new!(-11,48),
-
-18000 => RubyCoreSupport.rational_new!(-5,24),
-
-16200 => RubyCoreSupport.rational_new!(-3,16),
-
-14400 => RubyCoreSupport.rational_new!(-1,6),
-
-12600 => RubyCoreSupport.rational_new!(-7,48),
-
-10800 => RubyCoreSupport.rational_new!(-1,8),
-
-9000 => RubyCoreSupport.rational_new!(-5,48),
-
-7200 => RubyCoreSupport.rational_new!(-1,12),
-
-5400 => RubyCoreSupport.rational_new!(-1,16),
-
-3600 => RubyCoreSupport.rational_new!(-1,24),
-
-1800 => RubyCoreSupport.rational_new!(-1,48),
-
0 => RubyCoreSupport.rational_new!(0,1),
-
1800 => RubyCoreSupport.rational_new!(1,48),
-
3600 => RubyCoreSupport.rational_new!(1,24),
-
5400 => RubyCoreSupport.rational_new!(1,16),
-
7200 => RubyCoreSupport.rational_new!(1,12),
-
9000 => RubyCoreSupport.rational_new!(5,48),
-
10800 => RubyCoreSupport.rational_new!(1,8),
-
12600 => RubyCoreSupport.rational_new!(7,48),
-
14400 => RubyCoreSupport.rational_new!(1,6),
-
16200 => RubyCoreSupport.rational_new!(3,16),
-
18000 => RubyCoreSupport.rational_new!(5,24),
-
19800 => RubyCoreSupport.rational_new!(11,48),
-
21600 => RubyCoreSupport.rational_new!(1,4),
-
23400 => RubyCoreSupport.rational_new!(13,48),
-
25200 => RubyCoreSupport.rational_new!(7,24),
-
27000 => RubyCoreSupport.rational_new!(5,16),
-
28800 => RubyCoreSupport.rational_new!(1,3),
-
30600 => RubyCoreSupport.rational_new!(17,48),
-
32400 => RubyCoreSupport.rational_new!(3,8),
-
34200 => RubyCoreSupport.rational_new!(19,48),
-
36000 => RubyCoreSupport.rational_new!(5,12),
-
37800 => RubyCoreSupport.rational_new!(7,16),
-
39600 => RubyCoreSupport.rational_new!(11,24),
-
41400 => RubyCoreSupport.rational_new!(23,48),
-
43200 => RubyCoreSupport.rational_new!(1,2),
-
45000 => RubyCoreSupport.rational_new!(25,48),
-
46800 => RubyCoreSupport.rational_new!(13,24),
-
48600 => RubyCoreSupport.rational_new!(9,16),
-
50400 => RubyCoreSupport.rational_new!(7,12)}.freeze
-
-
# Returns a Rational expressing the fraction of a day that offset in
-
# seconds represents (i.e. equivalent to Rational(offset, 86400)).
-
2
def rational_for_offset(offset)
-
@@rational_cache[offset] || Rational(offset, 86400)
-
end
-
2
module_function :rational_for_offset
-
end
-
end
-
2
require 'date'
-
2
require 'rational' unless defined?(Rational)
-
-
2
module TZInfo
-
-
# Methods to support different versions of Ruby.
-
#
-
# @private
-
2
module RubyCoreSupport #:nodoc:
-
-
# Use Rational.new! for performance reasons in Ruby 1.8.
-
# This has been removed from 1.9, but Rational performs better.
-
2
if Rational.respond_to? :new!
-
def self.rational_new!(numerator, denominator = 1)
-
Rational.new!(numerator, denominator)
-
end
-
else
-
2
def self.rational_new!(numerator, denominator = 1)
-
116
Rational(numerator, denominator)
-
end
-
end
-
-
# Ruby 1.8.6 introduced new! and deprecated new0.
-
# Ruby 1.9.0 removed new0.
-
# Ruby trunk revision 31668 removed the new! method.
-
# Still support new0 for better performance on older versions of Ruby (new0 indicates
-
# that the rational has already been reduced to its lowest terms).
-
# Fallback to jd with conversion from ajd if new! and new0 are unavailable.
-
2
if DateTime.respond_to? :new!
-
def self.datetime_new!(ajd = 0, of = 0, sg = Date::ITALY)
-
DateTime.new!(ajd, of, sg)
-
end
-
elsif DateTime.respond_to? :new0
-
def self.datetime_new!(ajd = 0, of = 0, sg = Date::ITALY)
-
DateTime.new0(ajd, of, sg)
-
end
-
else
-
2
HALF_DAYS_IN_DAY = rational_new!(1, 2)
-
-
2
def self.datetime_new!(ajd = 0, of = 0, sg = Date::ITALY)
-
# Convert from an Astronomical Julian Day number to a civil Julian Day number.
-
jd = ajd + of + HALF_DAYS_IN_DAY
-
-
# Ruby trunk revision 31862 changed the behaviour of DateTime.jd so that it will no
-
# longer accept a fractional civil Julian Day number if further arguments are specified.
-
# Calculate the hours, minutes and seconds to pass to jd.
-
-
jd_i = jd.to_i
-
jd_i -= 1 if jd < 0
-
hours = (jd - jd_i) * 24
-
hours_i = hours.to_i
-
minutes = (hours - hours_i) * 60
-
minutes_i = minutes.to_i
-
seconds = (minutes - minutes_i) * 60
-
-
DateTime.jd(jd_i, hours_i, minutes_i, seconds, of, sg)
-
end
-
end
-
-
# DateTime in Ruby 1.8.6 doesn't consider times within the 60th second to be
-
# valid. When attempting to specify such a DateTime, subtract the fractional
-
# part and then add it back later
-
2
if Date.respond_to?(:valid_time?) && !Date.valid_time?(0, 0, rational_new!(59001, 1000)) # 0:0:59.001
-
def self.datetime_new(y=-4712, m=1, d=1, h=0, min=0, s=0, of=0, sg=Date::ITALY)
-
if !s.kind_of?(Integer) && s > 59
-
dt = DateTime.new(y, m, d, h, min, 59, of, sg)
-
dt + (s - 59) / 86400
-
else
-
DateTime.new(y, m, d, h, min, s, of, sg)
-
end
-
end
-
else
-
2
def self.datetime_new(y=-4712, m=1, d=1, h=0, min=0, s=0, of=0, sg=Date::ITALY)
-
DateTime.new(y, m, d, h, min, s, of, sg)
-
end
-
end
-
-
# Returns true if Time on the runtime platform supports Times defined
-
# by negative 32-bit timestamps, otherwise false.
-
2
begin
-
2
Time.at(-1)
-
2
Time.at(-2147483648)
-
-
2
def self.time_supports_negative
-
true
-
end
-
rescue ArgumentError
-
def self.time_supports_negative
-
false
-
end
-
end
-
-
# Returns true if Time on the runtime platform supports Times defined by
-
# 64-bit timestamps, otherwise false.
-
2
begin
-
2
Time.at(-2147483649)
-
2
Time.at(2147483648)
-
-
2
def self.time_supports_64bit
-
2
true
-
end
-
rescue RangeError
-
def self.time_supports_64bit
-
false
-
end
-
end
-
-
# Return the result of Time#nsec if it exists, otherwise return the
-
# result of Time#usec * 1000.
-
2
if Time.method_defined?(:nsec)
-
2
def self.time_nsec(time)
-
534
time.nsec
-
end
-
else
-
def self.time_nsec(time)
-
time.usec * 1000
-
end
-
end
-
-
# Call String#force_encoding if this version of Ruby has encoding support
-
# otherwise treat as a no-op.
-
2
if String.method_defined?(:force_encoding)
-
2
def self.force_encoding(str, encoding)
-
2
str.force_encoding(encoding)
-
end
-
else
-
def self.force_encoding(str, encoding)
-
str
-
end
-
end
-
-
-
# Wrapper for File.open that supports passing hash options for specifying
-
# encodings on Ruby 1.9+. The options are ignored on earlier versions of
-
# Ruby.
-
2
if RUBY_VERSION =~ /\A1\.[0-8]\./
-
def self.open_file(file_name, mode, opts, &block)
-
File.open(file_name, mode, &block)
-
end
-
else
-
2
def self.open_file(file_name, mode, opts, &block)
-
4
File.open(file_name, mode, opts, &block)
-
end
-
end
-
end
-
end
-
2
module TZInfo
-
# Represents information about a country returned by RubyDataSource.
-
#
-
# @private
-
2
class RubyCountryInfo < CountryInfo #:nodoc:
-
# Constructs a new CountryInfo with an ISO 3166 country code, name and
-
# block. The block will be evaluated to obtain the timezones for the
-
# country when the zones are first needed.
-
2
def initialize(code, name, &block)
-
super(code, name)
-
@block = block
-
@zones = nil
-
@zone_identifiers = nil
-
end
-
-
# Returns a frozen array of all the zone identifiers for the country. These
-
# are in the order they were added using the timezone method.
-
2
def zone_identifiers
-
# Thread-safety: It is possible that the value of @zone_identifiers may be
-
# calculated multiple times in concurrently executing threads. It is not
-
# worth the overhead of locking to ensure that @zone_identifiers is only
-
# calculated once.
-
-
unless @zone_identifiers
-
@zone_identifiers = zones.collect {|zone| zone.identifier}.freeze
-
end
-
-
@zone_identifiers
-
end
-
-
# Returns a frozen array of all the timezones for the for the country as
-
# CountryTimezone instances. These are in the order they were added using
-
# the timezone method.
-
2
def zones
-
# Thread-safety: It is possible that the value of @zones may be
-
# calculated multiple times in concurrently executing threads. It is not
-
# worth the overhead of locking to ensure that @zones is only
-
# calculated once.
-
-
unless @zones
-
zones = Zones.new
-
@block.call(zones) if @block
-
@block = nil
-
@zones = zones.list.freeze
-
end
-
-
@zones
-
end
-
-
# An instance of the Zones class is passed to the block used to define
-
# timezones.
-
#
-
# @private
-
2
class Zones #:nodoc:
-
2
attr_reader :list
-
-
2
def initialize
-
@list = []
-
end
-
-
# Called by the index data to define a timezone for the country.
-
2
def timezone(identifier, latitude_numerator, latitude_denominator,
-
longitude_numerator, longitude_denominator, description = nil)
-
@list << CountryTimezone.new!(identifier, latitude_numerator,
-
latitude_denominator, longitude_numerator, longitude_denominator,
-
description)
-
end
-
end
-
end
-
end
-
2
module TZInfo
-
# A DataSource that loads data from the set of Ruby modules included in the
-
# TZInfo::Data library (tzinfo-data gem).
-
#
-
# To have TZInfo use this DataSource, call TZInfo::DataSource.set as follows:
-
#
-
# TZInfo::DataSource.set(:ruby)
-
2
class RubyDataSource < DataSource
-
# Base path for require.
-
2
REQUIRE_PATH = File.join('tzinfo', 'data', 'definitions')
-
-
# Whether the timezone index has been loaded yet.
-
2
@@timezone_index_loaded = false
-
-
# Whether the country index has been loaded yet.
-
2
@@country_index_loaded = false
-
-
# Returns a TimezoneInfo instance for a given identifier.
-
# Raises InvalidTimezoneIdentifier if the timezone is not found or the
-
# identifier is invalid.
-
2
def load_timezone_info(identifier)
-
raise InvalidTimezoneIdentifier, 'Invalid identifier' if identifier !~ /^[A-Za-z0-9\+\-_]+(\/[A-Za-z0-9\+\-_]+)*$/
-
-
identifier = identifier.gsub(/-/, '__m__').gsub(/\+/, '__p__')
-
-
# Untaint identifier after it has been reassigned to a new string. We
-
# don't want to modify the original identifier. identifier may also be
-
# frozen and therefore cannot be untainted.
-
identifier.untaint
-
-
identifier = identifier.split('/')
-
begin
-
require_definition(identifier)
-
-
m = Data::Definitions
-
identifier.each {|part|
-
m = m.const_get(part)
-
}
-
-
m.get
-
rescue LoadError, NameError => e
-
raise InvalidTimezoneIdentifier, e.message
-
end
-
end
-
-
# Returns an array of all the available timezone identifiers.
-
2
def timezone_identifiers
-
load_timezone_index
-
Data::Indexes::Timezones.timezones
-
end
-
-
# Returns an array of all the available timezone identifiers for
-
# data timezones (i.e. those that actually contain definitions).
-
2
def data_timezone_identifiers
-
load_timezone_index
-
Data::Indexes::Timezones.data_timezones
-
end
-
-
# Returns an array of all the available timezone identifiers that
-
# are links to other timezones.
-
2
def linked_timezone_identifiers
-
load_timezone_index
-
Data::Indexes::Timezones.linked_timezones
-
end
-
-
# Returns a CountryInfo instance for the given ISO 3166-1 alpha-2
-
# country code. Raises InvalidCountryCode if the country could not be found
-
# or the code is invalid.
-
2
def load_country_info(code)
-
load_country_index
-
info = Data::Indexes::Countries.countries[code]
-
raise InvalidCountryCode, 'Invalid country code' unless info
-
info
-
end
-
-
# Returns an array of all the available ISO 3166-1 alpha-2
-
# country codes.
-
2
def country_codes
-
load_country_index
-
Data::Indexes::Countries.countries.keys.freeze
-
end
-
-
# Returns the name of this DataSource.
-
2
def to_s
-
"Ruby DataSource"
-
end
-
-
2
private
-
-
# Requires a zone definition by its identifier (split on /).
-
2
def require_definition(identifier)
-
require_data(*(['definitions'] + identifier))
-
end
-
-
# Requires an index by its name.
-
2
def self.require_index(name)
-
require_data(*['indexes', name])
-
end
-
-
# Requires a file from tzinfo/data.
-
2
def require_data(*file)
-
self.class.require_data(*file)
-
end
-
-
# Requires a file from tzinfo/data.
-
2
def self.require_data(*file)
-
require File.join('tzinfo', 'data', *file)
-
end
-
-
# Loads in the index of timezones if it hasn't already been loaded.
-
2
def load_timezone_index
-
self.class.load_timezone_index
-
end
-
-
# Loads in the index of timezones if it hasn't already been loaded.
-
2
def self.load_timezone_index
-
unless @@timezone_index_loaded
-
require_index('timezones')
-
@@timezone_index_loaded = true
-
end
-
end
-
-
# Loads in the index of countries if it hasn't already been loaded.
-
2
def load_country_index
-
self.class.load_country_index
-
end
-
-
# Loads in the index of countries if it hasn't already been loaded.
-
2
def self.load_country_index
-
unless @@country_index_loaded
-
require_index('countries')
-
@@country_index_loaded = true
-
end
-
end
-
end
-
end
-
2
require 'date'
-
2
require 'rational' unless defined?(Rational)
-
2
require 'time'
-
-
2
module TZInfo
-
# Used by TZInfo internally to represent either a Time, DateTime or
-
# an Integer timestamp (seconds since 1970-01-01 00:00:00).
-
2
class TimeOrDateTime
-
2
include Comparable
-
-
# Constructs a new TimeOrDateTime. timeOrDateTime can be a Time, DateTime
-
# or Integer. If using a Time or DateTime, any time zone information
-
# is ignored.
-
#
-
# Integer timestamps must be within the range supported by Time on the
-
# platform being used.
-
2
def initialize(timeOrDateTime)
-
534
@time = nil
-
534
@datetime = nil
-
534
@timestamp = nil
-
-
534
if timeOrDateTime.is_a?(Time)
-
534
@time = timeOrDateTime
-
-
# Avoid using the slower Rational class unless necessary.
-
534
nsec = RubyCoreSupport.time_nsec(@time)
-
534
usec = nsec % 1000 == 0 ? nsec / 1000 : Rational(nsec, 1000)
-
-
534
@time = Time.utc(@time.year, @time.mon, @time.mday, @time.hour, @time.min, @time.sec, usec) unless @time.utc?
-
534
@orig = @time
-
elsif timeOrDateTime.is_a?(DateTime)
-
@datetime = timeOrDateTime
-
@datetime = @datetime.new_offset(0) unless @datetime.offset == 0
-
@orig = @datetime
-
else
-
@timestamp = timeOrDateTime.to_i
-
-
if !RubyCoreSupport.time_supports_64bit && (@timestamp > 2147483647 || @timestamp < -2147483648 || (@timestamp < 0 && !RubyCoreSupport.time_supports_negative))
-
raise RangeError, 'Timestamp is outside the supported range of Time on this platform'
-
end
-
-
@orig = @timestamp
-
end
-
end
-
-
# Returns the time as a Time.
-
#
-
# When converting from a DateTime, the result is truncated to microsecond
-
# precision.
-
2
def to_time
-
# Thread-safety: It is possible that the value of @time may be
-
# calculated multiple times in concurrently executing threads. It is not
-
# worth the overhead of locking to ensure that @time is only
-
# calculated once.
-
-
534
unless @time
-
if @timestamp
-
@time = Time.at(@timestamp).utc
-
else
-
@time = Time.utc(year, mon, mday, hour, min, sec, usec)
-
end
-
end
-
-
534
@time
-
end
-
-
# Returns the time as a DateTime.
-
#
-
# When converting from a Time, the result is truncated to microsecond
-
# precision.
-
2
def to_datetime
-
# Thread-safety: It is possible that the value of @datetime may be
-
# calculated multiple times in concurrently executing threads. It is not
-
# worth the overhead of locking to ensure that @datetime is only
-
# calculated once.
-
-
unless @datetime
-
# Avoid using Rational unless necessary.
-
u = usec
-
s = u == 0 ? sec : Rational(sec * 1000000 + u, 1000000)
-
@datetime = RubyCoreSupport.datetime_new(year, mon, mday, hour, min, s)
-
end
-
-
@datetime
-
end
-
-
# Returns the time as an integer timestamp.
-
2
def to_i
-
# Thread-safety: It is possible that the value of @timestamp may be
-
# calculated multiple times in concurrently executing threads. It is not
-
# worth the overhead of locking to ensure that @timestamp is only
-
# calculated once.
-
-
unless @timestamp
-
@timestamp = to_time.to_i
-
end
-
-
@timestamp
-
end
-
-
# Returns the time as the original time passed to new.
-
2
def to_orig
-
@orig
-
end
-
-
# Returns a string representation of the TimeOrDateTime.
-
2
def to_s
-
if @orig.is_a?(Time)
-
"Time: #{@orig.to_s}"
-
elsif @orig.is_a?(DateTime)
-
"DateTime: #{@orig.to_s}"
-
else
-
"Timestamp: #{@orig.to_s}"
-
end
-
end
-
-
# Returns internal object state as a programmer-readable string.
-
2
def inspect
-
"#<#{self.class}: #{@orig.inspect}>"
-
end
-
-
# Returns the year.
-
2
def year
-
if @time
-
@time.year
-
elsif @datetime
-
@datetime.year
-
else
-
to_time.year
-
end
-
end
-
-
# Returns the month of the year (1..12).
-
2
def mon
-
if @time
-
@time.mon
-
elsif @datetime
-
@datetime.mon
-
else
-
to_time.mon
-
end
-
end
-
2
alias :month :mon
-
-
# Returns the day of the month (1..n).
-
2
def mday
-
if @time
-
@time.mday
-
elsif @datetime
-
@datetime.mday
-
else
-
to_time.mday
-
end
-
end
-
2
alias :day :mday
-
-
# Returns the hour of the day (0..23).
-
2
def hour
-
if @time
-
@time.hour
-
elsif @datetime
-
@datetime.hour
-
else
-
to_time.hour
-
end
-
end
-
-
# Returns the minute of the hour (0..59).
-
2
def min
-
if @time
-
@time.min
-
elsif @datetime
-
@datetime.min
-
else
-
to_time.min
-
end
-
end
-
-
# Returns the second of the minute (0..60). (60 for a leap second).
-
2
def sec
-
if @time
-
@time.sec
-
elsif @datetime
-
@datetime.sec
-
else
-
to_time.sec
-
end
-
end
-
-
# Returns the number of microseconds for the time.
-
2
def usec
-
if @time
-
@time.usec
-
elsif @datetime
-
# Ruby 1.8 has sec_fraction (of which the documentation says
-
# 'I do NOT recommend you to use this method'). sec_fraction no longer
-
# exists in Ruby 1.9.
-
-
# Calculate the sec_fraction from the day_fraction.
-
((@datetime.day_fraction - OffsetRationals.rational_for_offset(@datetime.hour * 3600 + @datetime.min * 60 + @datetime.sec)) * 86400000000).to_i
-
else
-
0
-
end
-
end
-
-
# Compares this TimeOrDateTime with another Time, DateTime, timestamp
-
# (Integer) or TimeOrDateTime. Returns -1, 0 or +1 depending
-
# whether the receiver is less than, equal to, or greater than
-
# timeOrDateTime.
-
#
-
# Returns nil if the passed in timeOrDateTime is not comparable with
-
# TimeOrDateTime instances.
-
#
-
# Comparisons involving a DateTime will be performed using DateTime#<=>.
-
# Comparisons that don't involve a DateTime, but include a Time will be
-
# performed with Time#<=>. Otherwise comparisons will be performed with
-
# Integer#<=>.
-
2
def <=>(timeOrDateTime)
-
return nil unless timeOrDateTime.is_a?(TimeOrDateTime) ||
-
timeOrDateTime.is_a?(Time) ||
-
timeOrDateTime.is_a?(DateTime) ||
-
timeOrDateTime.respond_to?(:to_i)
-
-
unless timeOrDateTime.is_a?(TimeOrDateTime)
-
timeOrDateTime = TimeOrDateTime.wrap(timeOrDateTime)
-
end
-
-
orig = timeOrDateTime.to_orig
-
-
if @orig.is_a?(DateTime) || orig.is_a?(DateTime)
-
# If either is a DateTime, assume it is there for a reason
-
# (i.e. for its larger range of acceptable values on 32-bit systems).
-
to_datetime <=> timeOrDateTime.to_datetime
-
elsif @orig.is_a?(Time) || orig.is_a?(Time)
-
to_time <=> timeOrDateTime.to_time
-
else
-
to_i <=> timeOrDateTime.to_i
-
end
-
end
-
-
# Adds a number of seconds to the TimeOrDateTime. Returns a new
-
# TimeOrDateTime, preserving what the original constructed type was.
-
# If the original type is a Time and the resulting calculation goes out of
-
# range for Times, then an exception will be raised by the Time class.
-
2
def +(seconds)
-
534
if seconds == 0
-
534
self
-
else
-
if @orig.is_a?(DateTime)
-
TimeOrDateTime.new(@orig + OffsetRationals.rational_for_offset(seconds))
-
else
-
# + defined for Time and Integer
-
TimeOrDateTime.new(@orig + seconds)
-
end
-
end
-
end
-
-
# Subtracts a number of seconds from the TimeOrDateTime. Returns a new
-
# TimeOrDateTime, preserving what the original constructed type was.
-
# If the original type is a Time and the resulting calculation goes out of
-
# range for Times, then an exception will be raised by the Time class.
-
2
def -(seconds)
-
self + (-seconds)
-
end
-
-
# Similar to the + operator, but converts to a DateTime based TimeOrDateTime
-
# where the Time or Integer timestamp to go out of the allowed range for a
-
# Time, converts to a DateTime based TimeOrDateTime.
-
#
-
# Note that the range of Time varies based on the platform.
-
2
def add_with_convert(seconds)
-
if seconds == 0
-
self
-
else
-
if @orig.is_a?(DateTime)
-
TimeOrDateTime.new(@orig + OffsetRationals.rational_for_offset(seconds))
-
else
-
# A Time or timestamp.
-
result = to_i + seconds
-
-
if ((result > 2147483647 || result < -2147483648) && !RubyCoreSupport.time_supports_64bit) || (result < 0 && !RubyCoreSupport.time_supports_negative)
-
result = TimeOrDateTime.new(to_datetime + OffsetRationals.rational_for_offset(seconds))
-
else
-
result = TimeOrDateTime.new(@orig + seconds)
-
end
-
end
-
end
-
end
-
-
# Returns true if todt represents the same time and was originally
-
# constructed with the same type (DateTime, Time or timestamp) as this
-
# TimeOrDateTime.
-
2
def eql?(todt)
-
todt.kind_of?(TimeOrDateTime) && to_orig.eql?(todt.to_orig)
-
end
-
-
# Returns a hash of this TimeOrDateTime.
-
2
def hash
-
@orig.hash
-
end
-
-
# If no block is given, returns a TimeOrDateTime wrapping the given
-
# timeOrDateTime. If a block is specified, a TimeOrDateTime is constructed
-
# and passed to the block. The result of the block must be a TimeOrDateTime.
-
#
-
# The result of the block will be converted to the type of the originally
-
# passed in timeOrDateTime and then returned as the result of wrap.
-
#
-
# timeOrDateTime can be a Time, DateTime, timestamp (Integer) or
-
# TimeOrDateTime. If a TimeOrDateTime is passed in, no new TimeOrDateTime
-
# will be constructed and the value passed to wrap will be used when
-
# calling the block.
-
2
def self.wrap(timeOrDateTime)
-
534
t = timeOrDateTime.is_a?(TimeOrDateTime) ? timeOrDateTime : TimeOrDateTime.new(timeOrDateTime)
-
-
534
if block_given?
-
534
t = yield t
-
-
534
if timeOrDateTime.is_a?(TimeOrDateTime)
-
t
-
534
elsif timeOrDateTime.is_a?(Time)
-
534
t.to_time
-
elsif timeOrDateTime.is_a?(DateTime)
-
t.to_datetime
-
else
-
t.to_i
-
end
-
else
-
t
-
end
-
end
-
end
-
end
-
2
require 'date'
-
2
require 'set'
-
2
require 'thread_safe'
-
-
2
module TZInfo
-
# AmbiguousTime is raised to indicates that a specified time in a local
-
# timezone has more than one possible equivalent UTC time. This happens when
-
# transitioning from daylight savings time to standard time where the clocks
-
# are rolled back.
-
#
-
# AmbiguousTime is raised by period_for_local and local_to_utc when using an
-
# ambiguous time and not specifying any means to resolve the ambiguity.
-
2
class AmbiguousTime < StandardError
-
end
-
-
# PeriodNotFound is raised to indicate that no TimezonePeriod matching a given
-
# time could be found.
-
2
class PeriodNotFound < StandardError
-
end
-
-
# Raised by Timezone#get if the identifier given is not valid.
-
2
class InvalidTimezoneIdentifier < StandardError
-
end
-
-
# Raised if an attempt is made to use a timezone created with
-
# Timezone.new(nil).
-
2
class UnknownTimezone < StandardError
-
end
-
-
# Timezone is the base class of all timezones. It provides a factory method,
-
# 'get', to access timezones by identifier. Once a specific Timezone has been
-
# retrieved, DateTimes, Times and timestamps can be converted between the UTC
-
# and the local time for the zone. For example:
-
#
-
# tz = TZInfo::Timezone.get('America/New_York')
-
# puts tz.utc_to_local(DateTime.new(2005,8,29,15,35,0)).to_s
-
# puts tz.local_to_utc(Time.utc(2005,8,29,11,35,0)).to_s
-
# puts tz.utc_to_local(1125315300).to_s
-
#
-
# Each time conversion method returns an object of the same type it was
-
# passed.
-
#
-
# The Timezone class is thread-safe. It is safe to use class and instance
-
# methods of Timezone in concurrently executing threads. Instances of Timezone
-
# can be shared across thread boundaries.
-
2
class Timezone
-
2
include Comparable
-
-
# Cache of loaded zones by identifier to avoid using require if a zone
-
# has already been loaded.
-
#
-
# @!visibility private
-
2
@@loaded_zones = nil
-
-
# Default value of the dst parameter of the local_to_utc and
-
# period_for_local methods.
-
#
-
# @!visibility private
-
2
@@default_dst = nil
-
-
# Sets the default value of the optional dst parameter of the
-
# local_to_utc and period_for_local methods. Can be set to nil, true or
-
# false.
-
#
-
# The value of default_dst defaults to nil if unset.
-
2
def self.default_dst=(value)
-
@@default_dst = value.nil? ? nil : !!value
-
end
-
-
# Gets the default value of the optional dst parameter of the
-
# local_to_utc and period_for_local methods. Can be set to nil, true or
-
# false.
-
2
def self.default_dst
-
@@default_dst
-
end
-
-
# Returns a timezone by its identifier (e.g. "Europe/London",
-
# "America/Chicago" or "UTC").
-
#
-
# Raises InvalidTimezoneIdentifier if the timezone couldn't be found.
-
2
def self.get(identifier)
-
2
instance = @@loaded_zones[identifier]
-
-
2
unless instance
-
# Thread-safety: It is possible that multiple equivalent Timezone
-
# instances could be created here in concurrently executing threads.
-
# The consequences of this are that the data may be loaded more than
-
# once (depending on the data source) and memoized calculations could
-
# be discarded. The performance benefit of ensuring that only a single
-
# instance is created is unlikely to be worth the overhead of only
-
# allowing one Timezone to be loaded at a time.
-
2
info = data_source.load_timezone_info(identifier)
-
2
instance = info.create_timezone
-
2
@@loaded_zones[instance.identifier] = instance
-
end
-
-
2
instance
-
end
-
-
# Returns a proxy for the Timezone with the given identifier. The proxy
-
# will cause the real timezone to be loaded when an attempt is made to
-
# find a period or convert a time. get_proxy will not validate the
-
# identifier. If an invalid identifier is specified, no exception will be
-
# raised until the proxy is used.
-
2
def self.get_proxy(identifier)
-
TimezoneProxy.new(identifier)
-
end
-
-
# If identifier is nil calls super(), otherwise calls get. An identfier
-
# should always be passed in when called externally.
-
2
def self.new(identifier = nil)
-
4
if identifier
-
get(identifier)
-
else
-
4
super()
-
end
-
end
-
-
# Returns an array containing all the available Timezones.
-
#
-
# Returns TimezoneProxy objects to avoid the overhead of loading Timezone
-
# definitions until a conversion is actually required.
-
2
def self.all
-
get_proxies(all_identifiers)
-
end
-
-
# Returns an array containing the identifiers of all the available
-
# Timezones.
-
2
def self.all_identifiers
-
data_source.timezone_identifiers
-
end
-
-
# Returns an array containing all the available Timezones that are based
-
# on data (are not links to other Timezones).
-
#
-
# Returns TimezoneProxy objects to avoid the overhead of loading Timezone
-
# definitions until a conversion is actually required.
-
2
def self.all_data_zones
-
get_proxies(all_data_zone_identifiers)
-
end
-
-
# Returns an array containing the identifiers of all the available
-
# Timezones that are based on data (are not links to other Timezones)..
-
2
def self.all_data_zone_identifiers
-
data_source.data_timezone_identifiers
-
end
-
-
# Returns an array containing all the available Timezones that are links
-
# to other Timezones.
-
#
-
# Returns TimezoneProxy objects to avoid the overhead of loading Timezone
-
# definitions until a conversion is actually required.
-
2
def self.all_linked_zones
-
get_proxies(all_linked_zone_identifiers)
-
end
-
-
# Returns an array containing the identifiers of all the available
-
# Timezones that are links to other Timezones.
-
2
def self.all_linked_zone_identifiers
-
data_source.linked_timezone_identifiers
-
end
-
-
# Returns all the Timezones defined for all Countries. This is not the
-
# complete set of Timezones as some are not country specific (e.g.
-
# 'Etc/GMT').
-
#
-
# Returns TimezoneProxy objects to avoid the overhead of loading Timezone
-
# definitions until a conversion is actually required.
-
2
def self.all_country_zones
-
Country.all_codes.inject([]) do |zones,country|
-
zones += Country.get(country).zones
-
end.uniq
-
end
-
-
# Returns all the zone identifiers defined for all Countries. This is not the
-
# complete set of zone identifiers as some are not country specific (e.g.
-
# 'Etc/GMT'). You can obtain a Timezone instance for a given identifier
-
# with the get method.
-
2
def self.all_country_zone_identifiers
-
Country.all_codes.inject([]) do |zones,country|
-
zones += Country.get(country).zone_identifiers
-
end.uniq
-
end
-
-
# Returns all US Timezone instances. A shortcut for
-
# TZInfo::Country.get('US').zones.
-
#
-
# Returns TimezoneProxy objects to avoid the overhead of loading Timezone
-
# definitions until a conversion is actually required.
-
2
def self.us_zones
-
Country.get('US').zones
-
end
-
-
# Returns all US zone identifiers. A shortcut for
-
# TZInfo::Country.get('US').zone_identifiers.
-
2
def self.us_zone_identifiers
-
Country.get('US').zone_identifiers
-
end
-
-
# The identifier of the timezone, e.g. "Europe/Paris".
-
2
def identifier
-
raise_unknown_timezone
-
end
-
-
# An alias for identifier.
-
2
def name
-
# Don't use alias, as identifier gets overridden.
-
identifier
-
end
-
-
# Returns a friendlier version of the identifier.
-
2
def to_s
-
friendly_identifier
-
end
-
-
# Returns internal object state as a programmer-readable string.
-
2
def inspect
-
"#<#{self.class}: #{identifier}>"
-
end
-
-
# Returns a friendlier version of the identifier. Set skip_first_part to
-
# omit the first part of the identifier (typically a region name) where
-
# there is more than one part.
-
#
-
# For example:
-
#
-
# Timezone.get('Europe/Paris').friendly_identifier(false) #=> "Europe - Paris"
-
# Timezone.get('Europe/Paris').friendly_identifier(true) #=> "Paris"
-
# Timezone.get('America/Indiana/Knox').friendly_identifier(false) #=> "America - Knox, Indiana"
-
# Timezone.get('America/Indiana/Knox').friendly_identifier(true) #=> "Knox, Indiana"
-
2
def friendly_identifier(skip_first_part = false)
-
parts = identifier.split('/')
-
if parts.empty?
-
# shouldn't happen
-
identifier
-
elsif parts.length == 1
-
parts[0]
-
else
-
if skip_first_part
-
result = ''
-
else
-
result = parts[0] + ' - '
-
end
-
-
parts[1, parts.length - 1].reverse_each {|part|
-
part.gsub!(/_/, ' ')
-
-
if part.index(/[a-z]/)
-
# Missing a space if a lower case followed by an upper case and the
-
# name isn't McXxxx.
-
part.gsub!(/([^M][a-z])([A-Z])/, '\1 \2')
-
part.gsub!(/([M][a-bd-z])([A-Z])/, '\1 \2')
-
-
# Missing an apostrophe if two consecutive upper case characters.
-
part.gsub!(/([A-Z])([A-Z])/, '\1\'\2')
-
end
-
-
result << part
-
result << ', '
-
}
-
-
result.slice!(result.length - 2, 2)
-
result
-
end
-
end
-
-
# Returns the TimezonePeriod for the given UTC time. utc can either be
-
# a DateTime, Time or integer timestamp (Time.to_i). Any timezone
-
# information in utc is ignored (it is treated as a UTC time).
-
2
def period_for_utc(utc)
-
raise_unknown_timezone
-
end
-
-
# Returns the set of TimezonePeriod instances that are valid for the given
-
# local time as an array. If you just want a single period, use
-
# period_for_local instead and specify how ambiguities should be resolved.
-
# Returns an empty array if no periods are found for the given time.
-
2
def periods_for_local(local)
-
raise_unknown_timezone
-
end
-
-
# Returns an Array of TimezoneTransition instances representing the times
-
# where the UTC offset of the timezone changes.
-
#
-
# Transitions are returned up to a given date and time up to a given date
-
# and time, specified in UTC (utc_to).
-
#
-
# A from date and time may also be supplied using the utc_from parameter
-
# (also specified in UTC). If utc_from is not nil, only transitions from
-
# that date and time onwards will be returned.
-
#
-
# Comparisons with utc_to are exclusive. Comparisons with utc_from are
-
# inclusive. If a transition falls precisely on utc_to, it will be excluded.
-
# If a transition falls on utc_from, it will be included.
-
#
-
# Transitions returned are ordered by when they occur, from earliest to
-
# latest.
-
#
-
# utc_to and utc_from can be specified using either DateTime, Time or
-
# integer timestamps (Time.to_i).
-
#
-
# If utc_from is specified and utc_to is not greater than utc_from, then
-
# transitions_up_to raises an ArgumentError exception.
-
2
def transitions_up_to(utc_to, utc_from = nil)
-
raise_unknown_timezone
-
end
-
-
# Returns the canonical Timezone instance for this Timezone.
-
#
-
# The IANA Time Zone database contains two types of definition: Zones and
-
# Links. Zones are defined by rules that set out when transitions occur.
-
# Links are just references to fully defined Zone, creating an alias for
-
# that Zone.
-
#
-
# Links are commonly used where a time zone has been renamed in a
-
# release of the Time Zone database. For example, the Zone US/Eastern was
-
# renamed as America/New_York. A US/Eastern Link was added in its place,
-
# linking to (and creating an alias for) for America/New_York.
-
#
-
# Links are also used for time zones that are currently identical to a full
-
# Zone, but that are administered seperately. For example, Europe/Vatican is
-
# a Link to (and alias for) Europe/Rome.
-
#
-
# For a full Zone, canonical_zone returns self.
-
#
-
# For a Link, canonical_zone returns a Timezone instance representing the
-
# full Zone that the link targets.
-
#
-
# TZInfo can be used with different data sources (see the documentation for
-
# TZInfo::DataSource). Please note that some DataSource implementations may
-
# not support distinguishing between full Zones and Links and will treat all
-
# time zones as full Zones. In this case, the canonical_zone will always
-
# return self.
-
#
-
# There are two built-in DataSource implementations. RubyDataSource (which
-
# will be used if the tzinfo-data gem is available) supports Link zones.
-
# ZoneinfoDataSource returns Link zones as if they were full Zones. If the
-
# canonical_zone or canonical_identifier methods are required, the
-
# tzinfo-data gem should be installed.
-
#
-
# The TZInfo::DataSource.get method can be used to check which DataSource
-
# implementation is being used.
-
2
def canonical_zone
-
raise_unknown_timezone
-
end
-
-
# Returns the TimezonePeriod for the given local time. local can either be
-
# a DateTime, Time or integer timestamp (Time.to_i). Any timezone
-
# information in local is ignored (it is treated as a time in the current
-
# timezone).
-
#
-
# Warning: There are local times that have no equivalent UTC times (e.g.
-
# in the transition from standard time to daylight savings time). There are
-
# also local times that have more than one UTC equivalent (e.g. in the
-
# transition from daylight savings time to standard time).
-
#
-
# In the first case (no equivalent UTC time), a PeriodNotFound exception
-
# will be raised.
-
#
-
# In the second case (more than one equivalent UTC time), an AmbiguousTime
-
# exception will be raised unless the optional dst parameter or block
-
# handles the ambiguity.
-
#
-
# If the ambiguity is due to a transition from daylight savings time to
-
# standard time, the dst parameter can be used to select whether the
-
# daylight savings time or local time is used. For example,
-
#
-
# Timezone.get('America/New_York').period_for_local(DateTime.new(2004,10,31,1,30,0))
-
#
-
# would raise an AmbiguousTime exception.
-
#
-
# Specifying dst=true would the daylight savings period from April to
-
# October 2004. Specifying dst=false would return the standard period
-
# from October 2004 to April 2005.
-
#
-
# If the dst parameter does not resolve the ambiguity, and a block is
-
# specified, it is called. The block must take a single parameter - an
-
# array of the periods that need to be resolved. The block can select and
-
# return a single period or return nil or an empty array
-
# to cause an AmbiguousTime exception to be raised.
-
#
-
# The default value of the dst parameter can be specified by setting
-
# Timezone.default_dst. If default_dst is not set, or is set to nil, then
-
# an AmbiguousTime exception will be raised in ambiguous situations unless
-
# a block is given to resolve the ambiguity.
-
2
def period_for_local(local, dst = Timezone.default_dst)
-
results = periods_for_local(local)
-
-
if results.empty?
-
raise PeriodNotFound
-
elsif results.size < 2
-
results.first
-
else
-
# ambiguous result try to resolve
-
-
if !dst.nil?
-
matches = results.find_all {|period| period.dst? == dst}
-
results = matches if !matches.empty?
-
end
-
-
if results.size < 2
-
results.first
-
else
-
# still ambiguous, try the block
-
-
if block_given?
-
results = yield results
-
end
-
-
if results.is_a?(TimezonePeriod)
-
results
-
elsif results && results.size == 1
-
results.first
-
else
-
raise AmbiguousTime, "#{local} is an ambiguous local time."
-
end
-
end
-
end
-
end
-
-
# Converts a time in UTC to the local timezone. utc can either be
-
# a DateTime, Time or timestamp (Time.to_i). The returned time has the same
-
# type as utc. Any timezone information in utc is ignored (it is treated as
-
# a UTC time).
-
2
def utc_to_local(utc)
-
TimeOrDateTime.wrap(utc) {|wrapped|
-
period_for_utc(wrapped).to_local(wrapped)
-
}
-
end
-
-
# Converts a time in the local timezone to UTC. local can either be
-
# a DateTime, Time or timestamp (Time.to_i). The returned time has the same
-
# type as local. Any timezone information in local is ignored (it is treated
-
# as a local time).
-
#
-
# Warning: There are local times that have no equivalent UTC times (e.g.
-
# in the transition from standard time to daylight savings time). There are
-
# also local times that have more than one UTC equivalent (e.g. in the
-
# transition from daylight savings time to standard time).
-
#
-
# In the first case (no equivalent UTC time), a PeriodNotFound exception
-
# will be raised.
-
#
-
# In the second case (more than one equivalent UTC time), an AmbiguousTime
-
# exception will be raised unless the optional dst parameter or block
-
# handles the ambiguity.
-
#
-
# If the ambiguity is due to a transition from daylight savings time to
-
# standard time, the dst parameter can be used to select whether the
-
# daylight savings time or local time is used. For example,
-
#
-
# Timezone.get('America/New_York').local_to_utc(DateTime.new(2004,10,31,1,30,0))
-
#
-
# would raise an AmbiguousTime exception.
-
#
-
# Specifying dst=true would return 2004-10-31 5:30:00. Specifying dst=false
-
# would return 2004-10-31 6:30:00.
-
#
-
# If the dst parameter does not resolve the ambiguity, and a block is
-
# specified, it is called. The block must take a single parameter - an
-
# array of the periods that need to be resolved. The block can return a
-
# single period to use to convert the time or return nil or an empty array
-
# to cause an AmbiguousTime exception to be raised.
-
#
-
# The default value of the dst parameter can be specified by setting
-
# Timezone.default_dst. If default_dst is not set, or is set to nil, then
-
# an AmbiguousTime exception will be raised in ambiguous situations unless
-
# a block is given to resolve the ambiguity.
-
2
def local_to_utc(local, dst = Timezone.default_dst)
-
TimeOrDateTime.wrap(local) {|wrapped|
-
if block_given?
-
period = period_for_local(wrapped, dst) {|periods| yield periods }
-
else
-
period = period_for_local(wrapped, dst)
-
end
-
-
period.to_utc(wrapped)
-
}
-
end
-
-
# Returns information about offsets used by the Timezone up to a given
-
# date and time, specified using UTC (utc_to). The information is returned
-
# as an Array of TimezoneOffset instances.
-
#
-
# A from date and time may also be supplied using the utc_from parameter
-
# (also specified in UTC). If utc_from is not nil, only offsets used from
-
# that date and time forward will be returned.
-
#
-
# Comparisons with utc_to are exclusive. Comparisons with utc_from are
-
# inclusive.
-
#
-
# Offsets may be returned in any order.
-
#
-
# utc_to and utc_from can be specified using either DateTime, Time or
-
# integer timestamps (Time.to_i).
-
#
-
# If utc_from is specified and utc_to is not greater than utc_from, then
-
# offsets_up_to raises an ArgumentError exception.
-
2
def offsets_up_to(utc_to, utc_from = nil)
-
utc_to = TimeOrDateTime.wrap(utc_to)
-
transitions = transitions_up_to(utc_to, utc_from)
-
-
if transitions.empty?
-
# No transitions in the range, find the period that covers it.
-
-
if utc_from
-
# Use the from date as it is inclusive.
-
period = period_for_utc(utc_from)
-
else
-
# utc_to is exclusive, so this can't be used with period_for_utc.
-
# However, any time earlier than utc_to can be used.
-
-
# Subtract 1 hour (since this is one of the cached OffsetRationals).
-
# Use add_with_convert so that conversion to DateTime is performed if
-
# required.
-
period = period_for_utc(utc_to.add_with_convert(-3600))
-
end
-
-
[period.offset]
-
else
-
result = Set.new
-
-
first = transitions.first
-
result << first.previous_offset unless utc_from && first.at == utc_from
-
-
transitions.each do |t|
-
result << t.offset
-
end
-
-
result.to_a
-
end
-
end
-
-
# Returns the canonical identifier for this Timezone.
-
#
-
# This is a shortcut for calling canonical_zone.identifier. Please refer
-
# to the canonical_zone documentation for further information.
-
2
def canonical_identifier
-
canonical_zone.identifier
-
end
-
-
# Returns the current time in the timezone as a Time.
-
2
def now
-
utc_to_local(Time.now.utc)
-
end
-
-
# Returns the TimezonePeriod for the current time.
-
2
def current_period
-
2
period_for_utc(Time.now.utc)
-
end
-
-
# Returns the current Time and TimezonePeriod as an array. The first element
-
# is the time, the second element is the period.
-
2
def current_period_and_time
-
utc = Time.now.utc
-
period = period_for_utc(utc)
-
[period.to_local(utc), period]
-
end
-
-
2
alias :current_time_and_period :current_period_and_time
-
-
# Converts a time in UTC to local time and returns it as a string
-
# according to the given format. The formatting is identical to
-
# Time.strftime and DateTime.strftime, except %Z is replaced with the
-
# timezone abbreviation for the specified time (for example, EST or EDT).
-
2
def strftime(format, utc = Time.now.utc)
-
period = period_for_utc(utc)
-
local = period.to_local(utc)
-
local = Time.at(local).utc unless local.kind_of?(Time) || local.kind_of?(DateTime)
-
abbreviation = period.abbreviation.to_s.gsub(/%/, '%%')
-
-
format = format.gsub(/(.?)%Z/) do
-
if $1 == '%'
-
# return %%Z so the real strftime treats it as a literal %Z too
-
'%%Z'
-
else
-
"#$1#{abbreviation}"
-
end
-
end
-
-
local.strftime(format)
-
end
-
-
# Compares two Timezones based on their identifier. Returns -1 if tz is less
-
# than self, 0 if tz is equal to self and +1 if tz is greater than self.
-
#
-
# Returns nil if tz is not comparable with Timezone instances.
-
2
def <=>(tz)
-
return nil unless tz.is_a?(Timezone)
-
identifier <=> tz.identifier
-
end
-
-
# Returns true if and only if the identifier of tz is equal to the
-
# identifier of this Timezone.
-
2
def eql?(tz)
-
self == tz
-
end
-
-
# Returns a hash of this Timezone.
-
2
def hash
-
identifier.hash
-
end
-
-
# Dumps this Timezone for marshalling.
-
2
def _dump(limit)
-
identifier
-
end
-
-
# Loads a marshalled Timezone.
-
2
def self._load(data)
-
Timezone.get(data)
-
end
-
-
2
private
-
# Initializes @@loaded_zones.
-
2
def self.init_loaded_zones
-
2
@@loaded_zones = ThreadSafe::Cache.new
-
end
-
2
init_loaded_zones
-
-
# Returns an array of proxies corresponding to the given array of
-
# identifiers.
-
2
def self.get_proxies(identifiers)
-
identifiers.collect {|identifier| get_proxy(identifier)}
-
end
-
-
# Returns the current DataSource.
-
2
def self.data_source
-
2
DataSource.get
-
end
-
-
# Raises an UnknownTimezone exception.
-
2
def raise_unknown_timezone
-
raise UnknownTimezone, 'TZInfo::Timezone constructed directly'
-
end
-
end
-
end
-
2
module TZInfo
-
-
# TimezoneDefinition is included into Timezone definition modules.
-
# TimezoneDefinition provides the methods for defining timezones.
-
#
-
# @private
-
2
module TimezoneDefinition #:nodoc:
-
# Add class methods to the includee.
-
2
def self.append_features(base)
-
super
-
base.extend(ClassMethods)
-
end
-
-
# Class methods for inclusion.
-
#
-
# @private
-
2
module ClassMethods #:nodoc:
-
# Returns and yields a TransitionDataTimezoneInfo object to define a
-
# timezone.
-
2
def timezone(identifier)
-
yield @timezone = TransitionDataTimezoneInfo.new(identifier)
-
end
-
-
# Defines a linked timezone.
-
2
def linked_timezone(identifier, link_to_identifier)
-
@timezone = LinkedTimezoneInfo.new(identifier, link_to_identifier)
-
end
-
-
# Returns the last TimezoneInfo to be defined with timezone or
-
# linked_timezone.
-
2
def get
-
@timezone
-
end
-
end
-
end
-
end
-
2
module TZInfo
-
# The timezone index file includes TimezoneIndexDefinition which provides
-
# methods used to define timezones in the index.
-
#
-
# @private
-
2
module TimezoneIndexDefinition #:nodoc:
-
# Add class methods to the includee and initialize class instance variables.
-
2
def self.append_features(base)
-
super
-
base.extend(ClassMethods)
-
base.instance_eval do
-
@timezones = []
-
@data_timezones = []
-
@linked_timezones = []
-
end
-
end
-
-
# Class methods for inclusion.
-
#
-
# @private
-
2
module ClassMethods #:nodoc:
-
# Defines a timezone based on data.
-
2
def timezone(identifier)
-
@timezones << identifier
-
@data_timezones << identifier
-
end
-
-
# Defines a timezone which is a link to another timezone.
-
2
def linked_timezone(identifier)
-
@timezones << identifier
-
@linked_timezones << identifier
-
end
-
-
# Returns a frozen array containing the identifiers of all the timezones.
-
# Identifiers appear in the order they were defined in the index.
-
2
def timezones
-
@timezones.freeze
-
end
-
-
# Returns a frozen array containing the identifiers of all data timezones.
-
# Identifiers appear in the order they were defined in the index.
-
2
def data_timezones
-
@data_timezones.freeze
-
end
-
-
# Returns a frozen array containing the identifiers of all linked
-
# timezones. Identifiers appear in the order they were defined in
-
# the index.
-
2
def linked_timezones
-
@linked_timezones.freeze
-
end
-
end
-
end
-
end
-
2
module TZInfo
-
# Represents a timezone defined by a data source.
-
2
class TimezoneInfo
-
-
# The timezone identifier.
-
2
attr_reader :identifier
-
-
# Constructs a new TimezoneInfo with an identifier.
-
2
def initialize(identifier)
-
2
@identifier = identifier
-
end
-
-
# Returns internal object state as a programmer-readable string.
-
2
def inspect
-
"#<#{self.class}: #@identifier>"
-
end
-
-
# Constructs a Timezone instance for the timezone represented by this
-
# TimezoneInfo.
-
2
def create_timezone
-
raise_not_implemented('create_timezone')
-
end
-
-
2
private
-
-
2
def raise_not_implemented(method_name)
-
raise NotImplementedError, "Subclasses must override #{method_name}"
-
end
-
end
-
end
-
2
module TZInfo
-
# Represents an offset defined in a Timezone data file.
-
2
class TimezoneOffset
-
# The base offset of the timezone from UTC in seconds.
-
2
attr_reader :utc_offset
-
-
# The offset from standard time for the zone in seconds (i.e. non-zero if
-
# daylight savings is being observed).
-
2
attr_reader :std_offset
-
-
# The total offset of this observance from UTC in seconds
-
# (utc_offset + std_offset).
-
2
attr_reader :utc_total_offset
-
-
# The abbreviation that identifies this observance, e.g. "GMT"
-
# (Greenwich Mean Time) or "BST" (British Summer Time) for "Europe/London". The returned identifier is a
-
# symbol.
-
2
attr_reader :abbreviation
-
-
# Constructs a new TimezoneOffset. utc_offset and std_offset are specified
-
# in seconds.
-
2
def initialize(utc_offset, std_offset, abbreviation)
-
2
@utc_offset = utc_offset
-
2
@std_offset = std_offset
-
2
@abbreviation = abbreviation
-
-
2
@utc_total_offset = @utc_offset + @std_offset
-
end
-
-
# True if std_offset is non-zero.
-
2
def dst?
-
@std_offset != 0
-
end
-
-
# Converts a UTC Time, DateTime or integer timestamp to local time, based on
-
# the offset of this period.
-
2
def to_local(utc)
-
534
TimeOrDateTime.wrap(utc) {|wrapped|
-
534
wrapped + @utc_total_offset
-
}
-
end
-
-
# Converts a local Time, DateTime or integer timestamp to UTC, based on the
-
# offset of this period.
-
2
def to_utc(local)
-
TimeOrDateTime.wrap(local) {|wrapped|
-
wrapped - @utc_total_offset
-
}
-
end
-
-
# Returns true if and only if toi has the same utc_offset, std_offset
-
# and abbreviation as this TimezoneOffset.
-
2
def ==(toi)
-
toi.kind_of?(TimezoneOffset) &&
-
utc_offset == toi.utc_offset && std_offset == toi.std_offset && abbreviation == toi.abbreviation
-
end
-
-
# Returns true if and only if toi has the same utc_offset, std_offset
-
# and abbreviation as this TimezoneOffset.
-
2
def eql?(toi)
-
self == toi
-
end
-
-
# Returns a hash of this TimezoneOffset.
-
2
def hash
-
utc_offset.hash ^ std_offset.hash ^ abbreviation.hash
-
end
-
-
# Returns internal object state as a programmer-readable string.
-
2
def inspect
-
"#<#{self.class}: #@utc_offset,#@std_offset,#@abbreviation>"
-
end
-
end
-
end
-
2
module TZInfo
-
# A period of time in a timezone where the same offset from UTC applies.
-
#
-
# All the methods that take times accept instances of Time or DateTime as well
-
# as Integer timestamps.
-
2
class TimezonePeriod
-
# The TimezoneTransition that defines the start of this TimezonePeriod
-
# (may be nil if unbounded).
-
2
attr_reader :start_transition
-
-
# The TimezoneTransition that defines the end of this TimezonePeriod
-
# (may be nil if unbounded).
-
2
attr_reader :end_transition
-
-
# The TimezoneOffset for this period.
-
2
attr_reader :offset
-
-
# Initializes a new TimezonePeriod.
-
#
-
# TimezonePeriod instances should not normally be constructed manually.
-
2
def initialize(start_transition, end_transition, offset = nil)
-
536
@start_transition = start_transition
-
536
@end_transition = end_transition
-
-
536
if offset
-
536
raise ArgumentError, 'Offset specified with transitions' if @start_transition || @end_transition
-
536
@offset = offset
-
else
-
if @start_transition
-
@offset = @start_transition.offset
-
elsif @end_transition
-
@offset = @end_transition.previous_offset
-
else
-
raise ArgumentError, 'No offset specified and no transitions to determine it from'
-
end
-
end
-
-
536
@utc_total_offset_rational = nil
-
end
-
-
# Base offset of the timezone from UTC (seconds).
-
2
def utc_offset
-
2
@offset.utc_offset
-
end
-
-
# Offset from the local time where daylight savings is in effect (seconds).
-
# E.g.: utc_offset could be -5 hours. Normally, std_offset would be 0.
-
# During daylight savings, std_offset would typically become +1 hours.
-
2
def std_offset
-
@offset.std_offset
-
end
-
-
# The identifier of this period, e.g. "GMT" (Greenwich Mean Time) or "BST"
-
# (British Summer Time) for "Europe/London". The returned identifier is a
-
# symbol.
-
2
def abbreviation
-
@offset.abbreviation
-
end
-
2
alias :zone_identifier :abbreviation
-
-
# Total offset from UTC (seconds). Equal to utc_offset + std_offset.
-
2
def utc_total_offset
-
@offset.utc_total_offset
-
end
-
-
# Total offset from UTC (days). Result is a Rational.
-
2
def utc_total_offset_rational
-
# Thread-safety: It is possible that the value of
-
# @utc_total_offset_rational may be calculated multiple times in
-
# concurrently executing threads. It is not worth the overhead of locking
-
# to ensure that @zone_identifiers is only calculated once.
-
-
unless @utc_total_offset_rational
-
@utc_total_offset_rational = OffsetRationals.rational_for_offset(utc_total_offset)
-
end
-
@utc_total_offset_rational
-
end
-
-
# The start time of the period in UTC as a DateTime. May be nil if unbounded.
-
2
def utc_start
-
@start_transition ? @start_transition.at.to_datetime : nil
-
end
-
-
# The start time of the period in UTC as a Time. May be nil if unbounded.
-
2
def utc_start_time
-
@start_transition ? @start_transition.at.to_time : nil
-
end
-
-
# The end time of the period in UTC as a DateTime. May be nil if unbounded.
-
2
def utc_end
-
@end_transition ? @end_transition.at.to_datetime : nil
-
end
-
-
# The end time of the period in UTC as a Time. May be nil if unbounded.
-
2
def utc_end_time
-
@end_transition ? @end_transition.at.to_time : nil
-
end
-
-
# The start time of the period in local time as a DateTime. May be nil if
-
# unbounded.
-
2
def local_start
-
@start_transition ? @start_transition.local_start_at.to_datetime : nil
-
end
-
-
# The start time of the period in local time as a Time. May be nil if
-
# unbounded.
-
2
def local_start_time
-
@start_transition ? @start_transition.local_start_at.to_time : nil
-
end
-
-
# The end time of the period in local time as a DateTime. May be nil if
-
# unbounded.
-
2
def local_end
-
@end_transition ? @end_transition.local_end_at.to_datetime : nil
-
end
-
-
# The end time of the period in local time as a Time. May be nil if
-
# unbounded.
-
2
def local_end_time
-
@end_transition ? @end_transition.local_end_at.to_time : nil
-
end
-
-
# true if daylight savings is in effect for this period; otherwise false.
-
2
def dst?
-
@offset.dst?
-
end
-
-
# true if this period is valid for the given UTC DateTime; otherwise false.
-
2
def valid_for_utc?(utc)
-
utc_after_start?(utc) && utc_before_end?(utc)
-
end
-
-
# true if the given UTC DateTime is after the start of the period
-
# (inclusive); otherwise false.
-
2
def utc_after_start?(utc)
-
!@start_transition || @start_transition.at <= utc
-
end
-
-
# true if the given UTC DateTime is before the end of the period
-
# (exclusive); otherwise false.
-
2
def utc_before_end?(utc)
-
!@end_transition || @end_transition.at > utc
-
end
-
-
# true if this period is valid for the given local DateTime; otherwise false.
-
2
def valid_for_local?(local)
-
local_after_start?(local) && local_before_end?(local)
-
end
-
-
# true if the given local DateTime is after the start of the period
-
# (inclusive); otherwise false.
-
2
def local_after_start?(local)
-
!@start_transition || @start_transition.local_start_at <= local
-
end
-
-
# true if the given local DateTime is before the end of the period
-
# (exclusive); otherwise false.
-
2
def local_before_end?(local)
-
!@end_transition || @end_transition.local_end_at > local
-
end
-
-
# Converts a UTC DateTime to local time based on the offset of this period.
-
2
def to_local(utc)
-
534
@offset.to_local(utc)
-
end
-
-
# Converts a local DateTime to UTC based on the offset of this period.
-
2
def to_utc(local)
-
@offset.to_utc(local)
-
end
-
-
# Returns true if this TimezonePeriod is equal to p. This compares the
-
# start_transition, end_transition and offset using ==.
-
2
def ==(p)
-
p.kind_of?(TimezonePeriod) &&
-
start_transition == p.start_transition &&
-
end_transition == p.end_transition &&
-
offset == p.offset
-
end
-
-
# Returns true if this TimezonePeriods is equal to p. This compares the
-
# start_transition, end_transition and offset using eql?
-
2
def eql?(p)
-
p.kind_of?(TimezonePeriod) &&
-
start_transition.eql?(p.start_transition) &&
-
end_transition.eql?(p.end_transition) &&
-
offset.eql?(p.offset)
-
end
-
-
# Returns a hash of this TimezonePeriod.
-
2
def hash
-
result = @start_transition.hash ^ @end_transition.hash
-
result ^= @offset.hash unless @start_transition || @end_transition
-
result
-
end
-
-
# Returns internal object state as a programmer-readable string.
-
2
def inspect
-
result = "#<#{self.class}: #{@start_transition.inspect},#{@end_transition.inspect}"
-
result << ",#{@offset.inspect}>" unless @start_transition || @end_transition
-
result + '>'
-
end
-
end
-
end
-
2
module TZInfo
-
-
# A proxy class representing a timezone with a given identifier. TimezoneProxy
-
# inherits from Timezone and can be treated like any Timezone loaded with
-
# Timezone.get.
-
#
-
# The first time an attempt is made to access the data for the timezone, the
-
# real Timezone is loaded. If the proxy's identifier was not valid, then an
-
# exception will be raised at this point.
-
2
class TimezoneProxy < Timezone
-
# Construct a new TimezoneProxy for the given identifier. The identifier
-
# is not checked when constructing the proxy. It will be validated on the
-
# when the real Timezone is loaded.
-
2
def self.new(identifier)
-
# Need to override new to undo the behaviour introduced in Timezone#new.
-
2
tzp = super()
-
2
tzp.send(:setup, identifier)
-
2
tzp
-
end
-
-
# The identifier of the timezone, e.g. "Europe/Paris".
-
2
def identifier
-
@real_timezone ? @real_timezone.identifier : @identifier
-
end
-
-
# Returns the TimezonePeriod for the given UTC time. utc can either be
-
# a DateTime, Time or integer timestamp (Time.to_i). Any timezone
-
# information in utc is ignored (it is treated as a UTC time).
-
2
def period_for_utc(utc)
-
536
real_timezone.period_for_utc(utc)
-
end
-
-
# Returns the set of TimezonePeriod instances that are valid for the given
-
# local time as an array. If you just want a single period, use
-
# period_for_local instead and specify how abiguities should be resolved.
-
# Returns an empty array if no periods are found for the given time.
-
2
def periods_for_local(local)
-
real_timezone.periods_for_local(local)
-
end
-
-
# Returns the canonical zone for this Timezone.
-
2
def canonical_zone
-
real_timezone.canonical_zone
-
end
-
-
# Dumps this TimezoneProxy for marshalling.
-
2
def _dump(limit)
-
identifier
-
end
-
-
# Loads a marshalled TimezoneProxy.
-
2
def self._load(data)
-
TimezoneProxy.new(data)
-
end
-
-
2
private
-
2
def setup(identifier)
-
2
@identifier = identifier
-
2
@real_timezone = nil
-
end
-
-
2
def real_timezone
-
# Thread-safety: It is possible that the value of @real_timezone may be
-
# calculated multiple times in concurrently executing threads. It is not
-
# worth the overhead of locking to ensure that @real_timezone is only
-
# calculated once.
-
536
@real_timezone ||= Timezone.get(@identifier)
-
end
-
end
-
end
-
2
module TZInfo
-
# Represents a transition from one timezone offset to another at a particular
-
# date and time.
-
2
class TimezoneTransition
-
# The offset this transition changes to (a TimezoneOffset instance).
-
2
attr_reader :offset
-
-
# The offset this transition changes from (a TimezoneOffset instance).
-
2
attr_reader :previous_offset
-
-
# Initializes a new TimezoneTransition.
-
#
-
# TimezoneTransition instances should not normally be constructed manually.
-
2
def initialize(offset, previous_offset)
-
@offset = offset
-
@previous_offset = previous_offset
-
@local_end_at = nil
-
@local_start_at = nil
-
end
-
-
# A TimeOrDateTime instance representing the UTC time when this transition
-
# occurs.
-
2
def at
-
raise_not_implemented('at')
-
end
-
-
# The UTC time when this transition occurs, returned as a DateTime instance.
-
2
def datetime
-
at.to_datetime
-
end
-
-
# The UTC time when this transition occurs, returned as a Time instance.
-
2
def time
-
at.to_time
-
end
-
-
# A TimeOrDateTime instance representing the local time when this transition
-
# causes the previous observance to end (calculated from at using
-
# previous_offset).
-
2
def local_end_at
-
# Thread-safety: It is possible that the value of @local_end_at may be
-
# calculated multiple times in concurrently executing threads. It is not
-
# worth the overhead of locking to ensure that @local_end_at is only
-
# calculated once.
-
-
@local_end_at = at.add_with_convert(@previous_offset.utc_total_offset) unless @local_end_at
-
@local_end_at
-
end
-
-
# The local time when this transition causes the previous observance to end,
-
# returned as a DateTime instance.
-
2
def local_end
-
local_end_at.to_datetime
-
end
-
-
# The local time when this transition causes the previous observance to end,
-
# returned as a Time instance.
-
2
def local_end_time
-
local_end_at.to_time
-
end
-
-
# A TimeOrDateTime instance representing the local time when this transition
-
# causes the next observance to start (calculated from at using offset).
-
2
def local_start_at
-
# Thread-safety: It is possible that the value of @local_start_at may be
-
# calculated multiple times in concurrently executing threads. It is not
-
# worth the overhead of locking to ensure that @local_start_at is only
-
# calculated once.
-
-
@local_start_at = at.add_with_convert(@offset.utc_total_offset) unless @local_start_at
-
@local_start_at
-
end
-
-
# The local time when this transition causes the next observance to start,
-
# returned as a DateTime instance.
-
2
def local_start
-
local_start_at.to_datetime
-
end
-
-
# The local time when this transition causes the next observance to start,
-
# returned as a Time instance.
-
2
def local_start_time
-
local_start_at.to_time
-
end
-
-
# Returns true if this TimezoneTransition is equal to the given
-
# TimezoneTransition. Two TimezoneTransition instances are
-
# considered to be equal by == if offset, previous_offset and at are all
-
# equal.
-
2
def ==(tti)
-
tti.kind_of?(TimezoneTransition) &&
-
offset == tti.offset && previous_offset == tti.previous_offset && at == tti.at
-
end
-
-
# Returns true if this TimezoneTransition is equal to the given
-
# TimezoneTransition. Two TimezoneTransition instances are
-
# considered to be equal by eql? if offset, previous_offset and at are all
-
# equal and the type used to define at in both instances is the same.
-
2
def eql?(tti)
-
tti.kind_of?(TimezoneTransition) &&
-
offset == tti.offset && previous_offset == tti.previous_offset && at.eql?(tti.at)
-
end
-
-
# Returns a hash of this TimezoneTransition instance.
-
2
def hash
-
@offset.hash ^ @previous_offset.hash ^ at.hash
-
end
-
-
# Returns internal object state as a programmer-readable string.
-
2
def inspect
-
"#<#{self.class}: #{at.inspect},#{@offset.inspect}>"
-
end
-
-
2
private
-
-
2
def raise_not_implemented(method_name)
-
raise NotImplementedError, "Subclasses must override #{method_name}"
-
end
-
end
-
end
-
2
module TZInfo
-
# A TimezoneTransition defined by as integer timestamp, as a rational to
-
# create a DateTime or as both.
-
#
-
# @private
-
2
class TimezoneTransitionDefinition < TimezoneTransition #:nodoc:
-
# The numerator of the DateTime if the transition time is defined as a
-
# DateTime, otherwise the transition time as a timestamp.
-
2
attr_reader :numerator_or_time
-
2
protected :numerator_or_time
-
-
# Either the denominator of the DateTime if the transition time is defined
-
# as a DateTime, otherwise nil.
-
2
attr_reader :denominator
-
2
protected :denominator
-
-
# Creates a new TimezoneTransitionDefinition with the given offset,
-
# previous_offset (both TimezoneOffset instances) and UTC time.
-
#
-
# The time can be specified as a timestamp, as a rational to create a
-
# DateTime, or as both.
-
#
-
# If both a timestamp and rational are given, then the rational will only
-
# be used if the timestamp falls outside of the range of Time on the
-
# platform being used at runtime.
-
#
-
# DateTimes are created from the rational as follows:
-
#
-
# RubyCoreSupport.datetime_new!(RubyCoreSupport.rational_new!(numerator, denominator), 0, Date::ITALY)
-
#
-
# For performance reasons, the numerator and denominator must be specified
-
# in their lowest form.
-
2
def initialize(offset, previous_offset, numerator_or_timestamp, denominator_or_numerator = nil, denominator = nil)
-
super(offset, previous_offset)
-
-
if denominator
-
numerator = denominator_or_numerator
-
timestamp = numerator_or_timestamp
-
elsif denominator_or_numerator
-
numerator = numerator_or_timestamp
-
denominator = denominator_or_numerator
-
timestamp = nil
-
else
-
numerator = nil
-
denominator = nil
-
timestamp = numerator_or_timestamp
-
end
-
-
# Determine whether to use the timestamp or the numerator and denominator.
-
if numerator && (
-
!timestamp ||
-
(timestamp < 0 && !RubyCoreSupport.time_supports_negative) ||
-
((timestamp < -2147483648 || timestamp > 2147483647) && !RubyCoreSupport.time_supports_64bit)
-
)
-
-
@numerator_or_time = numerator
-
@denominator = denominator
-
else
-
@numerator_or_time = timestamp
-
@denominator = nil
-
end
-
-
@at = nil
-
end
-
-
# A TimeOrDateTime instance representing the UTC time when this transition
-
# occurs.
-
2
def at
-
# Thread-safety: It is possible that the value of @at may be calculated
-
# multiple times in concurrently executing threads. It is not worth the
-
# overhead of locking to ensure that @at is only calculated once.
-
-
unless @at
-
unless @denominator
-
@at = TimeOrDateTime.new(@numerator_or_time)
-
else
-
r = RubyCoreSupport.rational_new!(@numerator_or_time, @denominator)
-
dt = RubyCoreSupport.datetime_new!(r, 0, Date::ITALY)
-
@at = TimeOrDateTime.new(dt)
-
end
-
end
-
-
@at
-
end
-
-
# Returns true if this TimezoneTransitionDefinition is equal to the given
-
# TimezoneTransitionDefinition. Two TimezoneTransitionDefinition instances
-
# are considered to be equal by eql? if offset, previous_offset,
-
# numerator_or_time and denominator are all equal.
-
2
def eql?(tti)
-
tti.kind_of?(TimezoneTransitionDefinition) &&
-
offset == tti.offset && previous_offset == tti.previous_offset &&
-
numerator_or_time == tti.numerator_or_time && denominator == tti.denominator
-
end
-
-
# Returns a hash of this TimezoneTransitionDefinition instance.
-
2
def hash
-
@offset.hash ^ @previous_offset.hash ^ @numerator_or_time.hash ^ @denominator.hash
-
end
-
end
-
end
-
2
module TZInfo
-
# Raised if no offsets have been defined when calling period_for_utc or
-
# periods_for_local. Indicates an error in the timezone data.
-
2
class NoOffsetsDefined < StandardError
-
end
-
-
# Represents a data timezone defined by a set of offsets and a set
-
# of transitions.
-
#
-
# @private
-
2
class TransitionDataTimezoneInfo < DataTimezoneInfo #:nodoc:
-
-
# Constructs a new TransitionDataTimezoneInfo with its identifier.
-
2
def initialize(identifier)
-
2
super(identifier)
-
2
@offsets = {}
-
2
@transitions = []
-
2
@previous_offset = nil
-
2
@transitions_index = nil
-
end
-
-
# Defines a offset. The id uniquely identifies this offset within the
-
# timezone. utc_offset and std_offset define the offset in seconds of
-
# standard time from UTC and daylight savings from standard time
-
# respectively. abbreviation describes the timezone offset (e.g. GMT, BST,
-
# EST or EDT).
-
#
-
# The first offset to be defined is treated as the offset that applies
-
# until the first transition. This will usually be in Local Mean Time (LMT).
-
#
-
# ArgumentError will be raised if the id is already defined.
-
2
def offset(id, utc_offset, std_offset, abbreviation)
-
2
raise ArgumentError, 'Offset already defined' if @offsets.has_key?(id)
-
-
2
offset = TimezoneOffset.new(utc_offset, std_offset, abbreviation)
-
2
@offsets[id] = offset
-
2
@previous_offset = offset unless @previous_offset
-
end
-
-
# Defines a transition. Transitions must be defined in chronological order.
-
# ArgumentError will be raised if a transition is added out of order.
-
# offset_id refers to an id defined with offset. ArgumentError will be
-
# raised if the offset_id cannot be found. numerator_or_time and
-
# denomiator specify the time the transition occurs as. See
-
# TimezoneTransition for more detail about specifying times.
-
2
def transition(year, month, offset_id, numerator_or_timestamp, denominator_or_numerator = nil, denominator = nil)
-
offset = @offsets[offset_id]
-
raise ArgumentError, 'Offset not found' unless offset
-
-
if @transitions_index
-
if year < @last_year || (year == @last_year && month < @last_month)
-
raise ArgumentError, 'Transitions must be increasing date order'
-
end
-
-
# Record the position of the first transition with this index.
-
index = transition_index(year, month)
-
@transitions_index[index] ||= @transitions.length
-
-
# Fill in any gaps
-
(index - 1).downto(0) do |i|
-
break if @transitions_index[i]
-
@transitions_index[i] = @transitions.length
-
end
-
else
-
@transitions_index = [@transitions.length]
-
@start_year = year
-
@start_month = month
-
end
-
-
@transitions << TimezoneTransitionDefinition.new(offset, @previous_offset,
-
numerator_or_timestamp, denominator_or_numerator, denominator)
-
@last_year = year
-
@last_month = month
-
@previous_offset = offset
-
end
-
-
# Returns the TimezonePeriod for the given UTC time.
-
# Raises NoOffsetsDefined if no offsets have been defined.
-
2
def period_for_utc(utc)
-
536
unless @transitions.empty?
-
utc = TimeOrDateTime.wrap(utc)
-
index = transition_index(utc.year, utc.mon)
-
-
start_transition = nil
-
start = transition_before_end(index)
-
if start
-
start.downto(0) do |i|
-
if @transitions[i].at <= utc
-
start_transition = @transitions[i]
-
break
-
end
-
end
-
end
-
-
end_transition = nil
-
start = transition_after_start(index)
-
if start
-
start.upto(@transitions.length - 1) do |i|
-
if @transitions[i].at > utc
-
end_transition = @transitions[i]
-
break
-
end
-
end
-
end
-
-
if start_transition || end_transition
-
TimezonePeriod.new(start_transition, end_transition)
-
else
-
# Won't happen since there are transitions. Must always find one
-
# transition that is either >= or < the specified time.
-
raise 'No transitions found in search'
-
end
-
else
-
536
raise NoOffsetsDefined, 'No offsets have been defined' unless @previous_offset
-
536
TimezonePeriod.new(nil, nil, @previous_offset)
-
end
-
end
-
-
# Returns the set of TimezonePeriods for the given local time as an array.
-
# Results returned are ordered by increasing UTC start date.
-
# Returns an empty array if no periods are found for the given time.
-
# Raises NoOffsetsDefined if no offsets have been defined.
-
2
def periods_for_local(local)
-
unless @transitions.empty?
-
local = TimeOrDateTime.wrap(local)
-
index = transition_index(local.year, local.mon)
-
-
result = []
-
-
start_index = transition_after_start(index - 1)
-
if start_index && @transitions[start_index].local_end_at > local
-
if start_index > 0
-
if @transitions[start_index - 1].local_start_at <= local
-
result << TimezonePeriod.new(@transitions[start_index - 1], @transitions[start_index])
-
end
-
else
-
result << TimezonePeriod.new(nil, @transitions[start_index])
-
end
-
end
-
-
end_index = transition_before_end(index + 1)
-
-
if end_index
-
start_index = end_index unless start_index
-
-
start_index.upto(transition_before_end(index + 1)) do |i|
-
if @transitions[i].local_start_at <= local
-
if i + 1 < @transitions.length
-
if @transitions[i + 1].local_end_at > local
-
result << TimezonePeriod.new(@transitions[i], @transitions[i + 1])
-
end
-
else
-
result << TimezonePeriod.new(@transitions[i], nil)
-
end
-
end
-
end
-
end
-
-
result
-
else
-
raise NoOffsetsDefined, 'No offsets have been defined' unless @previous_offset
-
[TimezonePeriod.new(nil, nil, @previous_offset)]
-
end
-
end
-
-
# Returns an Array of TimezoneTransition instances representing the times
-
# where the UTC offset of the timezone changes.
-
#
-
# Transitions are returned up to a given date and time up to a given date
-
# and time, specified in UTC (utc_to).
-
#
-
# A from date and time may also be supplied using the utc_from parameter
-
# (also specified in UTC). If utc_from is not nil, only transitions from
-
# that date and time onwards will be returned.
-
#
-
# Comparisons with utc_to are exclusive. Comparisons with utc_from are
-
# inclusive. If a transition falls precisely on utc_to, it will be excluded.
-
# If a transition falls on utc_from, it will be included.
-
#
-
# Transitions returned are ordered by when they occur, from earliest to
-
# latest.
-
#
-
# utc_to and utc_from can be specified using either DateTime, Time or
-
# integer timestamps (Time.to_i).
-
#
-
# If utc_from is specified and utc_to is not greater than utc_from, then
-
# transitions_up_to raises an ArgumentError exception.
-
2
def transitions_up_to(utc_to, utc_from = nil)
-
utc_to = TimeOrDateTime.wrap(utc_to)
-
utc_from = utc_from ? TimeOrDateTime.wrap(utc_from) : nil
-
-
if utc_from && utc_to <= utc_from
-
raise ArgumentError, 'utc_to must be greater than utc_from'
-
end
-
-
unless @transitions.empty?
-
if utc_from
-
from = transition_after_start(transition_index(utc_from.year, utc_from.mon))
-
-
if from
-
while from < @transitions.length && @transitions[from].at < utc_from
-
from += 1
-
end
-
-
if from >= @transitions.length
-
return []
-
end
-
else
-
# utc_from is later than last transition.
-
return []
-
end
-
else
-
from = 0
-
end
-
-
to = transition_before_end(transition_index(utc_to.year, utc_to.mon))
-
-
if to
-
while to >= 0 && @transitions[to].at >= utc_to
-
to -= 1
-
end
-
-
if to < 0
-
return []
-
end
-
else
-
# utc_to is earlier than first transition.
-
return []
-
end
-
-
@transitions[from..to]
-
else
-
[]
-
end
-
end
-
-
2
private
-
# Returns the index into the @transitions_index array for a given year
-
# and month.
-
2
def transition_index(year, month)
-
index = (year - @start_year) * 2
-
index += 1 if month > 6
-
index -= 1 if @start_month > 6
-
index
-
end
-
-
# Returns the index into @transitions of the first transition that occurs
-
# on or after the start of the given index into @transitions_index.
-
# Returns nil if there are no such transitions.
-
2
def transition_after_start(index)
-
if index >= @transitions_index.length
-
nil
-
else
-
index = 0 if index < 0
-
@transitions_index[index]
-
end
-
end
-
-
# Returns the index into @transitions of the first transition that occurs
-
# before the end of the given index into @transitions_index.
-
# Returns nil if there are no such transitions.
-
2
def transition_before_end(index)
-
index = index + 1
-
-
if index <= 0
-
nil
-
elsif index >= @transitions_index.length
-
@transitions.length - 1
-
else
-
@transitions_index[index] - 1
-
end
-
end
-
end
-
end
-
2
module TZInfo
-
# Represents information about a country returned by ZoneinfoDataSource.
-
#
-
# @private
-
2
class ZoneinfoCountryInfo < CountryInfo #:nodoc:
-
# Constructs a new CountryInfo with an ISO 3166 country code, name and
-
# an array of CountryTimezones.
-
2
def initialize(code, name, zones)
-
498
super(code, name)
-
498
@zones = zones.dup.freeze
-
498
@zone_identifiers = nil
-
end
-
-
# Returns a frozen array of all the zone identifiers for the country ordered
-
# geographically, most populous first.
-
2
def zone_identifiers
-
# Thread-safety: It is possible that the value of @zone_identifiers may be
-
# calculated multiple times in concurrently executing threads. It is not
-
# worth the overhead of locking to ensure that @zone_identifiers is only
-
# calculated once.
-
-
unless @zone_identifiers
-
@zone_identifiers = zones.collect {|zone| zone.identifier}.freeze
-
end
-
-
@zone_identifiers
-
end
-
-
# Returns a frozen array of all the timezones for the for the country
-
# ordered geographically, most populous first.
-
2
def zones
-
@zones
-
end
-
end
-
end
-
2
module TZInfo
-
# An InvalidZoneinfoDirectory exception is raised if the DataSource is
-
# set to a specific zoneinfo path, which is not a valid zoneinfo directory
-
# (i.e. a directory containing index files named iso3166.tab and zone.tab
-
# as well as other timezone files).
-
2
class InvalidZoneinfoDirectory < StandardError
-
end
-
-
# A ZoneinfoDirectoryNotFound exception is raised if no valid zoneinfo
-
# directory could be found when checking the paths listed in
-
# ZoneinfoDataSource.search_path. A valid zoneinfo directory is one that
-
# contains timezone files, a country code index file named iso3166.tab and a
-
# timezone index file named zone1970.tab or zone.tab.
-
2
class ZoneinfoDirectoryNotFound < StandardError
-
end
-
-
# A DataSource that loads data from a 'zoneinfo' directory containing
-
# compiled "TZif" version 3 (or earlier) files in addition to iso3166.tab and
-
# zone1970.tab or zone.tab index files.
-
#
-
# To have TZInfo load the system zoneinfo files, call TZInfo::DataSource.set
-
# as follows:
-
#
-
# TZInfo::DataSource.set(:zoneinfo)
-
#
-
# To load zoneinfo files from a particular directory, pass the directory to
-
# TZInfo::DataSource.set:
-
#
-
# TZInfo::DataSource.set(:zoneinfo, directory)
-
#
-
# Note that the platform used at runtime may limit the range of available
-
# transition data that can be loaded from zoneinfo files. There are two
-
# factors to consider:
-
#
-
# First of all, the zoneinfo support in TZInfo makes use of Ruby's Time class.
-
# On 32-bit builds of Ruby 1.8, the Time class only supports 32-bit
-
# timestamps. This means that only Times between 1901-12-13 20:45:52 and
-
# 2038-01-19 03:14:07 can be represented. Furthermore, certain platforms only
-
# allow for positive 32-bit timestamps (notably Windows), making the earliest
-
# representable time 1970-01-01 00:00:00.
-
#
-
# 64-bit builds of Ruby 1.8 and all builds of Ruby 1.9 support 64-bit
-
# timestamps. This means that there is no practical restriction on the range
-
# of the Time class on these platforms.
-
#
-
# TZInfo will only load transitions that fall within the supported range of
-
# the Time class. Any queries performed on times outside of this range may
-
# give inaccurate results.
-
#
-
# The second factor concerns the zoneinfo files. Versions of the 'zic' tool
-
# (used to build zoneinfo files) that were released prior to February 2006
-
# created zoneinfo files that used 32-bit integers for transition timestamps.
-
# Later versions of zic produce zoneinfo files that use 64-bit integers. If
-
# you have 32-bit zoneinfo files on your system, then any queries falling
-
# outside of the range 1901-12-13 20:45:52 to 2038-01-19 03:14:07 may be
-
# inaccurate.
-
#
-
# Most modern platforms include 64-bit zoneinfo files. However, Mac OS X (up
-
# to at least 10.8.4) still uses 32-bit zoneinfo files.
-
#
-
# To check whether your zoneinfo files contain 32-bit or 64-bit transition
-
# data, you can run the following code (substituting the identifier of the
-
# zone you want to test for zone_identifier):
-
#
-
# TZInfo::DataSource.set(:zoneinfo)
-
# dir = TZInfo::DataSource.get.zoneinfo_dir
-
# File.open(File.join(dir, zone_identifier), 'r') {|f| f.read(5) }
-
#
-
# If the last line returns "TZif\\x00", then you have a 32-bit zoneinfo file.
-
# If it returns "TZif2" or "TZif3" then you have a 64-bit zoneinfo file.
-
#
-
# If you require support for 64-bit transitions, but are restricted to 32-bit
-
# zoneinfo support, then you may want to consider using TZInfo::RubyDataSource
-
# instead.
-
2
class ZoneinfoDataSource < DataSource
-
# The default value of ZoneinfoDataSource.search_path.
-
2
DEFAULT_SEARCH_PATH = ['/usr/share/zoneinfo', '/usr/share/lib/zoneinfo', '/etc/zoneinfo'].freeze
-
-
# The default value of ZoneinfoDataSource.alternate_iso3166_tab_search_path.
-
2
DEFAULT_ALTERNATE_ISO3166_TAB_SEARCH_PATH = ['/usr/share/misc/iso3166.tab', '/usr/share/misc/iso3166'].freeze
-
-
# Paths to be checked to find the system zoneinfo directory.
-
2
@@search_path = DEFAULT_SEARCH_PATH.dup
-
-
# Paths to possible alternate iso3166.tab files (used to locate the
-
# system-wide iso3166.tab files on FreeBSD and OpenBSD).
-
2
@@alternate_iso3166_tab_search_path = DEFAULT_ALTERNATE_ISO3166_TAB_SEARCH_PATH.dup
-
-
# An Array of directories that will be checked to find the system zoneinfo
-
# directory.
-
#
-
# Directories are checked in the order they appear in the Array.
-
#
-
# The default value is ['/usr/share/zoneinfo', '/usr/share/lib/zoneinfo', '/etc/zoneinfo'].
-
2
def self.search_path
-
2
@@search_path
-
end
-
-
# Sets the directories to be checked when locating the system zoneinfo
-
# directory.
-
#
-
# Can be set to an Array of directories or a String containing directories
-
# separated with File::PATH_SEPARATOR.
-
#
-
# Directories are checked in the order they appear in the Array or String.
-
#
-
# Set to nil to revert to the default paths.
-
2
def self.search_path=(search_path)
-
@@search_path = process_search_path(search_path, DEFAULT_SEARCH_PATH)
-
end
-
-
# An Array of paths that will be checked to find an alternate iso3166.tab
-
# file if one was not included in the zoneinfo directory (for example, on
-
# FreeBSD and OpenBSD systems).
-
#
-
# Paths are checked in the order they appear in the array.
-
#
-
# The default value is ['/usr/share/misc/iso3166.tab', '/usr/share/misc/iso3166'].
-
2
def self.alternate_iso3166_tab_search_path
-
2
@@alternate_iso3166_tab_search_path
-
end
-
-
# Sets the paths to check to locate an alternate iso3166.tab file if one was
-
# not included in the zoneinfo directory.
-
#
-
# Can be set to an Array of directories or a String containing directories
-
# separated with File::PATH_SEPARATOR.
-
#
-
# Paths are checked in the order they appear in the array.
-
#
-
# Set to nil to revert to the default paths.
-
2
def self.alternate_iso3166_tab_search_path=(alternate_iso3166_tab_search_path)
-
@@alternate_iso3166_tab_search_path = process_search_path(alternate_iso3166_tab_search_path, DEFAULT_ALTERNATE_ISO3166_TAB_SEARCH_PATH)
-
end
-
-
# The zoneinfo directory being used.
-
2
attr_reader :zoneinfo_dir
-
-
# Creates a new ZoneinfoDataSource.
-
#
-
# If zoneinfo_dir is specified, it will be checked and used as the source
-
# of zoneinfo files.
-
#
-
# The directory must contain a file named iso3166.tab and a file named
-
# either zone1970.tab or zone.tab. These may either be included in the root
-
# of the directory or in a 'tab' sub-directory and named 'country.tab' and
-
# 'zone_sun.tab' respectively (as is the case on Solaris.
-
#
-
# Additionally, the path to iso3166.tab can be overridden using the
-
# alternate_iso3166_tab_path parameter.
-
#
-
# InvalidZoneinfoDirectory will be raised if the iso3166.tab and
-
# zone1970.tab or zone.tab files cannot be found using the zoneinfo_dir and
-
# alternate_iso3166_tab_path parameters.
-
#
-
# If zoneinfo_dir is not specified or nil, the paths referenced in
-
# search_path are searched in order to find a valid zoneinfo directory
-
# (one that contains zone1970.tab or zone.tab and iso3166.tab files as
-
# above).
-
#
-
# The paths referenced in alternate_iso3166_tab_search_path are also
-
# searched to find an iso3166.tab file if one of the searched zoneinfo
-
# directories doesn't contain an iso3166.tab file.
-
#
-
# If no valid directory can be found by searching, ZoneinfoDirectoryNotFound
-
# will be raised.
-
2
def initialize(zoneinfo_dir = nil, alternate_iso3166_tab_path = nil)
-
2
if zoneinfo_dir
-
iso3166_tab_path, zone_tab_path = validate_zoneinfo_dir(zoneinfo_dir, alternate_iso3166_tab_path)
-
-
unless iso3166_tab_path && zone_tab_path
-
raise InvalidZoneinfoDirectory, "#{zoneinfo_dir} is not a directory or doesn't contain a iso3166.tab file and a zone1970.tab or zone.tab file."
-
end
-
-
@zoneinfo_dir = zoneinfo_dir
-
else
-
2
@zoneinfo_dir, iso3166_tab_path, zone_tab_path = find_zoneinfo_dir
-
-
2
unless @zoneinfo_dir && iso3166_tab_path && zone_tab_path
-
raise ZoneinfoDirectoryNotFound, "None of the paths included in TZInfo::ZoneinfoDataSource.search_path are valid zoneinfo directories."
-
end
-
end
-
-
2
@zoneinfo_dir = File.expand_path(@zoneinfo_dir).freeze
-
2
@timezone_index = load_timezone_index.freeze
-
2
@country_index = load_country_index(iso3166_tab_path, zone_tab_path).freeze
-
end
-
-
# Returns a TimezoneInfo instance for a given identifier.
-
# Raises InvalidTimezoneIdentifier if the timezone is not found or the
-
# identifier is invalid.
-
2
def load_timezone_info(identifier)
-
2
begin
-
2
if @timezone_index.include?(identifier)
-
2
path = File.join(@zoneinfo_dir, identifier)
-
-
# Untaint path rather than identifier. We don't want to modify
-
# identifier. identifier may also be frozen and therefore cannot be
-
# untainted.
-
2
path.untaint
-
-
2
begin
-
2
ZoneinfoTimezoneInfo.new(identifier, path)
-
rescue InvalidZoneinfoFile => e
-
raise InvalidTimezoneIdentifier, e.message
-
end
-
else
-
raise InvalidTimezoneIdentifier, 'Invalid identifier'
-
end
-
rescue Errno::ENOENT, Errno::ENAMETOOLONG, Errno::ENOTDIR
-
raise InvalidTimezoneIdentifier, 'Invalid identifier'
-
rescue Errno::EACCES => e
-
raise InvalidTimezoneIdentifier, e.message
-
end
-
end
-
-
# Returns an array of all the available timezone identifiers.
-
2
def timezone_identifiers
-
@timezone_index
-
end
-
-
# Returns an array of all the available timezone identifiers for
-
# data timezones (i.e. those that actually contain definitions).
-
#
-
# For ZoneinfoDataSource, this will always be identical to
-
# timezone_identifers.
-
2
def data_timezone_identifiers
-
@timezone_index
-
end
-
-
# Returns an array of all the available timezone identifiers that
-
# are links to other timezones.
-
#
-
# For ZoneinfoDataSource, this will always be an empty array.
-
2
def linked_timezone_identifiers
-
[].freeze
-
end
-
-
# Returns a CountryInfo instance for the given ISO 3166-1 alpha-2
-
# country code. Raises InvalidCountryCode if the country could not be found
-
# or the code is invalid.
-
2
def load_country_info(code)
-
info = @country_index[code]
-
raise InvalidCountryCode, 'Invalid country code' unless info
-
info
-
end
-
-
# Returns an array of all the available ISO 3166-1 alpha-2
-
# country codes.
-
2
def country_codes
-
@country_index.keys.freeze
-
end
-
-
# Returns the name and information about this DataSource.
-
2
def to_s
-
"Zoneinfo DataSource: #{@zoneinfo_dir}"
-
end
-
-
# Returns internal object state as a programmer-readable string.
-
2
def inspect
-
"#<#{self.class}: #{@zoneinfo_dir}>"
-
end
-
-
2
private
-
-
# Processes a path for use as the search_path or
-
# alternate_iso3166_tab_search_path.
-
2
def self.process_search_path(path, default)
-
if path
-
if path.kind_of?(String)
-
path.split(File::PATH_SEPARATOR)
-
else
-
path.collect {|p| p.to_s}
-
end
-
else
-
default.dup
-
end
-
end
-
-
# Validates a zoneinfo directory and returns the paths to the iso3166.tab
-
# and zone1970.tab or zone.tab files if valid. If the directory is not
-
# valid, returns nil.
-
#
-
# The path to the iso3166.tab file may be overriden by passing in a path.
-
# This is treated as either absolute or relative to the current working
-
# directory.
-
2
def validate_zoneinfo_dir(path, iso3166_tab_path = nil)
-
2
if File.directory?(path)
-
2
if iso3166_tab_path
-
return nil unless File.file?(iso3166_tab_path)
-
else
-
2
iso3166_tab_path = resolve_tab_path(path, ['iso3166.tab'], 'country.tab')
-
2
return nil unless iso3166_tab_path
-
end
-
-
2
zone_tab_path = resolve_tab_path(path, ['zone1970.tab', 'zone.tab'], 'zone_sun.tab')
-
2
return nil unless zone_tab_path
-
-
2
[iso3166_tab_path, zone_tab_path]
-
else
-
nil
-
end
-
end
-
-
# Attempts to resolve the path to a tab file given its standard names and
-
# tab sub-directory name (as used on Solaris).
-
2
def resolve_tab_path(zoneinfo_path, standard_names, tab_name)
-
4
standard_names.each do |standard_name|
-
6
path = File.join(zoneinfo_path, standard_name)
-
6
return path if File.file?(path)
-
end
-
-
path = File.join(zoneinfo_path, 'tab', tab_name)
-
return path if File.file?(path)
-
-
nil
-
end
-
-
# Finds a zoneinfo directory using search_path and
-
# alternate_iso3166_tab_search_path. Returns the paths to the directory,
-
# the iso3166.tab file and the zone.tab file or nil if not found.
-
2
def find_zoneinfo_dir
-
2
alternate_iso3166_tab_path = self.class.alternate_iso3166_tab_search_path.detect do |path|
-
4
File.file?(path)
-
end
-
-
2
self.class.search_path.each do |path|
-
# Try without the alternate_iso3166_tab_path first.
-
2
iso3166_tab_path, zone_tab_path = validate_zoneinfo_dir(path)
-
2
return path, iso3166_tab_path, zone_tab_path if iso3166_tab_path && zone_tab_path
-
-
if alternate_iso3166_tab_path
-
iso3166_tab_path, zone_tab_path = validate_zoneinfo_dir(path, alternate_iso3166_tab_path)
-
return path, iso3166_tab_path, zone_tab_path if iso3166_tab_path && zone_tab_path
-
end
-
end
-
-
# Not found.
-
nil
-
end
-
-
# Scans @zoneinfo_dir and returns an Array of available timezone
-
# identifiers.
-
2
def load_timezone_index
-
2
index = []
-
-
# Ignoring particular files:
-
# +VERSION is included on Mac OS X.
-
# localtime current local timezone (may be a link).
-
# posix, posixrules and right are directories containing other versions of the zoneinfo files.
-
# src is a directory containing the tzdata source included on Solaris.
-
# Factory is the compiled in default timezone.
-
-
2
enum_timezones(nil, ['+VERSION', 'localtime', 'posix', 'posixrules', 'right', 'src', 'Factory']) do |identifier|
-
1192
index << identifier
-
end
-
-
2
index.sort
-
end
-
-
# Recursively scans a directory of timezones, calling the passed in block
-
# for each identifier found.
-
2
def enum_timezones(dir, exclude = [], &block)
-
44
Dir.foreach(dir ? File.join(@zoneinfo_dir, dir) : @zoneinfo_dir) do |entry|
-
1336
unless entry =~ /\./ || exclude.include?(entry)
-
1234
entry.untaint
-
1234
path = dir ? File.join(dir, entry) : entry
-
1234
full_path = File.join(@zoneinfo_dir, path)
-
-
1234
if File.directory?(full_path)
-
42
enum_timezones(path, [], &block)
-
elsif File.file?(full_path)
-
1192
yield path
-
end
-
end
-
end
-
end
-
-
# Uses the iso3166.tab and zone1970.tab or zone.tab files to build an index
-
# of the available countries and their timezones.
-
2
def load_country_index(iso3166_tab_path, zone_tab_path)
-
-
# Handle standard 3 to 4 column zone.tab files as well as the 4 to 5
-
# column format used by Solaris.
-
#
-
# On Solaris, an extra column before the comment gives an optional
-
# linked/alternate timezone identifier (or '-' if not set).
-
#
-
# Additionally, there is a section at the end of the file for timezones
-
# covering regions. These are given lower-case "country" codes. The timezone
-
# identifier column refers to a continent instead of an identifier. These
-
# lines will be ignored by TZInfo.
-
#
-
# Since the last column is optional in both formats, testing for the
-
# Solaris format is done in two passes. The first pass identifies if there
-
# are any lines using 5 columns.
-
-
-
# The first column is allowed to be a comma separated list of country
-
# codes, as used in zone1970.tab (introduced in tzdata 2014f).
-
#
-
# The first country code in the comma-separated list is the country that
-
# contains the city the zone identifer is based on. The first country
-
# code on each line is considered to be primary with the others
-
# secondary.
-
#
-
# The zones for each country are ordered primary first, then secondary.
-
# Within the primary and secondary groups, the zones are ordered by their
-
# order in the file.
-
-
2
file_is_5_column = false
-
2
zone_tab = []
-
-
2
RubyCoreSupport.open_file(zone_tab_path, 'r', :external_encoding => 'UTF-8', :internal_encoding => 'UTF-8') do |file|
-
2
file.each_line do |line|
-
882
line.chomp!
-
-
882
if line =~ /\A([A-Z]{2}(?:,[A-Z]{2})*)\t(?:([+\-])(\d{2})(\d{2})([+\-])(\d{3})(\d{2})|([+\-])(\d{2})(\d{2})(\d{2})([+\-])(\d{3})(\d{2})(\d{2}))\t([^\t]+)(?:\t([^\t]+))?(?:\t([^\t]+))?\z/
-
834
codes = $1
-
-
834
if $2
-
736
latitude = dms_to_rational($2, $3, $4)
-
736
longitude = dms_to_rational($5, $6, $7)
-
else
-
98
latitude = dms_to_rational($8, $9, $10, $11)
-
98
longitude = dms_to_rational($12, $13, $14, $15)
-
end
-
-
834
zone_identifier = $16
-
834
column4 = $17
-
834
column5 = $18
-
-
834
file_is_5_column = true if column5
-
-
834
zone_tab << [codes.split(','), zone_identifier, latitude, longitude, column4, column5]
-
end
-
end
-
end
-
-
2
primary_zones = {}
-
2
secondary_zones = {}
-
-
2
zone_tab.each do |codes, zone_identifier, latitude, longitude, column4, column5|
-
834
description = file_is_5_column ? column5 : column4
-
834
country_timezone = CountryTimezone.new(zone_identifier, latitude, longitude, description)
-
-
# codes will always have at least one element
-
-
834
(primary_zones[codes.first] ||= []) << country_timezone
-
-
834
codes[1..-1].each do |code|
-
(secondary_zones[code] ||= []) << country_timezone
-
end
-
end
-
-
2
countries = {}
-
-
2
RubyCoreSupport.open_file(iso3166_tab_path, 'r', :external_encoding => 'UTF-8', :internal_encoding => 'UTF-8') do |file|
-
2
file.each_line do |line|
-
548
line.chomp!
-
-
# Handle both the two column alpha-2 and name format used in the tz
-
# database as well as the 4 column alpha-2, alpha-3, numeric-3 and
-
# name format used by FreeBSD and OpenBSD.
-
-
548
if line =~ /\A([A-Z]{2})(?:\t[A-Z]{3}\t[0-9]{3})?\t(.+)\z/
-
498
code = $1
-
498
name = $2
-
498
zones = (primary_zones[code] || []) + (secondary_zones[code] || [])
-
-
498
countries[code] = ZoneinfoCountryInfo.new(code, name, zones)
-
end
-
end
-
end
-
-
2
countries
-
end
-
-
# Converts degrees, minutes and seconds to a Rational.
-
2
def dms_to_rational(sign, degrees, minutes, seconds = nil)
-
1668
result = degrees.to_i + Rational(minutes.to_i, 60)
-
1668
result += Rational(seconds.to_i, 3600) if seconds
-
1668
result = -result if sign == '-'
-
1668
result
-
end
-
end
-
end
-
2
module TZInfo
-
# An InvalidZoneinfoFile exception is raised if an attempt is made to load an
-
# invalid zoneinfo file.
-
2
class InvalidZoneinfoFile < StandardError
-
end
-
-
# Represents a timezone defined by a compiled zoneinfo TZif (\0, 2 or 3) file.
-
#
-
# @private
-
2
class ZoneinfoTimezoneInfo < TransitionDataTimezoneInfo #:nodoc:
-
-
# Minimum supported timestamp (inclusive).
-
#
-
# Time.utc(1700, 1, 1).to_i
-
2
MIN_TIMESTAMP = -8520336000
-
-
# Maximum supported timestamp (exclusive).
-
#
-
# Time.utc(2500, 1, 1).to_i
-
2
MAX_TIMESTAMP = 16725225600
-
-
# Constructs the new ZoneinfoTimezoneInfo with an identifier and path
-
# to the file.
-
2
def initialize(identifier, file_path)
-
2
super(identifier)
-
-
2
File.open(file_path, 'rb') do |file|
-
2
parse(file)
-
end
-
end
-
-
2
private
-
# Unpack will return unsigned 32-bit integers. Translate to
-
# signed 32-bit.
-
2
def make_signed_int32(long)
-
2
long >= 0x80000000 ? long - 0x100000000 : long
-
end
-
-
# Unpack will return a 64-bit integer as two unsigned 32-bit integers
-
# (most significant first). Translate to signed 64-bit
-
2
def make_signed_int64(high, low)
-
unsigned = (high << 32) | low
-
unsigned >= 0x8000000000000000 ? unsigned - 0x10000000000000000 : unsigned
-
end
-
-
# Read bytes from file and check that the correct number of bytes could
-
# be read. Raises InvalidZoneinfoFile if the number of bytes didn't match
-
# the number requested.
-
2
def check_read(file, bytes)
-
8
result = file.read(bytes)
-
-
8
unless result && result.length == bytes
-
raise InvalidZoneinfoFile, "Expected #{bytes} bytes reading '#{file.path}', but got #{result ? result.length : 0} bytes"
-
end
-
-
8
result
-
end
-
-
# Zoneinfo doesn't include the offset from standard time (std_offset).
-
# Derive the missing offsets by looking at changes in the total UTC
-
# offset.
-
#
-
# This will be run through forwards and then backwards by the parse
-
# method.
-
2
def derive_offsets(transitions, offsets)
-
4
previous_offset = nil
-
-
4
transitions.each do |t|
-
offset = offsets[t[:offset]]
-
-
if !offset[:std_offset] && offset[:is_dst] && previous_offset
-
difference = offset[:utc_total_offset] - previous_offset[:utc_total_offset]
-
-
if previous_offset[:is_dst]
-
if previous_offset[:std_offset]
-
std_offset = previous_offset[:std_offset] + difference
-
else
-
std_offset = nil
-
end
-
else
-
std_offset = difference
-
end
-
-
if std_offset && std_offset > 0
-
offset[:std_offset] = std_offset
-
offset[:utc_offset] = offset[:utc_total_offset] - std_offset
-
end
-
end
-
-
previous_offset = offset
-
end
-
end
-
-
# Parses a zoneinfo file and intializes the DataTimezoneInfo structures.
-
2
def parse(file)
-
2
magic, version, ttisgmtcnt, ttisstdcnt, leapcnt, timecnt, typecnt, charcnt =
-
check_read(file, 44).unpack('a4 a x15 NNNNNN')
-
-
2
if magic != 'TZif'
-
raise InvalidZoneinfoFile, "The file '#{file.path}' does not start with the expected header."
-
end
-
-
2
if (version == '2' || version == '3') && RubyCoreSupport.time_supports_64bit
-
# Skip the first 32-bit section and read the header of the second 64-bit section
-
2
file.seek(timecnt * 5 + typecnt * 6 + charcnt + leapcnt * 8 + ttisgmtcnt + ttisstdcnt, IO::SEEK_CUR)
-
-
2
prev_version = version
-
-
2
magic, version, ttisgmtcnt, ttisstdcnt, leapcnt, timecnt, typecnt, charcnt =
-
check_read(file, 44).unpack('a4 a x15 NNNNNN')
-
-
2
unless magic == 'TZif' && (version == prev_version)
-
raise InvalidZoneinfoFile, "The file '#{file.path}' contains an invalid 64-bit section header."
-
end
-
-
2
using_64bit = true
-
elsif version != '3' && version != '2' && version != "\0"
-
raise InvalidZoneinfoFile, "The file '#{file.path}' contains a version of the zoneinfo format that is not currently supported."
-
else
-
using_64bit = false
-
end
-
-
2
unless leapcnt == 0
-
raise InvalidZoneinfoFile, "The zoneinfo file '#{file.path}' contains leap second data. TZInfo requires zoneinfo files that omit leap seconds."
-
end
-
-
2
transitions = []
-
-
2
if using_64bit
-
2
(0...timecnt).each do |i|
-
high, low = check_read(file, 8).unpack('NN')
-
transition_time = make_signed_int64(high, low)
-
transitions << {:at => transition_time}
-
end
-
else
-
(0...timecnt).each do |i|
-
transition_time = make_signed_int32(check_read(file, 4).unpack('N')[0])
-
transitions << {:at => transition_time}
-
end
-
end
-
-
2
(0...timecnt).each do |i|
-
localtime_type = check_read(file, 1).unpack('C')[0]
-
transitions[i][:offset] = localtime_type
-
end
-
-
2
offsets = []
-
-
2
(0...typecnt).each do |i|
-
2
gmtoff, isdst, abbrind = check_read(file, 6).unpack('NCC')
-
2
gmtoff = make_signed_int32(gmtoff)
-
2
isdst = isdst == 1
-
2
offset = {:utc_total_offset => gmtoff, :is_dst => isdst, :abbr_index => abbrind}
-
-
2
unless isdst
-
2
offset[:utc_offset] = gmtoff
-
2
offset[:std_offset] = 0
-
end
-
-
2
offsets << offset
-
end
-
-
2
abbrev = check_read(file, charcnt)
-
-
2
offsets.each do |o|
-
2
abbrev_start = o[:abbr_index]
-
2
raise InvalidZoneinfoFile, "Abbreviation index is out of range in file '#{file.path}'" unless abbrev_start < abbrev.length
-
-
2
abbrev_end = abbrev.index("\0", abbrev_start)
-
2
raise InvalidZoneinfoFile, "Missing abbreviation null terminator in file '#{file.path}'" unless abbrev_end
-
-
2
o[:abbr] = RubyCoreSupport.force_encoding(abbrev[abbrev_start...abbrev_end], 'UTF-8')
-
end
-
-
2
transitions.each do |t|
-
if t[:offset] < 0 || t[:offset] >= offsets.length
-
raise InvalidZoneinfoFile, "Invalid offset referenced by transition in file '#{file.path}'."
-
end
-
end
-
-
# Derive the offsets from standard time (std_offset).
-
2
derive_offsets(transitions, offsets)
-
2
derive_offsets(transitions.reverse, offsets)
-
-
# Assign anything left a standard offset of one hour
-
2
offsets.each do |o|
-
2
if !o[:std_offset] && o[:is_dst]
-
o[:std_offset] = 3600
-
o[:utc_offset] = o[:utc_total_offset] - 3600
-
end
-
end
-
-
# Find the first non-dst offset. This is used as the offset for the time
-
# before the first transition.
-
2
first = nil
-
2
offsets.each_with_index do |o, i|
-
2
if !o[:is_dst]
-
2
first = i
-
2
break
-
end
-
end
-
-
2
if first
-
2
offset first, offsets[first][:utc_offset], offsets[first][:std_offset], offsets[first][:abbr].untaint.to_sym
-
end
-
-
2
offsets.each_with_index do |o, i|
-
2
offset i, o[:utc_offset], o[:std_offset], o[:abbr].untaint.to_sym unless i == first
-
end
-
-
2
if !using_64bit && !RubyCoreSupport.time_supports_negative
-
# Filter out transitions that are not supported by Time on this
-
# platform.
-
-
# Move the last transition before the epoch up to the epoch. This
-
# allows for accurate conversions for all supported timestamps on the
-
# platform.
-
-
before_epoch, after_epoch = transitions.partition {|t| t[:at] < 0}
-
-
if before_epoch.length > 0 && after_epoch.length > 0 && after_epoch.first[:at] != 0
-
last_before = before_epoch.last
-
last_before[:at] = 0
-
transitions = [last_before] + after_epoch
-
else
-
transitions = after_epoch
-
end
-
end
-
-
# Ignore transitions that occur outside of a defined window. The
-
# transition index cannot handle a large range of transition times.
-
#
-
# This is primarily intended to ignore the far in the past transition
-
# added in zic 2014c (at timestamp -2**63 in zic 2014c and at the
-
# approximate time of the big bang from zic 2014d).
-
2
transitions.each do |t|
-
at = t[:at]
-
if at >= MIN_TIMESTAMP && at < MAX_TIMESTAMP
-
time = Time.at(at).utc
-
transition time.year, time.mon, t[:offset], at
-
end
-
end
-
end
-
end
-
end
-
# encoding: UTF-8
-
-
2
require "execjs"
-
2
require "json"
-
2
require "uglifier/version"
-
-
# A wrapper around the UglifyJS interface
-
2
class Uglifier
-
# Error class for compilation errors.
-
2
Error = ExecJS::Error
-
# JavaScript code to call UglifyJS
-
2
JS = <<-JS
-
(function(options) {
-
function comments(option) {
-
if (Object.prototype.toString.call(option) === '[object Array]') {
-
return new RegExp(option[0], option[1]);
-
} else if (option == "jsdoc") {
-
return function(node, comment) {
-
if (comment.type == "comment2") {
-
return /@preserve|@license|@cc_on/i.test(comment.value);
-
} else {
-
return false;
-
}
-
}
-
} else {
-
return option;
-
}
-
}
-
-
var source = options.source;
-
var ast = UglifyJS.parse(source, options.parse_options);
-
ast.figure_out_scope();
-
-
if (options.compress) {
-
var compressor = UglifyJS.Compressor(options.compress);
-
ast = ast.transform(compressor);
-
ast.figure_out_scope();
-
}
-
-
if (options.mangle) {
-
ast.compute_char_frequency();
-
ast.mangle_names(options.mangle);
-
}
-
-
if (options.enclose) {
-
ast = ast.wrap_enclose(options.enclose);
-
}
-
-
var gen_code_options = options.output;
-
gen_code_options.comments = comments(options.output.comments);
-
-
if (options.generate_map) {
-
var source_map = UglifyJS.SourceMap(options.source_map_options);
-
gen_code_options.source_map = source_map;
-
}
-
-
var stream = UglifyJS.OutputStream(gen_code_options);
-
-
ast.print(stream);
-
-
if (options.source_map_options.map_url) {
-
stream += "\\n//# sourceMappingURL=" + options.source_map_options.map_url;
-
}
-
-
if (options.source_map_options.url) {
-
stream += "\\n//# sourceURL=" + options.source_map_options.url;
-
}
-
-
if (options.generate_map) {
-
return [stream.toString(), source_map.toString()];
-
} else {
-
return stream.toString();
-
}
-
})
-
JS
-
-
# UglifyJS source path
-
2
SourcePath = File.expand_path("../uglify.js", __FILE__)
-
# ES5 shims source path
-
2
ES5FallbackPath = File.expand_path("../es5.js", __FILE__)
-
# String.split shim source path
-
2
SplitFallbackPath = File.expand_path("../split.js", __FILE__)
-
-
# Default options for compilation
-
2
DEFAULTS = {
-
# rubocop:disable LineLength
-
:output => {
-
:ascii_only => true, # Escape non-ASCII characterss
-
:comments => :copyright, # Preserve comments (:all, :jsdoc, :copyright, :none)
-
:inline_script => false, # Escape occurrences of </script in strings
-
:quote_keys => false, # Quote keys in object literals
-
:max_line_len => 32 * 1024, # Maximum line length in minified code
-
:bracketize => false, # Bracketize if, for, do, while or with statements, even if their body is a single statement
-
:semicolons => true, # Separate statements with semicolons
-
:preserve_line => false, # Preserve line numbers in outputs
-
:beautify => false, # Beautify output
-
:indent_level => 4, # Indent level in spaces
-
:indent_start => 0, # Starting indent level
-
:space_colon => false, # Insert space before colons (only with beautifier)
-
:width => 80, # Specify line width when beautifier is used (only with beautifier)
-
:preamble => nil # Preamble for the generated JS file. Can be used to insert any code or comment.
-
},
-
:mangle => {
-
:eval => false, # Mangle names when eval of when is used in scope
-
:except => ["$super"], # Argument names to be excluded from mangling
-
:sort => false, # Assign shorter names to most frequently used variables. Often results in bigger output after gzip.
-
:toplevel => false # Mangle names declared in the toplevel scope
-
}, # Mangle variable and function names, set to false to skip mangling
-
:compress => {
-
:sequences => true, # Allow statements to be joined by commas
-
:properties => true, # Rewrite property access using the dot notation
-
:dead_code => true, # Remove unreachable code
-
:drop_debugger => true, # Remove debugger; statements
-
:unsafe => false, # Apply "unsafe" transformations
-
:conditionals => true, # Optimize for if-s and conditional expressions
-
:comparisons => true, # Apply binary node optimizations for comparisons
-
:evaluate => true, # Attempt to evaluate constant expressions
-
:booleans => true, # Various optimizations to boolean contexts
-
:loops => true, # Optimize loops when condition can be statically determined
-
:unused => true, # Drop unreferenced functions and variables
-
:hoist_funs => true, # Hoist function declarations
-
:hoist_vars => false, # Hoist var declarations
-
:if_return => true, # Optimizations for if/return and if/continue
-
:join_vars => true, # Join consecutive var statements
-
:cascade => true, # Cascade sequences
-
:negate_iife => true, # Negate immediately invoked function expressions to avoid extra parens
-
:pure_getters => false, # Assume that object property access does not have any side-effects
-
:pure_funcs => nil, # List of functions without side-effects. Can safely discard function calls when the result value is not used
-
:drop_console => false, # Drop calls to console.* functions
-
:angular => false, # Process @ngInject annotations
-
:keep_fargs => false # Preserve unused function arguments
-
}, # Apply transformations to code, set to false to skip
-
:define => {}, # Define values for symbol replacement
-
:enclose => false, # Enclose in output function wrapper, define replacements as key-value pairs
-
:source_filename => nil, # The filename of the input file
-
:source_root => nil, # The URL of the directory which contains :source_filename
-
:output_filename => nil, # The filename or URL where the minified output can be found
-
:input_source_map => nil, # The contents of the source map describing the input
-
:screw_ie8 => false, # Don't bother to generate safe code for IE8
-
:source_map_url => false, # Url for source mapping to be appended in minified source
-
:source_url => false # Url for original source to be appended in minified source
-
}
-
# rubocop:enable LineLength
-
-
# Minifies JavaScript code using implicit context.
-
#
-
# @param source [IO, String] valid JS source code.
-
# @param options [Hash] optional overrides to +Uglifier::DEFAULTS+
-
# @return [String] minified code.
-
2
def self.compile(source, options = {})
-
new(options).compile(source)
-
end
-
-
# Minifies JavaScript code and generates a source map using implicit context.
-
#
-
# @param source [IO, String] valid JS source code.
-
# @param options [Hash] optional overrides to +Uglifier::DEFAULTS+
-
# @return [Array(String, String)] minified code and source map.
-
2
def self.compile_with_map(source, options = {})
-
new(options).compile_with_map(source)
-
end
-
-
# Initialize new context for Uglifier with given options
-
#
-
# @param options [Hash] optional overrides to +Uglifier::DEFAULTS+
-
2
def initialize(options = {})
-
(options.keys - DEFAULTS.keys - [:comments, :squeeze, :copyright])[0..1].each do |missing|
-
raise ArgumentError, "Invalid option: #{missing}"
-
end
-
@options = options
-
@context = ExecJS.compile(uglifyjs_source)
-
end
-
-
# Minifies JavaScript code
-
#
-
# @param source [IO, String] valid JS source code.
-
# @return [String] minified code.
-
2
def compile(source)
-
run_uglifyjs(source, false)
-
end
-
2
alias_method :compress, :compile
-
-
# Minifies JavaScript code and generates a source map
-
#
-
# @param source [IO, String] valid JS source code.
-
# @return [Array(String, String)] minified code and source map.
-
2
def compile_with_map(source)
-
run_uglifyjs(source, true)
-
end
-
-
2
private
-
-
2
def uglifyjs_source
-
[ES5FallbackPath, SplitFallbackPath, SourcePath].map do |file|
-
File.open(file, "r:UTF-8") { |f| f.read }
-
end.join("\n")
-
end
-
-
# Run UglifyJS for given source code
-
2
def run_uglifyjs(source, generate_map)
-
options = {
-
:source => read_source(source),
-
:output => output_options,
-
:compress => compressor_options,
-
:mangle => mangle_options,
-
:parse_options => parse_options,
-
:source_map_options => source_map_options,
-
:generate_map => generate_map,
-
:enclose => enclose_options
-
}
-
-
@context.call(Uglifier::JS, options)
-
end
-
-
2
def read_source(source)
-
if source.respond_to?(:read)
-
source.read
-
else
-
source.to_s
-
end
-
end
-
-
2
def mangle_options
-
conditional_option(@options[:mangle], DEFAULTS[:mangle])
-
end
-
-
2
def compressor_options
-
defaults = conditional_option(
-
DEFAULTS[:compress],
-
:global_defs => @options[:define] || {},
-
:screw_ie8 => @options[:screw_ie8] || DEFAULTS[:screw_ie8]
-
)
-
conditional_option(@options[:compress] || @options[:squeeze], defaults)
-
end
-
-
2
def comment_options
-
case comment_setting
-
when :all, true
-
true
-
when :jsdoc
-
"jsdoc"
-
when :copyright
-
encode_regexp(/(^!)|Copyright/i)
-
when Regexp
-
encode_regexp(comment_setting)
-
else
-
false
-
end
-
end
-
-
2
def comment_setting
-
if @options.has_key?(:output) && @options[:output].has_key?(:comments)
-
@options[:output][:comments]
-
elsif @options.has_key?(:comments)
-
@options[:comments]
-
elsif @options[:copyright] == false
-
:none
-
else
-
DEFAULTS[:output][:comments]
-
end
-
end
-
-
2
def output_options
-
DEFAULTS[:output].merge(@options[:output] || {}).merge(
-
:comments => comment_options,
-
:screw_ie8 => screw_ie8?
-
).reject { |key, _| key == :ie_proof }
-
end
-
-
2
def screw_ie8?
-
if (@options[:output] || {}).has_key?(:ie_proof)
-
false
-
else
-
@options[:screw_ie8] || DEFAULTS[:screw_ie8]
-
end
-
end
-
-
2
def source_map_options
-
{
-
:file => @options[:output_filename],
-
:root => @options[:source_root],
-
:orig => @options[:input_source_map],
-
:map_url => @options[:source_map_url],
-
:url => @options[:source_url]
-
}
-
end
-
-
2
def parse_options
-
{ :filename => @options[:source_filename] }
-
end
-
-
2
def enclose_options
-
if @options[:enclose]
-
@options[:enclose].map do |pair|
-
pair.first + ':' + pair.last
-
end
-
else
-
false
-
end
-
end
-
-
2
def encode_regexp(regexp)
-
modifiers = if regexp.casefold?
-
"i"
-
else
-
""
-
end
-
-
[regexp.source, modifiers]
-
end
-
-
2
def conditional_option(value, defaults)
-
if value == true || value.nil?
-
defaults
-
elsif value
-
defaults.merge(value)
-
else
-
false
-
end
-
end
-
end
-
2
class Uglifier
-
# Current version of Uglifier.
-
2
VERSION = "2.7.2"
-
end
-
2
require 'videojs_rails/tags'
-
2
require 'videojs_rails/railtie'
-
2
require 'videojs_rails/engine' if defined?(Rails && Rails::VERSION::MAJOR == 3 && Rails::VERSION::MINOR >=1)
-
2
module VideojsRails
-
2
module Rails
-
2
class Engine < ::Rails::Engine
-
end
-
end
-
end
-
2
require 'videojs_rails/view_helpers'
-
-
2
module VideojsRails
-
2
class Railtie < Rails::Railtie
-
2
initializer "videojs_rails.view_helpers" do
-
2
ActionView::Base.send(:include, ViewHelpers)
-
end
-
end
-
end
-
2
require 'videojs_rails/tags/tag'
-
2
require 'videojs_rails/tags/video'
-
2
require 'videojs_rails/tags/caption'
-
2
require 'videojs_rails/tags/source'
-
-
2
module VideojsRails
-
2
module Tags
-
end
-
end
-
2
module VideojsRails
-
2
module Tags
-
2
class Caption < Tag
-
2
def initialize(lang, default_language, options)
-
@lang = lang.to_sym
-
@default_language = default_language
-
parse_options(options)
-
end
-
-
2
def to_html
-
tag :track, attributes
-
end
-
-
2
private
-
-
2
attr_reader :src, :label, :lang, :default_language
-
-
2
def default?
-
default_language == lang
-
end
-
-
2
def parse_options(options)
-
case options
-
when String, Symbol
-
@src = options
-
when Hash
-
@src, @label = options.values_at(:src, :label)
-
else
-
raise ArgumentError
-
end
-
end
-
-
2
def attributes
-
{
-
kind: :captions,
-
src: src,
-
srclang: lang,
-
label: label,
-
default: default?
-
}
-
end
-
end
-
-
end
-
end
-
2
module VideojsRails
-
2
module Tags
-
2
class Source < Tag
-
2
def initialize(video_type, options)
-
@video_type = video_type
-
@attributes = parse_options(options)
-
end
-
-
2
def to_html
-
tag :source, @attributes
-
end
-
-
2
private
-
-
2
attr_reader :video_type
-
-
2
def parse_options(options)
-
case options
-
when String, Symbol
-
{
-
src: options,
-
type: type
-
}
-
when Hash
-
options
-
else
-
raise ArgumentError
-
end
-
end
-
-
2
def type
-
"video/#{video_type}"
-
end
-
end
-
end
-
end
-
2
module VideojsRails
-
2
module Tags
-
2
class Tag
-
2
include ActionView::Helpers::TagHelper
-
2
include ActionView::Context
-
2
include ActionView::Helpers::TextHelper
-
end
-
end
-
end
-
2
module VideojsRails
-
2
module Tags
-
2
class Video < Tag
-
2
DEFAULT_LANGUAGE_KEY = :default_caption_language
-
2
DEFAULT_OPTIONS = {
-
controls: true,
-
preload: :auto
-
}.freeze
-
-
2
def initialize(options, &no_js)
-
@no_js = no_js
-
prepare_options(options)
-
end
-
-
2
def to_html
-
content_tag(:video, options) do
-
sources.each {|type, options| concat Source.new(type, options).to_html }
-
captions.each {|lang, options| concat Caption.new(lang, default_caption_language, options).to_html }
-
generate_no_js
-
end
-
end
-
-
2
private
-
-
2
attr_reader :no_js, :sources, :captions, :options, :default_caption_language
-
-
2
def prepare_options(user_options)
-
@sources = user_options.delete(:sources) || []
-
@captions = user_options.delete(:captions) || []
-
@default_caption_language = user_options.delete(DEFAULT_LANGUAGE_KEY)
-
@options = DEFAULT_OPTIONS.merge(user_options)
-
options[:'data-setup'] = options.delete(:setup) if options.key?(:setup)
-
options[:class] = [:'video-js', :'vjs-default-skin', *options[:class]]
-
end
-
-
2
def generate_no_js
-
return if no_js.nil?
-
concat content_tag(:p, no_js.call(), class: :'vjs-no-js')
-
end
-
end
-
end
-
end
-
2
module VideojsRails
-
2
module ViewHelpers
-
2
def videojs_rails(user_options, &blk)
-
VideojsRails::Tags::Video.new(user_options, &blk).to_html
-
end
-
end
-
end
-
# encoding: utf-8
-
2
require 'forwardable'
-
-
2
require 'warden/mixins/common'
-
2
require 'warden/proxy'
-
2
require 'warden/manager'
-
2
require 'warden/errors'
-
2
require 'warden/session_serializer'
-
2
require 'warden/strategies'
-
2
require 'warden/strategies/base'
-
-
2
module Warden
-
2
class NotAuthenticated < StandardError; end
-
-
2
module Test
-
2
autoload :WardenHelpers, 'warden/test/warden_helpers'
-
2
autoload :Helpers, 'warden/test/helpers'
-
2
autoload :Mock, 'warden/test/mock'
-
end
-
-
# Provides helper methods to warden for testing.
-
#
-
# To setup warden in test mode call the +test_mode!+ method on warden
-
#
-
# @example
-
# Warden.test_mode!
-
#
-
# This will provide a number of methods.
-
# Warden.on_next_request(&blk) - captures a block which is yielded the warden proxy on the next request
-
# Warden.test_reset! - removes any captured blocks that would have been executed on the next request
-
#
-
# Warden.test_reset! should be called in after blocks for rspec, or teardown methods for Test::Unit
-
2
def self.test_mode!
-
unless Warden::Test::WardenHelpers === Warden
-
Warden.extend Warden::Test::WardenHelpers
-
Warden::Manager.on_request do |proxy|
-
unless proxy.asset_request?
-
while blk = Warden._on_next_request.shift
-
blk.call(proxy)
-
end
-
end
-
end
-
end
-
true
-
end
-
end
-
# encoding: utf-8
-
-
2
module Warden
-
# This class is yielded inside Warden::Manager. If you have a plugin and want to
-
# add more configuration to warden, you just need to extend this class.
-
2
class Config < Hash
-
# Creates an accessor that simply sets and reads a key in the hash:
-
#
-
# class Config < Hash
-
# hash_accessor :failure_app
-
# end
-
#
-
# config = Config.new
-
# config.failure_app = Foo
-
# config[:failure_app] #=> Foo
-
#
-
# config[:failure_app] = Bar
-
# config.failure_app #=> Bar
-
#
-
2
def self.hash_accessor(*names) #:nodoc:
-
2
names.each do |name|
-
6
class_eval <<-METHOD, __FILE__, __LINE__ + 1
-
def #{name}
-
self[:#{name}]
-
end
-
-
def #{name}=(value)
-
self[:#{name}] = value
-
end
-
METHOD
-
end
-
end
-
-
2
hash_accessor :failure_app, :default_scope, :intercept_401
-
-
2
def initialize(other={})
-
2
merge!(other)
-
2
self[:default_scope] ||= :default
-
2
self[:scope_defaults] ||= {}
-
2
self[:default_strategies] ||= {}
-
2
self[:intercept_401] = true unless key?(:intercept_401)
-
end
-
-
2
def initialize_copy(other)
-
13
super
-
13
deep_dup(:scope_defaults, other)
-
13
deep_dup(:default_strategies, other)
-
end
-
-
# Do not raise an error if a missing strategy is given.
-
# :api: plugin
-
2
def silence_missing_strategies!
-
self[:silence_missing_strategies] = true
-
end
-
-
2
def silence_missing_strategies? #:nodoc:
-
!!self[:silence_missing_strategies]
-
end
-
-
# Set the default strategies to use.
-
# :api: public
-
2
def default_strategies(*strategies)
-
opts = Hash === strategies.last ? strategies.pop : {}
-
hash = self[:default_strategies]
-
scope = opts[:scope] || :_all
-
-
hash[scope] = strategies.flatten unless strategies.empty?
-
hash[scope] || hash[:_all] || []
-
end
-
-
# A short hand way to set up a particular scope
-
# :api: public
-
2
def scope_defaults(scope, opts = {})
-
if strategies = opts.delete(:strategies)
-
default_strategies(strategies, :scope => scope)
-
end
-
-
if opts.empty?
-
self[:scope_defaults][scope] || {}
-
else
-
self[:scope_defaults][scope] ||= {}
-
self[:scope_defaults][scope].merge!(opts)
-
end
-
end
-
-
# Quick accessor to strategies from manager
-
# :api: public
-
2
def strategies
-
Warden::Strategies
-
end
-
-
# Hook from configuration to serialize_into_session.
-
# :api: public
-
2
def serialize_into_session(*args, &block)
-
Warden::Manager.serialize_into_session(*args, &block)
-
end
-
-
# Hook from configuration to serialize_from_session.
-
# :api: public
-
2
def serialize_from_session(*args, &block)
-
Warden::Manager.serialize_from_session(*args, &block)
-
end
-
-
2
protected
-
-
2
def deep_dup(key, other)
-
26
self[key] = hash = other[key].dup
-
26
hash.each { |k, v| hash[k] = v.dup }
-
end
-
end
-
end
-
# encoding: utf-8
-
2
module Warden
-
2
class Proxy
-
# Lifted from DataMapper's dm-validations plugin :)
-
# @author Guy van den Berg
-
# @since DM 0.9
-
2
class Errors
-
-
2
include Enumerable
-
-
# Clear existing authentication errors.
-
2
def clear!
-
errors.clear
-
end
-
-
# Add a authentication error. Use the field_name :general if the errors does
-
# not apply to a specific field of the Resource.
-
#
-
# @param <Symbol> field_name the name of the field that caused the error
-
# @param <String> message the message to add
-
2
def add(field_name, message)
-
(errors[field_name] ||= []) << message
-
end
-
-
# Collect all errors into a single list.
-
2
def full_messages
-
errors.inject([]) do |list,pair|
-
list += pair.last
-
end
-
end
-
-
# Return authentication errors for a particular field_name.
-
#
-
# @param <Symbol> field_name the name of the field you want an error for
-
2
def on(field_name)
-
errors_for_field = errors[field_name]
-
blank?(errors_for_field) ? nil : errors_for_field
-
end
-
-
2
def each
-
errors.map.each do |k,v|
-
next if blank?(v)
-
yield(v)
-
end
-
end
-
-
2
def empty?
-
entries.empty?
-
end
-
-
2
def method_missing(meth, *args, &block)
-
errors.send(meth, *args, &block)
-
end
-
-
2
private
-
2
def errors
-
@errors ||= {}
-
end
-
-
2
def blank?(thing)
-
thing.nil? || thing == "" || (thing.respond_to?(:empty?) && thing.empty?)
-
end
-
-
end # class Errors
-
end # Proxy
-
end # Warden
-
# encoding: utf-8
-
2
module Warden
-
2
module Hooks
-
-
# Hook to _run_callbacks asserting for conditions.
-
2
def _run_callbacks(kind, *args) #:nodoc:
-
13
options = args.last # Last callback arg MUST be a Hash
-
-
13
send("_#{kind}").each do |callback, conditions|
-
invalid = conditions.find do |key, value|
-
value.is_a?(Array) ? !value.include?(options[key]) : (value != options[key])
-
end
-
-
callback.call(*args) unless invalid
-
end
-
end
-
-
# A callback hook set to run every time after a user is set.
-
# This callback is triggered the first time one of those three events happens
-
# during a request: :authentication, :fetch (from session) and :set_user (when manually set).
-
# You can supply as many hooks as you like, and they will be run in order of declaration.
-
#
-
# If you want to run the callbacks for a given scope and/or event, you can specify them as options.
-
# See parameters and example below.
-
#
-
# Parameters:
-
# <options> Some options which specify when the callback should be executed
-
# scope - Executes the callback only if it matches the scope(s) given
-
# only - Executes the callback only if it matches the event(s) given
-
# except - Executes the callback except if it matches the event(s) given
-
# <block> A block where you can set arbitrary logic to run every time a user is set
-
# Block Parameters: |user, auth, opts|
-
# user - The user object that is being set
-
# auth - The raw authentication proxy object.
-
# opts - any options passed into the set_user call including :scope
-
#
-
# Example:
-
# Warden::Manager.after_set_user do |user,auth,opts|
-
# scope = opts[:scope]
-
# if auth.session["#{scope}.last_access"].to_i > (Time.now - 5.minutes)
-
# auth.logout(scope)
-
# throw(:warden, :scope => scope, :reason => "Times Up")
-
# end
-
# auth.session["#{scope}.last_access"] = Time.now
-
# end
-
#
-
# Warden::Manager.after_set_user :except => :fetch do |user,auth,opts|
-
# user.login_count += 1
-
# end
-
#
-
# :api: public
-
2
def after_set_user(options = {}, method = :push, &block)
-
4
raise BlockNotGiven unless block_given?
-
-
4
if options.key?(:only)
-
options[:event] = options.delete(:only)
-
elsif options.key?(:except)
-
options[:event] = [:set_user, :authentication, :fetch] - Array(options.delete(:except))
-
end
-
-
4
_after_set_user.send(method, [block, options])
-
end
-
-
# Provides access to the array of after_set_user blocks to run
-
# :api: private
-
2
def _after_set_user # :nodoc:
-
4
@_after_set_user ||= []
-
end
-
-
# after_authentication is just a wrapper to after_set_user, which is only invoked
-
# when the user is set through the authentication path. The options and yielded arguments
-
# are the same as in after_set_user.
-
#
-
# :api: public
-
2
def after_authentication(options = {}, method = :push, &block)
-
2
after_set_user(options.merge(:event => :authentication), method, &block)
-
end
-
-
# after_fetch is just a wrapper to after_set_user, which is only invoked
-
# when the user is fetched from session. The options and yielded arguments
-
# are the same as in after_set_user.
-
#
-
# :api: public
-
2
def after_fetch(options = {}, method = :push, &block)
-
after_set_user(options.merge(:event => :fetch), method, &block)
-
end
-
-
# A callback that runs just prior to the failure application being called.
-
# This callback occurs after PATH_INFO has been modified for the failure (default /unauthenticated)
-
# In this callback you can mutate the environment as required by the failure application
-
# If a Rails controller were used for the failure_app for example, you would need to set request[:params][:action] = :unauthenticated
-
#
-
# Parameters:
-
# <options> Some options which specify when the callback should be executed
-
# scope - Executes the callback only if it matches the scope(s) given
-
# <block> A block to contain logic for the callback
-
# Block Parameters: |env, opts|
-
# env - The rack env hash
-
# opts - any options passed into the authenticate call including :scope
-
#
-
# Example:
-
# Warden::Manager.before_failure do |env, opts|
-
# params = Rack::Request.new(env).params
-
# params[:action] = :unauthenticated
-
# params[:warden_failure] = opts
-
# end
-
#
-
# :api: public
-
2
def before_failure(options = {}, method = :push, &block)
-
raise BlockNotGiven unless block_given?
-
_before_failure.send(method, [block, options])
-
end
-
-
# Provides access to the callback array for before_failure
-
# :api: private
-
2
def _before_failure
-
@_before_failure ||= []
-
end
-
-
# A callback that runs if no user could be fetched, meaning there is now no user logged in.
-
#
-
# Parameters:
-
# <options> Some options which specify when the callback should be executed
-
# scope - Executes the callback only if it matches the scope(s) given
-
# <block> A block to contain logic for the callback
-
# Block Parameters: |user, auth, scope|
-
# user - The authenticated user for the current scope
-
# auth - The warden proxy object
-
# opts - any options passed into the authenticate call including :scope
-
#
-
# Example:
-
# Warden::Manager.after_failed_fetch do |user, auth, opts|
-
# I18n.locale = :en
-
# end
-
#
-
# :api: public
-
2
def after_failed_fetch(options = {}, method = :push, &block)
-
raise BlockNotGiven unless block_given?
-
_after_failed_fetch.send(method, [block, options])
-
end
-
-
# Provides access to the callback array for after_failed_fetch
-
# :api: private
-
2
def _after_failed_fetch
-
@_after_failed_fetch ||= []
-
end
-
-
# A callback that runs just prior to the logout of each scope.
-
#
-
# Parameters:
-
# <options> Some options which specify when the callback should be executed
-
# scope - Executes the callback only if it matches the scope(s) given
-
# <block> A block to contain logic for the callback
-
# Block Parameters: |user, auth, scope|
-
# user - The authenticated user for the current scope
-
# auth - The warden proxy object
-
# opts - any options passed into the authenticate call including :scope
-
#
-
# Example:
-
# Warden::Manager.before_logout do |user, auth, opts|
-
# user.forget_me!
-
# end
-
#
-
# :api: public
-
2
def before_logout(options = {}, method = :push, &block)
-
raise BlockNotGiven unless block_given?
-
_before_logout.send(method, [block, options])
-
end
-
-
# Provides access to the callback array for before_logout
-
# :api: private
-
2
def _before_logout
-
@_before_logout ||= []
-
end
-
-
# A callback that runs on each request, just after the proxy is initialized
-
#
-
# Parameters:
-
# <block> A block to contain logic for the callback
-
# Block Parameters: |proxy|
-
# proxy - The warden proxy object for the request
-
#
-
# Example:
-
# user = "A User"
-
# Warden::Manager.on_request do |proxy|
-
# proxy.set_user = user
-
# end
-
#
-
# :api: public
-
2
def on_request(options = {}, method = :push, &block)
-
raise BlockNotGiven unless block_given?
-
_on_request.send(method, [block, options])
-
end
-
-
# Provides access to the callback array for before_logout
-
# :api: private
-
2
def _on_request
-
13
@_on_request ||= []
-
end
-
-
# Add prepend filters version
-
%w(after_set_user after_authentication after_fetch on_request
-
2
before_failure before_logout).each do |filter|
-
12
class_eval <<-METHOD, __FILE__, __LINE__ + 1
-
def prepend_#{filter}(options={}, &block)
-
#{filter}(options, :unshift, &block)
-
end
-
METHOD
-
end
-
end # Hooks
-
end # Warden
-
# encoding: utf-8
-
2
require 'warden/hooks'
-
2
require 'warden/config'
-
-
2
module Warden
-
# The middleware for Rack Authentication
-
# The middleware requires that there is a session upstream
-
# The middleware injects an authentication object into
-
# the rack environment hash
-
2
class Manager
-
2
extend Warden::Hooks
-
-
2
attr_accessor :config
-
-
# Initialize the middleware. If a block is given, a Warden::Config is yielded so you can properly
-
# configure the Warden::Manager.
-
# :api: public
-
2
def initialize(app, options={})
-
2
default_strategies = options.delete(:default_strategies)
-
-
2
@app, @config = app, Warden::Config.new(options)
-
2
@config.default_strategies(*default_strategies) if default_strategies
-
2
yield @config if block_given?
-
2
self
-
end
-
-
# Invoke the application guarding for throw :warden.
-
# If this is downstream from another warden instance, don't do anything.
-
# :api: private
-
2
def call(env) # :nodoc:
-
13
return @app.call(env) if env['warden'] && env['warden'].manager != self
-
-
13
env['warden'] = Proxy.new(env, self)
-
13
result = catch(:warden) do
-
13
@app.call(env)
-
end
-
-
13
result ||= {}
-
13
case result
-
when Array
-
13
handle_chain_result(result.first, result, env)
-
when Hash
-
process_unauthenticated(env, result)
-
when Rack::Response
-
handle_chain_result(result.status, result, env)
-
end
-
end
-
-
# :api: private
-
2
def _run_callbacks(*args) #:nodoc:
-
13
self.class._run_callbacks(*args)
-
end
-
-
2
class << self
-
# Prepares the user to serialize into the session.
-
# Any object that can be serialized into the session in some way can be used as a "user" object
-
# Generally however complex object should not be stored in the session.
-
# If possible store only a "key" of the user object that will allow you to reconstitute it.
-
#
-
# You can supply different methods of serialization for different scopes by passing a scope symbol
-
#
-
# Example:
-
# Warden::Manager.serialize_into_session{ |user| user.id }
-
# # With Scope:
-
# Warden::Manager.serialize_into_session(:admin) { |user| user.id }
-
#
-
# :api: public
-
2
def serialize_into_session(scope = nil, &block)
-
method_name = scope.nil? ? :serialize : "#{scope}_serialize"
-
Warden::SessionSerializer.send :define_method, method_name, &block
-
end
-
-
# Reconstitutes the user from the session.
-
# Use the results of user_session_key to reconstitute the user from the session on requests after the initial login
-
# You can supply different methods of de-serialization for different scopes by passing a scope symbol
-
#
-
# Example:
-
# Warden::Manager.serialize_from_session{ |id| User.get(id) }
-
# # With Scope:
-
# Warden::Manager.serialize_from_session(:admin) { |id| AdminUser.get(id) }
-
#
-
# :api: public
-
2
def serialize_from_session(scope = nil, &block)
-
method_name = scope.nil? ? :deserialize : "#{scope}_deserialize"
-
-
if Warden::SessionSerializer.method_defined? method_name
-
Warden::SessionSerializer.send :remove_method, method_name
-
end
-
-
Warden::SessionSerializer.send :define_method, method_name, &block
-
end
-
end
-
-
2
private
-
-
2
def handle_chain_result(status, result, env)
-
13
if status == 401 && intercept_401?(env)
-
process_unauthenticated(env)
-
else
-
13
result
-
end
-
end
-
-
2
def intercept_401?(env)
-
config[:intercept_401] && !env['warden'].custom_failure?
-
end
-
-
# When a request is unauthenticated, here's where the processing occurs.
-
# It looks at the result of the proxy to see if it's been executed and what action to take.
-
# :api: private
-
2
def process_unauthenticated(env, options={})
-
options[:action] ||= begin
-
opts = config[:scope_defaults][config.default_scope] || {}
-
opts[:action] || 'unauthenticated'
-
end
-
-
proxy = env['warden']
-
result = options[:result] || proxy.result
-
-
case result
-
when :redirect
-
body = proxy.message || "You are being redirected to #{proxy.headers['Location']}"
-
[proxy.status, proxy.headers, [body]]
-
when :custom
-
proxy.custom_response
-
else
-
options[:message] ||= proxy.message
-
call_failure_app(env, options)
-
end
-
end
-
-
# Calls the failure app.
-
# The before_failure hooks are run on each failure
-
# :api: private
-
2
def call_failure_app(env, options = {})
-
if config.failure_app
-
options.merge!(:attempted_path => ::Rack::Request.new(env).fullpath)
-
env["PATH_INFO"] = "/#{options[:action]}"
-
env["warden.options"] = options
-
-
_run_callbacks(:before_failure, env, options)
-
config.failure_app.call(env).to_a
-
else
-
raise "No Failure App provided"
-
end
-
end # call_failure_app
-
end
-
end # Warden
-
# encoding: utf-8
-
2
module Warden
-
2
module Mixins
-
2
module Common
-
-
# Convenience method to access the session
-
# :api: public
-
2
def session
-
env['rack.session']
-
end # session
-
-
# Alias :session to :raw_session since the former will be user API for storing scoped data.
-
2
alias :raw_session :session
-
-
# Convenience method to access the rack request.
-
# :api: public
-
2
def request
-
@request ||= Rack::Request.new(@env)
-
end # request
-
-
# Provides a warden repository for cookies. Those are sent to the client
-
# when the response is streamed back from the app.
-
# :api: public
-
2
def warden_cookies
-
warn "warden_cookies was never functional and is going to be removed in next versions"
-
env['warden.cookies'] ||= {}
-
end # warden_cookies
-
-
# Convenience method to access the rack request params
-
# :api: public
-
2
def params
-
request.params
-
end # params
-
-
# Resets the session. By using this non-hash like sessions can
-
# be cleared by overwriting this method in a plugin
-
# @api overwritable
-
2
def reset_session!
-
raw_session.clear
-
end # reset_session!
-
-
end # Common
-
end # Mixins
-
end # Warden
-
# encoding: utf-8
-
-
2
module Warden
-
2
class UserNotSet < RuntimeError; end
-
-
2
class Proxy
-
# An accessor to the winning strategy
-
# :api: private
-
2
attr_accessor :winning_strategy
-
-
# An accessor to the rack env hash, the proxy owner and its config
-
# :api: public
-
2
attr_reader :env, :manager, :config, :winning_strategies
-
-
2
extend ::Forwardable
-
2
include ::Warden::Mixins::Common
-
-
2
ENV_WARDEN_ERRORS = 'warden.errors'.freeze
-
2
ENV_SESSION_OPTIONS = 'rack.session.options'.freeze
-
-
# :api: private
-
2
def_delegators :winning_strategy, :headers, :status, :custom_response
-
-
# :api: public
-
2
def_delegators :config, :default_strategies
-
-
2
def initialize(env, manager) #:nodoc:
-
13
@env, @users, @winning_strategies, @locked = env, {}, {}, false
-
13
@manager, @config = manager, manager.config.dup
-
13
@strategies = Hash.new { |h,k| h[k] = {} }
-
13
manager._run_callbacks(:on_request, self)
-
end
-
-
# Lazily initiate errors object in session.
-
# :api: public
-
2
def errors
-
@env[ENV_WARDEN_ERRORS] ||= Errors.new
-
end
-
-
# Points to a SessionSerializer instance responsible for handling
-
# everything related with storing, fetching and removing the user
-
# session.
-
# :api: public
-
2
def session_serializer
-
@session_serializer ||= Warden::SessionSerializer.new(@env)
-
end
-
-
# Clear the cache of performed strategies so far. Warden runs each
-
# strategy just once during the request lifecycle. You can clear the
-
# strategies cache if you want to allow a strategy to be run more than
-
# once.
-
#
-
# This method has the same API as authenticate, allowing you to clear
-
# specific strategies for given scope:
-
#
-
# Parameters:
-
# args - a list of symbols (labels) that name the strategies to attempt
-
# opts - an options hash that contains the :scope of the user to check
-
#
-
# Example:
-
# # Clear all strategies for the configured default_scope
-
# env['warden'].clear_strategies_cache!
-
#
-
# # Clear all strategies for the :admin scope
-
# env['warden'].clear_strategies_cache!(:scope => :admin)
-
#
-
# # Clear password strategy for the :admin scope
-
# env['warden'].clear_strategies_cache!(:password, :scope => :admin)
-
#
-
# :api: public
-
2
def clear_strategies_cache!(*args)
-
scope, _opts = _retrieve_scope_and_opts(args)
-
-
@winning_strategies.delete(scope)
-
@strategies[scope].each do |k, v|
-
v.clear! if args.empty? || args.include?(k)
-
end
-
end
-
-
# Locks the proxy so new users cannot authenticate during the
-
# request lifecycle. This is useful when the request cannot
-
# be verified (for example, using a CSRF verification token).
-
# Notice that already authenticated users are kept as so.
-
#
-
# :api: public
-
2
def lock!
-
@locked = true
-
end
-
-
# Run the authentication strategies for the given strategies.
-
# If there is already a user logged in for a given scope, the strategies are not run
-
# This does not halt the flow of control and is a passive attempt to authenticate only
-
# When scope is not specified, the default_scope is assumed.
-
#
-
# Parameters:
-
# args - a list of symbols (labels) that name the strategies to attempt
-
# opts - an options hash that contains the :scope of the user to check
-
#
-
# Example:
-
# env['warden'].authenticate(:password, :basic, :scope => :sudo)
-
#
-
# :api: public
-
2
def authenticate(*args)
-
user, _opts = _perform_authentication(*args)
-
user
-
end
-
-
# Same API as authenticated, but returns a boolean instead of a user.
-
# The difference between this method (authenticate?) and authenticated?
-
# is that the former will run strategies if the user has not yet been
-
# authenticated, and the second relies on already performed ones.
-
# :api: public
-
2
def authenticate?(*args)
-
result = !!authenticate(*args)
-
yield if result && block_given?
-
result
-
end
-
-
# The same as +authenticate+ except on failure it will throw an :warden symbol causing the request to be halted
-
# and rendered through the +failure_app+
-
#
-
# Example
-
# env['warden'].authenticate!(:password, :scope => :publisher) # throws if it cannot authenticate
-
#
-
# :api: public
-
2
def authenticate!(*args)
-
user, opts = _perform_authentication(*args)
-
throw(:warden, opts) unless user
-
user
-
end
-
-
# Check to see if there is an authenticated user for the given scope.
-
# This brings the user from the session, but does not run strategies before doing so.
-
# If you want strategies to be run, please check authenticate?.
-
#
-
# Parameters:
-
# scope - the scope to check for authentication. Defaults to default_scope
-
#
-
# Example:
-
# env['warden'].authenticated?(:admin)
-
#
-
# :api: public
-
2
def authenticated?(scope = @config.default_scope)
-
result = !!user(scope)
-
yield if block_given? && result
-
result
-
end
-
-
# Same API as authenticated?, but returns false when authenticated.
-
# :api: public
-
2
def unauthenticated?(scope = @config.default_scope)
-
result = !authenticated?(scope)
-
yield if block_given? && result
-
result
-
end
-
-
# Manually set the user into the session and auth proxy
-
#
-
# Parameters:
-
# user - An object that has been setup to serialize into and out of the session.
-
# opts - An options hash. Use the :scope option to set the scope of the user, set the :store option to false to skip serializing into the session, set the :run_callbacks to false to skip running the callbacks (the default is true).
-
#
-
# :api: public
-
2
def set_user(user, opts = {})
-
scope = (opts[:scope] ||= @config.default_scope)
-
-
# Get the default options from the master configuration for the given scope
-
opts = (@config[:scope_defaults][scope] || {}).merge(opts)
-
opts[:event] ||= :set_user
-
@users[scope] = user
-
-
if opts[:store] != false && opts[:event] != :fetch
-
options = env[ENV_SESSION_OPTIONS]
-
options[:renew] = true if options
-
session_serializer.store(user, scope)
-
end
-
-
run_callbacks = opts.fetch(:run_callbacks, true)
-
manager._run_callbacks(:after_set_user, user, self, opts) if run_callbacks
-
-
@users[scope]
-
end
-
-
# Provides access to the user object in a given scope for a request.
-
# Will be nil if not logged in. Please notice that this method does not
-
# perform strategies.
-
#
-
# Example:
-
# # without scope (default user)
-
# env['warden'].user
-
#
-
# # with scope
-
# env['warden'].user(:admin)
-
#
-
# # as a Hash
-
# env['warden'].user(:scope => :admin)
-
#
-
# # with default scope and run_callbacks option
-
# env['warden'].user(:run_callbacks => false)
-
#
-
# # with a scope and run_callbacks option
-
# env['warden'].user(:scope => :admin, :run_callbacks => true)
-
#
-
# :api: public
-
2
def user(argument = {})
-
opts = argument.is_a?(Hash) ? argument : { :scope => argument }
-
scope = (opts[:scope] ||= @config.default_scope)
-
-
if @users.has_key?(scope)
-
@users[scope]
-
else
-
unless user = session_serializer.fetch(scope)
-
run_callbacks = opts.fetch(:run_callbacks, true)
-
manager._run_callbacks(:after_failed_fetch, user, self, :scope => scope) if run_callbacks
-
end
-
-
@users[scope] = user ? set_user(user, opts.merge(:event => :fetch)) : nil
-
end
-
end
-
-
# Provides a scoped session data for authenticated users.
-
# Warden manages clearing out this data when a user logs out
-
#
-
# Example
-
# # default scope
-
# env['warden'].session[:foo] = "bar"
-
#
-
# # :sudo scope
-
# env['warden'].session(:sudo)[:foo] = "bar"
-
#
-
# :api: public
-
2
def session(scope = @config.default_scope)
-
raise NotAuthenticated, "#{scope.inspect} user is not logged in" unless authenticated?(scope)
-
raw_session["warden.user.#{scope}.session"] ||= {}
-
end
-
-
# Provides logout functionality.
-
# The logout also manages any authenticated data storage and clears it when a user logs out.
-
#
-
# Parameters:
-
# scopes - a list of scopes to logout
-
#
-
# Example:
-
# # Logout everyone and clear the session
-
# env['warden'].logout
-
#
-
# # Logout the default user but leave the rest of the session alone
-
# env['warden'].logout(:default)
-
#
-
# # Logout the :publisher and :admin user
-
# env['warden'].logout(:publisher, :admin)
-
#
-
# :api: public
-
2
def logout(*scopes)
-
if scopes.empty?
-
scopes = @users.keys
-
reset_session = true
-
end
-
-
scopes.each do |scope|
-
user = @users.delete(scope)
-
manager._run_callbacks(:before_logout, user, self, :scope => scope)
-
-
raw_session.delete("warden.user.#{scope}.session") unless raw_session.nil?
-
session_serializer.delete(scope, user)
-
end
-
-
reset_session! if reset_session
-
end
-
-
# proxy methods through to the winning strategy
-
# :api: private
-
2
def result # :nodoc:
-
winning_strategy && winning_strategy.result
-
end
-
-
# Proxy through to the authentication strategy to find out the message that was generated.
-
# :api: public
-
2
def message
-
winning_strategy && winning_strategy.message
-
end
-
-
# Provides a way to return a 401 without warden deferring to the failure app
-
# The result is a direct passthrough of your own response
-
# :api: public
-
2
def custom_failure!
-
@custom_failure = true
-
end
-
-
# Check to see if the custom failure flag has been set
-
# :api: public
-
2
def custom_failure?
-
if instance_variable_defined?(:@custom_failure)
-
!!@custom_failure
-
else
-
false
-
end
-
end
-
-
# Check to see if this is an asset request
-
# :api: public
-
2
def asset_request?
-
::Warden::asset_paths.any? { |r| env['PATH_INFO'].to_s.match(r) }
-
end
-
-
2
def inspect(*args)
-
"Warden::Proxy:#{object_id} @config=#{@config.inspect}"
-
end
-
-
2
def to_s(*args)
-
inspect(*args)
-
end
-
-
2
private
-
-
2
def _perform_authentication(*args)
-
scope, opts = _retrieve_scope_and_opts(args)
-
user = nil
-
-
# Look for an existing user in the session for this scope.
-
# If there was no user in the session. See if we can get one from the request.
-
return user, opts if user = user(opts.merge(:scope => scope))
-
_run_strategies_for(scope, args)
-
-
if winning_strategy && winning_strategy.successful?
-
opts[:store] = opts.fetch(:store, winning_strategy.store?)
-
set_user(winning_strategy.user, opts.merge!(:event => :authentication))
-
end
-
-
[@users[scope], opts]
-
end
-
-
2
def _retrieve_scope_and_opts(args) #:nodoc:
-
opts = args.last.is_a?(Hash) ? args.pop : {}
-
scope = opts[:scope] || @config.default_scope
-
opts = (@config[:scope_defaults][scope] || {}).merge(opts)
-
[scope, opts]
-
end
-
-
# Run the strategies for a given scope
-
2
def _run_strategies_for(scope, args) #:nodoc:
-
self.winning_strategy = @winning_strategies[scope]
-
return if winning_strategy && winning_strategy.halted?
-
-
# Do not run any strategy if locked
-
return if @locked
-
-
if args.empty?
-
defaults = @config[:default_strategies]
-
strategies = defaults[scope] || defaults[:_all]
-
end
-
-
(strategies || args).each do |name|
-
strategy = _fetch_strategy(name, scope)
-
next unless strategy && !strategy.performed? && strategy.valid?
-
-
self.winning_strategy = @winning_strategies[scope] = strategy
-
strategy._run!
-
break if strategy.halted?
-
end
-
end
-
-
# Fetches strategies and keep them in a hash cache.
-
2
def _fetch_strategy(name, scope)
-
@strategies[scope][name] ||= if klass = Warden::Strategies[name]
-
klass.new(@env, scope)
-
elsif @config.silence_missing_strategies?
-
nil
-
else
-
raise "Invalid strategy #{name}"
-
end
-
end
-
end # Proxy
-
-
end # Warden
-
# encoding: utf-8
-
2
module Warden
-
2
class SessionSerializer
-
2
attr_reader :env
-
-
2
def initialize(env)
-
@env = env
-
end
-
-
2
def key_for(scope)
-
"warden.user.#{scope}.key"
-
end
-
-
2
def serialize(user)
-
user
-
end
-
-
2
def deserialize(key)
-
key
-
end
-
-
2
def store(user, scope)
-
return unless user
-
method_name = "#{scope}_serialize"
-
specialized = respond_to?(method_name)
-
session[key_for(scope)] = specialized ? send(method_name, user) : serialize(user)
-
end
-
-
2
def fetch(scope)
-
key = session[key_for(scope)]
-
return nil unless key
-
-
method_name = "#{scope}_deserialize"
-
user = respond_to?(method_name) ? send(method_name, key) : deserialize(key)
-
delete(scope) unless user
-
user
-
end
-
-
2
def stored?(scope)
-
!!session[key_for(scope)]
-
end
-
-
2
def delete(scope, user=nil)
-
session.delete(key_for(scope))
-
end
-
-
# We can't cache this result because the session can be lazy loaded
-
2
def session
-
env["rack.session"] || {}
-
end
-
end # SessionSerializer
-
end # Warden
-
# encoding: utf-8
-
2
module Warden
-
2
module Strategies
-
2
class << self
-
# Add a strategy and store it in a hash.
-
2
def add(label, strategy = nil, &block)
-
strategy ||= Class.new(Warden::Strategies::Base)
-
strategy.class_eval(&block) if block_given?
-
-
unless strategy.method_defined?(:authenticate!)
-
raise NoMethodError, "authenticate! is not declared in the #{label.inspect} strategy"
-
end
-
-
base = Warden::Strategies::Base
-
unless strategy.ancestors.include?(base)
-
raise "#{label.inspect} is not a #{base}"
-
end
-
-
_strategies[label] = strategy
-
end
-
-
# Update a previously given strategy.
-
2
def update(label, &block)
-
strategy = _strategies[label]
-
raise "Unknown strategy #{label.inspect}" unless strategy
-
add(label, strategy, &block)
-
end
-
-
# Provides access to strategies by label
-
# :api: public
-
2
def [](label)
-
_strategies[label]
-
end
-
-
# Clears all declared.
-
# :api: public
-
2
def clear!
-
_strategies.clear
-
end
-
-
# :api: private
-
2
def _strategies
-
@strategies ||= {}
-
end
-
end # << self
-
end # Strategies
-
end # Warden
-
# encoding: utf-8
-
2
module Warden
-
2
module Strategies
-
# A strategy is a place where you can put logic related to authentication. Any strategy inherits
-
# from Warden::Strategies::Base.
-
#
-
# The Warden::Strategies.add method is a simple way to provide custom strategies.
-
# You _must_ declare an @authenticate!@ method.
-
# You _may_ provide a @valid?@ method.
-
# The valid method should return true or false depending on if the strategy is a valid one for the request.
-
#
-
# The parameters for Warden::Strategies.add method are:
-
# <label: Symbol> The label is the name given to a strategy. Use the label to refer to the strategy when authenticating
-
# <strategy: Class|nil> The optional strategy argument if set _must_ be a class that inherits from Warden::Strategies::Base and _must_
-
# implement an @authenticate!@ method
-
# <block> The block acts as a convenient way to declare your strategy. Inside is the class definition of a strategy.
-
#
-
# Examples:
-
#
-
# Block Declared Strategy:
-
# Warden::Strategies.add(:foo) do
-
# def authenticate!
-
# # authentication logic
-
# end
-
# end
-
#
-
# Class Declared Strategy:
-
# Warden::Strategies.add(:foo, MyStrategy)
-
#
-
2
class Base
-
# :api: public
-
2
attr_accessor :user, :message
-
-
# :api: private
-
2
attr_accessor :result, :custom_response
-
-
# :api: public
-
2
attr_reader :env, :scope, :status
-
-
2
include ::Warden::Mixins::Common
-
-
# :api: private
-
2
def initialize(env, scope=nil) # :nodoc:
-
@env, @scope = env, scope
-
@status, @headers = nil, {}
-
@halted, @performed = false, false
-
end
-
-
# The method that is called from above. This method calls the underlying authenticate! method
-
# :api: private
-
2
def _run! # :nodoc:
-
@performed = true
-
authenticate!
-
self
-
end
-
-
# Returns if this strategy was already performed.
-
# :api: private
-
2
def performed? #:nodoc:
-
@performed
-
end
-
-
# Marks this strategy as not performed.
-
# :api: private
-
2
def clear!
-
@performed = false
-
end
-
-
# Acts as a guarding method for the strategy.
-
# If #valid? responds false, the strategy will not be executed
-
# Overwrite with your own logic
-
# :api: overwritable
-
2
def valid?; true; end
-
-
# Provides access to the headers hash for setting custom headers
-
# :api: public
-
2
def headers(header = {})
-
@headers ||= {}
-
@headers.merge! header
-
@headers
-
end
-
-
# Access to the errors object.
-
# :api: public
-
2
def errors
-
@env['warden'].errors
-
end
-
-
# Cause the processing of the strategies to stop and cascade no further
-
# :api: public
-
2
def halt!
-
@halted = true
-
end
-
-
# Checks to see if a strategy was halted
-
# :api: public
-
2
def halted?
-
!!@halted
-
end
-
-
# Checks to see if a strategy should result in a permanent login
-
# :api: public
-
2
def store?
-
true
-
end
-
-
# A simple method to return from authenticate! if you want to ignore this strategy
-
# :api: public
-
2
def pass; end
-
-
# Returns true only if the result is a success and a user was assigned.
-
2
def successful?
-
@result == :success && !user.nil?
-
end
-
-
# Whenever you want to provide a user object as "authenticated" use the +success!+ method.
-
# This will halt the strategy, and set the user in the appropriate scope.
-
# It is the "login" method
-
#
-
# Parameters:
-
# user - The user object to login. This object can be anything you have setup to serialize in and out of the session
-
#
-
# :api: public
-
2
def success!(user, message = nil)
-
halt!
-
@user = user
-
@message = message
-
@result = :success
-
end
-
-
# This causes the strategy to fail. It does not throw an :warden symbol to drop the request out to the failure application
-
# You must throw an :warden symbol somewhere in the application to enforce this
-
# Halts the strategies so that this is the last strategy checked
-
# :api: public
-
2
def fail!(message = "Failed to Login")
-
halt!
-
@message = message
-
@result = :failure
-
end
-
-
# Causes the strategy to fail, but not halt. The strategies will cascade after this failure and warden will check the next strategy. The last strategy to fail will have it's message displayed.
-
# :api: public
-
2
def fail(message = "Failed to Login")
-
@message = message
-
@result = :failure
-
end
-
-
# Causes the authentication to redirect. An :warden symbol must be thrown to actually execute this redirect
-
#
-
# Parameters:
-
# url <String> - The string representing the URL to be redirected to
-
# params <Hash> - Any parameters to encode into the URL
-
# opts <Hash> - Any options to redirect with.
-
# available options: permanent => (true || false)
-
#
-
# :api: public
-
2
def redirect!(url, params = {}, opts = {})
-
halt!
-
@status = opts[:permanent] ? 301 : 302
-
headers["Location"] = url
-
headers["Location"] << "?" << Rack::Utils.build_query(params) unless params.empty?
-
headers["Content-Type"] = opts[:content_type] || 'text/plain'
-
-
@message = opts[:message] || "You are being redirected to #{headers["Location"]}"
-
@result = :redirect
-
-
headers["Location"]
-
end
-
-
# Return a custom rack array. You must throw an :warden symbol to activate this
-
# :api: public
-
2
def custom!(response)
-
halt!
-
@custom_response = response
-
@result = :custom
-
end
-
-
end # Base
-
end # Strategies
-
end # Warden
-
2
require 'nokogiri'
-
-
2
require 'xpath/dsl'
-
2
require 'xpath/expression'
-
2
require 'xpath/literal'
-
2
require 'xpath/union'
-
2
require 'xpath/renderer'
-
2
require 'xpath/html'
-
-
2
module XPath
-
-
2
extend XPath::DSL::TopLevel
-
2
include XPath::DSL::TopLevel
-
-
2
def self.generate
-
4
yield(self)
-
end
-
end
-
2
module XPath
-
2
module DSL
-
2
module TopLevel
-
2
def current
-
87
Expression.new(:this_node)
-
end
-
-
2
def name
-
Expression.new(:node_name, current)
-
end
-
-
2
def descendant(*expressions)
-
22
Expression.new(:descendant, current, expressions)
-
end
-
-
2
def child(*expressions)
-
Expression.new(:child, current, expressions)
-
end
-
-
2
def axis(name, tag_name=:*)
-
Expression.new(:axis, current, name, tag_name)
-
end
-
-
2
def next_sibling(*expressions)
-
Expression.new(:next_sibling, current, expressions)
-
end
-
-
2
def previous_sibling(*expressions)
-
Expression.new(:previous_sibling, current, expressions)
-
end
-
-
2
def anywhere(*expressions)
-
2
Expression.new(:anywhere, expressions)
-
end
-
-
2
def attr(expression)
-
58
Expression.new(:attribute, current, expression)
-
end
-
-
2
def contains(expression)
-
Expression.new(:contains, current, expression)
-
end
-
-
2
def starts_with(expression)
-
Expression.new(:starts_with, current, expression)
-
end
-
-
2
def text
-
Expression.new(:text, current)
-
end
-
-
2
def string
-
7
Expression.new(:string_function, current)
-
end
-
-
2
def css(selector)
-
Expression.new(:css, current, Literal.new(selector))
-
end
-
end
-
-
2
module ExpressionLevel
-
2
include XPath::DSL::TopLevel
-
-
2
def where(expression)
-
41
Expression.new(:where, current, expression)
-
end
-
2
alias_method :[], :where
-
-
2
def one_of(*expressions)
-
4
Expression.new(:one_of, current, expressions)
-
end
-
-
2
def equals(expression)
-
17
Expression.new(:equality, current, expression)
-
end
-
2
alias_method :==, :equals
-
-
2
def is(expression)
-
33
Expression.new(:is, current, expression)
-
end
-
-
2
def or(expression)
-
29
Expression.new(:or, current, expression)
-
end
-
2
alias_method :|, :or
-
-
2
def and(expression)
-
Expression.new(:and, current, expression)
-
end
-
2
alias_method :&, :and
-
-
2
def union(*expressions)
-
14
Union.new(*[self, expressions].flatten)
-
end
-
2
alias_method :+, :union
-
-
2
def inverse
-
8
Expression.new(:inverse, current)
-
end
-
2
alias_method :~, :inverse
-
-
2
def string_literal
-
Expression.new(:string_literal, self)
-
end
-
-
2
def normalize
-
7
Expression.new(:normalized_space, current)
-
end
-
2
alias_method :n, :normalize
-
end
-
end
-
end
-
2
module XPath
-
2
class Expression
-
2
attr_accessor :expression, :arguments
-
2
include XPath::DSL::ExpressionLevel
-
-
2
def initialize(expression, *arguments)
-
315
@expression = expression
-
315
@arguments = arguments
-
end
-
-
2
def current
-
139
self
-
end
-
-
2
def to_xpath(type=nil)
-
5
Renderer.render(self, type)
-
end
-
2
alias_method :to_s, :to_xpath
-
end
-
end
-
2
module XPath
-
2
module HTML
-
2
include XPath::DSL::TopLevel
-
2
extend self
-
-
# Match an `a` link element.
-
#
-
# @param [String] locator
-
# Text, id, title, or image alt attribute of the link
-
#
-
2
def link(locator)
-
locator = locator.to_s
-
link = descendant(:a)[attr(:href)]
-
link[attr(:id).equals(locator) | string.n.is(locator) | attr(:title).is(locator) | descendant(:img)[attr(:alt).is(locator)]]
-
end
-
-
# Match a `submit`, `image`, or `button` element.
-
#
-
# @param [String] locator
-
# Value, title, id, or image alt attribute of the button
-
#
-
2
def button(locator)
-
locator = locator.to_s
-
button = descendant(:input)[attr(:type).one_of('submit', 'reset', 'image', 'button')][attr(:id).equals(locator) | attr(:value).is(locator) | attr(:title).is(locator)]
-
button += descendant(:button)[attr(:id).equals(locator) | attr(:value).is(locator) | string.n.is(locator) | attr(:title).is(locator)]
-
button += descendant(:input)[attr(:type).equals('image')][attr(:alt).is(locator)]
-
end
-
-
-
# Match anything returned by either {#link} or {#button}.
-
#
-
# @param [String] locator
-
# Text, id, title, or image alt attribute of the link or button
-
#
-
2
def link_or_button(locator)
-
link(locator) + button(locator)
-
end
-
-
-
# Match any `fieldset` element.
-
#
-
# @param [String] locator
-
# Legend or id of the fieldset
-
#
-
2
def fieldset(locator)
-
locator = locator.to_s
-
descendant(:fieldset)[attr(:id).equals(locator) | child(:legend)[string.n.is(locator)]]
-
end
-
-
-
# Match any `input`, `textarea`, or `select` element that doesn't have a
-
# type of `submit`, `image`, or `hidden`.
-
#
-
# @param [String] locator
-
# Label, id, or name of field to match
-
#
-
2
def field(locator)
-
locator = locator.to_s
-
xpath = descendant(:input, :textarea, :select)[~attr(:type).one_of('submit', 'image', 'hidden')]
-
xpath = locate_field(xpath, locator)
-
xpath
-
end
-
-
-
# Match any `input` or `textarea` element that can be filled with text.
-
# This excludes any inputs with a type of `submit`, `image`, `radio`,
-
# `checkbox`, `hidden`, or `file`.
-
#
-
# @param [String] locator
-
# Label, id, or name of field to match
-
#
-
2
def fillable_field(locator)
-
locator = locator.to_s
-
xpath = descendant(:input, :textarea)[~attr(:type).one_of('submit', 'image', 'radio', 'checkbox', 'hidden', 'file')]
-
xpath = locate_field(xpath, locator)
-
xpath
-
end
-
-
-
# Match any `select` element.
-
#
-
# @param [String] locator
-
# Label, id, or name of the field to match
-
#
-
2
def select(locator)
-
locator = locator.to_s
-
locate_field(descendant(:select), locator)
-
end
-
-
-
# Match any `input` element of type `checkbox`.
-
#
-
# @param [String] locator
-
# Label, id, or name of the checkbox to match
-
#
-
2
def checkbox(locator)
-
locator = locator.to_s
-
locate_field(descendant(:input)[attr(:type).equals('checkbox')], locator)
-
end
-
-
-
# Match any `input` element of type `radio`.
-
#
-
# @param [String] locator
-
# Label, id, or name of the radio button to match
-
#
-
2
def radio_button(locator)
-
locator = locator.to_s
-
locate_field(descendant(:input)[attr(:type).equals('radio')], locator)
-
end
-
-
-
# Match any `input` element of type `file`.
-
#
-
# @param [String] locator
-
# Label, id, or name of the file field to match
-
#
-
2
def file_field(locator)
-
locator = locator.to_s
-
locate_field(descendant(:input)[attr(:type).equals('file')], locator)
-
end
-
-
-
# Match an `optgroup` element.
-
#
-
# @param [String] name
-
# Label for the option group
-
#
-
2
def optgroup(locator)
-
locator = locator.to_s
-
descendant(:optgroup)[attr(:label).is(locator)]
-
end
-
-
-
# Match an `option` element.
-
#
-
# @param [String] name
-
# Visible text of the option
-
#
-
2
def option(locator)
-
locator = locator.to_s
-
descendant(:option)[string.n.is(locator)]
-
end
-
-
-
# Match any `table` element.
-
#
-
# @param [String] locator
-
# Caption or id of the table to match
-
# @option options [Array] :rows
-
# Content of each cell in each row to match
-
#
-
2
def table(locator)
-
locator = locator.to_s
-
descendant(:table)[attr(:id).equals(locator) | descendant(:caption).is(locator)]
-
end
-
-
# Match any 'dd' element.
-
#
-
# @param [String] locator
-
# Id of the 'dd' element or text from preciding 'dt' element content
-
2
def definition_description(locator)
-
locator = locator.to_s
-
descendant(:dd)[attr(:id).equals(locator) | previous_sibling(:dt)[string.n.equals(locator)] ]
-
end
-
-
2
protected
-
-
2
def locate_field(xpath, locator)
-
locate_field = xpath[attr(:id).equals(locator) | attr(:name).equals(locator) | attr(:placeholder).equals(locator) | attr(:id).equals(anywhere(:label)[string.n.is(locator)].attr(:for))]
-
locate_field += descendant(:label)[string.n.is(locator)].descendant(xpath)
-
locate_field
-
end
-
end
-
end
-
2
module XPath
-
2
class Literal
-
2
attr_reader :value
-
2
def initialize(value)
-
@value = value
-
end
-
end
-
end
-
2
module XPath
-
2
class Renderer
-
2
def self.render(node, type)
-
11
new(type).render(node)
-
end
-
-
2
def initialize(type)
-
11
@type = type
-
end
-
-
2
def render(node)
-
897
arguments = node.arguments.map { |argument| convert_argument(argument) }
-
375
send(node.expression, *arguments)
-
end
-
-
2
def convert_argument(argument)
-
578
case argument
-
364
when Expression, Union then render(argument)
-
88
when Array then argument.map { |element| convert_argument(element) }
-
74
when String then string_literal(argument)
-
when Literal then argument.value
-
108
else argument.to_s
-
end
-
end
-
-
2
def string_literal(string)
-
74
if string.include?("'")
-
string = string.split("'", -1).map do |substr|
-
"'#{substr}'"
-
end.join(%q{,"'",})
-
"concat(#{string})"
-
else
-
74
"'#{string}'"
-
end
-
end
-
-
2
def this_node
-
101
'.'
-
end
-
-
2
def descendant(parent, element_names)
-
26
if element_names.length == 1
-
22
"#{parent}//#{element_names.first}"
-
4
elsif element_names.length > 1
-
16
"#{parent}//*[#{element_names.map { |e| "self::#{e}" }.join(" | ")}]"
-
else
-
"#{parent}//*"
-
end
-
end
-
-
2
def child(parent, element_names)
-
if element_names.length == 1
-
"#{parent}/#{element_names.first}"
-
elsif element_names.length > 1
-
"#{parent}/*[#{element_names.map { |e| "self::#{e}" }.join(" | ")}]"
-
else
-
"#{parent}/*"
-
end
-
end
-
-
2
def axis(parent, name, tag_name)
-
"#{parent}/#{name}::#{tag_name}"
-
end
-
-
2
def node_name(current)
-
"name(#{current})"
-
end
-
-
2
def where(on, condition)
-
49
"#{on}[#{condition}]"
-
end
-
-
2
def attribute(current, name)
-
68
"#{current}/@#{name}"
-
end
-
-
2
def equality(one, two)
-
58
"#{one} = #{two}"
-
end
-
-
2
def is(one, two)
-
37
if @type == :exact
-
37
equality(one, two)
-
else
-
contains(one, two)
-
end
-
end
-
-
2
def variable(name)
-
"%{#{name}}"
-
end
-
-
2
def text(current)
-
"#{current}/text()"
-
end
-
-
2
def normalized_space(current)
-
7
"normalize-space(#{current})"
-
end
-
-
2
def literal(node)
-
node
-
end
-
-
2
def css(current, selector)
-
paths = Nokogiri::CSS.xpath_for(selector).map do |xpath_selector|
-
"#{current}#{xpath_selector}"
-
end
-
union(paths)
-
end
-
-
2
def union(*expressions)
-
14
expressions.join(' | ')
-
end
-
-
2
def anywhere(element_names)
-
2
if element_names.length == 1
-
"//#{element_names.first}"
-
2
elsif element_names.length > 1
-
8
"//*[#{element_names.map { |e| "self::#{e}" }.join(" | ")}]"
-
else
-
"//*"
-
end
-
end
-
-
2
def contains(current, value)
-
"contains(#{current}, #{value})"
-
end
-
-
2
def starts_with(current, value)
-
"starts-with(#{current}, #{value})"
-
end
-
-
2
def and(one, two)
-
"(#{one} and #{two})"
-
end
-
-
2
def or(one, two)
-
29
"(#{one} or #{two})"
-
end
-
-
2
def one_of(current, values)
-
20
values.map { |value| "#{current} = #{value}" }.join(' or ')
-
end
-
-
2
def next_sibling(current, element_names)
-
if element_names.length == 1
-
"#{current}/following-sibling::*[1]/self::#{element_names.first}"
-
elsif element_names.length > 1
-
"#{current}/following-sibling::*[1]/self::*[#{element_names.map { |e| "self::#{e}" }.join(" | ")}]"
-
else
-
"#{current}/following-sibling::*[1]/self::*"
-
end
-
end
-
-
2
def previous_sibling(current, element_names)
-
if element_names.length == 1
-
"#{current}/preceding-sibling::*[1]/self::#{element_names.first}"
-
elsif element_names.length > 1
-
"#{current}/preceding-sibling::*[1]/self::*[#{element_names.map { |e| "self::#{e}" }.join(" | ")}]"
-
else
-
"#{current}/preceding-sibling::*[1]/self::*"
-
end
-
end
-
-
2
def inverse(current)
-
10
"not(#{current})"
-
end
-
-
2
def string_function(current)
-
7
"string(#{current})"
-
end
-
end
-
end
-
2
module XPath
-
2
class Union
-
2
include Enumerable
-
-
2
attr_reader :expressions
-
2
alias_method :arguments, :expressions
-
-
2
def initialize(*expressions)
-
20
@expressions = expressions
-
end
-
-
2
def expression
-
14
:union
-
end
-
-
2
def each(&block)
-
arguments.each(&block)
-
end
-
-
2
def method_missing(*args)
-
18
XPath::Union.new(*arguments.map { |e| e.send(*args) })
-
end
-
-
2
def to_xpath(type=nil)
-
6
Renderer.render(self, type)
-
end
-
2
alias_method :to_s, :to_xpath
-
end
-
end
-
class ActivitiesController < ApplicationController
-
def index
-
@activities = PublicActivity::Activity.order("created_at desc")
-
end
-
end
-
2
class ApplicationController < ActionController::Base
-
# Prevent CSRF attacks by raising an exception.
-
# For APIs, you may want to use :null_session instead.
-
2
include PublicActivity::StoreController
-
2
protect_from_forgery with: :exception
-
2
include SessionsHelper
-
2
include PatientSessionsHelper
-
2
include DoctorSessionsHelper
-
2
def current_patuser
-
@current_user ||= Patient.find_by(id: session[:user_id])
-
end
-
2
def current_docuser
-
@current_user ||= Doctor.find_by(id: session[:user_id])
-
end
-
2
helper_method :current_user
-
2
hide_action :current_patuser
-
end
-
1
class AppointmentsController < ApplicationController
-
1
def new
-
@doctor = Doctor.find(params[:docid])
-
@patient = Patient.find(params[:patient])
-
@slots = officehours
-
@appointment = @doctor.appointments.build
-
end
-
1
def create
-
@doctor = Doctor.find(params[:docid])
-
@patient = Patient.find(params[:patient])
-
@appointment = @doctor.appointments.build(user_params)
-
@patappointment =@patient.appointments.build(user_params)
-
#make a check for both Doctor and patient
-
if @appointment.save
-
redirect_to(controller: 'appointments',action: 'show1' ,docid: @doctor.id, id:@patient.id)
-
end
-
end
-
-
1
def show
-
@doctor = Doctor.find(params[:id])
-
@office = @doctor.appointments
-
-
end
-
1
def show1
-
-
@patient = Patient.find(params[:id])
-
@office = @patient.appointments
-
-
end
-
1
private
-
1
def user_params
-
params.require(:appointment).permit(:appdate, :appointtime,:patient_id)
-
end
-
1
def officehours
-
offstart = @doctor.profession.offstart
-
offend = @doctor.profession.offend
-
avgtime = 20
-
checker = "00"
-
allslots = []
-
while(offstart <= offend)
-
# if checker == 60
-
# checker == 00
-
# offstart = offstart.to_i + 1
-
# offstart = offstart.to_s
-
# end
-
slotstart = offstart + ":" + checker.to_s
-
puts "first checker "
-
puts checker
-
checker = checker.to_i + avgtime
-
puts"second checker"
-
puts checker
-
if checker >= 60
-
checker = 00
-
offstart = offstart.to_i + 1
-
offstart = offstart.to_s
-
end
-
slotend = offstart + ":" + checker.to_s
-
slot = slotstart.to_s + "-" + slotend.to_s
-
puts "checker"
-
puts checker
-
puts "offstart"
-
puts offstart
-
allslots.push(slot)
-
end
-
return allslots
-
end
-
end
-
1
class CommentsController < ApplicationController
-
1
def index
-
-
end
-
1
def update
-
-
end
-
1
def new
-
-
end
-
1
def show
-
-
end
-
1
def create
-
@forum = Forum.find(params[:forum_id])
-
@patient = Patient.find(params[:comment][:patient_id])
-
@comment=@forum.comments.create(params[:comment].permit(:body));
-
redirect_to(:controller=>:forums,:action=>:search,:patid=>@patient.id,:id=>@forum.id)
-
end
-
1
def edit
-
-
end
-
1
def destroy
-
-
end
-
-
end
-
class DegreesController < ApplicationController
-
def show
-
@doctor = Doctor.find(params[:id])
-
@degree = @doctor.degrees
-
end
-
-
def new
-
@doctor = Doctor.find(params[:id])
-
@degree=@doctor.degrees.build
-
end
-
-
def create
-
@doctor = Doctor.find(params[:id])
-
@degree=@doctor.degrees.build(degree_params)
-
if @degree.save
-
redirect_to(controller: 'doctors',action: 'show' ,id: @doctor.id)
-
else
-
redirect_to @doctor
-
end
-
end
-
private
-
-
def degree_params
-
params.require(:degree).permit(:uniName, :degreeName , :doctor_id)
-
end
-
end
-
1
class DoctorSessionsController < ApplicationController
-
1
def new
-
-
-
end
-
1
def create
-
2
user = Doctor.find_by(email: params[:doctor_session][:email].downcase)
-
2
if user && user.authenticate(params[:doctor_session][:password])
-
log_in user
-
redirect_to user
-
else
-
2
flash.now[:danger] = 'Invalid email/password combination'
-
2
render 'new'
-
end
-
end
-
1
def destroy
-
log_out
-
redirect_to static_pages_Home_path
-
end
-
end
-
2
class DoctorsController < ApplicationController
-
#shows the ProfessionsController
-
2
def profile
-
@doctor= Doctor.find(params[:id])
-
-
end
-
2
def show
-
#shows all the doctors per id
-
#change it later and ask TA for help
-
@doctor = Doctor.find(params[:id])
-
end
-
-
2
def edit
-
@doctor = Doctor.find(params[:id])
-
end
-
-
2
def index
-
end
-
2
def update
-
@doctor = Doctor.find(params[:id])
-
if @doctor.update(user_params)
-
redirect_to(controller: 'doctors',action: 'show' ,id: @doctor.id)
-
else
-
#redirect_to(controller: 'doctors',action: 'show' ,id: @doctor.id)
-
end
-
end
-
-
2
def create
-
#to do back end of new
-
1
@doctor = Doctor.new(user_params)
-
1
if @doctor.save
-
log_in @doctor
-
flash[:success] = "Welcome to the Sample App!"
-
redirect_to @doctor
-
else
-
1
render 'new'
-
end
-
end
-
-
2
def new
-
#to show in the views
-
2
@doctor = Doctor.new
-
end
-
-
#extra method
-
2
def show1
-
@doctor = Doctor.find(params[:id])
-
end
-
-
2
def destroy
-
end
-
-
2
private
-
2
def user_params
-
1
params.require(:doctor).permit(:name, :email, :password,:phone,:sex,
-
:password_confirmation, :image)
-
end
-
end
-
class EducationsController < ApplicationController
-
def edit
-
-
end
-
-
def create
-
@degree=current_user.education.build(degree_params)
-
if @degree.save
-
redirect_to doctor_path
-
-
end
-
end
-
-
def new
-
@doctor = Doctor.find(params[:id])
-
@degree=@doctor.build_education
-
end
-
-
def update
-
end
-
-
private
-
-
def degree_params
-
params.require(:degree).permit(:uniName, :degreeName , :doctor_id)
-
end
-
end
-
class FollowersController < ApplicationController
-
def index
-
end
-
def new
-
@doctor = Doctor.find(params[:id])
-
#@patient = Patient.find(params[:id])
-
-
end
-
-
def create
-
@doctor = Doctor.find(params[:follower][:doctor_id]);
-
@patient = Patient.find(params[:follower][:patient_id]);
-
#@follow = @docfollowed.followers.build
-
@docfollow = @doctor.followers.create(follower_params);
-
#Rails.logger.debug("My object: #{@docfollowed.inspect}")
-
#@patfollow = @patient.followers.create(follower_params);
-
#Rails.logger.debug("My object: #{@patfollow.inspect}")
-
if @docfollow.save
-
-
#redirect_to static_pages_Home_path
-
redirect_to(controller: "followers" , action:"new",:id =>@doctor.id ,:pid => @patient.id);
-
else
-
redirect_to static_pages_Home_path
-
end
-
end
-
-
def show
-
end
-
-
def destroy
-
end
-
def add_follower
-
-
end
-
-
private
-
def follower_params
-
params.require(:follower).permit(:doctor_id,:patient_id)
-
end
-
end
-
class ForumsController < ApplicationController
-
def index
-
-
end
-
def update
-
-
end
-
def new
-
@patient = Patient.find(params[:patid]);
-
@forum = @patient.forums.build
-
end
-
def show
-
#@patient = Patient.find(params[:forum][:patient_id]);
-
@forum = Forum.all
-
@patient = Patient.find(params[:patid]);
-
end
-
def create
-
@patient = Patient.find(params[:forum][:patient_id]);
-
@forum = @patient.forums.build(forum_params);
-
if @forum.save
-
redirect_to(:controller =>:forums , :action => :show,:patid=>@patient.id, :id=>@forum.id);
-
#redirect_to discussion_form_path
-
end
-
-
end
-
def edit
-
-
end
-
def destroy
-
-
end
-
def search
-
@patient =Patient.find(params[:patid])
-
@forum = Forum.find(params[:id])
-
end
-
-
private
-
def forum_params
-
params.require(:forum).permit(:title,:body,:patient_id)
-
end
-
end
-
class PatientSessionsController < ApplicationController
-
-
def new
-
-
-
end
-
def create
-
user = Patient.find_by(email: params[:patient_session][:email].downcase)
-
if user && user.authenticate(params[:patient_session][:password])
-
log_in user
-
redirect_to user
-
else
-
flash.now[:danger] = 'Invalid email/password combination'
-
render 'new'
-
end
-
end
-
def destroy
-
log_out
-
redirect_to static_pages_Home_path
-
end
-
-
end
-
2
class PatientsController < ApplicationController
-
-
2
def show
-
#shows all the Patients per id
-
@patient = Patient.find(params[:id])
-
end
-
2
def show1
-
@patient = Patient.find(params[:id])
-
end
-
2
def edit
-
@patient = Patient.find(params[:id])
-
end
-
-
2
def index
-
end
-
2
def update
-
@patient = Patient.find(params[:id])
-
if @patient.update_attributes(user_params)
-
redirect_to @patient
-
end
-
end
-
-
2
def create
-
#to do back end of new
-
1
@patient = Patient.new(user_params)
-
1
if @patient.save
-
log_in @patient
-
flash[:success] = "Welcome to the Sample App!"
-
redirect_to @patient
-
else
-
1
render 'new'
-
end
-
end
-
-
2
def new
-
#to show in the views
-
2
@patient = Patient.new
-
end
-
-
2
def destroy
-
end
-
#my extra actions
-
2
def search
-
@patient = Patient.find(params[:id])
-
end
-
2
private
-
2
def user_params
-
1
params.require(:patient).permit(:name, :email, :password,:sex,:phone,
-
:password_confirmation,:image)
-
end
-
end
-
class ProfessionsController < ApplicationController
-
-
#appy edit but then there will be no create and new
-
def show
-
@doctor = Doctor.find(params[:id])
-
@office = @doctor.profession
-
end
-
def edit
-
@doctor = Doctor.find(params[:id])
-
@office=@doctor.profession
-
-
end
-
def update
-
@doctor = Doctor.find(params[:id])
-
@office = @doctor.profession
-
if @office.update(profession_params)
-
redirect_to(controller: 'doctors',action: 'show' ,id: @doctor.id)
-
end
-
end
-
def new
-
@doctor = Doctor.find(params[:id])
-
@office=@doctor.build_profession
-
-
end
-
-
def create
-
@doctor = Doctor.find(params[:id])
-
@office=@doctor.build_profession(profession_params)
-
if @office.save
-
redirect_to(controller: 'doctors',action: 'show' ,id: @doctor.id)
-
-
end
-
end
-
private
-
-
def profession_params
-
params.require(:profession).permit(:spec, :offstart ,:offend,:address,:fee, :doctor_id)
-
end
-
end
-
1
class ReviewsController < ApplicationController
-
1
def index
-
end
-
1
def create
-
@doctor = Doctor.find(params[:review][:doctor_id])
-
@patient = Patient.find(params[:review][:patient_id])
-
-
@review = @doctor.reviews.build(review_params)
-
# @patreview =@patient.reviews.create(review_params)
-
if @review.save
-
redirect_to(controller: 'appointments',action: 'show1' ,:id => @patient.id, :docid => @doctor.id )
-
else
-
redirect_to static_pages_Home_path
-
end
-
end
-
1
def edit
-
end
-
1
def new
-
-
@doctor = Doctor.find(params[:docid])
-
@patient = Patient.find(params[:patid])
-
@reviews = @doctor.reviews.build
-
@reviews1 = @patient.reviews.build
-
-
end
-
1
def show
-
-
@patient = Patient.find(params[:id])
-
@reviews = @patient.reviews
-
end
-
1
def show1
-
@doctor = Doctor.find(params[:did])
-
@reviews = @doctor.reviews
-
end
-
1
private
-
1
def review_params
-
params.require(:review).permit(:waitTime,:overallRating,:besideManner,:patient_id,:doctor_id)
-
end
-
end
-
class SearchesController < ApplicationController
-
-
def new
-
@search = Search.new
-
@patient = Patient.find(params[:patid])
-
end
-
-
def create
-
@search = Search.new(search_params)
-
#@patient = Patient.find(params[:patient_id]);
-
if @search.save
-
redirect_to @search
-
else
-
-
end
-
end
-
-
def show
-
@search = Search.find(params[:id])
-
-
end
-
-
private
-
def search_params
-
params.require(:search).permit(:name, :speciality, :address, :sex, :patient_id)
-
end
-
def pat_params
-
params.require(:search).permit(:patid)
-
end
-
end
-
class SessionsController < ApplicationController
-
def new
-
-
-
end
-
def create
-
user = Doctor.find_by(email: params[:session][:email].downcase)
-
if user && user.authenticate(params[:session][:password])
-
log_in user
-
redirect_to user
-
else
-
flash.now[:danger] = 'Invalid email/password combination'
-
render 'new'
-
end
-
end
-
def destroy
-
log_out
-
redirect_to static_pages_Home_path
-
end
-
end
-
2
class StaticPagesController < ApplicationController
-
2
def Home
-
end
-
2
def Home2
-
end
-
2
def Services
-
end
-
-
2
def Contact
-
end
-
-
2
def SignIn
-
end
-
end
-
class UsersController < ApplicationController
-
def index
-
end
-
def show
-
@user = User.find(params[:id])
-
-
end
-
def create
-
@user = User.new(user_params)
-
if @user.save
-
log_in @user
-
flash[:success] = "Welcome to the Sample App!"
-
redirect_to @user
-
else
-
render 'new'
-
end
-
end
-
def destroy
-
end
-
def new
-
@user = User.new
-
end
-
private
-
-
def user_params
-
params.require(:user).permit(:name, :email, :password,
-
:password_confirmation)
-
end
-
end
-
2
module ActivitiesHelper
-
end
-
2
module ApplicationHelper
-
end
-
2
module AppointmentsHelper
-
2
def scheduler (starttime, endtime)
-
-
end
-
end
-
2
module CommentsHelper
-
end
-
2
module DegreesHelper
-
end
-
2
module DoctorSessionsHelper
-
-
#
-
2
def log_in(user)
-
session[:user_id] = user.id
-
end
-
# Returns the current logged-in user (if any).
-
2
def current_user
-
13
@current_user ||= Doctor.find_by(id: session[:user_id])
-
end
-
2
def logged_in?
-
!current_user.nil?
-
end
-
-
# Logs out the current user.
-
2
def log_out
-
session.delete(:user_id)
-
@current_user = nil
-
end
-
-
end
-
2
module DoctorsHelper
-
end
-
2
module EducationsHelper
-
end
-
2
module FollowersHelper
-
end
-
2
module ForumsHelper
-
end
-
2
module PatientSessionsHelper
-
2
def log_in(user)
-
session[:user_id] = user.id
-
end
-
# Returns the current logged-in user (if any).
-
2
def current_user
-
@current_user ||= Doctor.find_by(id: session[:user_id])
-
end
-
2
def logged_in?
-
!current_user.nil?
-
end
-
-
# Logs out the current user.
-
2
def log_out
-
session.delete(:user_id)
-
@current_user = nil
-
end
-
end
-
2
module PatientsHelper
-
end
-
2
module ProfessionsHelper
-
end
-
2
module ReviewsHelper
-
end
-
2
module SearchesHelper
-
end
-
2
module SessionsHelper
-
2
def log_in(user)
-
session[:user_id] = user.id
-
end
-
# Returns the current logged-in user (if any).
-
2
def current_user
-
@current_user ||= Doctor.find_by(id: session[:user_id])
-
end
-
2
def logged_in?
-
13
!current_user.nil?
-
end
-
-
# Logs out the current user.
-
2
def log_out
-
session.delete(:user_id)
-
@current_user = nil
-
end
-
end
-
2
module StaticPagesHelper
-
end
-
class Appointment < ActiveRecord::Base
-
belongs_to :doctor
-
belongs_to :patient
-
validates :apptime, presence: true
-
validates :appdate, presence: true
-
end
-
1
class Comment < ActiveRecord::Base
-
1
include PublicActivity::Model
-
1
tracked owner: ->(controller, model) { controller && controller.current_patuser }
-
-
1
belongs_to :doctor
-
1
belongs_to :patient
-
1
belongs_to :forum
-
end
-
class Degree < ActiveRecord::Base
-
belongs_to :doctor
-
end
-
2
class Doctor < ActiveRecord::Base
-
# has_attached_file :photo, :styles => { :small => "150x150>" },
-
# :url => "/assets/products/:id/:style/:basename.:extension",
-
# :path => ":rails_root/public/assets/products/:id/:style/:basename.:extension"
-
#
-
# validates_attachment_presence :photo
-
# validates_attachment_size :photo, :less_than => 5.megabytes
-
# validates_attachment_content_type :photo, :content_type => ['image/jpeg', 'image/png']
-
2
mount_uploader :image, ImageUploader
-
2
has_many :comments
-
2
has_many :appointments
-
2
has_one :profession
-
2
has_many :degrees
-
2
has_many :reviews
-
2
has_many :followers
-
123
before_save { self.email = email.downcase }
-
2
validates :name, presence: true, length: { maximum: 50 }
-
2
VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
-
2
validates :email, presence: true, length: { maximum: 255 },format: { with: VALID_EMAIL_REGEX },uniqueness: true
-
-
2
has_secure_password
-
2
validates :password, presence: true, length: { minimum: 6 }
-
-
2
def User.digest(string)
-
cost = ActiveModel::SecurePassword.min_cost ? BCrypt::Engine::MIN_COST :
-
BCrypt::Engine.cost
-
BCrypt::Password.create(string, cost: cost)
-
end
-
-
end
-
class Education < ActiveRecord::Base
-
belongs_to :doctors
-
end
-
class Follower < ActiveRecord::Base
-
include PublicActivity::Model
-
tracked owner: ->(controller, model) { controller && controller.current_user }
-
-
belongs_to :doctor
-
belongs_to :patient
-
#validates :patient_id, uniqueness: true
-
end
-
class Forum < ActiveRecord::Base
-
belongs_to :patient
-
has_many :comments
-
end
-
2
class Patient < ActiveRecord::Base
-
2
include PublicActivity::Model
-
74
tracked owner: ->(controller, model) { controller && controller.current_patuser }
-
2
mount_uploader :image, ImageUploader
-
2
has_many :doctors
-
2
has_many :comments
-
2
has_many :forums
-
2
has_many :appointments
-
2
has_many :searches
-
2
has_many :reviews
-
2
has_many :followers
-
74
before_save { self.email = email.downcase }
-
2
validates :name, presence: true, length: { maximum: 50 }
-
2
VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
-
2
validates :email, presence: true, length: { maximum: 255 },format: { with: VALID_EMAIL_REGEX },uniqueness: true
-
-
2
has_secure_password
-
2
validates :password, presence: true, length: { minimum: 6 }
-
-
2
def User.digest(string)
-
cost = ActiveModel::SecurePassword.min_cost ? BCrypt::Engine::MIN_COST :
-
BCrypt::Engine.cost
-
BCrypt::Password.create(string, cost: cost)
-
end
-
end
-
class Profession < ActiveRecord::Base
-
belongs_to :doctor
-
-
end
-
1
class Review < ActiveRecord::Base
-
1
belongs_to :patient
-
1
belongs_to :doctor
-
-
end
-
1
class Search < ActiveRecord::Base
-
#to help in searching methodolgy
-
1
belongs_to :patient
-
1
def search_docs
-
doctors = Doctor.select(:name, :sex, :id, :image);
-
profession = Profession.select(:address, :spec, :doctor_id);
-
# puts doctors[0].profession.address
-
doctors = doctors.where(["name LIKE ?",name]) if name.present?
-
doctors = doctors.where(["sex LIKE ?",sex]) if gender.present?
-
doctors = doctors.map { |d| (!d.profession.nil? && (d.profession.address == address)) ? d : nil } if address.present?
-
doctors = doctors.delete_if {|d| (d == nil) == true} if address.present?
-
doctors = doctors.map { |d| (!d.profession.nil? && (d.profession.spec == speciality)) ? d : nil } if speciality.present?
-
doctors = doctors.delete_if {|d| (d == nil) == true} if speciality.present?
-
-
puts "printing professions"
-
# puts professions
-
puts "printing professions done"
-
return doctors
-
end
-
end
-
2
class User < ActiveRecord::Base
-
2
before_save { self.email = email.downcase }
-
2
validates :name, presence: true, length: { maximum: 50 }
-
2
VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
-
2
validates :email, presence: true, length: { maximum: 255 },format: { with: VALID_EMAIL_REGEX },uniqueness: true
-
-
2
has_secure_password
-
2
validates :password, presence: true, length: { minimum: 6 }
-
-
2
def User.digest(string)
-
cost = ActiveModel::SecurePassword.min_cost ? BCrypt::Engine::MIN_COST :
-
BCrypt::Engine.cost
-
BCrypt::Password.create(string, cost: cost)
-
end
-
end
-
# encoding: utf-8
-
-
2
class ImageUploader < CarrierWave::Uploader::Base
-
-
# Include RMagick or MiniMagick support:
-
# include CarrierWave::RMagick
-
# include CarrierWave::MiniMagick
-
2
def auto_orient
-
manipulate! do |image|
-
image.tap(&:auto_orient)
-
end
-
end
-
# Choose what kind of storage to use for this uploader:
-
2
storage :file
-
# storage :fog
-
-
# Override the directory where uploaded files will be stored.
-
# This is a sensible default for uploaders that are meant to be mounted:
-
2
def store_dir
-
"uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
-
end
-
-
# Provide a default URL as a default if there hasn't been a file uploaded:
-
# def default_url
-
# # For Rails 3.1+ asset pipeline compatibility:
-
# # ActionController::Base.helpers.asset_path("fallback/" + [version_name, "default.png"].compact.join('_'))
-
#
-
# "/images/fallback/" + [version_name, "default.png"].compact.join('_')
-
# end
-
-
# Process files as they are uploaded:
-
# process :scale => [200, 300]
-
#
-
# def scale(width, height)
-
# # do something
-
# end
-
-
# Create different versions of your uploaded files:
-
# version :thumb do
-
# process :resize_to_fit => [50, 50]
-
# end
-
-
# Add a white list of extensions which are allowed to be uploaded.
-
# For images you might use something like this:
-
# def extension_white_list
-
# %w(jpg jpeg gif png)
-
# end
-
-
# Override the filename of the uploaded files:
-
# Avoid using model.id or version_name here, see uploader/store.rb for details.
-
# def filename
-
# "something.jpg" if original_filename
-
# end
-
-
end